流程
- 导入所要使用的包
- 引入kaggle的数据集csv文件
- 查看数据集有无空值
- 填充这些空值
- 提取特征
- 分离训练集和测试集
- 调用模型
代码和数据位置
https://gitee.com/heibaizi2000/machine-learning.git
代码和数据
导入需要的包
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
引入kaggle的数据集csv文件
train=pd.read_csv('train.csv')
test=pd.read_csv('test.csv')
datas = pd.concat([train, test], ignore_index = True)
得到女性的存活率
# 取出表格中的两列,性别和存活率构建一个新的数据集women
women = train.loc[train.Sex == 'female']["Survived"]
# 一共有314条女性记录,由于存活的情况是1,所以累加所有存活特征,就能得到存活数量
# 再用存活数量/女性总数得到女性存活率
rate_women = sum(women)/len(women)
print("% of women who survived:", rate_women)
# 获得女性的存活率
得到男性的存活率
men = train.loc[train.Sex == 'male']["Survived"]
rate_men = sum(men)/len(men)
print("% of men who survived:", rate_men)
调用模型
from sklearn.ensemble import RandomForestClassifier
y = train["Survived"]
features = ["Pclass", "Sex", "SibSp", "Parch","Embarked","Cabin"]
X = pd.get_dummies(train[features])
X_test = pd.get_dummies(test[features])
model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=1)
model.fit(X, y)
predictions = model.predict(X_test)
score=model.score(X, y)
print(score)
output = pd.DataFrame({'PassengerId': test.PassengerId, 'Survived': predictions})
输出文件
output.to_csv('mypredict.csv', index=False)