量化投資學習筆記23——支持向量機:實操,泰坦尼克號乘客生還機會預測

用剛學的支持向量機來解決一下泰坦尼克號問題。
數據的載入,清洗完全跟之前的一樣,直接複製粘貼。從建模開始。
代碼
建模,使用SVM模型
劃分訓練集和測試集
predictors = ['Pclass', 'Sex', 'Age', 'Family', 'Embarked', 'Cabin']
x = train_data[predictors]
y = train_data["Survived"]
train_x, train_y, x_label, y_label = train_test_split(x, y, random_state = 1, train_size = 0.6, test_size = 0.4)
print("訓練集大小:", train_x.shape)
print("測試集大小:", train_y.shape)
訓練SVM分類器
classifier = svm.SVC(C = 2, kernel = "rbf", gamma = 10, decision_function_shape = "ovr")
classifier.fit(train_x, x_label)
計算分類準確率
print("建模的結果")
print("訓練集:", classifier.score(train_x, x_label))
print("測試集:", classifier.score(train_y, y_label))
結果
建模的結果
訓練集: 0.9569288389513109
測試集: 0.6190476190476191
在測試集上效果不好啊。換個核函數試試。
classifier = svm.SVC(C = 2, kernel = "linear", gamma = 10, decision_function_shape = "ovr")
看看結果
建模的結果
訓練集: 0.8108614232209738
測試集: 0.7507002801120448
換成線性核函數,好了很多。輸出到結果文件,提交。
預測,輸出結果
pred = classifier.predict(test_data[predictors])
print(pred)
output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': pred})
output.to_csv("submit04.csv", index = False)
print("結果輸出完畢!")

跟用邏輯迴歸一模一樣?
我用一個測試數據提交了一下,所有結果均爲0。

看來提交是正常的。OK,進行下一個算法的學習吧。
本文代碼
https://github.com/zwdnet/MyQuant/blob/master/titanic/submit04.py

我發文章的四個地方,歡迎大家在朋友圈等地方分享,歡迎點“在看”。
我的個人博客地址:https://zwdnet.github.io
我的知乎文章地址: https://www.zhihu.com/people/zhao-you-min/posts
我的博客園博客地址: https://www.cnblogs.com/zwdnet/
我的微信個人訂閱號:趙瑜敏的口腔醫學學習園地

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章