pytorch & tensorflow 保存和加载模型

1. Pytorch

1.1.1 save网络结构和参数:

注意最后一行为"self.state_dict()"

python 复制代码
    def save(self,t):
        current_path = os.path.dirname(os.path.abspath(__file__))
        model_path = 'model/2E_model_' + t + '_'+self.name+'/'

        save_path = os.path.join(current_path,model_path)
        if not os.path.exists(save_path):
            os.makedirs(save_path)

        save_file_path=os.path.join(save_path, 'model.pth')

        torch.save(self.state_dict(),save_file_path)

1.1.2 对应的加载模型参数:

注意对应"agent.load_state_dict(checkpoint)"

python 复制代码
    def load(self,agent,model_path):
        model_pth = 'model.pth'
        model_path = os.path.join(model_path,model_pth)
        checkpoint = torch.load(model_path)
        agent.load_state_dict(checkpoint)
        agent.eval()

1.2.1 保存整个模型

注意为"torch.save(self.model,save_file_path)"

python 复制代码
    def save(self,t):
        current_path = os.path.dirname(os.path.abspath(__file__))
        model_path = 'model/model_' + t + '_'+self.name+'/'

        save_path = os.path.join(current_path,model_path)
        if not os.path.exists(save_path):
            os.makedirs(save_path)

        save_file_path=os.path.join(save_path, 'model.pth')

        torch.save(self.model,save_file_path)

1.2.2 加载整个模型

注意"self.model = torch.load(model_path)"

python 复制代码
    def load(self,model_path):
        model_pth = 'model.pth'
        model_path = os.path.join(model_path,model_pth)
        self.model = torch.load(model_path)
        self.model.eval()

如果没对应上会报错:torch.nn.modules.module.ModuleAttributeError: object has no attribute 'copy',参考此链接

2. Tensorflow

2.1 保存模型

python 复制代码
    def save(self,time):
        current_path = os.path.dirname(os.path.abspath(__file__))
        model_path='model/model_'+time+'_'+self.name+'/weights_'+self.name
        save_path = os.path.join(current_path,model_path)
        if not os.path.exists(save_path):os.makedirs(save_path)
        self.saver.save(self.sess,save_path)

2.2 加载模型

python 复制代码
    def load(self,model_path):
        meta_path = 'weights_'+self.name+'.meta'

        mata_path_dir = os.path.join(model_path,meta_path)

        self.saver = tf.compat.v1.train.import_meta_graph(mata_path_dir)
        a=model_path+'/'
        self.saver.restore(self.sess, tf.train.latest_checkpoint(a))
相关推荐
Spey_Events12 分钟前
首发定档!2026中国航空维修制造及航材供应链展览会将于10 月在上海举办!
人工智能·制造
DeepModel28 分钟前
机器学习非线性降维:局部线性嵌入 LLE
人工智能·机器学习
lUie INGA34 分钟前
rust web框架actix和axum比较
前端·人工智能·rust
新缸中之脑1 小时前
HDRI-Generator: 环境贴图生成AI
人工智能·贴图
网安情报局1 小时前
企业押注Agentic SOC:AI重塑安全运营新范式
人工智能·网络安全
夜幕下的ACM之路1 小时前
一、基础知识学习(Transformer + 上下文窗口 + Token 计算 + Embedding 向量)
人工智能·学习·transformer·embedding
东离与糖宝1 小时前
LangChain4j vs Spring AI:最新对比,Java企业级Agent开发
java·人工智能
私人珍藏库1 小时前
[Windows] 绘画工具 Krita v5.3.1
人工智能·windows·媒体·工具·软件·多功能
前端摸鱼匠1 小时前
【AI大模型春招面试题13】残差连接(Residual Connection)与层归一化(Layer Norm)在Transformer中的作用?
人工智能·深度学习·语言模型·面试·transformer·求职招聘