2016-12-20 53 views
4

我想創建tensorflow記錄來餵養我的模型; 到目前爲止我使用下面的代碼將uint8 numpy數組存儲爲TFRecord格式;tensorflow記錄與浮動numpy陣列

def _int64_feature(value): 
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) 


def _bytes_feature(value): 
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) 


def _floats_feature(value): 
    return tf.train.Feature(float_list=tf.train.FloatList(value=[value])) 


def convert_to_record(name, image, label, map): 
    filename = os.path.join(params.TRAINING_RECORDS_DATA_DIR, name + '.' + params.DATA_EXT) 

    writer = tf.python_io.TFRecordWriter(filename) 

    image_raw = image.tostring() 
    map_raw = map.tostring() 
    label_raw = label.tostring() 

    example = tf.train.Example(features=tf.train.Features(feature={ 
     'image_raw': _bytes_feature(image_raw), 
     'map_raw': _bytes_feature(map_raw), 
     'label_raw': _bytes_feature(label_raw) 
    }))   
    writer.write(example.SerializeToString()) 
    writer.close() 

我與這個示例代碼

features = tf.parse_single_example(example, features={ 
    'image_raw': tf.FixedLenFeature([], tf.string), 
    'map_raw': tf.FixedLenFeature([], tf.string), 
    'label_raw': tf.FixedLenFeature([], tf.string), 
}) 

image = tf.decode_raw(features['image_raw'], tf.uint8) 
image.set_shape(params.IMAGE_HEIGHT*params.IMAGE_WIDTH*3) 
image = tf.reshape(image_, (params.IMAGE_HEIGHT,params.IMAGE_WIDTH,3)) 

map = tf.decode_raw(features['map_raw'], tf.uint8) 
map.set_shape(params.MAP_HEIGHT*params.MAP_WIDTH*params.MAP_DEPTH) 
map = tf.reshape(map, (params.MAP_HEIGHT,params.MAP_WIDTH,params.MAP_DEPTH)) 

label = tf.decode_raw(features['label_raw'], tf.uint8) 
label.set_shape(params.NUM_CLASSES) 

和工作的罰款讀取。現在我想對我的數組「map」做一個浮點numpy數組而不是uint8,並且我找不到有關如何執行它的示例; 我試過函數_floats_feature,如果我將標量傳遞給它,但不與數組一起工作; 與uint8序列化可以通過tostring()方法完成;

我怎樣才能序列化一個浮點numpy數組,我怎樣才能讀回來?

回答

6

FloatListBytesList預期可迭代。所以你需要將它傳遞給一個浮動列表。刪除您的_float_feature的額外括號,即

def _floats_feature(value): 
    return tf.train.Feature(float_list=tf.train.FloatList(value=value)) 

numpy_arr = np.ones((3,)).astype(np.float) 
example = tf.train.Example(features=tf.train.Features(feature={"bytes": _floats_feature(numpy_arr)})) 
print(example) 

features { 
    feature { 
    key: "bytes" 
    value { 
     float_list { 
     value: 1.0 
     value: 1.0 
     value: 1.0 
     } 
    } 
    } 
} 
2

我會對雅羅斯拉夫的答案進行擴展。

Int64List,BytesList和FloatList期望iterator of the underlying elements(重複字段)。在你的情況下,你可以使用列表作爲迭代器。

你提到:它的工作原理,如果我傳遞一個標量,但不能與數組。這是預料之中的,因爲當你傳遞一個標量時,你的_floats_feature會創建一個包含一個float元素的數組(正如預期的那樣)。但是當你傳遞一個數組時,你會創建一個數組列表並將其傳遞給一個需要列表的浮點數的函數。

所以只是從你的函數中刪除的陣列結構:float_list=tf.train.FloatList(value=value)

1

雅羅斯拉夫的例子失敗時,第二陣列是輸入:

numpy_arr = np.ones((3,3))astype( np.float)

我發現它在我使用numpy_arr.ravel()作爲輸入時起作用。但有沒有更好的方法來做到這一點?

+0

雅羅斯拉夫提到你需要浮動列表,num_arr不是一個列表,所以你必須以某種方式平坦化它,然後在將其傳遞給模型之前修正它的形狀。 – cberkay