25 Pandas结合Sklearn实现泰坦尼克存活率预测
实例目标:实现泰坦尼克存活预测
处理步骤:
1、输入数据:使用Pandas读取训练数据(历史数据,特点是已经知道了这个人最后有没有活下来)
2、训练模型:使用Sklearn训练模型
3、使用模型:对于一个新的不知道存活的人,预估他存活的概率
步骤1:读取训练数据
import pandas as pd
df_train = pd.read_csv("./datas/titanic/titanic_train.csv")
df_train.head()
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
<pre><code>.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</code></pre>
PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | |
---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S |
1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C |
2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S |
3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 113803 | 53.1000 | C123 | S |
4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | NaN | S |
其中,Survived==1代表这个人活下来了、==0代表没活下来;其他的都是这个人的信息和当时的仓位、票务情况
# 我们只挑选两列,作为预测需要的特征
feature_cols = ['Pclass', 'Parch']
X = df_train.loc[:, feature_cols]
X.head()
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
<pre><code>.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</code></pre>
Pclass | Parch | |
---|---|---|
0 | 3 | 0 |
1 | 1 | 0 |
2 | 3 | 0 |
3 | 1 | 0 |
4 | 3 | 0 |
# 单独提取是否存活的列,作为预测的目标
y = df_train.Survived
y.head()
0 0
1 1
2 1
3 1
4 0
Name: Survived, dtype: int64
步骤2:训练模型
from sklearn.linear_model import LogisticRegression
# 创建模型对象
logreg = LogisticRegression()
# 实现模型训练
logreg.fit(X, y)
//anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
FutureWarning)
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, l1_ratio=None, max_iter=100,
multi_class='warn', n_jobs=None, penalty='l2',
random_state=None, solver='warn', tol=0.0001, verbose=0,
warm_start=False)
logreg.score(X, y)
0.6879910213243546
步骤3:对于未知数据使用模型
机器学习的核心目标,是使用模型预测未知的事物
比如预测股票明天是涨还是跌、一套新的二手房成交价大概多少钱、用户打开APP最可能看那些视频等问题
# 找一个历史数据中不存在的数据
X.drop_duplicates().sort_values(by=["Pclass", "Parch"])
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
<pre><code>.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</code></pre>
Pclass | Parch | |
---|---|---|
1 | 1 | 0 |
54 | 1 | 1 |
27 | 1 | 2 |
438 | 1 | 4 |
9 | 2 | 0 |
98 | 2 | 1 |
43 | 2 | 2 |
437 | 2 | 3 |
0 | 3 | 0 |
7 | 3 | 1 |
8 | 3 | 2 |
86 | 3 | 3 |
167 | 3 | 4 |
13 | 3 | 5 |
678 | 3 | 6 |
# 预测这个数据存活的概率
logreg.predict([[2, 4]])
array([1])
logreg.predict_proba([[2, 4]])
array([[0.35053893, 0.64946107]])
本文使用 文章同步助手 同步
网友评论