以下是用python 3.6编写的程序
import numpy as np
def linmodel(x, y, alp, ep):
x = np.array(x)
y = np.array(y)
(m, n) = x.shape
yh = np.zeros((m,1))
J = []
w = np.array(np.random.rand(n+1, 1))
for i in range(m):
yh[i][0] = np.matmul(x[i],w[1:])
yh[i][0] += w[0]
yh = np.array(yh)
J.append(0.5/m*sum((y-yh)**2))
err = 1
iter = 1
while(err>ep):
dj = np.zeros((n+1,1))
dj = np.array(dj)
pred_err = yh - y
dj[0][0] = sum(pred_err)/m
for j in range(1,n+1):
dj[j][0] = sum(pred_err * x[:][j-1])/m
w = w - alp*dj
for i in range(m):
yh[i][0] = np.matmul(x[i],w[1:])
yh[i][0] += w[0]
iter = iter+1
J.append(0.5/m*sum((y-yh)**2))
err = np.linalg.norm(alp*dj, 2)
T = np.array(range(-341,80))
T = T[::-20]
Talp = [6.47,6.36,6.24,6.12,6.00,5.86,5.72,5.58,5.43,5.28,5.09,4.91,4.72,4.52,4.3,4.08,3.83,3.58,3.33,3.07,2.76,2.45]
Talp = np.array(Talp)[np.newaxis]
Talp = Talp*(1.0E-6)
T = np.array(T)[np.newaxis]
x = T.T
y = Talp.T
alp = 0.1
ep = 1.0E-5
linmodel(x, y, alp, ep)
当我运行该程序时,出现运行时错误,这对我完全没有意义。
RuntimeWarning: overflow encountered in square
J.append(0.5/m*sum((y-yh)**2))
RuntimeWarning: overflow encountered in multiply
dj[j][0] = sum(pred_err * x[:][j-1])/m
RuntimeWarning: invalid value encountered in add
dj[j][0] = sum(pred_err * x[:][j-1])/m
我== 此错误的原因是什么? 我该如何纠正?