写一个linearregression.fit()函数代码的例子
时间: 2024-05-13 07:17:33 浏览: 144
好的,以下是一个简单的线性回归模型的fit函数实现示例:
```python
import numpy as np
class LinearRegression:
def __init__(self, lr=0.01, n_iters=1000):
self.lr = lr
self.n_iters = n_iters
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.n_iters):
y_predicted = np.dot(X, self.weights) + self.bias
dw = (1 / n_samples) * np.dot(X.T, (y_predicted - y))
db = (1 / n_samples) * np.sum(y_predicted - y)
self.weights -= self.lr * dw
self.bias -= self.lr * db
def predict(self, X):
y_predicted = np.dot(X, self.weights) + self.bias
return y_predicted
```
其中,fit函数使用梯度下降法更新权重和偏差,训练模型。X是输入样本的特征矩阵,y是对应的目标值。在这个例子中,我们只考虑一个单变量的线性回归模型。
阅读全文