随机森林python代码

Posted matrioc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了随机森林python代码相关的知识,希望对你有一定的参考价值。

载入数据

import pandas as pd

# Load data
melbourne_file_path = \'../input/melbourne-housing-snapshot/melb_data.csv\'
melbourne_data = pd.read_csv(melbourne_file_path) 
# Filter rows with missing price values
filtered_melbourne_data = melbourne_data.dropna(axis=0)
# Choose target and features
y = filtered_melbourne_data.Price
melbourne_features = [\'Rooms\', \'Bathroom\', \'Landsize\', \'BuildingArea\', 
                        \'YearBuilt\', \'Lattitude\', \'Longtitude\']
X = filtered_melbourne_data[melbourne_features]

分割数据

from sklearn.model_selection import train_test_split

# split data into training and validation data, for both features and target
# The split is based on a random number generator. Supplying a numeric value to
# the random_state argument guarantees we get the same split every time we
# run this script.
train_X, val_X, train_y, val_y = train_test_split(X, y, random_state = 0)

随机森林

from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error

forest_model = RandomForestRegressor(random_state=1)
forest_model.fit(train_X, train_y)
melb_preds = forest_model.predict(val_X)
print(mean_absolute_error(val_y, melb_preds))

以上是关于随机森林python代码的主要内容,如果未能解决你的问题,请参考以下文章

Python应用实战案例-深入浅出Python随机森林预测实战(附源码)

Python Scikit 随机森林回归器错误

将随机森林分类分解成python中的碎片?

R 和 Python 中随机森林回归的不同结果

使用 python sklearn 增量训练随机森林模型

如何在 python 中的大型数据集上训练随机森林?