Python 梯度下降函数实现 - 线性回归模型
下面是一个简单的梯度下降函数的示例,可以用于线性回归问题:
import numpy as np
def gradient_descent(X, y, theta, alpha, num_iters):
m = len(y)
J_history = np.zeros(num_iters)
for i in range(num_iters):
h = np.dot(X, theta)
error = h - y
theta = theta - (alpha/m) * np.dot(X.T, error)
J_history[i] = np.sum(error ** 2) / (2 * m)
return theta, J_history
其中,X是输入特征矩阵,y是输出向量,theta是模型参数向量,alpha是学习率,num_iters是迭代次数。函数返回最优的theta和每次迭代的损失函数值。
原文地址: https://www.cveoy.top/t/topic/lfhX 著作权归作者所有。请勿转载和采集!