吴恩达机器学习作业二:线性可分逻辑回归

数据集在作业一

线性可分逻辑回归

线性可分逻辑回归是逻辑回归在线性可分数据集上的应用形式,它结合了线性模型的结构和逻辑回归的概率解释,用于解决二分类问题。其核心特点是:存在一个线性超平面能够将两类样本完全分开,且模型通过逻辑函数(sigmoid)将线性输出映射为类别概率。

数学定义

算法流程

1.初始化参数

2.定义损失函数

3.梯度下降

代码实现

读取数据集及可视化

复制代码
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.optimize as opt

"""读取数据"""
data=pd.read_csv('ex2data1.txt',names=['Exam 1 score','Exam 2 score','Admitted'])
# print(data.head())

# """数据可视化"""
# fig, ax = plt.subplots()
# ax.scatter(data[data['Admitted'] == 1]['Exam 1 score'], data[data['Admitted'] == 1]['Exam 2 score'],  c='b', marker='o', label='Admitted')
# ax.scatter(data[data['Admitted']==0]['Exam 1 score'], data[data['Admitted']==0]['Exam 2 score'], c='r', marker='x', label='Not Admitted')
# ax.legend()
# ax.set_xlabel('Exam 1 score')
# ax.set_ylabel('Exam 2 score')
# plt.show()

数据预处理

复制代码
def getXy(data):
    data.insert(0,'ones',1)
    X=data.iloc[:,0:-1]
    X=X.values
    y=data.iloc[:,-1]
    y=y.values
    y=y.reshape((y.shape[0],1))
    return X,y

X,y=getXy(data)

损失函数(交叉熵函数)

复制代码
def sigmoid(z):
    return 1/(1+np.exp(-z))
def cost_function(theta,X,y):
    m=len(y)
    h=sigmoid(np.dot(X,theta))
    J=-1/m*np.sum(y*np.log(h)+(1-y)*np.log(1-h))
    return J
    theta=np.zeros((3,1))

这个也是由最大似然估计推导而来。

梯度下降算法

复制代码
def gradient_descent(X,y,theta,alpha,count):
    m=len(y)
    costs=[]
    for i in range(count):
        theta=theta-alpha*(1/m)*np.dot(X.T,(sigmoid(np.dot(X,theta))-y))
        cost=cost_function(theta,X,y)
        costs.append(cost)
        if i%1000==0:
            print(cost)
    return theta,costs

预测

复制代码
def predict(theta,X):
    prob=sigmoid(np.dot(X,theta))
    return [1 if x>=0.5 else 0 for x in prob]

y_pred=np.array(predict(theta,X))
print(y_pred)
y_pred=y_pred.reshape((y_pred.shape[0],1))
accuracy=np.mean(y_pred==y)
print(accuracy)#准确率

可视化

复制代码
fig, ax = plt.subplots()
ax.scatter(data[data['Admitted'] == 1]['Exam 1 score'], data[data['Admitted'] == 1]['Exam 2 score'],  c='b', marker='o', label='Admitted')
ax.scatter(data[data['Admitted']==0]['Exam 1 score'], data[data['Admitted']==0]['Exam 2 score'], c='r', marker='x', label='Not Admitted')
ax.legend()
ax.set_xlabel('Exam 1 score')
ax.set_ylabel('Exam 2 score')
x1=np.arange(20,100,1)
x2=(-theta[0]-theta[1]*x1)/theta[2]
ax.plot(x1,x2,c='g')
plt.show()

总结

读取数据集------预处理------损失函数------梯度下降算法------预测

相关推荐
TTGGGFF4 小时前
控制系统建模仿真(四):线性控制系统的数学模型
人工智能·算法
UXbot4 小时前
UI设计工具推荐合集
前端·人工智能·ui
kicikng4 小时前
智能体来了(西南总部)实战指南:AI调度官与AI Agent指挥官的Prompt核心逻辑
人工智能·prompt·多智能体系统
抓个马尾女孩4 小时前
为什么self-attention除以根号dk而不是其他值
人工智能·深度学习·机器学习·transformer
叫我辉哥e14 小时前
新手进阶Python:办公看板集成ERP跨系统同步+自动备份+AI异常复盘
开发语言·人工智能·python
Loo国昌4 小时前
【LangChain1.0】第五阶段:RAG高级篇(高级检索与优化)
人工智能·后端·语言模型·架构
伊克罗德信息科技4 小时前
技术分享 | 用Dify搭建个人AI知识助手
人工智能
TOPGUS4 小时前
谷歌发布三大AI购物新功能:从对话式搜索到AI代你下单
大数据·人工智能·搜索引擎·chatgpt·谷歌·seo·数字营销
Godspeed Zhao4 小时前
从零开始学AI4——背景知识3
人工智能