#训练集(x,y)共 5 个样本,每个样本点有 3 个分量 (x0,x1,x2) x = [(1, 0., 3), (1, 1., 3), (1, 2., 3), (1, 3., 2), (1, 4., 4)] y = [95.364, 97.217205, 75.195834, 60.105519, 49.342380] #y[i] 样本点对应的输出 epsilon = 0.0001 #迭代阀值,当两次迭代损失函数之差小于该阀值时停止迭代 alpha = 0.01 #学习率 diff = [0, 0] max_itor = 1000 error1 = 0 error0 = 0 cnt = 0 m = len(x) #初始化参数 theta0 = 0 theta1 = 0 theta2 = 0 while True: cnt += 1 # 参数迭代计算 for i in range(m): # 拟合函数为 y = theta0 * x[0] + theta1 * x[1] +theta2 * x[2] # 计算残差,即拟合函数值-真实值 diff[0] = (theta0* x[i][0] + theta1 * x[i][1] + theta2 * x[i][2]) -y[i] # 梯度 = diff[0] * x[i][j]。根据步长*梯度更新参数 theta0 -= alpha * diff[0] * x[i][0] theta1 -= alpha * diff[0] * x[i][1] theta2 -= alpha * diff[0] * x[i][2] # 计算损失函数 error1 = 0 for lp in range(len(x)): error1 += (y[lp]-(theta0* x[lp][0] + theta1 * x[lp][1] + theta2 *x[lp][2]))**2/2 #若当两次迭代损失函数之差小于该阀值时停止迭代,跳出循环; if abs(error1-error0) < epsilon: break else: error0 = error1 print(' theta0 : %f, theta1 : %f, theta2 : %f, error1 : %f' % (theta0, theta1, theta2, error1) ) print('Done: theta0 : %f, theta1 : %f, theta2 : %f' % (theta0, theta1, theta2) ) print('迭代次数: %d' % cnt )解决代码无法输出迭代过程
时间: 2024-03-27 17:40:25 浏览: 86
要输出迭代过程,可以将每次迭代的参数和损失函数值记录下来,最后一起输出。具体修改代码如下:
```python
# 记录每次迭代的参数和损失函数值
theta0_list = []
theta1_list = []
theta2_list = []
error_list = []
while True:
cnt += 1
# 参数迭代计算
for i in range(m):
# 拟合函数为 y = theta0 * x[0] + theta1 * x[1] +theta2 * x[2]
# 计算残差,即拟合函数值-真实值
diff[0] = (theta0* x[i][0] + theta1 * x[i][1] + theta2 * x[i][2]) -y[i]
# 梯度 = diff[0] * x[i][j]。根据步长*梯度更新参数
theta0 -= alpha * diff[0] * x[i][0]
theta1 -= alpha * diff[0] * x[i][1]
theta2 -= alpha * diff[0] * x[i][2]
# 计算损失函数
error1 = 0
for lp in range(len(x)):
error1 += (y[lp]-(theta0* x[lp][0] + theta1 * x[lp][1] + theta2 *x[lp][2]))**2/2
# 记录参数和损失函数值
theta0_list.append(theta0)
theta1_list.append(theta1)
theta2_list.append(theta2)
error_list.append(error1)
# 若当两次迭代损失函数之差小于该阀值时停止迭代,跳出循环;
if abs(error1-error0) < epsilon:
break
else:
error0 = error1
# 输出迭代过程
for i in range(len(theta0_list)):
print('第%d次迭代: theta0 : %f, theta1 : %f, theta2 : %f, error : %f' % (i+1, theta0_list[i], theta1_list[i], theta2_list[i], error_list[i]))
print('Done: theta0 : %f, theta1 : %f, theta2 : %f' % (theta0, theta1, theta2) )
print('迭代次数: %d' % cnt )
```
这样修改后,每次迭代的参数和损失函数值都会被记录下来,并输出迭代过程。
阅读全文