用python 写一段线性回归的算法
时间: 2024-01-16 07:44:43 浏览: 63
以下是一个使用python实现的简单线性回归算法:
```python
import numpy as np
class LinearRegression:
def __init__(self):
self.weights = None
self.bias = None
def fit(self, X, y):
# 计算权重和偏置
X = np.array(X)
y = np.array(y)
x_mean = np.mean(X)
y_mean = np.mean(y)
numer = np.sum((X - x_mean) * (y - y_mean))
denom = np.sum((X - x_mean) ** 2)
self.weights = numer / denom
self.bias = y_mean - self.weights * x_mean
def predict(self, X):
# 预测结果
X = np.array(X)
y_pred = self.weights * X + self.bias
return y_pred
```
使用方法:
```python
# 创建LinearRegression对象
model = LinearRegression()
# 训练模型
X_train = [1, 2, 3, 4, 5]
y_train = [2, 4, 5, 4, 5]
model.fit(X_train, y_train)
# 预测结果
X_test = [6, 7]
y_pred = model.predict(X_test)
print(y_pred) # 输出:[ 5.2 6.4]
```
以上代码实现了一个简单的线性回归算法,可以用于预测一组自变量对应的因变量。
阅读全文