我目前正在使用 TensorFlow 處理 CIFAR10 資料集。由于各種原因,我需要通過預定義的規則更改標簽,例如。每個標簽為 4 的示例應更改為 3,或者每個標簽為 1 的示例應更改為 6。
我嘗試了以下方法:
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
builder = tfds.image.Cifar10()
builder.download_and_prepare()
ds_train: tf.data.Dataset = builder.as_dataset(split='train')
def relabel_map(l):
return {0: 0, 1: 6, 2: 1, 3: 2, 4: 3, 5: 4, 6: 9, 7: 5, 8: 7, 9: 8}[l]
ds_train = ds_train.map(lambda example: (example['image'], tf.py_function(relabel_map, [example['label']], [tf.int64])))
for ex in ds_train.take(1):
plt.imshow(np.array(ex[0], dtype=np.uint8))
plt.show()
print(ex[1])
當我嘗試運行它時,我在以下行中收到以下錯誤for ex in ds_train.take(1)::
型別錯誤:張量是不可散列的。相反,使用 tensor.ref() 作為鍵。
我的python版本是3.8.12,TensorFlow版本是2.7.0。
PS:也許我可以通過轉換為 one-hot 并用矩陣對其進行轉換來進行這種轉換,但這在代碼中看起來不那么簡單。
uj5u.com熱心網友回復:
我建議tf.lookup.StaticHashTable為您的情況使用 a :
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
builder = tfds.image.Cifar10()
builder.download_and_prepare()
ds_train: tf.data.Dataset = builder.as_dataset(split='train')
table = tf.lookup.StaticHashTable(
initializer=tf.lookup.KeyValueTensorInitializer(
keys=tf.constant([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=tf.int64),
values=tf.constant([0, 6, 1, 2, 3, 4, 9, 5, 7, 8], dtype=tf.int64),
),
default_value= tf.constant(0, dtype=tf.int64)
)
def relabel_map(example):
example['label'] = table.lookup(example['label'])
return example
ds_train = ds_train.map(relabel_map)
for ex in ds_train.take(1):
plt.imshow(np.array(ex['image'], dtype=np.uint8))
plt.show()
print(ex['label'])

tf.Tensor(5, shape=(), dtype=int64)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/368274.html
下一篇:我無法弄清楚python中的錯誤
