使用tensorflow DataSet实现高效加载变长文本输入

yipeiwu_com4年前Python基础

DataSet是tensorflow 1.3版本推出的一个high-level的api,在1.3版本还只是处于测试阶段,1.4版本已经正式推出。

在网上搜了一遍,发现关于使用DataSet加载文本的资料比较少,官方举的例子只是csv格式的,要求csv文件中所有样本必须具有相同的维度,也就是padding必须在写入csv文件之前做掉,这会增加文件的大小。

经过一番折腾试验,这里给出一个DataSet+TFRecords加载变长样本的范例。

首先先把变长的数据写入到TFRecords文件:

def writedata():
 xlist = [[1,2,3],[4,5,6,8]]
 ylist = [1,2]
 #这里的数据只是举个例子来说明样本的文本长度不一样,第一个样本3个词标签1,第二个样本4个词标签2
 writer = tf.python_io.TFRecordWriter("train.tfrecords")
 for i in range(2):
  x = xlist[i]
  y = ylist[i]
  example = tf.train.Example(features=tf.train.Features(feature={
   "y": tf.train.Feature(int64_list=tf.train.Int64List(value=[y])),
   'x': tf.train.Feature(int64_list=tf.train.Int64List(value=x))
  }))
  writer.write(example.SerializeToString())
 writer.close()

然后用DataSet加载:

feature_names = ['x']
 
def my_input_fn(file_path, perform_shuffle=False, repeat_count=1):
 def parse(example_proto):
  features = {"x": tf.VarLenFeature(tf.int64),
    "y": tf.FixedLenFeature([1], tf.int64)}
  parsed_features = tf.parse_single_example(example_proto, features)
  x = tf.sparse_tensor_to_dense(parsed_features["x"])
  x = tf.cast(x, tf.int32)
  x = dict(zip(feature_names, [x]))
  y = tf.cast(parsed_features["y"], tf.int32)
  return x, y
 
 dataset = (tf.contrib.data.TFRecordDataset(file_path)
    .map(parse))
 if perform_shuffle:
  dataset = dataset.shuffle(buffer_size=256)
 dataset = dataset.repeat(repeat_count)
 dataset = dataset.padded_batch(2, padded_shapes=({'x':[6]},[1])) #batch size为2,并且x按maxlen=6来做padding
 iterator = dataset.make_one_shot_iterator()
 batch_features, batch_labels = iterator.get_next()
 return batch_features, batch_labels
 
next_batch = my_input_fn('train.tfrecords', True)
init = tf.initialize_all_variables()
with tf.Session() as sess:
 sess.run(init)
 for i in range(1):
  xs, y =sess.run(next_batch)
  print(xs['x'])
  print(y)

注意变长的数据TFRecords解析要用VarLenFeature,然后用sparse_tensor_to_dense转换。

以上这篇使用tensorflow DataSet实现高效加载变长文本输入就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python网络编程详解

1、服务器就是一系列硬件或软件,为一个或多个客户端(服务的用户)提供所需的“服务”。它存在唯一目的就是等待客户端的请求,并响应它们(提供服务),然后等待更多请求。 2、客户端/服务器架...

Python实现学校管理系统

Python实现学校管理系统

本文实例为大家分享了Python实现学校管理系统的具体代码,供大家参考,具体内容如下 一、功能分析 此学校管理系统应该可以实现学校的师资力量的调配,学生的入学、学习以及修学或者退学的情...

简单了解Python3里的一些新特性

概述 到2020年,Python2的官方维护期就要结束了,越来越多的Python项目从Python2切换到了Python3。其实在实际工作中,很多伙伴都还是在用Python2的思维写Py...

python模拟登录并且保持cookie的方法详解

前言 最近在爬行 nosec.org 的数据,看了下需要模拟登录拿到cookie后才能访问想抓的数据,重要的是 nosec.org 的登录页面 form 中有个 authenticit...

python嵌套函数使用外部函数变量的方法(Python2和Python3)

python嵌套函数使用外部函数变量的方法,Python2和Python3均可使用 python3 def b(): b = 1 def bchange(): nonlo...