Kaggle--泰坦尼克號失蹤者生死情況預測原始碼(附Titanic資料集)
資料視覺化分析
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np titanic=pd.read_csv('train.csv') #print(titanic.head()) #設定某一列為索引 #print(titanic.set_index('PassengerId').head()) # ============================================================================= # #繪製一個展示男女乘客比例的扇形圖 # #sum the instances of males and females # males=(titanic['Sex']=='male').sum() # females=(titanic['Sex']=='female').sum() # #put them into a list called proportions # proportions=[males,females] # #Create a pie chart # plt.pie( # # using proportions # proportions, # # with the labels being officer names # labels=['Males','Females'], # # with no shadows # shadow=False, # # with colors # colors=['blue','red'], # explode=(0.15,0), # startangle=90, # autopct='%1.1f%%' # ) # plt.axis('equal') # plt.title("Sex Proportion") # plt.tight_layout() # plt.show() # ============================================================================= # ============================================================================= # #繪製一個展示船票Fare,與乘客年齡和性別的散點圖 # #creates the plot using # lm=sns.lmplot(x='Age',y='Fare',data=titanic,hue='Survived',fit_reg=False) # #set title # lm.set(title='Fare x Age') # #get the axes object and tweak it # axes=lm.axes # axes[0,0].set_ylim(-5,) # axes[0,0].set_xlim(-5,85) # ============================================================================= # ============================================================================= # #繪製一個展示船票價格的直方圖 # #sort the values from the top to least value and slice the first 5 items # df=titanic.Fare.sort_values(ascending=False) # #create bins interval using numpy # binsVal=np.arange(0,600,10) # #create the plot # plt.hist(df,bins=binsVal) # plt.xlabel('Fare') # plt.ylabel('Frequency') # plt.title('Fare Payed Histrogram') # plt.show() # ============================================================================= #哪個性別的年齡的平均值更大 #print(titanic.groupby('Sex').Age.mean()) #打印出不同性別的年齡的描述性統計資訊 #print(titanic.groupby('Sex').Age.describe()) #print(titanic.groupby(['Sex','Survived']).Fare.describe()) #先對Survived再Fare進行排序 #a=titanic.sort_values(['Survived','Fare'],ascending=False) #print(a) #選取名字以字母A開頭的資料 #b=titanic[titanic.Name.str.startswith('A')] #print(b) #找到其中三個人的存活情況 #c=titanic.loc[titanic.Name.isin(['Youseff, Mr. Gerious','Saad, Mr. Amin','Yousif, Mr. Wazli'])\ # ,['Name','Survived']] #print(c) # ============================================================================= # ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) # ts = ts.cumsum() # ts.plot() # plt.show() # # df = pd.DataFrame(np.random.randn(1000, 4),index=ts.index,columns=['A', 'B', 'C', 'D']) # df=df.cumsum() # plt.figure() # df.plot() # plt.legend(loc='best') # plt.show() # ============================================================================= #對應每一個location,一共有多少資料值缺失 #print(titanic.isnull().sum()) #對應每一個location,一共有多少資料值完整 #print(titanic.shape[0]-titanic.isnull().sum()) #檢視每個列的資料型別 #print(titanic.info()) #print(titanic.dtypes)
主程式
附:連結:https://pan.baidu.com/s/1K1USWVQQOEM9OLr3M1pniw 密碼:n8wz# -*- coding: utf-8 -*- """ Created on Tue Apr 10 17:21:16 2018 @author: CSH """ import pandas as pd titanic=pd.read_csv("train.csv") #print(titanic.describe()) titanic["Age"]=titanic["Age"].fillna(titanic["Age"].median()) #print(titanic.describe()) #print(titanic["Sex"].unique()) titanic.loc[titanic["Sex"]=="male","Sex"]=0 titanic.loc[titanic["Sex"]=="female","Sex"]=1 #print(titanic["Embarked"].value_counts()) titanic["Embarked"]=titanic["Embarked"].fillna("S") titanic.loc[titanic["Embarked"]=="S","Embarked"]=0 titanic.loc[titanic["Embarked"]=="C","Embarked"]=1 titanic.loc[titanic["Embarked"]=="Q","Embarked"]=2 #線性迴歸 # ============================================================================= # from sklearn.linear_model import LinearRegression # from sklearn.cross_validation import KFold # predictors=["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked"] # alg=LinearRegression() # kf=KFold(titanic.shape[0],n_folds=3,random_state=1) # predictions=[] # for train,test in kf: # train_predictors=(titanic[predictors].iloc[train,:]) # train_target=titanic["Survived"].iloc[train] # alg.fit(train_predictors,train_target) # test_predictions=alg.predict(titanic[predictors].iloc[test,:]) # predictions.append(test_predictions) # # # import numpy as np # predictions=np.concatenate(predictions,axis=0) # predictions[predictions>.5]=1 # predictions[predictions<=.5]=0 # accuracy=sum(predictions==titanic["Survived"])/len(predictions) # print(accuracy) # ============================================================================= #邏輯迴歸 # ============================================================================= from sklearn.linear_model import LogisticRegression from sklearn import cross_validation # predictors=["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked"] # alg=LogisticRegression(random_state=1) # scores=cross_validation.cross_val_score(alg,titanic[predictors],titanic["Survived"],cv=3) # print(scores.mean()) # ============================================================================= #隨機森林 # ============================================================================= # from sklearn import cross_validation # from sklearn.ensemble import RandomForestClassifier # predictors=["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked"] # alg=RandomForestClassifier(random_state=1,n_estimators=150,min_samples_split=12,min_samples_leaf=1) # kf=cross_validation.KFold(titanic.shape[0],n_folds=3,random_state=1) # scores=cross_validation.cross_val_score(alg,titanic[predictors],titanic["Survived"],cv=kf) # print(scores.mean()) # ============================================================================= titanic["FamilySize"]=titanic["SibSp"]+titanic["Parch"] titanic["NameLength"]=titanic["Name"].apply(lambda x:len(x)) #提取名字資訊 import re def get_title(name): title_search=re.search('([A-Za-z]+)\.',name) if title_search: return title_search.group(1) return "" titles=titanic["Name"].apply(get_title) #print(pd.value_counts(titles)) title_mapping={"Mr":1,"Miss":2,"Mrs":3,"Master":4,"Dr":5,"Rev":6,"Mlle":7,"Major":8,"Col":9,"Ms":10,"Mme":11,"Lady":12,"Sir":13,"Capt":14,"Don":15,"Jonkheer":16,"Countess":17} for k,v in title_mapping.items(): titles[titles==k]=v #print(pd.value_counts(titles)) titanic["Title"]=titles #特徵選擇 # ============================================================================= # 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","FamilySize","Title","NameLength"] # selector=SelectKBest(f_classif,k=5) # selector.fit(titanic[predictors],titanic["Survived"]) # scores=-np.log10(selector.pvalues_) # # plt.bar(range(len(predictors)),scores) # plt.xticks(range(len(predictors)),predictors,rotation='vertical') # plt.show() # ============================================================================= # ============================================================================= # from sklearn import cross_validation # from sklearn.ensemble import RandomForestClassifier # predictors=["Pclass","Sex","Fare","Title","NameLength"] # alg=RandomForestClassifier(random_state=1,n_estimators=50,min_samples_split=12,min_samples_leaf=1) # kf=cross_validation.KFold(titanic.shape[0],n_folds=3,random_state=1) # scores=cross_validation.cross_val_score(alg,titanic[predictors],titanic["Survived"],cv=kf) # print(scores.mean()) # ============================================================================= #整合學習 from sklearn.cross_validation import KFold from sklearn.ensemble import GradientBoostingClassifier import numpy as np algorithms=[ [GradientBoostingClassifier(random_state=1,n_estimators=25,max_depth=3),["Pclass","Sex","Fare","Title","NameLength"]], [LogisticRegression(random_state=1),["Pclass","Sex","Fare","Title","NameLength"]]] kf=KFold(titanic.shape[0],n_folds=3,random_state=1) predictions=[] for train,test in kf: train_target=titanic["Survived"].iloc[train] full_test_predictions=[] for alg,predictors in algorithms: alg.fit(titanic[predictors].iloc[train,:],train_target) test_predictions=alg.predict_proba(titanic[predictors].iloc[test,:].astype(float))[:,1] full_test_predictions.append(test_predictions) test_predictions=(full_test_predictions[0]+full_test_predictions[1])/2 test_predictions[test_predictions<=.5]=0 test_predictions[test_predictions>.5]=1 predictions.append(test_predictions) predictions=np.concatenate(predictions,axis=0) accuracy=sum(predictions==titanic["Survived"])/len(predictions) print(accuracy)
相關推薦
Kaggle--泰坦尼克號失蹤者生死情況預測原始碼(附Titanic資料集)
資料視覺化分析import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np titanic=pd.read_csv('train.csv') #pri
kaggle——泰坦尼克號生死預測
把很久以前做的泰坦尼克號的程式碼貼出來。 # -*- coding: utf-8 -*- """ Created on Fri Mar 30 14:23:12 2017 @author: Yichengfan """ import pandas as pd
Kaggle —— 泰坦尼克號Titanic
1. 資料總覽 Titanic 生存模型預測,其中包含了兩組資料:train.csv 和 test.csv,分別為訓練集合和測試集合。 import re import numpy as np import pandas as pd import matpl
【Kaggle筆記】預測泰坦尼克號乘客生還情況(決策樹)
資料集 程式碼 # -*- coding: utf-8 -*- """ 泰坦尼克號乘客生還情況預測 模型 決策樹 """ # 匯入pandas用於資料分析。 import panda
kaggle泰坦尼克號python和r
之前用了一陣子spss modeler,自己整了r,後來發現國內高手都用python,發現了網上兩篇類似的python和r寫的文章,這裡加上原文連結,可以一起學習: 1:python版本連結:http://blog.csdn.net/longxinchen_ml/artic
kaggle 泰坦尼克號生存預測——六種演算法模型實現與比較
Hi,大家好,這是我第一篇部落格。 作為非專業程式小白,部落格內容必然有不少錯誤之處,還望各位大神多多批評指正。 在開始正式內容想先介紹下自己和一些異想天開的想法。 我是一名研究生,研究的方向是蛋白質結構與功能方向。在研究過程中發現生物系統是如此複雜,猶如一張網,資訊流動,
Kaggle: 泰坦尼克號生存預測
0.前言 本文對Kaggle泰坦尼克比賽的訓練集和測試集進行分析,並對乘客的生存結果進行了預測.作為資料探勘的入門專案,本人將思路記錄下來,以供參考.如有不足之處,歡迎指正. 1.匯入資料 import pandas as pd import n
量化投資學習筆記19——迴歸分析:實操,泰坦尼克號乘客生還機會預測,線性迴歸方法。
用kaggle上的泰坦尼克的資料來實操。 https://www.kaggle.com/c/titanic/overview 在主頁上下載了資料。 任務:使用泰坦尼克號乘客資料建立機器學習模型,來預測乘客在海難中是否生存。 在實際海難中,2224位乘客中有1502位遇難了。似乎有的乘客比其它乘客更有機會獲救。
ML之SVM:基於Js程式碼利用SVM演算法的實現根據Kaggle資料集預測泰坦尼克號生存人員
ML之SVM:基於Js程式碼利用SVM演算法的實現根據Kaggle資料集預測泰坦尼克號生存人員 實驗資料 設計思路 實現程式碼(部分程式碼) /** js程式碼實現SVM演算法 */ //ML之SVM:基於Js程式碼利用SVM演算法的實現根據Kagg
機器學習 (十七)kaggle競賽之泰坦尼克號專案實戰-2
導航 想寫這篇部落格的由衷是做完幾個專案,有時對於圖的畫法和模型融合演算法原理理解還很膚淺,特此加深一下印象。 內容概覽 圖 pandas、matplotlib、seaborn 餅圖 直方圖
機器學習 (八)kaggle競賽之泰坦尼克號專案實戰-1
引言 機器學習演算法都是為專案為資料服務的,某一個演算法都有它自己的適用範圍,以及優勢與劣勢,研究演算法由於平日的日常操練,那麼用它去做專案就如同上戰場殺敵一樣,去發揮它的價值,kaggle就是這樣一個刷怪升級
人工智障也刷題!Kaggle 入門之實戰泰坦尼克號
背景 關於 Kaggle www.kaggle.com/ 這是一個為你提供完美資料,為你提供實際應用場景,可以與小夥伴在資料探勘領域 high 的不要不要的的地方啊!!! Kaggle 是一個用來學習、分享和競賽的線上資料實驗平臺,有點類似 KDD—CUP(國際知識發現和資料探勘競賽),企
機器學習kaggle實戰-泰坦尼克號問題知識梳理
工作流程: 在資料科學競賽的解決問題的七個步驟: 1.問題或問題的定義。(理解題目)2.獲得培訓和測試資料。(獲取資料)3.爭論,準備清理資料。(初步清洗資料)4.分析、識別模式,並探索資料。(特徵工程)5.模型,預測和解決問題。(機器學習演算法介入)6.視覺化報告,並提出解決問題的步驟和最終的解決方案。
【SciKit-Learn學習筆記】4:決策樹擬合泰坦尼克號資料集並提交到Kaggle
學習《scikit-learn機器學習》時的一些實踐。 決策樹擬合泰坦尼克號資料集 這裡用繪製引數-score曲線的方式去直觀看出模型引數對模型得分的影響,作者使用了GridSearchCV來自動做k-fold交叉驗證,並且能在多組模型引數中找到最優的一組和最優值(用平均s
kaggle初探--泰坦尼克號生存預測
繼續學習資料探勘,嘗試了kaggle上的泰坦尼克號生存預測。 Titanic for Machine Learning 匯入和讀取 # data processing import numpy as np import pandas as pd impor
Kaggle專案案例分析 泰坦尼克號生存預測
一、資料來源及說明 1.1 資料來源 來自Kaggle的非常經典資料專案 Titanic:Machine Learning1.2 資料說明 資料包含train.csv 和test.csv 兩個檔案資料集,一個訓練用,一個測試用。train文件資料是用來分析和建模,包含泰
Kaggle競賽 —— 泰坦尼克號(Titanic)
Titanic大概是kaggle上最受歡迎的專案了,有7000多支隊伍參加,多年來誕生了無數關於該比賽的經驗分享。正是由於前人們的無私奉獻,我才能無痛完成本篇。事實上kaggle上的很多kernel都聚焦於某個特定的層面(比如提取某個不為人知的特徵、使用超複雜的演算法、專做E
Kaggle入門——泰坦尼克號生還者預測
前言 這個是Kaggle比賽中泰坦尼克號生存率的分析。強烈建議在做這個比賽的時候,再看一遍電源《泰坦尼克號》,可能會給你一些啟發,比如婦女兒童先上船等。所以是否獲救其實並非隨機,而是基於一些背景有先後順序的。 1,背景介紹 1912年4月15日,載著1316號乘客和891名船員的豪華巨輪泰坦尼克號在首
機器學習之路: python 決策樹分類 預測泰坦尼克號乘客是否幸存
現象 info n) 指標 ssi 直觀 learn 保持 afr 使用python3 學習了決策樹分類器的api 涉及到 特征的提取,數據類型保留,分類類型抽取出來新的類型 需要網上下載數據集,我把他們下載到了本地, 可以到我的git下載代碼和數據集: https
【金米米】現實版“泰坦尼克號”上演!這一刻竟是永別!
與他 進行 現實 潛水 可能 重復 保持 個人 也不能 北京時間7月5日傍晚6點45分左右,在泰國南部普吉府,兩艘共載有127名中國遊客的遊船在返航普吉島途中,突遇特大暴風雨,分別在珊瑚島和梅通島發生傾覆。截止至9日上午10時已有42人遇難,41名中國遊客,其中有13名中國