TypeError: predict() missing 1 required positional argument: 'X' in sklearn KMeans

TypeError: predict() missing 1 required positional argument: 'X' in sklearn KMeans

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import warnings
import graphviz
warnings.filterwarnings('ignore')
%matplotlib inline
import os
from sklearn.cluster import KMeans

#Importing the dataset
Diabetes2 = pd.read_csv('C:\Users\PPP\Desktop\Python_Practice\Datasets\Diabetes\diabetic_data.csv', index_col=False)

#Split into input and output features
y = Diabetes2["readmittedFL"]
X = Diabetes2[["time_in_hospital","num_lab_procedures","num_procedures","num_medications",
               "number_outpatient","number_emergency","number_inpatient","number_diagnoses"]]
X.head()
y.head()

#Select the annual income and the spending score columns 
KMeans = KMeans()
X_array=X.iloc[0:8:1].values
y_kmeans = KMeans.predict(X_array)
plt.scatter(X_array[:, 0], X_array[:, 1], c=y_kmeans, s=50, cmap='viridis')

我刚开始练习 KMeans 时遇到了这个错误。我不明白哪里出了问题。

当我运行命令y_kmeans = KMeans.predict(X_array)时, 它显示错误 TypeError: predict() missing 1 required positional argument: X

如何解决这个错误?

你需要使用 fit_predict 而不是 predict

  • fit_predict :训练和预测你的训练点集群
  • 预测:当你得到新的数据点时用于推理 未出现在您的火车数据中

此外,您没有通过 n_clusters 参数指定簇数,它将采用默认数字 8

有关更多信息,请查看此 link