机器学习:模型评估和模型保存

一、模型评估

python 复制代码
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

# 使用测试集进行预测
y_pred = model.predict(X_test)

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy*100:.2f}%")

# 打印混淆矩阵
conf_matrix = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(conf_matrix)

# 打印分类报告,包括精确率、召回率和F1分数
class_report = classification_report(y_test, y_pred)
print("Classification Report:")
print(class_report)

二、模型保存

python 复制代码
#使用joblib保存模型
import joblib
joblib.dump(model, "./yorelee_model.pth")
#模型的后缀名是无所谓的

三、后话

模型选择的时候,也可以使用模型融合,即结果由用不同模型的结果按比例得到。

比如pre=(pre_1*a+pre_2*b)/(a+b)。

那么我们在保存模型的时候,这两个模型要一起保存,然后之后训练就导入两个模型,pre这样算出来就行。

python 复制代码
%%time
# 2种模型融合
def model_mix(pred_1, pred_2):
    result = pd.DataFrame(columns=['LinearRegression','XGBRegressor','Combine'])

    for a in range (80):
        for b in range(1,80):
                    y_pred = (a*pred_1 + b*pred_2 ) / (a+b)
                    
                    mse = mean_squared_error(y_test,y_pred)
                    
                    mse = mean_squared_error(y_test,y_pred)
                    new_row = pd.DataFrame([{'LinearRegression':a, 
                                             'XGBRegressor':b, 
                                             'Combine':mse}])
                    result = pd.concat([result, new_row], ignore_index=True)
    return result

linear_predict=model_linear.predict(x_test)
xgb_predict=XGBClassifier.predict(x_test)
model_combine = model_mix(linear_predict,  xgb_predict)

model_combine.sort_values(by='Combine', inplace=True)
model_combine.head()
#各种比例来一份,看看mse最高分,查看 a和b的具体值
相关推荐
Python×CATIA工业智造15 分钟前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
IT古董20 分钟前
【第二章:机器学习与神经网络概述】04.回归算法理论与实践 -(4)模型评价与调整(Model Evaluation & Tuning)
神经网络·机器学习·回归
onceco1 小时前
领域LLM九讲——第5讲 为什么选择OpenManus而不是QwenAgent(附LLM免费api邀请码)
人工智能·python·深度学习·语言模型·自然语言处理·自动化
狐凄1 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python
悦悦子a啊2 小时前
Python之--基本知识
开发语言·前端·python
笑稀了的野生俊4 小时前
在服务器中下载 HuggingFace 模型:终极指南
linux·服务器·python·bash·gpu算力
Naiva4 小时前
【小技巧】Python+PyCharm IDE 配置解释器出错,环境配置不完整或不兼容。(小智AI、MCP、聚合数据、实时新闻查询、NBA赛事查询)
ide·python·pycharm
路来了5 小时前
Python小工具之PDF合并
开发语言·windows·python
蓝婷儿5 小时前
Python 机器学习核心入门与实战进阶 Day 3 - 决策树 & 随机森林模型实战
人工智能·python·机器学习
大千AI助手5 小时前
PageRank:互联网的马尔可夫链平衡态
人工智能·机器学习·贝叶斯·mc·pagerank·条件概率·马尔科夫链