#计算代价函数J(θ) def computeCost(X, y, theta): # X 、 y 、 theta 与数据预处理参数保持一致 #返回代价函数的值(参考编程要求中的代价函数函数) #********** Begin # m = len(y) J = np.sum(np.square(np.dot(X, theta) - y)) / (2 * m) # End **********# 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 #********** Begin # 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) # End **********# return theta, cos

import numpy as npimport pandas as pd#计算代价函数Jθdef computeCostX y theta# X 、 y 、 theta 与数据预处理参数保持一致#返回代价函数的值参考编程要求中的代价函数函数# Begin ## End ##批量梯度下降#返回参数 θ 的值和每次迭代后代价函数的值梯度下降公式参考编程要求梯度下降公式def gradientDesc

原文地址: https://www.cveoy.top/t/topic/cso3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录