我試圖弄清楚如何使用FixedLengthRecordDataset以下方法加載二進制資料檔案:
import tensorflow as tf
import struct
import numpy as np
RAW_N = 2 20*20 1
def convert_binary_to_float_array(register):
return struct.unpack('f'*RAW_N, register.numpy())
raw_dataset = tf.data.FixedLengthRecordDataset(filenames=['mydata.bin'],record_bytes=RAW_N*4)
float_ds = raw_dataset.map(map_func=convert_binary_to_float_array)
此代碼拋出:
AttributeError: in user code:
tf-load-data.py:14 convert_binary_to_float_array *
return struct.unpack('f'*RAW_N, register.numpy())
AttributeError: 'Tensor' object has no attribute 'numpy'
numpy() 如果我嘗試迭代資料集,則可用:
raw_dataset = tf.data.FixedLengthRecordDataset(filenames=['mydata.bin'],record_bytes=RAW_N*4)
for register in raw_dataset:
print(struct.unpack('f'*RAW_N, register.numpy()))
通過閱讀Tensor型別描述,我意識到它numpy()僅在急切執行期間可用。因此,我可以推斷出在map()呼叫期間元素未提供為EagerTensor.
如何將此資料加載到資料集中?
我正在使用 TensorFlow 2.4.1
uj5u.com熱心網友回復:
我建議使用tf.io.decode_raw。不幸的是,我不知道是什么mydata.bin樣子,所以我創建了一些虛擬資料:
import random
import struct
import tensorflow as tf
import numpy as np
RAW_N = 2 20*20 1
bytess = random.sample(range(1, 5000), RAW_N*4)
with open('mydata.bin', 'wb') as f:
f.write(struct.pack('1612i', *bytess))
def convert_binary_to_float_array(register):
return tf.io.decode_raw(register, out_type=tf.float32)
raw_dataset = tf.data.FixedLengthRecordDataset(filenames=['/content/mydata.bin'], record_bytes=RAW_N*4)
raw_dataset = raw_dataset.map(convert_binary_to_float_array)
for register in raw_dataset:
print(register)
您也可以嘗試首先將資料解碼為整數,tf.io.decode_raw然后轉換為浮點數tf.cast,但我不確定它是否會有所作為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/408862.html
標籤:
上一篇:在撰寫自定義損失函式期間何時使用tf.GradientTape
下一篇:嘗試堆疊兩個參差不齊的張量時出錯
