你能用python写一个函数z=(x-2)2+(y-1)2+10,用梯度下降求最小值的代码吗
时间: 2023-03-15 14:10:47 浏览: 96
python实现梯度下降算法
可以的,代码如下:import numpy as npdef z(x, y):
return (x - 2)**2 + (y - 1)**2 + 10def gradient_descent(x, y, learning_rate):
grad_x = 2 * (x - 2)
grad_y = 2 * (y - 1)
x = x - learning_rate * grad_x
y = y - learning_rate * grad_y
return x, yif __name__=='__main__':
x = y = 0
learning_rate = 0.1
for i in range(101):
x, y = gradient_descent(x, y, learning_rate)
z_val = z(x, y)
print('Iter: {}, x: {}, y: {}, z: {}'.format(i, x, y, z_val))
阅读全文