使用 Python 实现线性回归的梯度下降算法
import numpy as np
import pandas as pd
# 计算代价函数 J(θ)
def computeCost(X, y, theta):
# X、y、theta 与数据预处理参数保持一致
# 返回代价函数的值
m = len(y)
J = np.sum(np.square(np.dot(X, theta) - y)) / (2 * m)
return J
# 批量梯度下降
# 返回参数 θ 的值和每次迭代后代价函数的值
def gradientDescent(X, y, theta, alpha, epoch):
# X、y、theta 与数据预处理参数保持一致
# alpha: 学习率 (取值: alpha = 0.01)
# epoch: 迭代次数 (取值: epoch = 1000)
cost = np.zeros(epoch) # 初始化一个 ndarray,包含每次 epoch 的 cost
m = len(y)
for i in range(epoch):
theta = theta - alpha / m * np.dot(X.T, np.dot(X, theta) - y)
cost[i] = computeCost(X, y, theta)
return theta, cost
原文地址: https://www.cveoy.top/t/topic/jUMf 著作权归作者所有。请勿转载和采集!