这是比较友好的小白入门机器学习的一个案例, 其主要是使用了 归一化的方法处理了数据, 使得数据处于一个维度(消除量纲),然后就是用模型进行预测是否能生存下来及其可能性 (概率)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# Load the passenger data
passengers = pd.read_csv("passer.csv") # 读取数据
print(passengers.shape)
# print(passengers['Sex'])
# Update sex column to numerical female -> 1 male -> 0
passengers['Sex'] = passengers['Sex'].map({'male':'0','female':'1'}) # 更新
# print(passengers['Sex'])
# Fill the nan values in the age column
# print(passengers['Age'].values) # 存在缺失值
passengers['Age'].fillna(value = passengers['Age'].mean(),inplace=True)
# print(passengers['Age'].values) # 使用平均值进行填补
# Create a first class column
passengers['FirstClass'] = passengers['Pclass'].apply(lambda x:1 if x == 1 else 0)
# print(passengers['FirstClass'])
# Create a second class column
passengers['SecondClass'] = passengers['Pclass'].apply(lambda x:2 if x == 1 else 0)
# Select the desired features
features = passengers[['Sex','Age','FirstClass','SecondClass']]
survival = passengers[['Survived']]
# Perform train, test, split
X_train,X_test,y_train,y_test = train_test_split(features,survival,test_size=0.4,random_state=100)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
print(y_train.head())
# Scale the feature data so it has mean = 0 and standard deviation = 1
model = StandardScaler()
model.fit_transform(X_train) # used on the training features
model.fit(y_train) # used on the test features
# Create and train the model
model_2 = LogisticRegression()
model_2.fit(X_train,y_train.values.ravel()) # .values will give the values in an array (shape: (n,1)) .ravel will convert that array shape to (n,)
# Score the model on the train data
print(model_2.score(X_train,y_train))
# Score the model on the test data
print(model_2.score(X_test,y_test))
# Analyze the coefficients
print(model_2.coef_)
print(list(zip(['Sex','Age','FirstClass','SecondClass'],model_2.coef_[0])))
# Sample passenger features
Jack = np.array([0.0,20.0,0.0,0.0])
Rose = np.array([1.0,17.0,1.0,0.0])
You = np.array([1.0,21.0,1.0,0.0])
# Combine passenger arrays
sample_passengers = np.array([Jack,Rose,You])
print(sample_passengers)
# Scale the sample passenger features
sample_passengers = model.fit_transform(sample_passengers)
print(sample_passengers)
# Make survival predictions! predict the probabilities of survival for sample_passengers
result_probabilities = model_2.predict_proba(sample_passengers) # predict 预测的是 谁会生存下来, 谁会不幸
print(result_probabilities) # 第一列是 和船一起灭亡的可能性, 第二列是 生存下来的可能性
result_predict = model_2.predict(sample_passengers)
print(result_predict) # 应该是 生存的可能性 > 灭亡的可能性 就会预测生存下来了~
希望大家喜欢, 有什么问题, 欢迎大家在留言区给我留言或者私信我也行。 谢谢大家的观看~