關(guān)于比賽的基本操作描述爬虱,參考簡(jiǎn)書(shū)隶债。
學(xué)習(xí)了比賽中排行第三(rank3)的源碼kernal,參考鏈接跑筝,對(duì)比起來(lái)內(nèi)容更加詳細(xì)綜合死讹,所以總結(jié)如下。
1继蜡、流程
就這個(gè)案例來(lái)講,導(dǎo)入數(shù)據(jù)之后要做的逛腿,分為3步走:
1稀并、觀察數(shù)據(jù),了解特征的含義以及與生存率的關(guān)系单默,方便做特征工程
2碘举、特征工程&數(shù)據(jù)清洗,這一步是為了得到一個(gè)可以用于訓(xùn)練的好且完整的數(shù)據(jù)搁廓。
3引颈、跑模型
4、提交
2境蜕、代碼及分析
先導(dǎo)入需要使用的庫(kù)
"""導(dǎo)入庫(kù)"""
# 數(shù)據(jù)分析與整理
import pandas as pd
import numpy as np
import random as rnd
# 可視化
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
# 機(jī)器學(xué)習(xí)
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import Perceptron
from sklearn.linear_model import SGDClassifier
from sklearn.tree import DecisionTreeClassifier
然后獲取訓(xùn)練集和測(cè)試集的數(shù)據(jù)
"""獲取數(shù)據(jù)"""
train_df = pd.read_csv('train.csv')
test_df = pd.read_csv('test.csv')
combine = [train_df, test_df]
2.1觀察數(shù)據(jù)
print(train_df.columns.values)# 初步了解有什么特征
Out[]:['PassengerId' 'Survived' 'Pclass' 'Name' 'Sex' 'Age' 'SibSp' 'Parch'
'Ticket' 'Fare' 'Cabin' 'Embarked']
train_df.head(3)# 預(yù)覽前3行
Out[]:
train_df.info()# 了解每列特征的非空值數(shù)量和數(shù)據(jù)類(lèi)型蝙场,方便數(shù)據(jù)清洗
test_df.info()
Out[]:
初步觀察到特征Age、Cabin粱年、Embarked有缺失值售滤,而Cabin缺失得比較嚴(yán)重,可能要?jiǎng)h去。特征Sex完箩、Embarked等的數(shù)據(jù)類(lèi)型是object赐俗。這些特征都要進(jìn)行數(shù)據(jù)清洗。
接著觀察單個(gè)特征與生存率的關(guān)系弊知,了解數(shù)據(jù)之間的相關(guān)性阻逮,為構(gòu)造特征工程做準(zhǔn)備。
train_df[['Pclass', 'Survived']].groupby(['Pclass'], as_index=False).mean().sort_values(by='Survived', ascending=False)
Out[]:
Pclass為1表示最高級(jí)車(chē)廂秩彤,也表示乘客社會(huì)階級(jí)越高叔扼,生存率也更高
train_df[["Sex", "Survived"]].groupby(['Sex'], as_index=False).mean().sort_values(by='Survived', ascending=False)
Out[]:
female的生存率更高,滿(mǎn)足電影里“女士先行呐舔,男士斷后”
還可以通過(guò)可視化的方式更直觀地體現(xiàn)多個(gè)特征與生存率的相關(guān)性
g = sns.FacetGrid(train_df, col='Survived')
g.map(plt.hist, 'Age', bins=20)
Out[]:
grid = sns.FacetGrid(train_df, col='Survived', row='Pclass', size=2.2, aspect=1.6)
grid.map(plt.hist, 'Age', alpha=.5, bins=20)
grid.add_legend();
Out[]:
grid = sns.FacetGrid(train_df, row='Embarked', col='Survived', size=2.2, aspect=1.6)
grid.map(sns.barplot, 'Sex', 'Fare', alpha=.5, ci=None)
grid.add_legend()
2.2特征工程&數(shù)據(jù)清洗
主要操作是刪除特征或提取新特征币励,并對(duì)特征進(jìn)行數(shù)據(jù)清洗。數(shù)據(jù)清洗包括缺失值填充珊拼、數(shù)據(jù)轉(zhuǎn)換(包括將數(shù)據(jù)類(lèi)型轉(zhuǎn)換為機(jī)器學(xué)習(xí)可以處理的int型食呻,或?qū)?shù)據(jù)映射到區(qū)間里,對(duì)滿(mǎn)足同個(gè)區(qū)間賦予同樣的處理值澎现,參考特征Age和Fare的處理)
缺失值補(bǔ)充分兩種情況
對(duì)于連續(xù)型特征:
1仅胞、最簡(jiǎn)單用中位數(shù)或者平均值填充。
2剑辫、平均值和標(biāo)準(zhǔn)差之間生成隨機(jī)數(shù)干旧。
3、使用其他相關(guān)特征妹蔽。假設(shè)猜測(cè)Age椎眯,可使用不同pclass和gender組合時(shí)的Age中值來(lái)猜測(cè)。pclass=1胳岂,gender=0编整,pclass=1,gender=1的中位年齡等等來(lái)填充
對(duì)于分類(lèi)型特征: 用類(lèi)別最多的類(lèi)別補(bǔ)充
由于特征Cabin包含許多空值乳丰。特征Ticket包含高重復(fù)率(22%)掌测,并且與生存率之間可能沒(méi)有相關(guān)性。所以將這兩個(gè)特征刪除产园。
train_df = train_df.drop(['Ticket', 'Cabin'], axis=1)
test_df = test_df.drop(['Ticket', 'Cabin'], axis=1)
combine = [train_df, test_df]
利用特征Name提取新特征Title
for dataset in combine:
dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\.', expand=False)# expand=False表示返回DataFrame
# 用一個(gè)更常見(jiàn)的名字替換許多標(biāo)題汞斧,分類(lèi)稀有標(biāo)題
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')
刪除特征Name和PassengerId
train_df = train_df.drop(['Name', 'PassengerId'], axis=1)
test_df = test_df.drop(['Name'], axis=1)
combine = [train_df, test_df]
將特征Sex的數(shù)據(jù)類(lèi)型轉(zhuǎn)換為機(jī)器學(xué)習(xí)可以處理的int型
for dataset in combine:
dataset['Sex'] = dataset['Sex'].map( {'female': 1, 'male': 0} ).astype(int)
特征Age缺失值填充:利用相關(guān)特征Sex和Pclass來(lái)估計(jì)Age的值
guess_ages = np.zeros((2,3))
# 迭代sex(0或1)和pclass(1,2什燕,3)來(lái)計(jì)算六個(gè)組合的年齡估計(jì)值粘勒。
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_guess = guess_df.median()
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)
利用特征Age提取新特征AgeBand,目的是根據(jù)AgeBand的區(qū)間重新賦予Age處理值
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)
Out[]:
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']
刪除特征AgeBand
train_df = train_df.drop(['AgeBand'], axis=1)
combine = [train_df, test_df]
利用特征Parch和SibSp提取新特征FamilySize屎即,目的是引出新特征IsAlone
for dataset in combine:
dataset['FamilySize'] = dataset['SibSp'] + dataset['Parch'] + 1
for dataset in combine:
dataset['IsAlone'] = 0
dataset.loc[dataset['FamilySize'] == 1, 'IsAlone'] = 1
刪除特征Parch仲义、SibSp、FamilySize(這些被用來(lái)提取出特征IsAlone)
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]
利用特征Age和Class提取新特征Age*Class
for dataset in combine:
dataset['Age*Class'] = dataset.Age * dataset.Pclass
Embarked缺失值填充(用最常見(jiàn)的類(lèi)別填充)并
freq_port = train_df.Embarked.dropna().mode()[0]# 眾數(shù)
for dataset in combine:
dataset['Embarked'] = dataset['Embarked'].fillna(freq_port)
for dataset in combine:
dataset['Embarked'] = dataset['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2} ).astype(int)
Fare缺失值填充并利用新特征FareBand的區(qū)間重新賦予Fare處理值,最后將特征FareBand刪除
test_df['Fare'].fillna(test_df['Fare'].dropna().median(), inplace=True)
train_df['FareBand'] = pd.qcut(train_df['Fare'], 4)
train_df[['FareBand', 'Survived']].groupby(['FareBand'], as_index=False).mean().sort_values(by='FareBand', ascending=True)
Out[]:
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]
最后預(yù)覽一下經(jīng)過(guò)特征工程和數(shù)據(jù)清洗后的訓(xùn)練集和測(cè)試集數(shù)據(jù)
train_df.head(10)
test_df.head(10)
2.3跑模型
X_train = train_df.drop("Survived", axis=1)
Y_train = train_df["Survived"]
X_test = test_df.drop("PassengerId", axis=1).copy()
邏輯回歸:
# Logistic Regression
logreg = LogisticRegression()
logreg.fit(X_train, Y_train)
Y_pred = logreg.predict(X_test)
acc_log = round(logreg.score(X_train, Y_train) * 100, 2)
acc_log
Out[]:
80.359999999999999
SVC:
# Support Vector Machines
svc = SVC()
svc.fit(X_train, Y_train)
Y_pred = svc.predict(X_test)
acc_svc = round(svc.score(X_train, Y_train) * 100, 2)
acc_svc
Out[]:
83.840000000000003
KNN:
knn = KNeighborsClassifier(n_neighbors = 3)
knn.fit(X_train, Y_train)
Y_pred = knn.predict(X_test)
acc_knn = round(knn.score(X_train, Y_train) * 100, 2)
acc_knn
Out[]:
84.739999999999995
樸素貝葉斯:
# Gaussian Naive Bayes
gaussian = GaussianNB()
gaussian.fit(X_train, Y_train)
Y_pred = gaussian.predict(X_test)
acc_gaussian = round(gaussian.score(X_train, Y_train) * 100, 2)
acc_gaussian
Out[]:
72.280000000000001
感知器:
# Perceptron
perceptron = Perceptron()
perceptron.fit(X_train, Y_train)
Y_pred = perceptron.predict(X_test)
acc_perceptron = round(perceptron.score(X_train, Y_train) * 100, 2)
acc_perceptron
Out[]:
78.0
Linear SVC:
# Linear SVC
linear_svc = LinearSVC()
linear_svc.fit(X_train, Y_train)
Y_pred = linear_svc.predict(X_test)
acc_linear_svc = round(linear_svc.score(X_train, Y_train) * 100, 2)
acc_linear_svc
Out[]:
79.120000000000005
隨機(jī)梯度下降:
# Stochastic Gradient Descent
sgd = SGDClassifier()
sgd.fit(X_train, Y_train)
Y_pred = sgd.predict(X_test)
acc_sgd = round(sgd.score(X_train, Y_train) * 100, 2)
acc_sgd
Out[]:
76.879999999999995
決策樹(shù):
# Decision Tree
decision_tree = DecisionTreeClassifier()
decision_tree.fit(X_train, Y_train)
Y_pred = decision_tree.predict(X_test)
acc_decision_tree = round(decision_tree.score(X_train, Y_train) * 100, 2)
acc_decision_tree
Out[]:
86.760000000000005
隨機(jī)森林:
# Random Forest
random_forest = RandomForestClassifier(n_estimators=100)
random_forest.fit(X_train, Y_train)
Y_pred = random_forest.predict(X_test)
random_forest.score(X_train, Y_train)
acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)
acc_random_forest
Out[]:
86.760000000000005
對(duì)所有模型的評(píng)估進(jìn)行排名埃撵,以選擇適合我們問(wèn)題的最佳模型赵颅。當(dāng)決策樹(shù)和隨機(jī)森林得分相同時(shí),我們選擇使用隨機(jī)森林暂刘,因?yàn)樗鼈兗m正了決策樹(shù)的過(guò)度適應(yīng)訓(xùn)練集的習(xí)慣饺谬。
models = pd.DataFrame({
'Model': ['Support Vector Machines', 'KNN', 'Logistic Regression',
'Random Forest', 'Naive Bayes', 'Perceptron',
'Stochastic Gradient Decent', 'Linear SVC',
'Decision Tree'],
'Score': [acc_svc, acc_knn, acc_log,
acc_random_forest, acc_gaussian, acc_perceptron,
acc_sgd, acc_linear_svc, acc_decision_tree]})
models.sort_values(by='Score', ascending=False)
Out[]:
2.3提交
submission = pd.DataFrame({
"PassengerId": test_df["PassengerId"],
"Survived": Y_pred
})
submission.to_csv('submission.csv', index=False)
3、優(yōu)點(diǎn)
相比其他kernal谣拣,能做到rank3募寨,我覺(jué)得最突出的優(yōu)點(diǎn)是在數(shù)據(jù)的處理上,即特征工程&數(shù)據(jù)清洗上森缠。下面我給出它與我上一篇泰坦尼克之災(zāi)1.0的一些對(duì)比拔鹰,直觀的了解這個(gè)kernal的優(yōu)點(diǎn)(1.0 vs 2.0,只給出對(duì)比)
4贵涵、總結(jié)
對(duì)于一般的簡(jiǎn)單機(jī)器學(xué)習(xí)列肢,先進(jìn)行數(shù)據(jù)觀察和探索,了解特征以及特征之間的關(guān)系(方便做特征工程)宾茂;然后進(jìn)行特征工程瓷马,得到用于訓(xùn)練的特征,并對(duì)特征做數(shù)據(jù)清洗跨晴,得到可以用于訓(xùn)練和測(cè)試的好且完整的數(shù)據(jù)欧聘;最后就可以跑模型了,可以跑多個(gè)基準(zhǔn)模型看看效果端盆,復(fù)雜的數(shù)據(jù)可以嘗試混合模型集成學(xué)習(xí)怀骤,具體情況具體分析。