04-11 随机森林代码(葡萄酒质量检测)
人工智能从入门到放弃完整教程目录:https://www.cnblogs.com/nickchen121/p/11686958.html
随机森林代码(葡萄酒质量检测)
一、导入模块
import pandas as pd
from sklearn import datasets
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
二、导入数据
X, y = datasets.load_wine(return_X_y=True)
三、数据预处理
le = LabelEncoder()
# 把label转换为0和1
y = le.fit_transform(y)
# 训练集和测试集比例为7:3
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.30, random_state=1)
四、训练模型
rf = RandomForestClassifier(n_estimators=1000, criterion='gini',
max_features='sqrt', min_samples_split=2, bootstrap=True)
rf = rf.fit(X_train, y_train)
五、度量模型
y_train_pred = rf.predict(X_train)
y_test_pred = rf.predict(X_test)
# 度量随机森林的准确性
tree_train = accuracy_score(y_train, y_train_pred)
tree_test = accuracy_score(y_test, y_test_pred)
print('随机森林训练集和测试集准确度分别为:{:.2f}/{:.2f}'.format(tree_train, tree_test))
随机森林训练集和测试集准确度分别为:1.00/0.98