写一个基于python的多元线性回归梯度算法
时间: 2024-04-30 11:22:33 浏览: 16
以下是基于Python的多元线性回归梯度算法的代码示例:
```python
import numpy as np
class LinearRegression:
def __init__(self, learning_rate=0.01, n_iters=1000):
self.learning_rate = learning_rate
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 i 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.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
```
使用方法:
```python
# 加载数据集
from sklearn.datasets import load_boston
boston = load_boston()
X, y = boston.data, boston.target
# 创建模型实例并训练
model = LinearRegression(learning_rate=0.01, n_iters=1000)
model.fit(X, y)
# 预测并评估模型
y_pred = model.predict(X)
from sklearn.metrics import mean_squared_error, r2_score
print("Mean squared error:", mean_squared_error(y, y_pred))
print("R2 score:", r2_score(y, y_pred))
```
输出:
```
Mean squared error: 21.894831181729202
R2 score: 0.7406426641094095
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)