当前位置:   article > 正文

Python机器学习1:线性回归与Logistic回归代码_python logistic代码

python logistic代码

记录机器学习中涉及的代码...


1. 线性回归分析

分析对象

生成 y=4+3*x函数的随机值,采用梯度下降算法进行代价函数计算。

计算程序

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # 生成一些模拟数据
  4. np.random.seed(0)
  5. X = 2 * np.random.rand(100, 1)
  6. y = 4 + 3 * X + np.random.randn(100, 1)
  7. # 在 X 前添加一列,用于计算截距
  8. X_b = np.c_[np.ones((100, 1)), X]
  9. # 设置梯度下降的参数
  10. eta = 0.001 # 学习率
  11. n_iterations = 1000
  12. # 随机初始化参数
  13. theta = np.random.randn(2, 1)
  14. # 初始化一个数组用于存储每次迭代的代价函数值
  15. cost_history = np.zeros(n_iterations)
  16. # 使用梯度下降算法求解参数
  17. for iteration in range(n_iterations):
  18. # 计算梯度
  19. gradients = 2/100 * X_b.T.dot(X_b.dot(theta) - y)
  20. # 更新参数
  21. theta = theta - eta * gradients
  22. # 计算代价函数并存储
  23. cost = np.mean((X_b.dot(theta) - y) ** 2)
  24. cost_history[iteration] = cost
  25. # 打印最终的参数
  26. print("最终参数(theta):", theta)
  27. # 绘制原始数据和拟合的直线
  28. plt.scatter(X, y)
  29. plt.plot(X, X_b.dot(theta), 'r-')
  30. plt.xlabel('X')
  31. plt.ylabel('y')
  32. plt.title('Linear Regression with Gradient Descent')
  33. # 绘制代价函数计算结果曲线
  34. plt.figure()
  35. plt.plot(range(1, n_iterations + 1), cost_history, color='blue')
  36. plt.xlabel('Iterations')
  37. plt.ylabel('Cost')
  38. plt.title('Cost Function Over Iterations')
  39. plt.show()

运行结果

theta参数为:

[[3.86291512]  [3.15339547]]

 

 说明

  • np.c_ 是 NumPy 中的一个类,它用于按列连接两个矩阵,类似于 np.column_stack。在上述代码中,np.c_ 用于在生成的随机数据 X 中添加一列偏置项,这是 logistic 回归中常用的操作。
  • np.hstack 是 NumPy 中的函数,用于在水平方向上(按列)堆叠数组。具体而言,np.hstack 将两个数组水平堆叠在一起,形成一个新的数组。在上述代码中,np.hstack((np.ones((num_samples, 1)), X)) 的目的是在数据集 X 的左侧添加一列全为 1 的列,即添加偏置项,以便在模型中使用。这是为了表示线性方程中的截距项。

  • 在代码的开头使用 np.random.seed(0) 是为了确保在生成随机数据时得到可重复的结果。通过设置随机种子(seed),可以使得每次运行程序时生成的随机数相同,这对于调试和验证代码的结果很有帮助。如果省略了 np.random.seed(0),每次运行程序时都会得到不同的随机数据,这可能导致结果的不确定性

2. Logistic分析

分析对象

计算程序

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from mpl_toolkits.mplot3d import Axes3D
  4. # 步骤1:生成数据集
  5. np.random.seed(0)
  6. num_samples = 100
  7. # 在范围[-1, 1]内生成随机数据
  8. X = np.random.rand(num_samples, 2) * 2 - 1
  9. # 如果 x1**2 + x2**2 小于1.0,则设置 y=1.0,否则设置 y=0.0
  10. y = (X[:, 0]**2 + X[:, 1]**2 < 1.0).astype(float)
  11. # 步骤2:定义逻辑函数及其梯度
  12. def sigmoid(z):
  13. return 1.0 / (1.0 + np.exp(-z))
  14. def sigmoid_gradient(z):
  15. return sigmoid(z) * (1 - sigmoid(z))
  16. # 步骤3:实现梯度下降
  17. def gradient_descent(X, y, learning_rate, num_iterations):
  18. num_samples, num_features = X.shape
  19. # 添加偏置列和输入特征的平方列
  20. X = np.hstack((np.ones((num_samples, 1)), X, np.square(X)))
  21. # 初始化参数
  22. theta = np.zeros(num_features + 2 + 1) # 包括偏置项和平方项
  23. # 记录每次迭代的代价
  24. costs = []
  25. for _ in range(num_iterations):
  26. # 计算预测值
  27. predictions = sigmoid(np.dot(X, theta))
  28. # 计算代价函数
  29. cost = -np.mean(y * np.log(predictions) + (1 - y) * np.log(1 - predictions))
  30. costs.append(cost)
  31. # 计算梯度
  32. gradient = np.dot(X.T, (predictions - y)) / num_samples
  33. # 更新参数
  34. theta -= learning_rate * gradient
  35. return theta, costs
  36. # 步骤4:绘制代价函数曲线和决策边界
  37. def plot_results(X, y, theta, costs):
  38. fig = plt.figure(figsize=(12, 8))
  39. # 绘制代价函数曲线
  40. ax1 = fig.add_subplot(221)
  41. ax1.plot(costs)
  42. ax1.set_title('Cost Function')
  43. # 绘制数据点
  44. ax2 = fig.add_subplot(222, projection='3d')
  45. ax2.scatter(X[:, 0], X[:, 1], y, c=y, cmap='viridis')
  46. ax2.set_title('Data Points')
  47. # 绘制决策边界
  48. ax3 = fig.add_subplot(223, projection='3d')
  49. x1_vals, x2_vals = np.meshgrid(np.linspace(-1, 1, 100), np.linspace(-1, 1, 100))
  50. X_vals = np.c_[x1_vals.flatten(), x2_vals.flatten()]
  51. X_vals = np.hstack((np.ones((X_vals.shape[0], 1)), X_vals, np.square(X_vals)))
  52. decision_boundary = sigmoid(np.dot(X_vals, theta))
  53. decision_boundary = decision_boundary.reshape(x1_vals.shape)
  54. ax3.plot_surface(x1_vals, x2_vals, decision_boundary, cmap='viridis', alpha=0.5)
  55. ax3.scatter(X[:, 0], X[:, 1], y, c=y, cmap='viridis')
  56. ax3.set_title('Decision Boundary')
  57. plt.show()
  58. # 运行梯度下降
  59. learning_rate = 0.1
  60. num_iterations = 20000
  61. theta, costs = gradient_descent(X, y, learning_rate, num_iterations)
  62. # 打印学到的参数
  63. print(theta)
  64. # 绘制结果
  65. plot_results(X, y, theta, costs)
  66. # 说明:
  67. #
  68. # 数据生成:在范围[-1, 1]内生成随机数据,并根据一个圆形区域分配标签。
  69. # 逻辑函数:定义逻辑函数及其梯度,用于逻辑回归。
  70. # 梯度下降:实现梯度下降,优化逻辑回归参数。
  71. # 绘图结果:绘制代价函数曲线、数据点和决策边界的三维图。

