python随机森林进行回归预测代码
时间: 2023-09-09 15:07:21 浏览: 101
您可以分享以下 Python 随机森林进行回归预测的代码:
首先,需要导入必要的库:
```python
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import pandas as pd
import numpy as np
```
接着,读取数据:
```python
df = pd.read_csv('data.csv')
```
将数据集分为训练集和测试集:
```python
X = df.drop('target_variable', axis=1)
y = df['target_variable']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
定义模型并进行训练:
```python
rf = RandomForestRegressor(n_estimators=10, random_state=42)
rf.fit(X_train, y_train)
```
用训练好的模型进行预测:
```python
y_pred = rf.predict(X_test)
```
计算模型预测的均方误差:
```python
mse = mean_squared_error(y_test, y_pred)
```
完整的代码示例如下:
```python
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import pandas as pd
import numpy as np
# 读取数据
df = pd.read_csv('data.csv')
# 将数据集分为训练集和测试集
X = df.drop('target_variable', axis=1)
y = df['target_variable']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义模型并进行训练
rf = RandomForestRegressor(n_estimators=10, random_state=42)
rf.fit(X_train, y_train)
# 用训练好的模型进行预测
y_pred = rf.predict(X_test)
# 计算模型预测的均方误差
mse = mean_squared_error(y_test, y_pred)
```
阅读全文