多元线性回归python编程
时间: 2024-08-13 17:02:36 浏览: 53
多元线性回归是一种预测模型,它假设因变量(目标变量)与一个或多个自变量(特征变量)之间存在线性关系。在Python中,可以使用sklearn库的LinearRegression模块来进行多元线性回归分析。以下是基本步骤:
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. 加载数据(例如CSV文件)并预处理:
```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)
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))
```
阅读全文