欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用tensorflow DataSet實(shí)現(xiàn)高效加載變長(zhǎng)文本輸入

 更新時(shí)間:2020年01月20日 15:45:38   作者:lyg5623  
今天小編就為大家分享一篇使用tensorflow DataSet實(shí)現(xiàn)高效加載變長(zhǎng)文本輸入,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

DataSet是tensorflow 1.3版本推出的一個(gè)high-level的api,在1.3版本還只是處于測(cè)試階段,1.4版本已經(jīng)正式推出。

在網(wǎng)上搜了一遍,發(fā)現(xiàn)關(guān)于使用DataSet加載文本的資料比較少,官方舉的例子只是csv格式的,要求csv文件中所有樣本必須具有相同的維度,也就是padding必須在寫入csv文件之前做掉,這會(huì)增加文件的大小。

經(jīng)過一番折騰試驗(yàn),這里給出一個(gè)DataSet+TFRecords加載變長(zhǎng)樣本的范例。

首先先把變長(zhǎng)的數(shù)據(jù)寫入到TFRecords文件:

def writedata():
 xlist = [[1,2,3],[4,5,6,8]]
 ylist = [1,2]
 #這里的數(shù)據(jù)只是舉個(gè)例子來說明樣本的文本長(zhǎng)度不一樣,第一個(gè)樣本3個(gè)詞標(biāo)簽1,第二個(gè)樣本4個(gè)詞標(biāo)簽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)

注意變長(zhǎng)的數(shù)據(jù)TFRecords解析要用VarLenFeature,然后用sparse_tensor_to_dense轉(zhuǎn)換。

以上這篇使用tensorflow DataSet實(shí)現(xiàn)高效加載變長(zhǎng)文本輸入就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論