训练逻辑回归模型时出错

Posted

技术标签:

【中文标题】训练逻辑回归模型时出错【英文标题】:Getting an error while training a logistic regression model 【发布时间】:2020-10-26 21:05:44 【问题描述】:

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

      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'

sn-p代码如下:

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

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

【问题讨论】:

【参考方案1】:

您不能将字符串传递给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]

【讨论】:

【参考方案2】:

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

【讨论】:

以上是关于训练逻辑回归模型时出错的主要内容,如果未能解决你的问题,请参考以下文章

TensorFlow训练Logistic回归

LR(逻辑回归)

逻辑回归 sklearn - 训练和应用模型

逻辑回归模型的校准性

逻辑回归模型

在 scikit learn 中训练具有不同特征维度的逻辑回归模型