线性回归算法样例,python语言编写
时间: 2023-08-04 17:11:57 浏览: 47
好的,这是一个简单的线性回归算法的Python代码样例:
```python
import numpy as np
class LinearRegression:
def __init__(self, lr=0.01, epochs=1000):
self.lr = lr
self.epochs = epochs
self.weights = None
self.bias = None
def fit(self, X, y):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0
for _ in range(self.epochs):
y_pred = np.dot(X, self.weights) + self.bias
dw = (1/n_samples) * np.dot(X.T, (y_pred - y))
db = (1/n_samples) * np.sum(y_pred - y)
self.weights -= self.lr * dw
self.bias -= self.lr * db
def predict(self, X):
y_pred = np.dot(X, self.weights) + self.bias
return y_pred
```
使用方法如下:
```python
# 导入数据,X和y分别为输入和输出数据
X = ...
y = ...
# 创建线性回归模型并训练
model = LinearRegression()
model.fit(X, y)
# 使用模型进行预测
X_test = ...
y_pred = model.predict(X_test)
```