Python线性回归:代价函数与梯度下降算法实现
import numpy as np import pandas as pd
计算代价函数J(θ)
def computeCost(X, y, theta): # X 、 y 、 theta 与数据预处理参数保持一致 # 返回代价函数的值(参考编程要求中的代价函数函数) m = len(y) predictions = X.dot(theta) square_err = (predictions - y) ** 2 J = (1.0 / (2 * m)) * np.sum(square_err) 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): predictions = X.dot(theta) theta = theta - alpha * (1.0 / m) * X.T.dot(predictions - y) cost[i] = computeCost(X, y, theta) return theta, cost
原文地址: https://www.cveoy.top/t/topic/nvZJ 著作权归作者所有。请勿转载和采集!