集成学习实验
实验要求
1.模型:Random Forest和Gradient Tree Boosting;
2.数据:自行下载;
3.要求:对比两种方法的回归/分类;
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import RandomForestRegressor,GradientBoostingRegressor,RandomForestClassifier,GradientBoostingClassifier
from sklearn.metrics import mean_squared_error
datasets = pd.read_csv("pulsar_stars.csv", header=0)
data = datasets.values
features = data[::, 1:-1]
labels = data[::, -1]train_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size=0.1, random_state=0) #RandomForestRegressor模型
rf = RandomForestRegressor() # 这里使用了默认的参数设置
rf.fit(train_features, train_labels) # 进行模型的训练
test_predict=rf.predict(test_features)mse=mean_squared_error(test_predict,test_labels)print('Mse of RandomForestRegressor:',mse) #GradientBoostingRegressor模型
rf1 = GradientBoostingRegressor() # 这里使用了默认的参数设置
rf1.fit(train_features, train_labels) # 进行模型的训练
test_predict_01=rf1.predict(test_features)
mse1=mean_squared_error(test_predict_01,test_labels)
print('Mse of GradientBoostingRegressor:',mse1) #RandomForestClassifier模型
rf2 = RandomForestClassifier() # 这里使用了默认的参数设置rf2.fit(train_features, train_labels) # 进行模型的训练test_predict_02=rf2.predict(test_features)
mse2=mean_squared_error(test_predict_02,test_labels)
print('Mse of RandomForestClassifier:',mse2)
#GradientBoostingClassifier模型
rf3 = GradientBoostingClassifier()
# 这里使用了默认的参数设置
rf3.fit(train_features, train_labels)
# 进行模型的训练test_predict_03=rf3.predict(test_features)
mse3=mean_squared_error(test_predict_03,test_labels)
print('Mse of GradientBoostingClassifier:',mse3)
实验结果:
实验结果分析调用了sklearn库中已经集成的随机森林回归,分类函数以及梯度提升树回归,分类函数。比较算法在数据集"pulsar_stars.csv"上的表现效果。从实验结果上看出,在做回归任务时,梯度提升树算法的均方误差较小,(0.014<0.015);在分类任务中,随机森林分类器的均方误差小,(0.015<0.017).