剃度下降法

剃度下降

import sys
import numpy as np
 
x1 = np.array([2104, 1600, 2400, 1416, 3000])
x2 = np.array([3, 3, 3, 2, 4])
y = np.array([400, 330, 369, 232, 540])
a0 = 0.01
w0 = 1
w1 = 1
w2 = 1
j = 0
alp = 0.01
 
xx = []
yy = []
zz = []
 
 
def hy(xx1, xx2):
    return w0 + w1 * xx1 + w2 * xx2
 

while (j < 10000000):
    w0 = w0 - (hy(x1[j % 4], x2[j % 4]) - y[j % 4]) * alp * 1e-2
    w1 = w1 - (hy(x1[j % 4], x2[j % 4]) - y[j % 4]) * x1[j % 4] * alp * 1e-5
    w2 = w2 - (hy(x1[j % 4], x2[j % 4]) - y[j % 4]) * x2[j % 4] * alp * 1e-2
 

    xx.append(w0)
    yy.append(w1)
    zz.append(w2)
    if (abs(hy(x1[j % 4], x2[j % 4]) - y[j % 4]) < a0 and abs(
            (hy(x1[j % 4], x2[j % 4]) - y[j % 4]) * x1[j % 4]) < a0 and abs(
            (hy(x1[j % 4], x2[j % 4]) - y[j % 4]) * x2[j % 4]) < a0):
        print("true")
        print(hy(x1[j % 4], x2[j % 4]) - y[j % 4])
        print(abs((hy(x1[j % 4], x2[j % 4]) - y[j % 4]) * x1[j % 4]))
        print(abs((hy(x1[j % 4], x2[j % 4]) - y[j % 4]) * x2[j % 4]))
        print(w0, w1, w2)
    j = j + 1
 
print("Y")
plt.plot(xx,yy,zz,"*")
print((hy(x1[0], x2[0]) - y[0]))
print(w0, w1, w2)
plt.show()剃度下降法_第1张图片

 

你可能感兴趣的:(python)