下面是一个工作示例,您可以使用它来比较代码并删除任何错误。我已经在数据框中添加了几行——细节和结果都在代码后面。正如你所看到的,模型已经正确预测了四个标签中的三个。
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
le = LabelEncoder()
sc = StandardScaler()
X = pd.get_dummies(df.iloc[:, :2], drop_first=True).values.astype('float')
y = le.fit_transform(df.iloc[:, -1].values).astype('float')
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0)
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
log_reg = LogisticRegression()
log_reg.fit(X_train, y_train)
y_pred = log_reg.predict(X_test)
conf_mat = confusion_matrix(y_test, y_pred)
df
Out[32]:
shop category season
0 594 4 2
1 644 4 2
2 636 4 2
3 675 5 2
4 644 4 0
5 642 2 1
6 638 1 1
7 466 3 0
8 455 4 0
9 643 2 1
y_test
Out[33]: array([2., 0., 0., 1.])
y_pred
Out[34]: array([2., 0., 2., 1.])
conf_mat
Out[35]:
array([[1, 0, 1],
[0, 1, 0],
[0, 0, 1]], dtype=int64)