介绍:
逻辑回归属于线性分类器,通过Logistic
函数(Sigmoid
函数),将数据特征映射到0~1区间的一个概率值(样本属于正例的可能性),通过与0.5的比对得出数据所属的分类。主要应用于二分类。
逻辑回归主要功能是区分数据,找到决策边界
逻辑回归相当于线性回归与sigmoid函数的结合。
二分类:
二分分类即分类结果标签只有两个。
EG:输入歌曲特征,输出喜欢/不喜欢
EG:输入学习时间,输出及格或者不及格
模型:
则 其中X和是对应的行向量。
根据图像可得:
若>0,即 >0.5,目标变量y=1。
若<0,即 <0.5,目标变量y=0。
代价函数:
表示y=1的概率。
m
合并得到
y取0或1
m个数据则
取对数:
即交叉熵函数
则代价函数为:
代入得:
梯度下降:
为矩阵,所有的同时更新
例子:
假设你是一家电商公司的数据科学家,你想根据用户的年龄和购买历史来预测用户是否会购买某个产品。
首先,你收集了一些用户的数据,包括他们的年龄和过去购买的产品数量。你把这些数据存储在一个表格中,列名分别为"Age"(年龄)和"PurchaseHistory"(购买历史),以及一个目标变量"Purchase"(购买标记),其中1表示购买,0表示不购买。
下面是一个简化的数据集:
Age | PurchaseHistory | Purchase |
---|---|---|
25 | 5 | 1 |
30 | 2 | 0 |
35 | 0 | 0 |
40 | 7 | 1 |
45 | 3 | 1 |
代码:
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def h(x, theta):
return sigmoid(x.dot(theta))
def J(h, y):
return -y * np.log(h) - (1 - y) * np.log(1 - h)
def gradient(x, theta, y):
h = sigmoid(x.dot(theta))
d = np.dot(x.T, (h - y))
return d / len(x)
def gradient_descent(theta, alpha, x, y):
return theta - alpha * gradient(x, theta, y)
X = np.array([[1, 25, 5],
[1, 30, 2],
[1, 35, 0],
[1, 40, 7],
[1, 45, 3]])
y = np.array([1, 0, 0, 1, 1])
# 初始化 theta
theta = np.zeros(X.shape[1])
alpha = 0.01
# 训练模型并输出参数 theta
for i in range(1000):
theta = gradient_descent(theta, alpha, X, y)
print('Theta:', theta)
# 绘制散点图,并根据类别使用不同颜色
colors = ['red' if label == 0 else 'blue' for label in y]
plt.scatter(X[:, 1], X[:, 2], c=colors)
# 预测新数据 [28, 4]
new_data = np.array([1, 28, 4])
prediction = h(new_data, theta)
print('Prediction for [28, 4]:', prediction)
plt.scatter(new_data[1], new_data[2], color='green', marker='x', label='New Data [28, 4]')
plt.xlabel('Age')
plt.ylabel('PurchaseHistory')
plt.legend()
plt.show()