无法将性别数据更改为二进制值

时间:2019-06-05 08:43:12

标签: python machine-learning scikit-learn linear-regression kaggle

我正在完成《泰坦尼克号》比赛。到目前为止,这是我的代码:

import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

train = pd.read_csv("https://raw.githubusercontent.com/oo92/Titanic-Kaggle/master/train.csv")
test = pd.read_csv("https://raw.githubusercontent.com/oo92/Titanic-Kaggle/master/test.csv")

train['Sex'].replace(['female', 'male'], [0, 1])
train['Embarked'].replace(['C', 'Q', 'S'], [1, 2, 3])

# Fill missing values in Age feature with each sex’s median value of Age
train['Age'].fillna(train.groupby('Sex')['Age'].transform("median"), inplace=True)

linReg = LinearRegression()

data = train[['Pclass', 'Sex', 'Parch', 'Fare', 'Age']]

# implement train_test_split
x_train, x_test, y_train, y_test = train_test_split(data, train['Survived'], test_size=0.2, random_state=0)

# Training the machine learning algorithm
linReg.fit(x_train, y_train)

# Checking the accuracy score of the model
accuracy = linReg.score(x_test, y_test)
print(accuracy*100, '%')

此行以前看起来像这样:data = train[['Pclass', 'Parch', 'Fare', 'Age']],最终给我的准确性得分是19.5%。我意识到自己不包括性生活,所以我继续这样做:

data = train[['Pclass', 'Sex', 'Parch', 'Fare', 'Age']]

然后,出现以下错误:

ValueError: could not convert string to float: 'female'

在这里,我意识到我对train['Sex']train['Age']所做的更改未反映在模型的训练和测试上,这似乎是我的模型执行的原因在19.5%。我怎么遇到这个问题?

更新

在第一个答案之后,我尝试相应地修改此行:

train['Age'].fillna(train.groupby('Sex')['Age'].transform("median"), inplace=True)

与:

train['Age'] = train['Age'].fillna(train.groupby('Sex')['Age'].transform("median"), inplace=True)

然后我决定打印Age列,结果显示值已损坏:

0      None
1      None
2      None
3      None
4      None
5      None
6      None
7      None
8      None
9      None
10     None
11     None
12     None
13     None
14     None
15     None
16     None
17     None
18     None
19     None
20     None
21     None
22     None
23     None
24     None
25     None
26     None
27     None
28     None
29     None
       ... 
861    None
862    None
863    None
864    None
865    None
866    None
867    None
868    None
869    None
870    None
871    None
872    None
873    None
874    None
875    None
876    None
877    None
878    None
879    None
880    None
881    None
882    None
883    None
884    None
885    None
886    None
887    None
888    None
889    None
890    None
Name: Age, Length: 891, dtype: object

2 个答案:

答案 0 :(得分:4)

那是因为您没有用该行保存数据框的修改:

train['Sex'].replace(['female', 'male'], [0, 1])

尝试用此替换它:

train['sex'] = train['Sex'].replace(['female', 'male'], [0, 1])

train['Embarked']相同。

更新

您无需为train['Age']进行操作,fillna已经使用inplace=true修改了现有的数据框。

答案 1 :(得分:0)

您只需要修改两行:

train['Sex'].replace(['female', 'male'], [0, 1],inplace = True)
train['Embarked'].replace(['C', 'Q', 'S'], [1, 2, 3],inplace=True)

然后它将起作用。