一.算法简介Bagging思想并行由多个弱学习器预测结果最红综合所有结果给出最终结果代表算法为随机森林。Boosting思想串行下一个学习器纠正上一个学习器的错误从而提高学习器的性能代表算法为Adaboost提高错误样本的权重减小正确样本的权重、GBDT借鉴残差的思想梯度下降提高树的性能、XGBXBG极端梯度提升树是GBDT的改进版在除了损失外还增加了正则化项减小模型复杂度从而防止过拟合的发生。二.案例简介三.代码详解1.数据读取以及分割def dm01_data_split(): #1.加载数据集 df pd.read_csv(./data/红酒品质分类.csv) #2.查看数据集 df.info() #3.抽取特征数据和标签数据 x df.iloc[:, :-1] y df.iloc[:, -1] - 3 #最后一列是标签,默认标签是[3-8],-3后转换为[0,5] #4.查看数据 print(x[:5]) print(y[:5]) print(f查看标签数据是否均衡{Counter(y)}) #5.切分训练集和测试集 参5参考数据集的标签分布 x_train, x_test, y_train, y_test train_test_split(x, y, test_size0.2, random_state23, stratifyy) #6.将上述的训练及特征 和 标签数据拼接到一起 测试集特征和 标签数据拼接到一起 最后写到文件中 #print(pd.concat([x_train, y_train], axis1)) #axis 1 表示横向拼接 pd.concat([x_train, y_train], axis1).to_csv(./data/红酒品质分类.csv_train, indexFalse) #忽略索引 pd.concat([x_test, y_test], axis1).to_csv(./data/红酒品质分类.csv_test, indexFalse) # 忽略索引由标签可以看出存在数据分布不均的问题解决方法是权重均衡2.模型训练、保存#2.训练模型并保存 def dm02_train_model(): #1.读取训练集和测试集 train_data pd.read_csv(./data/红酒品质分类.csv_train) test_data pd.read_csv(./data/红酒品质分类.csv_test) #2.提取特征数据和标签数据 x_train train_data.iloc[:, :-1] #所有行除了最后一列 y_train train_data.iloc[:, -1] #所有行最后一列 x_test test_data.iloc[:, :-1] # 所有行除了最后一列 y_test test_data.iloc[:, -1] # 所有行最后一列 #3.创建模型 estimator xgb.XGBClassifier( max_depth 5, n_estimators 100, learning_rate 0.1, random_state 23, #随机种子 objective multi:softmax ) #加入 平衡权重应为数据是不均衡的 快速导入ALT回车 # 参1平衡权重 参2标签数据即参考标签数据分布平衡权重 class_weight.compute_sample_weight(balanced, y_train) #4.模型训练 estimator.fit(x_train, y_train) #5.模型评估 print(f准确率{estimator.score(x_test, y_test)}) #6.保存模型 joblib.dump(estimator, ./model/红酒品质分类.pkl) #后缀名也可以写.pth都是pickle文件格式 print(模型保持成功)3.模型预测#3.测试模型 def dm03_ues_model(): # 1.读取训练集和测试集 train_data pd.read_csv(./data/红酒品质分类.csv_train) test_data pd.read_csv(./data/红酒品质分类.csv_test) # 2.提取特征数据和标签数据 x_train train_data.iloc[:, :-1] # 所有行除了最后一列 y_train train_data.iloc[:, -1] # 所有行最后一列 x_test test_data.iloc[:, :-1] # 所有行除了最后一列 y_test test_data.iloc[:, -1] # 所有行最后一列 #3.加载模型 estimator joblib.load(./model/红酒品质分类.pkl) #4.创建网格搜索交叉验证结合分层采样数据训练模型 #4.1定义变量记录参数组合 param_dict { max_depth:[2, 3, 5, 6], n_estimators:[50, 100, 150], learning_rate:[0.2, 0.3, 1.0] } #4.2创建分层采样对象 # 参1折数 参2是否打乱数据 参3随机种子 skf StratifiedKFold(n_splits5, shuffleTrue, random_state23) #4.3创建 网格搜索 交叉验证结合分层采用数据对象 gs_estimator GridSearchCV(estimator, param_gridparam_dict, cvskf) #5.模型训练 gs_estimator.fit(x_train, y_train) #6.模型预测 y_pred gs_estimator.predict(x_test) print(f预测值为{y_pred}) #7.打印模型评估系数 print(f最优参数组合{gs_estimator.best_params_}) print(f最优模型对象{gs_estimator.best_estimator_}) print(f最优评分{gs_estimator.best_score_}) print(f准确率{accuracy_score(y_test, y_pred)})4.完整代码 新学数据预处理 1.标签重置 2.不均衡数据提取 3.特征和标签拼接 4.处理保存训练集和测试集 5.权重平衡 import joblib #保存模型 import numpy as np #数据运算 import pandas as pd #读数据 import xgboost as xgb #极限提升树 from collections import Counter #统计数据 from sklearn.model_selection import train_test_split,GridSearchCV from sklearn.metrics import classification_report, accuracy_score # 模型评估报告 from sklearn.model_selection import StratifiedKFold #分层K折叠交叉验证类似于网格搜索时cv 折数 from sklearn.utils import class_weight #平衡权重 #1.对红酒品质分类源数据-》拆分成训练集和测试集并保存导csv文件中 def dm01_data_split(): #1.加载数据集 df pd.read_csv(./data/红酒品质分类.csv) #2.查看数据集 df.info() #3.抽取特征数据和标签数据 x df.iloc[:, :-1] y df.iloc[:, -1] - 3 #最后一列是标签,默认标签是[3-8],-3后转换为[0,5] #4.查看数据 print(x[:5]) print(y[:5]) print(f查看标签数据是否均衡{Counter(y)}) #5.切分训练集和测试集 参5参考数据集的标签分布 x_train, x_test, y_train, y_test train_test_split(x, y, test_size0.2, random_state23, stratifyy) #6.将上述的训练及特征 和 标签数据拼接到一起 测试集特征和 标签数据拼接到一起 最后写到文件中 #print(pd.concat([x_train, y_train], axis1)) #axis 1 表示横向拼接 pd.concat([x_train, y_train], axis1).to_csv(./data/红酒品质分类.csv_train, indexFalse) #忽略索引 pd.concat([x_test, y_test], axis1).to_csv(./data/红酒品质分类.csv_test, indexFalse) # 忽略索引 #2.训练模型并保存 def dm02_train_model(): #1.读取训练集和测试集 train_data pd.read_csv(./data/红酒品质分类.csv_train) test_data pd.read_csv(./data/红酒品质分类.csv_test) #2.提取特征数据和标签数据 x_train train_data.iloc[:, :-1] #所有行除了最后一列 y_train train_data.iloc[:, -1] #所有行最后一列 x_test test_data.iloc[:, :-1] # 所有行除了最后一列 y_test test_data.iloc[:, -1] # 所有行最后一列 #3.创建模型 estimator xgb.XGBClassifier( max_depth 5, n_estimators 100, learning_rate 0.1, random_state 23, #随机种子 objective multi:softmax ) #加入 平衡权重应为数据是不均衡的 快速导入ALT回车 # 参1平衡权重 参2标签数据即参考标签数据分布平衡权重 class_weight.compute_sample_weight(balanced, y_train) #4.模型训练 estimator.fit(x_train, y_train) #5.模型评估 print(f准确率{estimator.score(x_test, y_test)}) #6.保存模型 joblib.dump(estimator, ./model/红酒品质分类.pkl) #后缀名也可以写.pth都是pickle文件格式 print(模型保持成功) #3.测试模型 def dm03_ues_model(): # 1.读取训练集和测试集 train_data pd.read_csv(./data/红酒品质分类.csv_train) test_data pd.read_csv(./data/红酒品质分类.csv_test) # 2.提取特征数据和标签数据 x_train train_data.iloc[:, :-1] # 所有行除了最后一列 y_train train_data.iloc[:, -1] # 所有行最后一列 x_test test_data.iloc[:, :-1] # 所有行除了最后一列 y_test test_data.iloc[:, -1] # 所有行最后一列 #3.加载模型 estimator joblib.load(./model/红酒品质分类.pkl) #4.创建网格搜索交叉验证结合分层采样数据训练模型 #4.1定义变量记录参数组合 param_dict { max_depth:[2, 3, 5, 6], n_estimators:[50, 100, 150], learning_rate:[0.2, 0.3, 1.0] } #4.2创建分层采样对象 # 参1折数 参2是否打乱数据 参3随机种子 skf StratifiedKFold(n_splits5, shuffleTrue, random_state23) #4.3创建 网格搜索 交叉验证结合分层采用数据对象 gs_estimator GridSearchCV(estimator, param_gridparam_dict, cvskf) #5.模型训练 gs_estimator.fit(x_train, y_train) #6.模型预测 y_pred gs_estimator.predict(x_test) print(f预测值为{y_pred}) #7.打印模型评估系数 print(f最优参数组合{gs_estimator.best_params_}) print(f最优模型对象{gs_estimator.best_estimator_}) print(f最优评分{gs_estimator.best_score_}) print(f准确率{accuracy_score(y_test, y_pred)}) #4.测试 if __name__ __main__: #dm01_data_split() #dm02_train_model() dm03_ues_model()四.总结通过此案例主要学习了数据的处理方法例如标签重置、处理数据部分不均问题并且加强了对XGB的认识
机器学习——基于XGB的红酒品质分类
发布时间:2026/5/22 3:36:09
一.算法简介Bagging思想并行由多个弱学习器预测结果最红综合所有结果给出最终结果代表算法为随机森林。Boosting思想串行下一个学习器纠正上一个学习器的错误从而提高学习器的性能代表算法为Adaboost提高错误样本的权重减小正确样本的权重、GBDT借鉴残差的思想梯度下降提高树的性能、XGBXBG极端梯度提升树是GBDT的改进版在除了损失外还增加了正则化项减小模型复杂度从而防止过拟合的发生。二.案例简介三.代码详解1.数据读取以及分割def dm01_data_split(): #1.加载数据集 df pd.read_csv(./data/红酒品质分类.csv) #2.查看数据集 df.info() #3.抽取特征数据和标签数据 x df.iloc[:, :-1] y df.iloc[:, -1] - 3 #最后一列是标签,默认标签是[3-8],-3后转换为[0,5] #4.查看数据 print(x[:5]) print(y[:5]) print(f查看标签数据是否均衡{Counter(y)}) #5.切分训练集和测试集 参5参考数据集的标签分布 x_train, x_test, y_train, y_test train_test_split(x, y, test_size0.2, random_state23, stratifyy) #6.将上述的训练及特征 和 标签数据拼接到一起 测试集特征和 标签数据拼接到一起 最后写到文件中 #print(pd.concat([x_train, y_train], axis1)) #axis 1 表示横向拼接 pd.concat([x_train, y_train], axis1).to_csv(./data/红酒品质分类.csv_train, indexFalse) #忽略索引 pd.concat([x_test, y_test], axis1).to_csv(./data/红酒品质分类.csv_test, indexFalse) # 忽略索引由标签可以看出存在数据分布不均的问题解决方法是权重均衡2.模型训练、保存#2.训练模型并保存 def dm02_train_model(): #1.读取训练集和测试集 train_data pd.read_csv(./data/红酒品质分类.csv_train) test_data pd.read_csv(./data/红酒品质分类.csv_test) #2.提取特征数据和标签数据 x_train train_data.iloc[:, :-1] #所有行除了最后一列 y_train train_data.iloc[:, -1] #所有行最后一列 x_test test_data.iloc[:, :-1] # 所有行除了最后一列 y_test test_data.iloc[:, -1] # 所有行最后一列 #3.创建模型 estimator xgb.XGBClassifier( max_depth 5, n_estimators 100, learning_rate 0.1, random_state 23, #随机种子 objective multi:softmax ) #加入 平衡权重应为数据是不均衡的 快速导入ALT回车 # 参1平衡权重 参2标签数据即参考标签数据分布平衡权重 class_weight.compute_sample_weight(balanced, y_train) #4.模型训练 estimator.fit(x_train, y_train) #5.模型评估 print(f准确率{estimator.score(x_test, y_test)}) #6.保存模型 joblib.dump(estimator, ./model/红酒品质分类.pkl) #后缀名也可以写.pth都是pickle文件格式 print(模型保持成功)3.模型预测#3.测试模型 def dm03_ues_model(): # 1.读取训练集和测试集 train_data pd.read_csv(./data/红酒品质分类.csv_train) test_data pd.read_csv(./data/红酒品质分类.csv_test) # 2.提取特征数据和标签数据 x_train train_data.iloc[:, :-1] # 所有行除了最后一列 y_train train_data.iloc[:, -1] # 所有行最后一列 x_test test_data.iloc[:, :-1] # 所有行除了最后一列 y_test test_data.iloc[:, -1] # 所有行最后一列 #3.加载模型 estimator joblib.load(./model/红酒品质分类.pkl) #4.创建网格搜索交叉验证结合分层采样数据训练模型 #4.1定义变量记录参数组合 param_dict { max_depth:[2, 3, 5, 6], n_estimators:[50, 100, 150], learning_rate:[0.2, 0.3, 1.0] } #4.2创建分层采样对象 # 参1折数 参2是否打乱数据 参3随机种子 skf StratifiedKFold(n_splits5, shuffleTrue, random_state23) #4.3创建 网格搜索 交叉验证结合分层采用数据对象 gs_estimator GridSearchCV(estimator, param_gridparam_dict, cvskf) #5.模型训练 gs_estimator.fit(x_train, y_train) #6.模型预测 y_pred gs_estimator.predict(x_test) print(f预测值为{y_pred}) #7.打印模型评估系数 print(f最优参数组合{gs_estimator.best_params_}) print(f最优模型对象{gs_estimator.best_estimator_}) print(f最优评分{gs_estimator.best_score_}) print(f准确率{accuracy_score(y_test, y_pred)})4.完整代码 新学数据预处理 1.标签重置 2.不均衡数据提取 3.特征和标签拼接 4.处理保存训练集和测试集 5.权重平衡 import joblib #保存模型 import numpy as np #数据运算 import pandas as pd #读数据 import xgboost as xgb #极限提升树 from collections import Counter #统计数据 from sklearn.model_selection import train_test_split,GridSearchCV from sklearn.metrics import classification_report, accuracy_score # 模型评估报告 from sklearn.model_selection import StratifiedKFold #分层K折叠交叉验证类似于网格搜索时cv 折数 from sklearn.utils import class_weight #平衡权重 #1.对红酒品质分类源数据-》拆分成训练集和测试集并保存导csv文件中 def dm01_data_split(): #1.加载数据集 df pd.read_csv(./data/红酒品质分类.csv) #2.查看数据集 df.info() #3.抽取特征数据和标签数据 x df.iloc[:, :-1] y df.iloc[:, -1] - 3 #最后一列是标签,默认标签是[3-8],-3后转换为[0,5] #4.查看数据 print(x[:5]) print(y[:5]) print(f查看标签数据是否均衡{Counter(y)}) #5.切分训练集和测试集 参5参考数据集的标签分布 x_train, x_test, y_train, y_test train_test_split(x, y, test_size0.2, random_state23, stratifyy) #6.将上述的训练及特征 和 标签数据拼接到一起 测试集特征和 标签数据拼接到一起 最后写到文件中 #print(pd.concat([x_train, y_train], axis1)) #axis 1 表示横向拼接 pd.concat([x_train, y_train], axis1).to_csv(./data/红酒品质分类.csv_train, indexFalse) #忽略索引 pd.concat([x_test, y_test], axis1).to_csv(./data/红酒品质分类.csv_test, indexFalse) # 忽略索引 #2.训练模型并保存 def dm02_train_model(): #1.读取训练集和测试集 train_data pd.read_csv(./data/红酒品质分类.csv_train) test_data pd.read_csv(./data/红酒品质分类.csv_test) #2.提取特征数据和标签数据 x_train train_data.iloc[:, :-1] #所有行除了最后一列 y_train train_data.iloc[:, -1] #所有行最后一列 x_test test_data.iloc[:, :-1] # 所有行除了最后一列 y_test test_data.iloc[:, -1] # 所有行最后一列 #3.创建模型 estimator xgb.XGBClassifier( max_depth 5, n_estimators 100, learning_rate 0.1, random_state 23, #随机种子 objective multi:softmax ) #加入 平衡权重应为数据是不均衡的 快速导入ALT回车 # 参1平衡权重 参2标签数据即参考标签数据分布平衡权重 class_weight.compute_sample_weight(balanced, y_train) #4.模型训练 estimator.fit(x_train, y_train) #5.模型评估 print(f准确率{estimator.score(x_test, y_test)}) #6.保存模型 joblib.dump(estimator, ./model/红酒品质分类.pkl) #后缀名也可以写.pth都是pickle文件格式 print(模型保持成功) #3.测试模型 def dm03_ues_model(): # 1.读取训练集和测试集 train_data pd.read_csv(./data/红酒品质分类.csv_train) test_data pd.read_csv(./data/红酒品质分类.csv_test) # 2.提取特征数据和标签数据 x_train train_data.iloc[:, :-1] # 所有行除了最后一列 y_train train_data.iloc[:, -1] # 所有行最后一列 x_test test_data.iloc[:, :-1] # 所有行除了最后一列 y_test test_data.iloc[:, -1] # 所有行最后一列 #3.加载模型 estimator joblib.load(./model/红酒品质分类.pkl) #4.创建网格搜索交叉验证结合分层采样数据训练模型 #4.1定义变量记录参数组合 param_dict { max_depth:[2, 3, 5, 6], n_estimators:[50, 100, 150], learning_rate:[0.2, 0.3, 1.0] } #4.2创建分层采样对象 # 参1折数 参2是否打乱数据 参3随机种子 skf StratifiedKFold(n_splits5, shuffleTrue, random_state23) #4.3创建 网格搜索 交叉验证结合分层采用数据对象 gs_estimator GridSearchCV(estimator, param_gridparam_dict, cvskf) #5.模型训练 gs_estimator.fit(x_train, y_train) #6.模型预测 y_pred gs_estimator.predict(x_test) print(f预测值为{y_pred}) #7.打印模型评估系数 print(f最优参数组合{gs_estimator.best_params_}) print(f最优模型对象{gs_estimator.best_estimator_}) print(f最优评分{gs_estimator.best_score_}) print(f准确率{accuracy_score(y_test, y_pred)}) #4.测试 if __name__ __main__: #dm01_data_split() #dm02_train_model() dm03_ues_model()四.总结通过此案例主要学习了数据的处理方法例如标签重置、处理数据部分不均问题并且加强了对XGB的认识