做數(shù)據(jù)分析許久了, 簡(jiǎn)單寫寫比賽的數(shù)據(jù)分析項(xiàng)目思路
一 使用邏輯回歸/隨機(jī)森林等對(duì)kaggle比賽項(xiàng)目 "給出泰坦尼克號(hào)上的乘客的信息, 預(yù)測(cè)乘客是否幸存"進(jìn)行簡(jiǎn)單的數(shù)據(jù)分析過(guò)程, 使用的工具是Jupyter Notebook
項(xiàng)目提供了兩份數(shù)據(jù),分別是titanic_train.csv(訓(xùn)練集,用來(lái)構(gòu)建模型)和test(測(cè)試集,用來(lái)對(duì)模型準(zhǔn)確度進(jìn)行測(cè)試)
讀取并觀察數(shù)據(jù)
import numpy as np
import pandas as pd
data = pd.read_csv("data/titanic_train.csv")
# 觀察數(shù)據(jù)結(jié)構(gòu)信息
print(data.info())
print(data.describe())
# 查看前兩行數(shù)據(jù)
data.head(2)
通過(guò)觀察可知,訓(xùn)練集共891行,并且Age, Cabin, Embarked字段存在缺失值:
PassengerId -- 類似于編號(hào),每個(gè)人對(duì)應(yīng)一個(gè)Id, 具有唯一性
Survived -- 是否幸存, 1表示幸存者, 0則表示否
Pclass -- 船艙等級(jí), 1為一等艙, 2為二等艙, 3為三等艙
Name -- 姓名
Sex -- 性別, female女性, male男性
Age -- 年齡(缺失值個(gè)數(shù):177,缺失占比:19.8%)
SibSp -- 同船配偶以及兄弟姐妹的人數(shù)
Parch -- 同船父母或者子女的人數(shù)
Ticket -- 船票號(hào)
Fare -- 船票的票價(jià)
Cabin -- 艙位號(hào)碼(缺失值個(gè)數(shù):687,缺失占比:77%)
Embarked -- 登船港口(缺失值個(gè)數(shù):2,占比:0.2%)
特征分析
在進(jìn)行數(shù)據(jù)建模前必須找出特征因素,找出與幸存有關(guān)的特征,特征的好壞直接決定了模型的可靠程度.
PassengerId僅僅是標(biāo)識(shí)船員的id和票號(hào)Ticket,理論上與是否幸存無(wú)關(guān),此特征先行放棄.
Cabin船位號(hào)碼缺失值較多,暫時(shí)不考慮.下面繼續(xù)分析其他特征值域幸存者的關(guān)聯(lián)
首先對(duì)特征的缺失值進(jìn)行補(bǔ)充:
#對(duì)年齡的缺失值取中位數(shù)
#對(duì)登船港口缺失值取S(S港口登船人員最多)
data["Age"] = data["Age"].fillna(data["Age"].median())
data["Embarked"] = data["Embarked"].fillna("S")
對(duì)特征值進(jìn)行轉(zhuǎn)換,以便利于建模
#將性別轉(zhuǎn)換為0,1
data.loc[data["Sex"] == "male", "Sex"] = 0
data.loc[data["Sex"] == "female", "Sex"] = 1
#將登船港口改為0,1,2
data.loc[data["Embarked"] == "S", "Embarked"] = 0
data.loc[data["Embarked"] == "C", "Embarked"] = 1
data.loc[data["Embarked"] == "Q", "Embarked"] = 2
使用data.loc[data["Embarked"] == "S", "Embarked"] = 0
首先運(yùn)用SelectKBest對(duì)特征進(jìn)行一個(gè)簡(jiǎn)單的分析
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
import matplotlib.pyplot as plt
predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"]
selector = SelectKBest(f_classif, k=5)
selector.fit(data[predictors], data["Survived"])
scores = -np.log10(selector.pvalues_)
plt.bar(range(len(predictors)), scores)
plt.xticks(range(len(predictors)), predictors, rotation='vertical')
plt.show()
上述可知,"Pclass, Sex, Fare, Embarked"這幾個(gè)特征相對(duì)比較重要,那我們首先用這幾個(gè)特征進(jìn)行建模
線性回歸算法
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold
predictors = ["Pclass", "Sex", "Fare", "Embarked"]
# 線性回歸 算法
alg = LinearRegression()
kf = KFold(n_splits=3,random_state = 1)
predictions = []
for train,test in kf.split(data):
train_predictors = (data[predictors].iloc[train,:])
train_target = data["Survived"].iloc[train]
alg.fit(train_predictors, train_target)
test_predictions = alg.predict(data[predictors].iloc[test,:])
predictions.append(test_predictions)
predictions = np.concatenate(predictions, axis=0)
predictions[predictions > 0.5] = 1
predictions[predictions <= 0.5] = 0
accuracy = sum(predictions[predictions == data["Survived"]]) / len(predictions)
print(accuracy)
0.2615039281705948(結(jié)果太差,可忽略)
邏輯回歸 算法
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X = data[predictors]
y = data["Survived"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)
alg = LogisticRegression(random_state=1)
alg.fit(X_train, y_train)
scores = cross_val_score(alg, X_train, y_train, cv=3)
print(scores.mean())
alg.score(X_test,y_test)
0.7834680134680134
0.7762711864406779
結(jié)果一般,再試試隨機(jī)森林
from sklearn.model_selection import cross_val_score, KFold
from sklearn.ensemble import RandomForestClassifier
predictors = ["Pclass", "Sex", "Fare", "Embarked"]
alg = RandomForestClassifier(random_state=1, n_estimators=10, min_samples_split=2, min_samples_leaf=1)
alg.fit(X_train, y_train)
kf = KFold(n_splits=3, random_state=1)
scores = cross_val_score(alg, X_train, y_train, cv=kf)
print(scores.mean())
alg.score(X_test,y_test)
0.7885894117049895
0.7864406779661017
alg = RandomForestClassifier(random_state=1, n_estimators=100, min_samples_split=2, min_samples_leaf=1)
alg.fit(X_train, y_train)
kf = KFold(n_splits=3, random_state=1)
scores = cross_val_score(alg, X_train, y_train, cv=kf)
print(scores.mean())
alg.score(X_test,y_test)
0.7952726595942675
0.8067796610169492
隨機(jī)森林參數(shù)隨意取得
這只是簡(jiǎn)單的特征提取和建模分析,后續(xù)可以進(jìn)一步提取特征值,進(jìn)行更多的建模分析
二 使用Lasso/隨機(jī)森林/SVM等對(duì)天池比賽項(xiàng)目 "工業(yè)蒸汽量預(yù)測(cè)建模算法"進(jìn)行簡(jiǎn)單的數(shù)據(jù)分析過(guò)程, 使用的工具是Jupyter Notebook
import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
warnings.filterwarnings("ignore")
train = pd.read_table("data/zhengqi_train.txt")
test = pd.read_table("data/zhengqi_test.txt")
train_x = train.drop(['target'],axis=1)
train_y = train['target']
data = pd.concat([train_x,test])
test.head()
from sklearn.feature_selection import SelectKBest, f_classif
figsize = 15,8
figure = plt.subplots(figsize=figsize)
selector = SelectKBest(f_classif, k=5)
selector.fit(train_x,train_y)
scores = -np.log10(selector.pvalues_)
plt.bar(range(38), scores)
plt.xticks(range(38),train_x.columns)
# plt.figure(figsize=(5,5))
plt.show()
fig = plt.subplots(figsize=(30,20))
j = 1
for cols in data.columns:
plt.subplot(5,8,j)
sns.distplot(train[cols])
sns.distplot(test[cols])
j+=1
從上面數(shù)據(jù)來(lái)看,特征'V5','V9','V11','V17','V22','V28'訓(xùn)練集和測(cè)試集分布不均,刪除類似特征,并且'V14'對(duì)目標(biāo)值影響較小,所以也刪除此特征.
# 刪除無(wú)用特征并進(jìn)行模型嘗試
data.drop(['V5','V9','V11','V14','V17','V22','V28'],axis=1,inplace=True)
#數(shù)據(jù)分割
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(train_x,train_y, test_size = 0.3,random_state = 0)
建模
from sklearn.linear_model import Lasso,LinearRegression
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor
import lightgbm as lgb
from sklearn.model_selection import KFold, cross_val_score
from sklearn.metrics import mean_squared_error
def kfold_scores(alg,x_train, y_train):
kf = KFold(n_splits = 5, random_state= 1, shuffle=False)
predict_y = []
for kf_train,kf_test in kf.split(x_train):
alg.fit(x_train.iloc[kf_train],y_train.iloc[kf_train])
y_pred_train = alg.predict(x_train.iloc[kf_test])
mse = mean_squared_error(y_train.iloc[kf_test],y_pred_train)
predict_y.append(mse)
print("交叉驗(yàn)證集MSE均值為 %s" % (np.mean(predict_y)))
y_pred_test = alg.predict(x_test)
mse = mean_squared_error(y_test, y_pred_test)
print("測(cè)試集MSE為 %s" % mse)
alg = Lasso(alpha = 0.002)
mse_mean = kfold_scores(alg,x_train,y_train)
交叉驗(yàn)證集MSE均值為 0.11694436512799282
測(cè)試集MSE為 0.11029985071315368
alg = RandomForestRegressor()
mse_mean = kfold_scores(alg,x_train,y_train)
交叉驗(yàn)證集MSE均值為 0.1404184691171128
測(cè)試集MSE為 0.1467028448096886
其他算法代入也如上即可,后續(xù)優(yōu)化空間:特征值選擇,目標(biāo)值處理,異常值剔除等!
alg = lgb.LGBMRegressor()
mse_mean = kfold_scores(alg,x_train,y_train)
y = alg.predict(test)
k = y.tolist()
with open('data/data.txt','w') as f:
for i in k:
f.write(str(i) + '\r\n')
f.close()
將test的結(jié)果輸出到txt文件