Python3利用pandas,sklearn进行关联度分析以及预测的demo
做个简单的demo记录下,防止忘记
先看原始数据:
一共有5列:日期,金钱,性别,工作年限,年龄。
我们的目的是要分析各个维度对金钱的影响。
关联度分析代码:
# -*- coding: utf-8 -*-
from numpy import array
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
df_base = pd.read_csv('F://tips.csv',)
plt.figure(figsize=(16,12))
#对性别进行onehot
pf = pd.get_dummies(df_base['sex'])
df = pd.concat([df_base, pf], axis=1)
df.drop(['sex'], axis=1, inplace=True)
print(df)
sns.heatmap(df.corr(),annot=True,fmt=".2f")
#删掉关联度比较小的列
df.drop(['age'], axis=1, inplace=True)
df.to_csv('result.csv')
plt.show()
运行后我们可以看到heatmap展示出了各个维度之间的关联系数:
图中很明显的可以看到,man对money有正相关系数0.6,woman对money有负相关-0.6,工作年限对money的正相关系数很高,age基本无相关。所以我们把age这一列删掉,将sex进行了一把onehot,转换为man和woman两列(String类型的列只能通过onehot才可以分析)。生成了新的csv。
接下来我们做预测:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from sklearn import linear_model
df=pd.read_csv('result.csv')
sns.set(style='whitegrid', context='notebook') #style控制默认样式,context控制着默认的画幅大小
cols = ['man', 'woman', 'money','workyears']
sns.pairplot(df[cols], size=2.5)
plt.tight_layout()
plt.show()
# 建立模型
model =linear_model.LinearRegression()
# 开始训练
model.fit(df[['man', 'woman','workyears']], df['money'])
print("coefficients: ", model.coef_)
w1 = model.coef_[0]
w2 = model.coef_[1]
w2 = model.coef_[2]
print("intercept: ", model.intercept_)
b = model.intercept_
x_test = [[1,0,6]]
predict = model.predict(x_test)
print("predict: ", predict)
分布基部符合上一步的猜测
这里我们用了【1,0,6】数据来做预测即:man:1,woman:0,workyears:6
结果: