目录随机森林代码(葡萄酒质量检测)一、导入模块二、导入数据三、数据预处理四、训练模型五、度量模型
更新、更全的《机器学习》的更新网站,更有python、go、数据结构与算法、爬虫、人工智能教学等着你: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
最新评论