逻辑回归模型--Python

本文详细介绍了如何使用Python实现逻辑回归模型,包括数据集读取、Sigmoid函数、代价函数(含正则化)、梯度下降算法以及模型预测和准确率计算。最后展示了使用X2和X3特征的逻辑回归0-1分布图。
摘要由CSDN通过智能技术生成

学习目标:

Python实现逻辑回归模型


学习内容:

1.数据集的读取
2.实现Sigmoid函数
3.实现逻辑回归的代价函数,并正则化逻辑回归
4.实现梯度下降函数,输出迭代过程中的代价函数值
5.通过梯度下降计算回归模型,用所得模型对测试集的数据进行预测,并计算准确率
使用X2,X3两组特征画出逻辑回归0-1分布图


学习产出:

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams[“font.family”]=[“Microsoft YaHei”]
#rcParams设置字体为微软雅黑

#数据集的读取
def load_data(file):
data=np.loadtxt(file,delimiter=“,”)
X=data[:,0:3]
y=data[:,3]
return X,y
X_train,y_train=load_data(“train.txt”)
X_test,y_test=load_data(“test.txt”)
#numpy库loadtxt函数加载数据集,delimiter设置分隔符为逗号
#提取特征和标签

#实现Sigmoid函数
def sigmoid(x):
return 1/(1+np.exp(-x))

#实现逻辑回归的代价函数,实现正则化逻辑回归
def cost_func(X,y,theta,lamda_val=0):
m=len(y)
h=sigmoid(np.dot(X,theta.T))
cost=-(np.dot(y,np.log(h))+np.dot(1-y,np.log(1-h)))/m
ll=(lamda_val/(2*m))*np.sum(theta[1:]**2)
cost+=ll
return cost
逻辑回归代价函数公式

#实现梯度下降函数,要求输出迭代过程中的代价函数值
def decrease(X,y,theta,alpha,num,lamda_val=0):
m=len(y)
history_j=np.zeros(num)
for i in range(num):
history_j[i]=cost_func(X,y,theta,lamda_val)
h=sigmoid(np.dot(X,theta.T))
error=h-y
grid=np.dot(X.T,error)/m+(lamda_val/m)theta
grid[0]=np.dot(X[:,0].T,error)/m#截距不参与正则化
theta-=alpha
grid
return theta,history_j梯度下降函数公式

#通过梯度下降计算回归模型,用所得模型对测试集的数据进行预测,并计算准确率
X_train=np.insert(X_train,0,1,axis=1)
X_test=np.insert(X_test,0,1,axis=1)
y_train=np.array(y_train)
y_test=np.array(y_test)
theta=np.zeros(X_train.shape[1])
alpha=0.02
lambda_val=0.2
theta,history_j=decrease(X_train,y_train,theta,alpha,1000,lambda_val)
print(theta,history_j)

#预测
y_pred=np.round(sigmoid(np.dot(X_test,theta.T)))
print(y_pred)

#准确率
acc=np.sum(y_pred==y_test)/len(y_test)
print(f’准确率:{acc}')

#使用X2,X3两组特征画出逻辑回归0-1分布图
plt.scatter(X_test[:,2],X_test[:,3],c=y_test,cmap=“bwr”,label=“真实值”)
plt.scatter(X_test[:,2],X_test[:,3],c=y_pred,cmap=“cool”,marker=“*”,label=“预测值”)
plt.title(“逻辑回归0-1分布图”)
plt.xlabel(“宽度”)
plt.ylabel(“高度”)
plt.legend()
plt.show()
scatter函数绘制散点图,cmap指定颜色映射,label设置图例

  • 8
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值