【问题标题】:ValueError: could not convert string to float: 'Q'ValueError:无法将字符串转换为浮点数:'Q'
【发布时间】:2020-04-27 11:57:02
【问题描述】:

我是编程新手,我正在使用来自 Kaggle 的 Titanic 数据集。在执行 one-hot 编码后,我一直在尝试构建逻辑回归模型。但我不断收到错误。我认为错误是由于虚拟变量引起的。下面是我的代码。

import numpy as np
import pandas as pd
import matplotlib as plt
import seaborn as sns

#Loading data
df=pd.read_csv(r"C:\Users\Downloads\train.csv")

#Deleting unwanted columns
df.drop(["PassengerId","Name","Cabin","Ticket"],axis=1,inplace=True)

#COunt of Missing values in each column
print(df.isnull().sum())

#Deleting rows with missing values based on column name
df.dropna(subset=['Embarked','Age'],inplace=True)
print(df.isnull().sum())

#One hot encoding for categorical variables
#Creating dummy variables for Sex column
dummies = pd.get_dummies(df.Sex)
dummies2=pd.get_dummies(df.Embarked)

#Appending the dummies dataframe with original dataframe
new_df= pd.concat([df,dummies,dummies2],axis='columns')

print(type(new_df))
#print(new_df.head(10))

#Drop the original sex,Embarked column and one of the dummy column for bth variables
new_df.drop(['Sex','Embarked'],axis='columns',inplace=True)
print(new_df.head(10))

new_df.info()

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix,accuracy_score

x = df.drop('Survived', axis=1)
y = df['Survived']

logmodel = LogisticRegression()

logmodel.fit(x, y)

【问题讨论】:

  • 这个错误到底发生在哪里?还请编辑您的代码以包含一个最小的可重现示例。
  • 我认为 xy 应该是:x =new_df.drop('Survived', axis=1)y = new_df['Survived'],方法是将 df 更改为 new_df。是这样吗?
  • 你能指出错误出现在哪一行吗?
  • 谢谢。实际上这是错误的。 @Anwarvic但是现在即使模型有效,我也会收到一些警告,例如“ConvergenceWarning:lbfgs 无法收敛(状态= 1):停止:迭代总数达到限制。”这可能是什么?
  • @JohnPaul,尝试像这样增加迭代次数:logmodel = LogisticRegression(max_iter=1000)

标签: python pandas logistic-regression one-hot-encoding


【解决方案1】:

正如我们在 cmets 中所讨论的,解决方案如下:

首先,您需要修改您的xy 变量以使用new_df 而不是df,就像这样:

x = new_df.drop('Survived', axis=1)
y = new_df['Survived']

然后,您需要像这样增加 Logistic 回归模型的迭代次数:

logmodel = LogisticRegression(max_iter=1000)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-23
    • 2018-06-13
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    相关资源
    最近更新 更多