【问题标题】: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

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

【问题讨论】:

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


    【解决方案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

      【讨论】:

        猜你喜欢
        • 2015-11-18
        • 2018-05-01
        • 2022-01-12
        • 1970-01-01
        • 2019-07-11
        • 2015-01-07
        • 1970-01-01
        • 1970-01-01
        • 2020-02-25
        相关资源
        最近更新 更多