运行结果

theta参数为:

[ 12.34895505   0.68837517  -0.0789526  -11.50124612 -13.1030072 ]

3. Logistic分析,采用正则化

分析对象

计算程序

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from mpl_toolkits.mplot3d import Axes3D
  4. # 步骤1:生成数据集
  5. np.random.seed(0)
  6. num_samples = 1000
  7. X = np.random.rand(num_samples, 2) * 2 - 1 # 生成在[-1, 1]范围内的随机数据
  8. y = (X[:, 0]**2 + X[:, 1]**2 < 1.0).astype(float)
  9. # 步骤2:定义 logistic 函数及其梯度
  10. def sigmoid(z):
  11. return 1.0 / (1.0 + np.exp(-z))
  12. def sigmoid_gradient(z):
  13. return sigmoid(z) * (1 - sigmoid(z))
  14. # 步骤3:实现带有 L2 正则化的梯度下降
  15. def gradient_descent_with_regularization(X, y, learning_rate, num_iterations, alpha):
  16. num_samples, num_features = X.shape
  17. X = np.hstack((np.ones((num_samples, 1)), X, np.square(X))) # 添加一列偏置项
  18. # 初始化参数
  19. theta = np.zeros(num_features + 2 + 1)
  20. # 记录每次迭代的代价
  21. costs = []
  22. for _ in range(num_iterations):
  23. # 计算预测值
  24. predictions = sigmoid(np.dot(X, theta))
  25. # 计算带有正则化的代价函数
  26. cost = -np.mean(y * np.log(predictions) + (1 - y) * np.log(1 - predictions)) + (alpha / (2 * num_samples)) * np.sum(theta[1:]**2)
  27. costs.append(cost)
  28. # 计算梯度
  29. gradient = (np.dot(X.T, (predictions - y)) + alpha * np.hstack((0, theta[1:]))) / num_samples
  30. # 更新参数
  31. theta -= learning_rate * gradient
  32. return theta, costs
  33. # 步骤4:绘制代价函数曲线和决策边界
  34. def plot_results(X, y, theta, costs):
  35. fig = plt.figure(figsize=(12, 8))
  36. # 绘制代价函数曲线
  37. ax1 = fig.add_subplot(221)
  38. ax1.plot(costs)
  39. ax1.set_title('Cost Function')
  40. # 绘制数据点
  41. ax2 = fig.add_subplot(222, projection='3d')
  42. ax2.scatter(X[:, 0], X[:, 1], y, c=y, cmap='viridis')
  43. ax2.set_title('Data Points')
  44. # 绘制决策边界
  45. ax3 = fig.add_subplot(223, projection='3d')
  46. x1_vals, x2_vals = np.meshgrid(np.linspace(-1, 1, 100), np.linspace(-1, 1, 100))
  47. X_vals = np.c_[x1_vals.flatten(), x2_vals.flatten()]
  48. X_vals = np.hstack((np.ones((X_vals.shape[0], 1)), X_vals, np.square(X_vals)))
  49. decision_boundary = sigmoid(np.dot(X_vals, theta))
  50. decision_boundary = decision_boundary.reshape(x1_vals.shape)
  51. ax3.plot_surface(x1_vals, x2_vals, decision_boundary, cmap='viridis', alpha=0.5)
  52. ax3.scatter(X[:, 0], X[:, 1], y, c=y, cmap='viridis')
  53. ax3.set_title('Decision Boundary')
  54. plt.show()
  55. # 运行梯度下降(使用正则化)
  56. learning_rate = 0.1
  57. num_iterations = 20000
  58. alpha = 10 # 正则化参数
  59. theta, costs = gradient_descent_with_regularization(X, y, learning_rate, num_iterations, alpha)
  60. # 打印学到的参数
  61. print(theta)
  62. # 绘制结果
  63. plot_results(X, y, theta, costs)

运行结果

随着正则参数增加,theta参数逐渐变小。样本数量越多,代价函数最终值也会越低。

theta参数:

[ 3.47261718 -0.06700464 -0.06413931 -2.89488142 -2.78282584]

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/629930
推荐阅读
相关标签
  

闽ICP备14008679号