在训练逻辑回归模型时遇到错误

我在尝试将逻辑回归模型拟合到一个数据集时,训练数据时遇到了以下错误:

      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]

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注