如何使用sci-kit Learn通过Logistic回归预测单个实例?

时间:2018-12-26 03:07:59

标签: python scikit-learn

我正在尝试构建可以预测新实例类的Logistic回归模型。
这是我所做的

path = 'diabetes.csv'
df = pd.read_csv(path, header = None)
print "Classifying with Logistic Regression"
values = df.values
X = values[1:,0:8]
y = values[1:,8]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=42)
model=LogisticRegression()
model.fit(X_train,y_train)

X_test = []
X_test.append(int(pregnancies_info))
X_test.append(int(glucose_info))
X_test.append(int(blood_press_info))
X_test.append(int(skin_thickness_info))
X_test.append(int(insulin_info))
X_test.append(float(BMI_info))
X_test.append(float(dpf_info))
X_test.append(int(age_info))
#X_test = np.array(X_test).reshape(-1, 1)
print X_test
y_pred=model.predict(X_test)
if y_pred == 0:
    Label(login_screen, text="Healthy").pack()
if y_pred == 1:
    Label(login_screen, text="Diabetes Metillus").pack()

pregnancies_entry.delete(0, END)
glucose_entry.delete(0, END)
blood_press_entry.delete(0, END)
skin_thickness_entry.delete(0, END)
insulin_entry.delete(0, END)
BMI_entry.delete(0, END)
dpf_entry.delete(0, END)
age_entry.delete(0, END)

但是我得到了这个错误:

  

如果数据具有单个特征,则使用array.reshape(-1,1)来重塑数据;如果包含单个样本,则使用array.reshape(1,-1)来重塑数据。

如果我取消注释此行X_test = np.array(X_test).reshape(-1, 1),则会出现此错误:

  

decision_function中的文件“ /anaconda2/lib/python2.7/site-packages/sklearn/linear_model/base.py”,第305行       %(X.shape [1],n_features))   ValueError:X每个样本具有1个功能;期望8

1 个答案:

答案 0 :(得分:1)

您必须将其指定为

\'[^\']*\'

或者您可以直接做

X_test = np.array(X_test).reshape(1, -1))

原因是y_pred=model.predict([X_test]) 函数需要二维数组,其维度为(n_samples,n_features)。如果只有需要预测的记录,请创建一个列表列表并将其提供!希望对您有所帮助。