使用sklearn的python库来建立一个线性回归模型来预测,并包含模型评估的代码
时间: 2024-10-23 08:04:08 浏览: 34
python源码集锦-多元线性回归模型预测房价
5星 · 资源好评率100%
要使用Python的scikit-learn (sklearn) 库建立一个多元线性回归模型来预测,你可以按照以下步骤操作[^1]:
1. **导入必要的库**:
```python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
import seaborn as sns
import matplotlib.pyplot as plt
```
2. **加载数据**:
假设你有一个CSV文件,其中包含特征和目标变量。
```python
data = pd.read_csv('your_data.csv')
X = data.drop('target_column', axis=1)
y = data['target_column']
```
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)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"Mean Squared Error: {mse:.2f}")
print(f"R-squared Score: {r2:.2f}")
```
6. **模型可视化** (可选):
```python
sns.scatterplot(x=y_test, y=y_pred)
plt.xlabel('Actual Target')
plt.ylabel('Predicted Target')
plt.title('Linear Regression Model Prediction')
plt.show()
```
记得替换`your_data.csv`和`target_column`为你实际的数据文件名和目标列名称。
阅读全文