tensorflow加载二进制文件

步骤

1.找到文件,创建文件列表
2.创建文件列表队列
3.创建文件阅读器,加载数据
4.解码,处理数据。
5.批处理

import tensorflow as tf
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'


class bin_file(object):
    """加载二进制文件
    """

    def __init__(self, file_list):
        self.file_list = file_list
        # 定义属性
        self.height = 32
        self.width = 32
        self.channels = 3
        self.label_bytes = 1
        self.image_bytes = self.height * self.width * self.channels
        self.bytes = self.label_bytes + self.image_bytes

    def read_and_decode(self):
        # 2.创建文件列表队列
        file_queue = tf.train.string_input_producer(self.file_list)
        # 3.创建文件阅读器,加载数据。record_bytes 每个样本的字节大小
        reader = tf.FixedLengthRecordReader(record_bytes=self.bytes)
        # 返回k-v格式的数据,key是文件名,value是文件内容
        key, value = reader.read(file_queue)
        # 4.解码,处理数据
        label_image = tf.decode_raw(value, tf.uint8)
        # 处理数据,切分特征和标签
        label = tf.cast(tf.slice(label_image, [0], [self.label_bytes]), tf.int32)
        image = tf.slice(label_image, [self.label_bytes], [self.image_bytes])
        # 处理数据,固定形状(统一特征维度)
        image_reshape = tf.reshape(image, [self.width, self.height, self.channels])
        # 5.批处理
        label_batch, image_batch = tf.train.batch([label, image_reshape], batch_size=20, num_threads=1, capacity=20)
        return label_batch, image_batch


if __name__ == '__main__':
    # 1.找到文件,创建文件列表
    file_names = os.listdir('../data/cifar-10-binary/')
    file_list = [os.path.join('../data/cifar-10-binary/', file_name) for file_name in file_names if
                 file_name[-3:] == 'bin']
    # 实例化
    bin_tfrec = bin_file(file_list)
    label_batch, image_batch = bin_tfrec.read_and_decode()
    # 会话运行
    with tf.Session() as sess:
        # 创建线程协调器
        coord = tf.train.Coordinator()
        # 启动加载数据的线程
        threads = tf.train.start_queue_runners(sess, coord)
        print(sess.run([label_batch, image_batch]))
        # 等待线程结束
        coord.request_stop()
        coord.join(threads)

注意

slice切分数据时,begin(第二个参数)和size(第三个参数)分别表示从第几个索引位置开始截取,截取长度是多少。这两个参数都需要使用一维数组来传参。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要添加自定义算子(例如Sin(x))到TensorFlow中,需要进行以下步骤: 1. 编写C++代码实现自定义算子,例如Sin(x)。 2. 将C++代码编译为动态链接库。 3. 使用TensorFlow API将动态链接库加载TensorFlow中。 以下是具体的步骤: 1. 编写C++代码实现自定义算子 首先,需要编写C++代码来实现自定义算子。在本例中,我们将编写一个名为"SinOp"的算子,该算子计算输入张量的每个元素的正弦值。 ```c++ #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor_types.h" using namespace tensorflow; REGISTER_OP("Sin") .Input("input: T") .Output("output: T") .Attr("T: {float, double}") .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) { c->set_output(0, c->input(0)); return Status::OK(); }); template<typename T> class SinOp : public OpKernel { public: explicit SinOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor& input_tensor = context->input(0); Tensor* output_tensor = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, input_tensor.shape(), &output_tensor)); auto input = input_tensor.flat<T>(); auto output = output_tensor->flat<T>(); const int N = input.size(); for (int i = 0; i < N; i++) { output(i) = sin(input(i)); } } }; REGISTER_KERNEL_BUILDER(Name("Sin").Device(DEVICE_CPU).TypeConstraint<float>("T"), SinOp<float>); REGISTER_KERNEL_BUILDER(Name("Sin").Device(DEVICE_CPU).TypeConstraint<double>("T"), SinOp<double>); ``` 在上面的代码中,我们首先使用REGISTER_OP宏注册了一个名为"Sin"的算子,该算子有一个输入张量和一个输出张量,并且具有一个类型参数T,该参数可以是float或double类型。然后,我们实现了SinOp类,该类继承自OpKernel,用于计算输入张量的正弦值。最后,我们使用REGISTER_KERNEL_BUILDER宏将SinOp类与"Sin"算子关联起来,以便TensorFlow可以使用它。 2. 将C++代码编译为动态链接库 接下来,我们需要将上述C++代码编译为动态链接库。可以使用CMake来创建一个新的项目,并将上述C++代码添加到项目中。然后,使用以下命令将代码编译为动态链接库: ``` mkdir build cd build cmake .. make ``` 这将在build文件夹中创建一个名为"libsin_op.so"的动态链接库。 3. 使用TensorFlow API将动态链接库加载TensorFlow中 最后,我们需要使用TensorFlow API将动态链接库加载TensorFlow中。可以使用以下代码将动态链接库加载TensorFlow中: ```python import tensorflow as tf # 加载动态链接库 sin_op_module = tf.load_op_library('/path/to/libsin_op.so') # 将算子添加到默认图中 with tf.Graph().as_default(): with tf.Session() as sess: # 创建输入张量 x = tf.constant([0.0, 1.0, 2.0, 3.0], dtype=tf.float32) # 使用自定义算子计算sin(x) y = sin_op_module.sin(x) # 运行计算图 print(sess.run(y)) ``` 在上面的代码中,我们首先使用tf.load_op_library函数加载动态链接库。然后,我们使用with tf.Graph().as_default()和with tf.Session()创建计算图和会话。接下来,我们创建一个名为"x"的输入张量,并使用sin_op_module.sin函数计算sin(x)。最后,我们使用sess.run函数运行计算图,并打印输出结果。 总结 通过上述步骤,我们可以将自定义算子(例如Sin(x))添加到TensorFlow中。需要注意的是,添加自定义算子需要一定的C++编程经验,并且需要进行编译和加载等操作,相对比较繁琐。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值