赞
踩
# sigmoid函数绘制
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-6, 6) # 通过linspace()函数生成-6到6的等差数列,默认50个数
y = 1.0 / (1.0 + np.exp(-x)) # Sigmoid函数计算公式
plt.grid()
plt.plot(x,y)
plt.annotate('$sigmoid(x)=\\frac{1}{1+e^{-x}}$'
,xy=(2,0.5)
,xytext=(0.2, 0.5)
,size = 15
)
plt.show()
# 构造数据
X = [[1, 0], [5, 1], [6, 4], [4, 2], [3, 2]]
y = [0, 1, 1, 0, 0]
# 模型训练
from sklearn.linear_model import LogisticRegression
model = LogisticRegression().fit(X, y)
# 打印系数和截距项
print(model.coef_) # 系数w1与w2
print(model.intercept_) # 截距项b
# 模型预测 - 预测单个数据
print(model.predict([[2,2]]))
# 模型预测 - 预测多个数据1
print(model.predict([[1,1], [2,2], [5, 5]]))
# 预测概率:左列是分类为0的概率,右列是分类为1的概率
y_pred_proba = model.predict_proba(X)
print(y_pred_proba)
# 通过DataFrame展示
import pandas as pd
pd.DataFrame(y_pred_proba, columns=['分类为0的概率', '分类为1的概率'])
分类为0的概率 | 分类为1的概率 | |
---|---|---|
0 | 0.973449 | 0.026551 |
1 | 0.390720 | 0.609280 |
2 | 0.179910 | 0.820090 |
3 | 0.631679 | 0.368321 |
4 | 0.824245 | 0.175755 |
不知道怎么上传Excel,有需要可以私信
# 逻辑回归模型案例 - 股票客户流失预警模型 # 1.读取数据 import pandas as pd df = pd.read_excel('股票客户流失.xlsx') # 2.划分特征变量和目标变量 X = df.drop(columns='是否流失') y = df['是否流失'] # 3.划分训练集和测试集 from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=90) # 4.模型搭建 from sklearn.linear_model import LogisticRegression model = LogisticRegression().fit(X_train, y_train) # 5.预测数据结果 y_pred = model.predict(X_test) print(y_pred[0:100]) # 打印预测内容的前100个看看 # 放到一个DataFrame里进行查看比对 a = pd.DataFrame() # 创建一个空DataFrame a['预测值'] = list(y_pred) a['实际值'] = list(y_test) a.head() # 可以看到此时前5个预测准确度为80% # 预测准确率 score = model.score(X_test, y_test) print(score) # 6.预测概率 y_pred_proba = model.predict_proba(X_test) print(y_pred_proba[0:5]) # 打印前5个客户的分类概率
# 评估股票客户流失预警模型 # 1.计算ROC曲线需要的假警报率(fpr)、命中率(tpr)及阈值(thres) from sklearn.metrics import roc_curve fpr, tpr, thres = roc_curve(y_test, y_pred_proba[:,1]) # 2.查看假警报率(fpr)、命中率(tpr)及阈值(thres) a = pd.DataFrame() # 创建一个空DataFrame a['阈值'] = list(thres) a['假警报率'] = list(fpr) a['命中率'] = list(tpr) a.head() # 3.绘制ROC曲线 import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['Arial Unicode MS'] #显示中文标签,Mac用这个显示中文 #plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置中文 plt.plot(fpr, tpr) # 绘制折线图 plt.title('ROC曲线') # 添加标题 plt.xlabel('FPR') # 添加X轴标签 plt.ylabel('TPR') # 添加Y轴标 plt.show() # 4.求出模型的AUC值 from sklearn.metrics import roc_auc_score AUC = roc_auc_score(y_test, y_pred_proba[:,1]) AUC
# 构造数据,此时y有多个分类
X = [[1, 0], [5, 1], [6, 4], [4, 2], [3, 2]]
y = [-1, 0, 1, 1, 1] # 这里有三个分类-1、0、1
# 模型训练
from sklearn.linear_model import LogisticRegression
model = LogisticRegression().fit(X, y)
print(model.predict([[0, 0]]))
print(model.predict(X))
print(model.predict_proba([[0, 0]]))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。