如何使用tensorflowDataSet實現(xiàn)高效加載變長文本輸入-創(chuàng)新互聯(lián)

這篇文章給大家分享的是有關如何使用tensorflow DataSet實現(xiàn)高效加載變長文本輸入的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

創(chuàng)新互聯(lián)公司專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務,包含不限于成都網(wǎng)站建設、網(wǎng)站建設、同仁網(wǎng)絡推廣、成都小程序開發(fā)、同仁網(wǎng)絡營銷、同仁企業(yè)策劃、同仁品牌公關、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務,您的肯定,是我們大的嘉獎;創(chuàng)新互聯(lián)公司為所有大學生創(chuàng)業(yè)者提供同仁建站搭建服務,24小時服務熱線:13518219792,官方網(wǎng)址:muchs.cn

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

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

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

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

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

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

感謝各位的閱讀!關于“如何使用tensorflow DataSet實現(xiàn)高效加載變長文本輸入”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

當前題目:如何使用tensorflowDataSet實現(xiàn)高效加載變長文本輸入-創(chuàng)新互聯(lián)
轉載源于:http://muchs.cn/article6/deicog.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導航、定制網(wǎng)站App設計、網(wǎng)頁設計公司、網(wǎng)站設計公司企業(yè)建站

廣告

聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

商城網(wǎng)站建設