tensorflow的pd文件

抄的

TensorFlow模型保存函数

save = tf.train.Saver()
......
saver.save(sess,"checkpoint/model.ckpt",global_step=step)

运行后保存模型,会得到三个文件,例如:

model.ckpt-129220.data-00000-of-00001#保存了模型的所有变量的值。
model.ckpt-129220.index
model.ckpt-129220.meta  # 保存了graph结构,包括GraphDef, SaverDef等。存在时,可以不在文件中定义模型,也可以运行

这三个模型的大小往往很大,而且客户端一般需要将模型保存为.pb文件。

1、直接将模型保存为.pb文件如下:

import tensorflow as tf
from tensorflow.python.framework import graph_util
var1 = tf.Variable(1.0, dtype=tf.float32, name='v1')
var2 = tf.Variable(2.0, dtype=tf.float32, name='v2')
var3 = tf.Variable(2.0, dtype=tf.float32, name='v3')
x = tf.placeholder(dtype=tf.float32, shape=None, name='x')
x2 = tf.placeholder(dtype=tf.float32, shape=None, name='x2')
addop = tf.add(x, x2, name='add')
addop2 = tf.add(var1, var2, name='add2')
addop3 = tf.add(var3, var2, name='add3')
initop = tf.global_variables_initializer()
model_path = './Test/model.pb'
with tf.Session() as sess:
    sess.run(initop)
    print(sess.run(addop, feed_dict={x: 12, x2: 23}))
    output_graph_def = graph_util.convert_variables_to_constants(sess, sess.graph_def, ['add', 'add2', 'add3'])
    # 将计算图写入到模型文件中
    model_f = tf.gfile.FastGFile(model_path, mode="wb")
    model_f.write(output_graph_def.SerializeToString())

####读取代码:
import tensorflow as tf
with tf.Session() as sess:
    model_f = tf.gfile.FastGFile("./Test/model.pb", mode='rb')
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(model_f.read())
    c = tf.import_graph_def(graph_def, return_elements=["add2:0"])
    c2 = tf.import_graph_def(graph_def, return_elements=["add3:0"])
    x, x2, c3 = tf.import_graph_def(graph_def, return_elements=["x:0", "x2:0", "add:0"])

    print(sess.run(c))
    print(sess.run(c2))
    print(sess.run(c3, feed_dict={x: 23, x2: 2}))

2、将保存的三个文件转成.pb文件

import tensorflow as tf
import deeplab_model

def export_graph(model, checkpoint_dir, model_name):
    '''
    model: the defined model
    checkpoint_dir: the dir of three files
    model_name: the name of .pb
    '''
    graph = tf.Graph()
    with graph.as_default():
        ### 输入占位符
        input_img = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_image')
        labels = tf.zeros([1, 512, 512,1])
        labels = tf.to_int32(tf.image.convert_image_dtype(labels, dtype=tf.uint8))
        ### 需要输出的Tensor
        output = model.deeplabv3_plus_model_fn(
                    input_img,
                    labels,
                    tf.estimator.ModeKeys.EVAL,
                    params={
                        'output_stride': 16,
                        'batch_size': 1,  # Batch size must be 1 because the images' size may differ
                        'base_architecture': 'resnet_v2_50',
                        'pre_trained_model': None,
                        'batch_norm_decay': None,
                        'num_classes': 2,
                        'freeze_batch_norm': True
                    }).predictions['classes']
        ### 给输出的tensor命名
        output = tf.identity(output, name='output_label')
        restore_saver = tf.train.Saver()

    with tf.Session(graph=graph) as sess:
        ### 初始化变量
        sess.run(tf.global_variables_initializer())
        ### load the model
        restore_saver.restore(sess, checkpoint_dir)
        
        output_graph_def = tf.graph_util.convert_variables_to_constants(
            sess, graph.as_graph_def(), [output.op.name])
        ### 将图写成.pb文件
        tf.train.write_graph(output_graph_def, 'pretrained', model_name, as_text=False)

### 调用函数,生成.pd文件
export_graph(deeplab_model, 'model/model.ckpt-133958', 'model.pd')

### 读取

import tensorflow as tf
import os

def inference():
    with tf.gfile.FastGFile('pretrained/model.pd', 'rb') as model_file:
        graph = tf.Graph()
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(model_file.read())
        [output_image] = tf.import_graph_def(graph_def,
                          input_map={'input_image': images},
                          return_elements=['output_label:0'],
                          name='output')
        sess = tf.Session()
        label = sess.run(output_image)
        return label
labels = inference()

 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
导入文件的方式取决于您要导入的文件类型和数据格式。这里提供几个常见情况的代码示例: 1. 导入文本文件 ```python import tensorflow as tf # 读取文本文件 dataset = tf.data.TextLineDataset('path/to/text/file') # 对每一行进行解码和处理 dataset = dataset.map(lambda x: tf.strings.split(x, ',')) dataset = dataset.map(lambda x: (tf.strings.to_number(x[0]), tf.strings.to_number(x[1]))) # 打乱数据并分成 batch dataset = dataset.shuffle(buffer_size=10000) dataset = dataset.batch(32) # 迭代数据 for x, y in dataset: # 训练模型 pass ``` 2. 导入图片文件 ```python import tensorflow as tf # 读取图片文件 dataset = tf.data.Dataset.list_files('path/to/image/files/*.jpg') # 对每一张图片进行解码和处理 dataset = dataset.map(lambda x: tf.io.read_file(x)) dataset = dataset.map(lambda x: tf.image.decode_jpeg(x, channels=3)) dataset = dataset.map(lambda x: tf.image.resize(x, [256, 256])) dataset = dataset.map(lambda x: x / 255.0) # 打乱数据并分成 batch dataset = dataset.shuffle(buffer_size=10000) dataset = dataset.batch(32) # 迭代数据 for x in dataset: # 训练模型 pass ``` 3. 导入其他格式的文件 对于其他格式的文件,您可以使用相应的库进行读取和处理,例如 pandas、numpy、csv、h5py 等。读取完成后,您可以将数据转换为 TensorFlow 支持的格式,例如张量(Tensor)或数据集(Dataset)。 ```python import tensorflow as tf import pandas as pd # 读取 csv 文件 data = pd.read_csv('path/to/csv/file.csv') # 将数据转换为张量 x = tf.convert_to_tensor(data['x'].values, dtype=tf.float32) y = tf.convert_to_tensor(data['y'].values, dtype=tf.float32) # 将数据转换为数据集 dataset = tf.data.Dataset.from_tensor_slices((x, y)) # 打乱数据并分成 batch dataset = dataset.shuffle(buffer_size=10000) dataset = dataset.batch(32) # 迭代数据 for x, y in dataset: # 训练模型 pass ``` 需要注意的是,在导入文件时,您需要指定文件路径和文件名。如果文件不在当前工作目录下,需要提供完整的路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值