python 实现 Linear模型
时间: 2024-01-31 12:01:57 浏览: 16
下面是一个简单的Python实现线性模型的示例代码:
```python
import numpy as np
class LinearRegression:
def __init__(self, learning_rate=0.01, n_iterations=1000):
self.learning_rate = learning_rate
self.n_iterations = n_iterations
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 i in range(self.n_iterations):
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.learning_rate * dw
self.bias -= self.learning_rate * db
def predict(self, X):
y_predicted = np.dot(X, self.weights) + self.bias
return y_predicted
```
这个示例代码中,我们使用梯度下降算法实现了线性回归模型。在 `__init__` 方法中我们定义了模型的超参数,包括学习率和迭代次数。在 `fit` 方法中,我们使用梯度下降算法来计算模型的权重和偏置,使得模型的预测值与真实值之间的误差最小化。在 `predict` 方法中,我们使用训练好的模型来预测新的数据样本。