机器学习多元线性回归python
时间: 2024-09-20 22:00:55 浏览: 43
机器学习中的多元线性回归是一种预测模型,它假设因变量(目标值)与一个或多个自变量(特征)之间存在线性关系。在Python中,我们可以使用Scikit-Learn库来进行多元线性回归。以下是基本步骤:
1. 导入库:
```python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
```
2. 加载数据:
```python
data = pd.read_csv('your_data.csv') # 替换为你的数据文件路径
X = data[['feature1', 'feature2', 'feature3']] # 根据实际特征列名替换
y = data['target'] # 目标变量
```
3. 数据预处理(分割数据集,标准化等):
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
4. 创建并训练模型:
```python
model = LinearRegression()
model.fit(X_train, y_train)
```
5. 预测:
```python
y_pred = model.predict(X_test)
```
6. 评估模型性能:
```python
print("Mean Absolute Error:", metrics.mean_absolute_error(y_test, y_pred))
print("Mean Squared Error:", metrics.mean_squared_error(y_test, y_pred))
print("R-squared Score:", metrics.r2_score(y_test, y_pred))
```
阅读全文