1 回答

TA貢獻1824條經(jīng)驗 獲得超5個贊
似乎您無法從映射函數(shù)(1、2)內(nèi)部調(diào)用 .numpy() 函數(shù),盡管我能夠使用來自(doc)的 py_function 進行管理。
在下面的示例中,我已將我解析的數(shù)據(jù)集映射到一個函數(shù),該函數(shù)將我的圖像轉(zhuǎn)換為np.uint8
以便使用 matplotlib繪制它們。
records_path = data_directory+'TFRecords'+'/data_0.tfrecord'
# Create a dataset
dataset = tf.data.TFRecordDataset(filenames=records_path)
# Map our dataset to the parsing function?
parsed_dataset = dataset.map(parsing_fn)
converted_dataset = parsed_dataset.map(lambda image,label:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?tf.py_function(func=converting_function,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? inp=[image,label],
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Tout=[np.uint8,tf.int64]))
# Gets the iterator
iterator = tf.compat.v1.data.make_one_shot_iterator(converted_dataset)?
for i in range(5):
? ? image,label = iterator.get_next()
? ? plt.imshow(image)
? ? plt.show()
? ? print('label: ', label)
輸出:
解析函數(shù):
def parsing_fn(serialized):
? ? # Define a dict with the data-names and types we expect to
? ? # find in the TFRecords file.
? ? features = \
? ? ? ? {
? ? ? ? ? ? 'image': tf.io.FixedLenFeature([], tf.string),
? ? ? ? ? ? 'label': tf.io.FixedLenFeature([], tf.int64)? ? ? ? ? ??
? ? ? ? }
? ? # Parse the serialized data so we get a dict with our data.
? ? parsed_example = tf.io.parse_single_example(serialized=serialized,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?features=features)
? ? # Get the image as raw bytes.
? ? image_raw = parsed_example['image']
? ? # Decode the raw bytes so it becomes a tensor with type.
? ? image = tf.io.decode_jpeg(image_raw)
? ??
? ? # Get the label associated with the image.
? ? label = parsed_example['label']
? ??
? ? # The image and label are now correct TensorFlow types.
? ? return image, label
更新:實際上并沒有簽出,但 tf.shape() 似乎也是一個有前途的選擇。
添加回答
舉報