滨州建设局网站,国外文本排版设计网站,社交软件开发费用,什么是c2c模式#x1f9e1;#x1f49b;#x1f49a;TensorFlow2实战-系列教程 总目录 有任何问题欢迎在下面留言 本篇文章的代码运行界面均在Jupyter Notebook中进行 本篇文章配套的代码资源已经上传 1、TFRecords
在训练过程中#xff0c;基本都是使用GPU来计算#xff0c;但是取一个…TensorFlow2实战-系列教程 总目录 有任何问题欢迎在下面留言 本篇文章的代码运行界面均在Jupyter Notebook中进行 本篇文章配套的代码资源已经上传 1、TFRecords
在训练过程中基本都是使用GPU来计算但是取一个一个batch取数据还是必须要用cpu这个过程耗费时间也会影响训练时间制作TFRecords可以有效解决这个问题此外制作TFRecords数据可以更好的管理存储数据
为了高效地读取数据可以将数据进行序列化存储这样也便于网络流式读取数据。TFRecord是一种比较常用的存储二进制序列数据的方法tf.Example类是一种将数据表示为{“string”: value}形式的meassage类型Tensorflow经常使用tf.Example来写入、读取TFRecord数据
通常情况下tf.Example中可以使用以下几种格式
tf.train.BytesList: 可以使用的类型包括 string和bytetf.train.FloatList: 可以使用的类型包括 float和doubletf.train.Int64List: 可以使用的类型包括 enum,bool, int32, uint32, int64
TFRecords是TensorFlow官方推荐的
2、转化示例
def _bytes_feature(value):Returns a bytes_list from a string/byte.if isinstance(value, type(tf.constant(0))):value value.numpy() # BytesList wont unpack a string from an EagerTensor.return tf.train.Feature(bytes_listtf.train.BytesList(value[value]))def _float_feature(value):Return a float_list form a float/double.return tf.train.Feature(float_listtf.train.FloatList(value[value]))def _int64_feature(value):Return a int64_list from a bool/enum/int/uint.return tf.train.Feature(int64_listtf.train.Int64List(value[value]))定义3个函数分别对3种类型的数据进行转换成对应的TensorFlow的数据格式
# tf.train.BytesList
print(_bytes_feature(btest_string))
print(_bytes_feature(test_string.encode(utf8)))# tf.train.FloatList
print(_float_feature(np.exp(1)))# tf.train.Int64List
print(_int64_feature(True))
print(_int64_feature(1))传进几个numpy格式的数据再调用上面的函数进行转换再打印 bytes_list { value: “test_string” } bytes_list { value: “test_string” } float_list { value: 2.7182817459106445 } int64_list { value: 1 } int64_list { value: 1 } 3、TFRecords制作方法
def serialize_example(feature0, feature1, feature2, feature3):创建tf.Example# 转换成相应类型feature {feature0: _int64_feature(feature0),feature1: _int64_feature(feature1),feature2: _bytes_feature(feature2),feature3: _float_feature(feature3),}#使用tf.train.Example来创建example_proto tf.train.Example(featurestf.train.Features(featurefeature))#SerializeToString方法转换为二进制字符串return example_proto.SerializeToString()定义一个函数传入4个参数使用前面定义的函数对4个参数分别转换成相应的格式构建Example将转换完的数据创建一条数据序列化 tf.Example返回一个二进制的字符串
n_observations int(1e4)
feature0 np.random.choice([False, True], n_observations)
feature1 np.random.randint(0, 5, n_observations)
strings np.array([bcat, bdog, bchicken, bhorse, bgoat])
feature2 strings[feature1]
feature3 np.random.randn(n_observations)定义一个一万备用随机选择一万个布尔数据随机选择一万个0、1、2、3、4这5个整数随机构造字符串随机构造浮点数
filename tfrecord-1with tf.io.TFRecordWriter(filename) as writer:for i in range(n_observations):example serialize_example(feature0[i], feature1[i], feature2[i], feature3[i])writer.write(example)定义文件名定义一个写的模块传进文件名写入数据迭代一万次按照零到一万的索引分别传入上面构造的4个特征写入数据
这段代码执行后会得到一个名为tfrecord-1的文件
4、加载tfrecord文件
filenames [filename]
raw_dataset tf.data.TFRecordDataset(filenames)
raw_dataset打印结果 TFRecordDatasetV2 shapes: (), types: tf.string