呆板学习讲堂5二分类与逻辑回归

[复制链接]
发表于 2025-10-4 02:34:27 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
1.2-8线性回归举行二分类

代码
  1. #  2-8线性回归进行二分类
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. #  参数设置
  5. iterations = 20  # 迭代次数
  6. learning_rate = 0.1  # 学习率
  7. dataset = 1  # 选择训练数据集
  8. threshold = 0.5  # 判决门限
  9. # 训练数据集
  10. if dataset == 1:  # 数据集1
  11.     x_train = np.array([50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70]).reshape(
  12.         (1, -1))
  13.     y_train = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]).reshape((1, -1))
  14. elif dataset == 2:  # 数据集2
  15.     x_train = np.array(
  16.         [0, 5, 10, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70]).reshape((-1, 1))
  17.     y_train = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]).reshape((1, -1))
  18. m_train = x_train.size  # 训练样本数量
  19. # 标准化输入特征
  20. mean = np.mean(x_train)
  21. std = np.std(x_train, ddof=1)
  22. x_train = (x_train - mean) / std
  23. # 初始化
  24. w, b = 0, 0
  25. v = np.ones((1, m_train)).reshape((1, -1))
  26. costs_saved = []
  27. # 梯度下降法
  28. for i in range(iterations):
  29.     e = w * x_train + b * v - y_train
  30.     b = b - 2. * learning_rate * np.dot(v, e.T) / m_train
  31.     w = w - 2. * learning_rate * np.dot(x_train, e.T) / m_train
  32.     #  保存代价函数值
  33.     costs = np.dot(e, e.T) / m_train
  34.     costs_saved.append(costs.item(0))
  35. #  打印最新权重与偏差
  36. print(f'Weight={w.item(0):.3f}')
  37. print(f'Bias={b.item(0):.3f}')
  38. # 画代价函数值
  39. plt.plot(range(1, np.size(costs_saved) + 1), costs_saved, 'r-o', linewidth=2, markersize=5)
  40. plt.ylabel('costs')
  41. plt.xlabel('itertions')
  42. plt.title('learning rate=' + str(learning_rate))
  43. plt.show()
  44. y_train_hat = (w * x_train + b) >= threshold
  45. print('Trainset class:', np.array2string(np.squeeze(y_train, axis=0)))
  46. print('Predicted class:', np.array2string(np.squeeze(y_train_hat.astype(int), axis=0)))
  47. # 画拟合直线
  48. plt.figure()
  49. plt.plot(x_train[0] * std + mean, y_train[0], 'xc', markersize=12, markeredgewidth=2,
  50.          label='training examples')
  51. plt.plot(x_train[1:] * std + mean, y_train[1:], 'xc', markersize=12, markeredgewidth=2)  # 画训练样本
  52. plot_x = np.arange(np.amin(x_train), np.amax(x_train) + 0.01, 0.01).reshape((-1, 1))  # 生成用于画图的x坐标
  53. plot_y = w * plot_x + b  # 拟合直线y坐标)
  54. plot_x = plot_x * std + mean  # 特征缩放的逆过程
  55. plt.plot(plot_x, plot_y >= threshold, '--y', linewidth=2, label='predicted grade')  # 画判决后的类别值
  56. plt.plot(plot_x, plot_y, 'r', linewidth=2, label='Fittted straight line')  # 画拟合直线
  57. plt.xlabel('Points')
  58. plt.ylabel('Grade')
  59. plt.legend()
  60. plt.show()
  61. 结果图<img alt=""  src="[img]https://dis.qidao123.com/imgproxy/aHR0cHM6Ly9pLWJsb2cuY3NkbmltZy5jbi9kaXJlY3QvYmVkMzU5NjZhZWU1NGYwZTlmMmQ5YzI1MzY5ODlkNzAucG5n[/img]"  />
复制代码
2.2-9逻辑回归分类猜测

代码
  1. #  2-9逻辑回归分类预测
  2. import pandas as pd
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. #  参数设置
  6. iterations = 1000  # 迭代次数
  7. learning_rate = 0.1  # 学习率
  8. m_train = 250  # 训练样本数量
  9. # 读入酒驾检测数据集
  10. df = pd.read_csv('alcohol_dataset.csv')
  11. data=np.array(df)
  12. m_all = np.shape(data)[0]  # 样本总数
  13. d =np.shape(data)[1] - 1  # 输入特征的维数
  14. m_test = m_all - m_train  # 测试数据集样本数量
  15. # 构造随机种子为指定值的随机数生成器,并对数据集中样本随机排序
  16. rng=np.random.default_rng(1)
  17. rng.shuffle(data)
  18. # 对输入特征标准化
  19. mean=np.mean(data[0:m_train, 0:d], axis=0)  # 计算训练样本输入特征的均值
  20. std=np.std(data[0:m_train, 0:d], axis=0, ddof=1)  # 计算训练样本输入特诊的标准差
  21. data[:, 0:d]=(data[:, 0:d]-mean)/std  # 标准化所有样本的输入特征
  22. # 划分数据集
  23. X_train = data[0:m_train, 0:d].T  # 训练集输入特征
  24. X_test = data[m_train:, 0:d].T  # 测试集输入特征
  25. Y_train = data[0:m_train, d].reshape((1, -1))  # 训练集目标值
  26. Y_test = data[m_train:, d].reshape((1, -1))  # 测试集目标值
  27. # 初始化
  28. w = np.zeros((d, 1)).reshape((-1, 1))  # 权重
  29. b = 0  # 偏差(标量)
  30. v = np.ones((1, m_train))  # 1向量
  31. costs_saved = []  # 用于保存代价函数的值
  32. # 训练过程,迭代循环
  33. for i in range(iterations):  # 更新权重与偏差
  34.     z=np.dot(w.T, X_train)+ b * v  # 线性回归部分
  35.     Y_hat = 1./(1+np.exp(-z))
  36.     e = Y_hat - Y_train  # 计算误差
  37.     Y_1_Y_hat=Y_hat * (1-Y_hat)
  38.     b = b - 2. * learning_rate * np.dot(Y_1_Y_hat, e.T) / m_train  # 更新偏差
  39.     w = w - 2. * learning_rate * np.dot(X_train, (Y_1_Y_hat*e).T) / m_train  # 更新权重
  40.     # 保存代价函数的值
  41.     costs = np.dot(e, e.T) / m_train
  42.     costs_saved.append(costs.item(0))
  43. #  打印最新权重与偏差
  44. print('Weights=', np.array2string(np.squeeze(w, axis=1), precision=3))
  45. print(f'Bias={b.item(0):.3f}')
  46. # 画代价函数值
  47. plt.plot(range(1, np.size(costs_saved) + 1), costs_saved, 'r-o', linewidth=2, markersize=5)
  48. plt.ylabel('costs')
  49. plt.xlabel('itertions')
  50. plt.title('learning rate=' + str(learning_rate))
  51. plt.show()
  52. # 训练数据集上的分类错误
  53. Y_train_hat = (np.dot(w.T, X_train) + b * v) >= 0
  54. errors_train=np.sum(np.abs(Y_train_hat-Y_train))
  55. print('Trainset Predicted errors=', errors_train.astype(int))
  56. # 测试数据集上的分类错误
  57. Y_test_hat=(np.dot(w.T,X_test)+b)>=0
  58. errors_test=np.sum(np.abs(Y_test_hat-Y_test))
  59. print('Testset Predicted errors=', errors_test.astype(int))
复制代码
结果图

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表