文章目录
1.形式化定义
解决的是分类问题,类别分别是0和1
2.逻辑回归求解
举例说明
3.逻辑回归代码实现
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import accuracy_score
# 定义加载数据的函数
def loaddata():
data = np.loadtxt('data2.txt', delimiter=',')
# 特征数
n = data.shape[1] - 1
X = data[:, 0:n]
y = data[:, -1].reshape(-1, 1)
return X, y
# 定义散点图函数
def scatter(X, y):
# 分别寻找y==1和y==0时,索引值的位置
pos = np.where(y == 1)
neg = np.where(y == 0)
plt.scatter(X[pos[0], 0], X[pos[0], 1], marker='x')
plt.scatter(X[neg[0], 0], X[neg[0], 1], marker='o')
plt.xlabel('Exam 1 score')
plt.xlabel('Exam 2 score')
plt.show()
# 实现sigmoid函数
def sigmoid(z):
r = 1 / (1 + np.exp(-z))
return r
# 实现假设函数
def hypothesis(X, theta):
z = np.dot(X, theta)
return sigmoid(z)
# 实现代价函数,先实现损失
def computeCost(X, y, theta):
m = X.shape[0]
l = -y * np.log(hypothesis(X, theta)) - (1 - y) * np.log(1 - hypothesis(X, theta))
return np.sum(l) / m
# 梯度下降法求解
def gradientDescent(X, y, theta, iterations, alpha):
# 数据量
m = X.shape[0]
# 在x最前面插入全为1的列
# np.vstack():在竖直方向上堆叠
# np.hstack表示在水平方向上平铺
X = np.hstack((np.ones((m, 1)), X))
for i in range(iterations):
for j in range(len(theta)):
theta[j] = theta[j] - (alpha / m) * np.sum((hypothesis(X, theta) - y) * X[:, j].reshape(-1, 1))
if (i % 10000 == 0):
# 每迭代10000次,输出一次损失值
print('第', i, '次迭代,当前损失为:', computeCost(X, y, theta), 'theta =', theta)
return theta
# 画决策边界
def plotDescionBoundary(X, y, theta):
# 样本点颜色
cm_dark = mpl.colors.ListedColormap(['g', 'r'])
plt.xlabel('Exam 1 score')
plt.ylabel('Exam 2 score')
# 根据y的结果自动的在cmap中选择颜色,c参数代表颜色
plt.scatter(X[:, 0], X[:, 1], c=np.array(y).squeeze(), cmap=cm_dark, s=30)
# 画分类决策面
x1 = np.arange(min(X[:, 0]), max(X[:, 0]), 0.1)
x2 = -(theta[0] + theta[1] * x1) / theta[2]
plt.plot(x1, x2)
plt.show()
# 定义预测函数
def predict(X):
m = X.shape[0]
# 在x最前面插入全为1的列
X = np.hstack((np.ones((m, 1)), X))
# 求解假设函数的值(预测值)
h = hypothesis(X, theta)
# 根据概率值决定最终的分类,>=0.5为1类,<0.5为0类
h[h >=