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

一、模型评估

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的具体值
相关推荐
Wilber的技术分享1 小时前
【机器学习实战笔记 14】集成学习:XGBoost算法(一) 原理简介与快速应用
人工智能·笔记·算法·随机森林·机器学习·集成学习·xgboost
巴里巴气1 小时前
selenium基础知识 和 模拟登录selenium版本
爬虫·python·selenium·爬虫模拟登录
19891 小时前
【零基础学AI】第26讲:循环神经网络(RNN)与LSTM - 文本生成
人工智能·python·rnn·神经网络·机器学习·tensorflow·lstm
JavaEdge在掘金1 小时前
Redis 数据倾斜?别慌!从成因到解决方案,一文帮你搞定
python
ansurfen1 小时前
我的第一个AI项目:从零搭建RAG知识库的踩坑之旅
python·llm
前端付豪2 小时前
20、用 Python + API 打造终端天气预报工具(支持城市查询、天气图标、美化输出🧊
后端·python
前端付豪2 小时前
19、用 Python + OpenAI 构建一个命令行 AI 问答助手
后端·python
amazinging2 小时前
北京-4年功能测试2年空窗-报培训班学测开-第四十三天
python·学习
JoernLee2 小时前
机器学习算法:支持向量机SVM
人工智能·算法·机器学习
wgyang20163 小时前
我的第一个LangFlow工作流——复读机
python