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

数据集在作业一

线性可分逻辑回归

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

总结

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

相关推荐
吴佳浩5 小时前
Python入门指南(七) - YOLO检测API进阶实战
人工智能·后端·python
tap.AI5 小时前
RAG系列(二)数据准备与向量索引
开发语言·人工智能
老蒋新思维6 小时前
知识IP的长期主义:当AI成为跨越增长曲线的“第二曲线引擎”|创客匠人
大数据·人工智能·tcp/ip·机器学习·创始人ip·创客匠人·知识变现
货拉拉技术6 小时前
出海技术挑战——Lalamove智能告警降噪
人工智能·后端·监控
wei20236 小时前
汽车智能体Agent:国务院“人工智能+”行动意见 对汽车智能体领域 革命性重塑
人工智能·汽车·agent·智能体
LinkTime_Cloud6 小时前
快手遭遇T0级“黑色闪电”:一场教科书式的“协同打击”,披上了AI“智能外衣”的攻击
人工智能
PPIO派欧云7 小时前
PPIO上线MiniMax-M2.1:聚焦多语言编程与真实世界复杂任务
人工智能
隔壁阿布都7 小时前
使用LangChain4j +Springboot 实现大模型与向量化数据库协同回答
人工智能·spring boot·后端
Coding茶水间7 小时前
基于深度学习的水面垃圾检测系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
图像处理·人工智能·深度学习·yolo·目标检测·机器学习·计算机视觉
乐迪信息7 小时前
乐迪信息:煤矿皮带区域安全管控:人员违规闯入智能识别
大数据·运维·人工智能·物联网·安全