python2.回归模型的参数估计算法代码
时间: 2023-10-02 22:13:11 浏览: 41
以下是一个简单的线性回归模型的参数估计算法的Python代码示例:
```
import numpy as np
#生成样本数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([3, 5, 7, 9, 11])
#添加偏置项
x = np.column_stack((np.ones(len(x)), x))
#初始化参数
theta = np.zeros(x.shape[1])
#定义代价函数
def cost_function(x, y, theta):
m = len(y)
J = np.sum((x.dot(theta) - y) ** 2) / (2 * m)
return J
#定义梯度下降函数
def gradient_descent(x, y, theta, alpha, num_iters):
m = len(y)
J_history = np.zeros(num_iters)
for i in range(num_iters):
theta = theta - (alpha / m) * x.T.dot(x.dot(theta) - y)
J_history[i] = cost_function(x, y, theta)
return theta, J_history
#运行梯度下降算法
alpha = 0.01
num_iters = 1000
theta, J_history = gradient_descent(x, y, theta, alpha, num_iters)
#输出参数估计结果
print('Theta found by gradient descent: {:.4f}, {:.4f}'.format(theta[0], theta[1]))
```
该代码使用梯度下降算法对线性回归模型进行参数估计,并使用样本数据进行示例运行。