HDOJlin 2019-06-28
本次分享的项目来自 Kaggle 的经典赛题:泰坦尼克号生还者预测。分为数据分析和数据挖掘两部分介绍。上一篇为数据分析篇,本篇为数据挖掘篇。
本篇的内容有以下几部分:
female/male
需要转换为模型可接受的 0/1 值
,也叫量化过程。在上一篇的分析中我们对特征缺失值情况进行了统计:
接下来分别对 Fare,Embarked,Cabin,Age 四个特征对缺失值进行处理。
查看Fare
特征缺失情况:
df[df['Fare'].isnull()]
发现只有一个缺失值,是一位年龄大于 60 岁的男性,乘坐的船舱等级为 3。
这里我们选择不删除这个值,而是用相似特征替换的方法来填补缺失值。与缺失值具有相似特征的其它样本数据:
df.loc[(df['Pclass']==3)&(df['Sex']=='male')&(df['Age']>60)]
我们用以上样本Fare
的均值来填补这个缺失值:
df['surname'] = df["Name"].apply(lambda x: x.split(',')[0].lower()) fare_mean_estimated = df.loc[(df['Pclass']==3)&(df['Age']>60)&(df['Sex']=='male')].Fare.mean() df.loc[df['surname']=='storey','Fare'] = fare_mean_estimated
查看Embarded
特征缺失情况:
df[df['Embarked'].isnull()]
在上篇分析中我们知道在 S 港口登陆的乘客人数最多,这里采用 S 港口进行填补:
df['Embarked'] = df['Embarked'].fillna('S')
Cabin 特征缺失严重,因此我们根据有无 Cabin 信息提取出一个新特征:
data_train['Has_Cabin'] = data_train["Cabin"].apply(lambda x: 0 if type(x) == float else 1) data_test['Has_Cabin'] = data_test["Cabin"].apply(lambda x: 0 if type(x) == float else 1)
得到处理后的数据集形如下列形式:
Age 特征存在一部分缺失值,且数值较多,我们在这一步处理缺失值后,也将对 Age 特征根据区间进行分类。
首先处理缺失值:
full_data = [data_train, data_test] for dataset in full_data: age_avg = dataset['Age'].mean() age_std = dataset['Age'].std() age_null_count = dataset['Age'].isnull().sum() age_null_random_list = np.random.randint(age_avg - age_std, age_avg + age_std, size=age_null_count) dataset['Age'][np.isnan(dataset['Age'])] = age_null_random_list dataset['Age'] = dataset['Age'].astype(int)
对众多的 Age 特征进行分组:
data_train['CategoricalAge'] = pd.cut(data_train['Age'], 5) for dataset in full_data: # Mapping Age 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'] = 4 ;
丢掉多余的特征:
drop_elements = ['PassengerId'] data_train = data_train.drop(drop_elements, axis = 1) data_train = data_train.drop(['CategoricalAge'], axis = 1)
最后,得到下列形式的数据集:
在这部分我们将对 Name 特征进行处理,即对特征进行衍生产生新特征变量。
# 定义函数从 name 中提取 title def get_title(name): title_search = re.search(' ([A-Za-z]+)\.', name) # If the title exists, extract and return it. if title_search: return title_search.group(1) return "" # 创建新特征 title for dataset in full_data: dataset['Title'] = dataset['Name'].apply(get_title) # 将不常见的 title 用"Rare"替换掉 for dataset in full_data: 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')
对数据进行数值化处理:
for dataset in full_data: # Sex dataset['Sex'] = dataset['Sex'].map( {'female': 0, 'male': 1} ).astype(int) # titles title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": 5} dataset['Title'] = dataset['Title'].map(title_mapping) dataset['Title'] = dataset['Title'].fillna(0) # Embarked dataset['Embarked'] = dataset['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2} ).astype(int) # Fare 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)
去掉多余的特征:
drop_elements = ['Name', 'Ticket'] drop_elements = ['Name', 'Ticket'] data_train = data_train.drop(drop_elements, axis = 1) data_test = data_test.drop(drop_elements, axis = 1)
得到如下形式的数据集:
查看到有如下特征:
Index(['Survived', 'Pclass', 'Sex', 'Age', 'Fare', 'Embarked', 'Family', 'Has_Cabin', 'Title'], dtype='object')
我们采用 ANOVA 方差分析的 F 值来对各个特征变量打分,打分的意义是:各个特征变量对目标变量的影响权重。代码如下:
from sklearn.feature_selection import SelectKBest, f_classif,chi2 target = data_train["Survived"].values features= ['Survived', 'Pclass', 'Sex', 'Age', 'Fare', 'Embarked', 'Family', 'Name_length', 'Has_Cabin', 'Title'] train = data_train.copy() test = data_train.copy() selector = SelectKBest(f_classif, k=len(features)) selector.fit(train[features], target) scores = -np.log10(selector.pvalues_) indices = np.argsort(scores)[::-1] print("Features importance :") for f in range(len(scores)): print("%0.2f %s" % (scores[indices[f]],features[indices[f]]))
得到结果:
对每个特征进行相关性分析,查看热力图:
features_selected = features df_corr = data_train[features_selected].copy() colormap = plt.cm.RdBu plt.figure(figsize=(20,20)) sns.heatmap(df_corr.corr(),linewidths=0.1,vmax=1.0, square=True, cmap=colormap, linecolor='white', annot=True)
相关性大的特征容易造成过拟合现象,因此需要进行剔除。最好的情况就是:所有特征相关性很低,各自的方差或者说信息量很高。
划分数据集:
from sklearn.model_selection import train_test_split X_all = data_train.drop(['Survived'], axis=1) y_all = data_train['Survived'] num_test = 0.20 X_train, X_test, y_train, y_test = train_test_split(X_all, y_all, test_size=num_test, random_state=23)
这里采用随机森林 RandomForest 模型,建立模型:
from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import make_scorer, accuracy_score from sklearn.model_selection import GridSearchCV clf = RandomForestClassifier() # 设定参数 parameters = {'n_estimators': [4, 6, 9], 'max_features': ['log2', 'sqrt','auto'], 'criterion': ['entropy', 'gini'], 'max_depth': [2, 3, 5, 10], 'min_samples_split': [2, 3, 5], 'min_samples_leaf': [1,5,8] } acc_scorer = make_scorer(accuracy_score) grid_obj = GridSearchCV(clf, parameters, scoring=acc_scorer) grid_obj = grid_obj.fit(X_train, y_train) clf = grid_obj.best_estimator_ clf.fit(X_train, y_train)
得到模型:
predictions = clf.predict(X_test) print(accuracy_score(y_test, predictions))
得到预测值为0.8435754189944135
,提交到 kaggle 上打分0.77990
,需进一步的改进。
from sklearn.cross_validation import KFold def run_kfold(clf): kf = KFold(891, n_folds=10) outcomes = [] fold = 0 for train_index, test_index in kf: fold += 1 X_train, X_test = X_all.values[train_index], X_all.values[test_index] y_train, y_test = y_all.values[train_index], y_all.values[test_index] clf.fit(X_train, y_train) predictions = clf.predict(X_test) accuracy = accuracy_score(y_test, predictions) outcomes.append(accuracy) print("Fold {0} accuracy: {1}".format(fold, accuracy)) mean_outcome = np.mean(outcomes) print("Mean Accuracy: {0}".format(mean_outcome)) run_kfold(clf)
得到:
ids = data_test['PassengerId'] predictions = clf.predict(data_test.drop('PassengerId', axis=1)) output = pd.DataFrame({ 'PassengerId' : ids, 'Survived': predictions }) output.to_csv('titanic-predictions.csv', index = False)
虽然这个入门赛题提交了比赛成绩,已经完成了这个赛题,暂时告一段落,目前排名 4986。但对于它的学习才刚刚开始,还有很多地方可以改进,还有很多值得学习的地方。如以下几点:
参考链接:
【Kaggle入门级竞赛top5%排名经验分享】— 建模篇
【机器学习】Cross-Validation(交叉验证)详解
不足之处,欢迎指正。