我在尝试将逻辑回归模型拟合到一个数据集时,训练数据时遇到了以下错误:
1 from sklearn.linear_model import LogisticRegression 2 classifier = LogisticRegression()----> 3 classifier.fit(X_train, y_train)ValueError: could not convert string to float: 'Cragorn'
代码片段如下:
import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlinedata = pd.read_csv('predict_death_in_GOT.csv')data.head(10)X = data.iloc[:, 0:4]y = data.iloc[:, 4]plt.rcParams['figure.figsize'] = (10, 10)alive = data.loc[y == 1]not_alive = data.loc[y == 0]plt.scatter(alive.iloc[:,0], alive.iloc[:,1], s = 10, label = "alive")plt.scatter(not_alive.iloc[:,0], not_alive.iloc[:,1], s = 10, label = "not alive")plt.legend()plt.show()from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20)print(X_train, y_train)print(X_test, y_test)from sklearn.linear_model import LogisticRegressionclassifier = LogisticRegression()**classifier.fit(X_train, y_train)**
数据集看起来像这样:
Sr No name houseID titleID isAlive0 0 Viserys II Targaryen 0 0 01 1 Tommen Baratheon 0 0 12 2 Viserys I Targaryen 0 0 03 3 Will (orphan) 0 0 14 4 Will (squire) 0 0 15 5 Willam 0 0 16 6 Willow Witch-eye 0 0 07 7 Woth 0 0 08 8 Wyl the Whittler 0 0 19 9 Wun Weg Wun Dar Wun 0 0 1
我在网上查看了但找不到任何相关解决方案。请帮助我解决这个错误。谢谢!
回答:
你不能将字符串传递给fit()
方法。列name
需要转换为浮点数。一个好的方法是使用:sklearn.preprocessing.LabelEncoder
根据上述数据集样本,这里是一个如何执行LabelEncoding的可重现示例:
from sklearn import preprocessingfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionle = preprocessing.LabelEncoder()data.name = le.fit_transform(data.name)X = data.iloc[:, 0:4]y = data.iloc[:, 5]X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20)classifier = LogisticRegression()classifier.fit(X_train, y_train)print(classifier.coef_,classifier.intercept_)
模型系数和截距结果如下:
[[ 0.09253555 0.09253555 -0.15407024 0. ]] [-0.1015314]