一、数据处理
上一节中我们对数据进行了完整的分析,接下来我们要着手将我们的想法实现了,我们将会校正、创造和完善一些特征。
1、通过删除一些无用数据来校正数据
把'Ticket', 'Cabin'删除
print("Before", train_df.shape, test_df.shape, combine[0].shape, combine[1].shape)
train_df = train_df.drop(['Ticket', 'Cabin'], axis=1)
test_df = test_df.drop(['Ticket', 'Cabin'], axis=1)
combine = [train_df, test_df]
"After", train_df.shape, test_df.shape, combine[0].shape, combine[1].shape
2、从原有的特征中派生出新特征
接下来我们从Name字段中取得称谓(Title),看看称谓和存活率有没有关系
代码中用到了正则表达式,主要思想就是获取 "." 符号前的所有字母
for dataset in combine:
dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\.', expand=False)
pd.crosstab(train_df['Title'], train_df['Sex'])
Title
里面有些称谓很少用,我们把他们换成常用的
for dataset in combine:
dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess','Capt', 'Col',\
'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss')
dataset['Title'] = dataset['Title'].replace('Ms', 'Miss')
dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs')
train_df[['Title', 'Survived']].groupby(['Title'], as_index=False).mean()
把Title换成数值型数据
title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": 5}
for dataset in combine:
dataset['Title'] = dataset['Title'].map(title_mapping)
dataset['Title'] = dataset['Title'].fillna(0)
train_df.head()
现在我们可以安全的把Name和PassengerId舍弃掉了
train_df = train_df.drop(['Name', 'PassengerId'], axis=1)
test_df = test_df.drop(['Name'], axis=1)
combine = [train_df, test_df]
train_df.shape, test_df.shape
shape
3、字符型特征数据类型转换
很多算法都有对特征数值类型的要求,我们需要把字符类特征转换为数值型数据
Sex字段:
for dataset in combine:
dataset['Sex'] = dataset['Sex'].map( {'female': 1, 'male': 0} ).astype(int)
train_df.head()
4、完善连续数值特征Age
可以考虑以三种方式来填充空值
1、最简单的方式是用平均值加减标准差之间的随机数来填充
2、更准确的方式是用Age与其他字段的关联关系来估计缺失值。前面的分析中我们能看出,Age与Pclass、Gender是有关联关系的,所以以Pclass、Gender为条件,取在这两个条件下的Age值得均值,这是一个合理取值方式
3、同时使用1、2两种方法,以Pclass、Gender为条件,用平均值加减标准差之间的随机数来填充空值。
方法1、3会系统中引入随机噪声。多次执行的结果可能会不同,我们更倾向于使用方法2。
观察Age与Pclass、Gender的关联关系:
grid = sns.FacetGrid(train_df, row='Pclass', col='Sex', height=2.2, aspect=1.6)
grid.map(plt.hist, 'Age', alpha=0.5, bins=20)
grid.add_legend()
Age
填充空值
guess_ages = np.zeros((2,3)) #创建2 * 3的0矩阵
for dataset in combine:
for i in range(0, 2):
for j in range(0, 3):
guess_df = dataset[(dataset['Sex'] == i) & \
(dataset['Pclass'] == j+1)]['Age'].dropna()
# age_mean = guess_df.mean()
# age_std = guess_df.std()
# age_guess = rnd.uniform(age_mean - age_std, age_mean + age_std)
age_guess = guess_df.median()
# Convert random age float to nearest .5 age
guess_ages[i,j] = int( age_guess/0.5 + 0.5 ) * 0.5
for i in range(0, 2):
for j in range(0, 3):
dataset.loc[ (dataset.Age.isnull()) & (dataset.Sex == i) & (dataset.Pclass == j+1),\
'Age'] = guess_ages[i,j]
dataset['Age'] = dataset['Age'].astype(int)
train_df.head()
创造AgeBand字段
train_df['AgeBand'] = pd.cut(train_df['Age'], 5)
train_df[['AgeBand', 'Survived']].groupby(['AgeBand'], as_index=False).mean().sort_values(by='AgeBand', ascending=True)
使用分类值替换Age
for dataset in combine:
dataset.loc[ dataset['Age'] <= 16, 'Age'] = 0
dataset.loc[(dataset['Age'] > 16) & (dataset['Age'] <= 32), 'Age'] = 1
dataset.loc[(dataset['Age'] > 32) & (dataset['Age'] <= 48), 'Age'] = 2
dataset.loc[(dataset['Age'] > 48) & (dataset['Age'] <= 64), 'Age'] = 3
dataset.loc[ dataset['Age'] > 64, 'Age']
train_df.head()
删除AgeBand
train_df = train_df.drop(['AgeBand'], axis=1)
combine = [train_df, test_df]
train_df.head()
5、把SibSp和Parch两个字段合并起来
把SibSp和Parch两个字段合并,可以生成FamilySize字段,表示乘客在船上有多少家人
生成FamilySize字段,再看看这个字段和survive有啥关系
for dataset in combine:
dataset['FamilySize'] = dataset['SibSp'] + dataset['Parch'] + 1
train_df[['FamilySize', 'Survived']].groupby(['FamilySize'], as_index=False).mean().sort_values(by='Survived', ascending=False)
我们还可以生成IsAlone特征
for dataset in combine:
dataset['IsAlone'] = 0
dataset.loc[dataset['FamilySize'] == 1, 'IsAlone'] = 1
train_df[['IsAlone', 'Survived']].groupby(['IsAlone'], as_index=False).mean()
有了IsAlone字段,我们可以把'Parch', 'SibSp', 'FamilySize'删除了
train_df = train_df.drop(['Parch', 'SibSp', 'FamilySize'], axis=1)
test_df = test_df.drop(['Parch', 'SibSp', 'FamilySize'], axis=1)
combine = [train_df, test_df]
train_df.head()
合并Pclass、Age创建Age*Class字段
for dataset in combine:
dataset['Age*Class'] = dataset.Age * dataset.Pclass
train_df.loc[:, ['Age*Class', 'Age', 'Pclass']].head(10)
6、完善登船港口参数Embarked
查找众值
freq_port = train_df.Embarked.dropna().mode()[0]
freq_port # S是最频繁出现的值
空值处填入S
for dataset in combine:
dataset['Embarked'] = dataset['Embarked'].fillna(freq_port)
train_df[['Embarked', 'Survived']].groupby(['Embarked'], as_index=False).mean().sort_values(by='Survived', ascending=False)
把Embarked的字符转换成数值类型
for dataset in combine:
dataset['Embarked'] = dataset['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2} ).astype(int)
train_df.head()
7、完善并转换Fare字段
由于只有test数据集中缺失了Fare字段,且只缺失了一个,我们直接用中值填充就好了
test_df['Fare'].fillna(test_df['Fare'].dropna().median(), inplace=True)
test_df.head()
然后创建FareBand字段,把费用字段分段显示
train_df['FareBand'] = pd.qcut(train_df['Fare'], 4) #qcut以数据出现频率来进行分段
train_df[['FareBand', 'Survived']].groupby(['FareBand'], as_index=False).mean().sort_values(by='FareBand', ascending=True)
把Fare替换为数值型分类
for dataset in combine:
dataset.loc[ dataset['Fare'] <= 7.91, 'Fare'] = 0
dataset.loc[(dataset['Fare'] > 7.91) & (dataset['Fare'] <= 14.454), 'Fare'] = 1
dataset.loc[(dataset['Fare'] > 14.454) & (dataset['Fare'] <= 31), 'Fare'] = 2
dataset.loc[ dataset['Fare'] > 31, 'Fare'] = 3
dataset['Fare'] = dataset['Fare'].astype(int)
train_df = train_df.drop(['FareBand'], axis=1)
combine = [train_df, test_df]
train_df.head(10)
再看看测试数据集啥样
test_df.head(10)
网友评论