梯度下降-python实现

import numpy as np
# 设定x,y对应的值,即二维空间对应的100个点
x = np.random.rand(100, 1)
y = 4 + (3*x) + (0.2 * np.random.rand(100, 1))
# 对每一行添加x0=1
x_b = np.c_[np.ones(shape=(100, 1)), x]
# 设定步长
eta = 0.1
# 设定迭代次数
n_iteration = 1000

# 利用迭代求解成本函数最小时的theta值
# 设定任意初始theta值,是两行一列数组
theta = np.random.rand(2, 1)
print('选取的初始θ值为:', theta)
for i in range(n_iteration):
    theta = theta - ((2 * eta * (x_b.T.dot(x_b.dot(theta) - y))) / 100)
print('迭代1000次的θ值为:', theta)

选取的初始θ值为: [[0.9779133 ]
[0.44816093]]
迭代1000次的θ值为: [[4.22714513]
[2.76511674]]

你可能感兴趣的:(机器学习,机器学习)