用python编程,设y是x的二次函数,选取测量的100组x和y数据,用梯度下降法求最优函数,学习率为0.01,迭代1000次
时间: 2023-04-10 08:03:23 浏览: 53
可以使用以下代码实现:
import numpy as np
# 生成随机数据
x = np.random.rand(100)
y = 2 * x ** 2 + np.random.randn(100) * 0.1
# 初始化参数
theta = np.random.randn(2)
# 定义梯度下降函数
def gradient_descent(x, y, theta, alpha, iterations):
m = len(y)
for i in range(iterations):
h = np.dot(x, theta)
loss = h - y
gradient = np.dot(x.T, loss) / m
theta -= alpha * gradient
return theta
# 添加偏置项
x = np.c_[np.ones((100, 1)), x]
# 运行梯度下降算法
theta = gradient_descent(x, y, theta, 0.01, 1000)
# 输出最优函数
print("最优函数为:y = {:.2f} + {:.2f}x^2".format(theta[0], theta[1]))