一 逻辑回归理论:
1原始数据散点图可视化
2模型训练——获得边界函数系数——对新数据进行预测
3生成新的属性数据(使得边界函数更准确)——建立二阶边界函数
4评估模型表现
二 代码实战
链接:https://pan.baidu.com/s/1pnmHggCwDAQfnO0VC0zntw?pwd=hhhh
提取码:hhhh
# 导入数据
import pandas as pd
import numpy as np
data = pd.read_csv('examdata.csv')
data.head()
#变量可视化——区分两个变量
from matplotlib import pyplot as plt
fig2 = plt.figure()
mask = data.loc[:,'Pass']==1
passed = plt.scatter(data.loc[:,'Exam1'][mask],data.loc[:,'Exam2'][mask])
failed = plt.scatter(data.loc[:,'Exam1'][~mask],data.loc[:,'Exam2'][~mask])
plt.title('Exam1-Exam2')
plt.xlabel('Exam1')
plt.ylabel('Exam2')
plt.legend((passed,failed),('passed','failed'))
#变量赋值
x = data.drop('Pass',axis=1)
x1 = data.loc[:,'Exam1']
x2 = data.loc[:,'Exam2']
y = data.loc[:,'Pass']
x.head()
# 建立模型
from sklearn.linear_model import LogisticRegression
Lr = LogisticRegression()
Lr.fit(x,y)
#模型预测
y_predict = Lr.predict(x)
print(y_predict)
# 模型评估
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y,y_predict)
print(accuracy)
# 确定值预测
x_test = [75,60]
y_test = Lr.predict([x_test])
print(y_test)
print('passed'if y_test==1 else 'failed')
发现模型准确率才89% 不是很高
# 获得边界函数系数
th0 = Lr.intercept_
th1,th2 = Lr.coef_[0][0],Lr.coef_[0][1]
print(th0,th1,th2)
x2_new = -(th0+th1*x1)/th2 #由上图公式进行变形得到新的x2
# 可视化边界函数
fig2 = plt.figure()
# 画出数据散点图
passed = plt.scatter(data.loc[:,'Exam1'][mask],data.loc[:,'Exam2'][mask])
failed = plt.scatter(data.loc[:,'Exam1'][~mask],data.loc[:,'Exam2'][~mask])
plt.title('Exam1-Exam2')
plt.xlabel('Exam1')
plt.ylabel('Exam2')
plt.legend((passed,failed),('passed','failed'))
# 画出边界函数
plt.plot(x1,x2_new)
发现模型拟合度不是很高,继续改进。。。
#生成新的数据,并创造更好的模型,利用二阶边界函数。
#创建新数据
x1_2 = x1*x1
x2_2 = x2*x2
x1_x2 = x1*x2
# 生成新数据 赋值程dataframe
x_new = {'x1':x1,'x2':x2,'x1_2':x1_2,'x2_2':x2_2,'x1_x2':x1_x2}
x_new = pd.DataFrame(x_new)
print(x_new)
# 利用新的数据 创建新模型 并进行训练
Lr1 = LogisticRegression()
Lr1.fit(x_new,y)
# 模型预测
y_predict2 = Lr1.predict(x_new)
# 模型评估
accuracy2 = accuracy_score(y,y_predict2)
print(accuracy2)
发现模型准确率达到了100%
# 排序后可视化时数据不会交叉,而是顺序描点成一条曲线
x1_new = x1.sort_values()
#利用二阶方程求两个x的格式
th0 = Lr1.intercept_
th1,th2,th3,th4,th5 = Lr1.coef_[0][0],Lr1.coef_[0][1],Lr1.coef_[0][2],Lr1.coef_[0][3],Lr1.coef_[0][4]
a = th4
b = th5*x1_new + th2
c = th0 + th1*x1_new + th3*x1_new*x1_new
x2_new_boundary = (-b+np.sqrt(b*b - 4*a*c))/(2*a)
print(x2_new_boundary)
# 可视化改进后的函数曲线
fig3 = plt.figure()
passed = plt.scatter(data.loc[:,'Exam1'][mask],data.loc[:,'Exam2'][mask])
failed = plt.scatter(data.loc[:,'Exam1'][~mask],data.loc[:,'Exam2'][~mask])
plt.title('Exam1-Exam2')
plt.xlabel('Exam1')
plt.ylabel('Exam2')
plt.legend((passed,failed),('passed','failed'))
plt.plot(x1_new,x2_new_boundary)
改进后的数据函数曲线拟合度很好。
链接:https://pan.baidu.com/s/1pnmHggCwDAQfnO0VC0zntw?pwd=hhhh
提取码:hhhh