训练逻辑回归模型时出错

时间:2020-07-06 17:14:43

标签: python pandas machine-learning scikit-learn logistic-regression

我正在尝试将逻辑回归模型拟合到数据集,并且在训练数据时,出现以下错误:

      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 np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

data = 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_split
X_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 LogisticRegression
classifier = LogisticRegression()
**classifier.fit(X_train, y_train)**

数据集如下:

  Sr No  name   houseID  titleID    isAlive
0   0   Viserys II Targaryen    0   0   0
1   1   Tommen Baratheon        0   0   1
2   2   Viserys I Targaryen     0   0   0
3   3   Will (orphan)           0   0   1
4   4   Will (squire)           0   0   1
5   5   Willam                  0   0   1
6   6   Willow Witch-eye        0   0   0
7   7   Woth                    0   0   0
8   8   Wyl the Whittler        0   0   1
9   9   Wun Weg Wun Dar Wun     0   0   1

我查看了网络,但找不到任何相关的解决方案。请帮助我解决此错误。 谢谢!

2 个答案:

答案 0 :(得分:2)

您不能将字符串传递给fit()方法。 name列需要转换为float。 好的方法是使用:sklearn.preprocessing.LabelEncoder

鉴于上面的数据集示例,这是如何执行LabelEncoding的可重现示例:

from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

le = 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]

答案 1 :(得分:2)

Sklearn模型仅接受浮点数作为参数。您需要先将变量转换为浮点数,然后再将其传递给fit方法。一种方法是为每个包含字符串的列创建一系列虚拟变量。检查:pandas.get_dummies