线性回归方法模拟sin函数
时间: 2023-12-31 12:03:42 浏览: 79
以下是使用线性回归方法模拟sin函数的Python代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 构造训练数据
x_train = np.linspace(0, 2*np.pi, 100)
y_train = np.sin(x_train)
# 初始化参数
theta = np.random.randn(2, 1)
# 定义模型函数
def model(X, theta):
return X @ theta
# 定义损失函数
def cost_function(X, y, theta):
m = len(y)
J = 1/(2*m) * np.sum((model(X, theta) - y)**2)
return J
# 定义梯度下降函数
def gradient_descent(X, y, theta, learning_rate, num_iterations):
m = len(y)
J_history = np.zeros(num_iterations)
for i in range(num_iterations):
theta = theta - learning_rate/m * X.T @ (model(X, theta)-y)
J_history[i] = cost_function(X, y, theta)
return theta, J_history
# 加入偏置项
X_train = np.c_[np.ones(len(x_train)), x_train]
# 训练模型
learning_rate = 0.1
num_iterations = 1000
theta, J_history = gradient_descent(X_train, y_train, theta, learning_rate, num_iterations)
# 预测结果
x_test = np.linspace(0, 2*np.pi, 100)
X_test = np.c_[np.ones(len(x_test)), x_test]
y_predict = model(X_test, theta)
# 绘制结果
plt.plot(x_train, y_train, 'ro', label='Training data')
plt.plot(x_test, y_predict, label='Linear regression')
plt.legend()
plt.show()
```
运行代码后,将会绘制出训练数据和线性回归模拟的sin函数的图像。可以看到,线性回归模型可以在一定程度上拟合sin函数的曲线。
阅读全文