逻辑回归算法实验

【实验目的】

理解逻辑回归算法原理,掌握逻辑回归算法框架;
理解逻辑回归的sigmoid函数;
理解逻辑回归的损失函数;
针对特定应用场景及数据,能应用逻辑回归算法解决实际分类问题。

【实验内容】

1.根据给定的数据集,编写python代码完成逻辑回归算法程序,实现如下功能:

建立一个逻辑回归模型来预测一个学生是否会被大学录取。假设您是大学部门的管理员,您想根据申请人的两次考试成绩来确定他们的入学机会。您有来自以前申请人的历史数据,可以用作逻辑回归的训练集。对于每个培训示例,都有申请人的两次考试成绩和录取决定。您的任务是建立一个分类模型,根据这两门考试的分数估计申请人被录取的概率。
算法步骤与要求:

(1)读取数据;(2)绘制数据观察数据分布情况;(3)编写sigmoid函数代码;(4)编写逻辑回归代价函数代码;(5)编写梯度函数代码;(6)编写寻找最优化参数代码(可使用scipy.opt.fmin_tnc()函数);(7)编写模型评估(预测)代码,输出预测准确率;(8)寻找决策边界,画出决策边界直线图。

2. 针对iris数据集,应用sklearn库的逻辑回归算法进行类别预测。

要求:

(1)使用seaborn库进行数据可视化;(2)将iri数据集分为训练集和测试集(两者比例为8:2)进行三分类训练和预测;(3)输出分类结果的混淆矩阵。

 

【实验过程】

#读取数据
import pandas as pd
import matplotlib.pyplot as plt
path='C:\Users\ROG\jixiexuexi2.txt'
data=pd.read_csv(path,header=None,names=['a1','a2','result'])
data

 

#将文本数据可视化
import matplotlib.pyplot as plt
data1=data[data['result'].isin(1)]
data2=data[data['result'].isin(0)]
plt.scatter(data1['a1'],data1['a2'])
plt.scatter(data2['a1'],data2['a2'])
plt.show()

 

什么是sigmoid函数?

  Sigmoid函数是一个在生物学中常见的S型函数,也称为S型生长曲线。在深度学习中,由于其单增以及反函数单增等性质,Sigmoid函数常被用作神经网络的激活函数,将变量映射到[0,1] [0,1][0,1]之间。

    

  Sigmoid函数的特性与优缺点:

  Sigmoid函数的输出范围是0到1。由于输出值限定在0到1,因此它对每个神经元的输出进行了归一化。

  用于将预测概率作为输出的模型。由于概率的取值范围是0到1,因此Sigmoid函数非常合适梯度平滑,避免跳跃的输出值函数是可的。

  这意味着可以找到任意两个点的Sigmoid曲线的斜率明确的预测,即非常接近1或0。函数输出不是以0为中心的,这会降低权重更新的效率Sigmoid函数执行指数运算,计算机运行得较慢。

#sigmoid函数
import numpy as np
def sigmoid(z):
    return 1/(1+np.exp(-z))
nums=np.arange(-10,10,step=1)
fig,ax=plt.subplots(figsize=(12,8))
ax.plot(nums,sigmoid(nums),"r")

 

#逻辑回归代价函数
def model(x,theta):
    return sigmoid(np.dot(x,theta.T))

def cost(theta,x,y):
    theta = np.matrix(theta) 
    L1=np.multiply(-y,np.log(model(x,theta)))
    L2=np.multiply(1-y,np.log(1-model(x,theta)))
    return np.sum(L1-L2)/(len(x))

Data.insert(0, 'Ones', 1)
cols=Data.shape[1]
x=np.array(Data.iloc[:,0:cols-1])
y=np.array(Data.iloc[:,cols-1:cols])
theta=np.zeros(x.shape[1])
print(cost(theta,x,y))

输出结果:

   

 

#梯度函数
def gradient(theta,x,y):
    theta = np.matrix(theta) #要先把theta转化为矩阵
    grad=np.dot(((model(x,theta)-y).T),x)/len(x)
    return np.array(grad).flatten()#因为下面寻找最优化参数的函数(opt.fmin_tnc())要求传入的gradient函返回值需要是一维数组,
                                   #因此需要利用flatten()将grad进行转换以下 
gradient(theta,x,y)

输出结果:

  

 

#寻找最优参
import scipy.optimize as opt
result = opt.fmin_tnc(func=cost, x0=theta, fprime=gradient, args=(X, y))
result

输出结果:

   

 

#对模型进行评估同时输出预测准确率
def predict(theta,x):
    theta=np.matrix(theta)
    temp=sigmoid(x*theta.T)
    return [1 if x >= 0.5 else 0 for x in temp]
theta=result[0]
predictValues=predict(theta,x)
hypothesis=[1 if a==b else 0 for (a,b)in zip(predictValues,y)]
accuracy=hypothesis.count(1)/len(hypothesis)
print ('accuracy = {0}%'.format(accuracy*100))

输出结果:

  

 

#寻找决策边界并输出决策边界直线图
import numpy as np

def find_x2(x1,theta):
    return [(-theta[0]-theta[1]*x_1)/theta[2] for x_1 in x1]
x1 = np.linspace(30, 100, 1000)
x2=find_x2(x1,theta)
admittedData=data[data['result'].isin([1])]
noAdmittedData=data[data['result'].isin([0])]
fig,ax=plt.subplots(figsize=(12,8))
ax.scatter(admittedData['score1'],admittedData['score2'],marker='+',label='addmitted')
ax.scatter(noAdmittedData['score2'],noAdmittedData['score1'],marker='o',label="not addmitted")
ax.plot(x1,x2,color='r',label="decision boundary")
ax.legend(loc=1)
ax.set_xlabel('Exam1 score')
ax.set_ylabel('Exam2 score')
ax.set_title("Training data with decision boundary")
plt.show()

   

#)应用sklearn库的逻辑回归算法对iris数据集进行类别预测
import numpy as np 
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import load_iris
data = load_iris()                                                          
iris_target = data.target                                                    
iris_features = pd.DataFrame(data=data.data, columns=data.feature_names)      
iris_all = iris_features.copy()                                              
iris_all['target'] = iris_target
sns.pairplot(data=iris_all,diag_kind='hist', hue= 'target')
plt.savefig("iris.png")
plt.show()

 

#训练和预测数据集
#将iri数据集按照8:2分为训练集和测试集进行训练和预测
from sklearn.model_selection import train_test_split
 X_train,X_test,y_train,y_test = train_test_split(iris_features,iris_target,test_size=0.2,random_state=2020)
 from sklearn.linear_model import LogisticRegression
 clf=LogisticRegression(random_state=0,solver='lbfgs')
 clf.fit(X_train,y_train)
 print('the weight of Logistic Regression:\n',clf.coef_)
 print('the intercept(w0) of Logistic Regression:\n',clf.intercept_)
 train_predict=clf.predict(X_train)
 test_predict=clf.predict(X_test)

输出:

  

 

#输出混淆矩阵
from sklearn import metrics
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_test,test_predict))
confusion_matrix_result=metrics.confusion_matrix(y_test,test_predict)
print('The confusion matrix result:\n',confusion_matrix_result)
plt.figure(figsize=(8,6))
sns.heatmap(confusion_matrix_result,annot=True,cmap='Blues')
plt.xlabel('Predictedlabels')
plt.ylabel('Truelabels')
plt.show()

 

 

posted @   1nfinite  阅读(96)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示