2016-12-30 165 views
5

我想寫一個csv文件(所有列都是浮動)到tfrecords文件,然後再讀出它們。我看到的所有示例都包裝了csv列,然後直接將其提供給sess.run(),但我無法弄清楚如何將特徵列和標籤列寫入tfrecord。我怎麼能這樣做?Tensorflow從csv創建一個tfrecords文件

+1

我的文章是否回答你的問題? – standy

+0

是的,抱歉花了這麼長時間我最近很忙。謝謝您的幫助! – Nitro

回答

13

您將需要一個單獨的腳本來將您的csv文件轉換爲TFRecords。

想象一下,你有下面的頭一個CSV:

feature_1, feature_2, ..., feature_n, label 

你需要的東西,如pandas讀您的CSV,手動構建tf.train.Example然後把它寫入與TFRecordWriter

csv = pandas.read_csv("your.csv").values 
with tf.python_io.TFRecordWriter("csv.tfrecords") as writer: 
    for row in csv: 
     features, label = row[:-1], row[-1] 
     example = tf.train.Example() 
     example.features.feature["features"].float_list.value.extend(features) 
     example.features.feature["label"].int64_list.value.append(label) 
     writer.write(example.SerializeToString()) 
-1
def convert_to(): 
filename = os.path.join(wdir, 'ml-100k' + '.tfrecords') 
print('Writing', filename) 
with tf.python_io.TFRecordWriter(filename) as writer: 
    with open("/Users/shishir/Documents/botconnect_Playground/tfRecords/ml-100k.train.rating", "r") as f: 
     line = f.readline() 
     while line != None and line != "": 
      arr = line.split("\t") 
      u, i, l = int(arr[0]), int(arr[1]), int(arr[2]) 
      u_arr = np.reshape(u,[1]).astype('int64') 
      i_arr = np.reshape(i,[1]).astype('int64') 
      l_arr = np.reshape(l,[1]).astype('int64') 
      example = tf.train.Example() 
      example.features.feature["user"].int64_list.value.extend(u_arr) 
      example.features.feature["item"].int64_list.value.extend(i_arr) 
      example.features.feature["label"].int64_list.value.append(int(l_arr)) 
      writer.write(example.SerializeToString()) 
      line = f.readline() 
到文件

這就是我的解決方案,它的工作原理!希望這可以幫助

乾杯。

+0

感謝您使用此代碼段,這可能會提供一些有限的短期幫助。通過展示*爲什麼*這是一個很好的解決方案,並且使它對未來的讀者更有用,一個正確的解釋[將大大提高](// meta.stackexchange.com/q/114762)其長期價值其他類似的問題。請[編輯]你的答案以添加一些解釋,包括你所做的假設。 –