训练逻辑回归模型时出错

Getting an error while training a logistic regression model

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

      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

我查看了网络,但找不到任何相关的 solutions.Please 帮助我解决这个错误。 谢谢!

您不能将字符串传递给 fit() 方法。 列 name 需要转换为浮点数。 好的方法是使用: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]

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