我想用 tensorflow 創建一個資料集,并將影像作為陣列(dtype=unit8)和標簽作為字串提供。影像和相應的標簽存盤在資料框中,列名為Image as Array和 Labels。
| 影像作為陣列(型別 = 陣列) | 標簽(型別 = 字串) |
|---|---|
| img_1 | '好的' |
| img_2 | '不好' |
| img_3 | '好的' |
| img_4 | '好的' |
我的挑戰:我不知道如何從資料框中輸入資料集,大多數教程更喜歡從目錄加載資料的方式。
謝謝你,我希望你能幫助我加載資料集中的影像。
uj5u.com熱心網友回復:
您實際上可以將資料框直接傳遞給tf.data.Dataset.from_tensor_slices:
import tensorflow as tf
import numpy as np
import pandas as pd
df = pd.DataFrame(data={'images': [np.random.random((64, 64, 3)) for _ in range(100)],
'labels': ['ok', 'not ok']*50})
dataset = tf.data.Dataset.from_tensor_slices((list(df['images'].values), df['labels'].values)).batch(2)
for x, y in dataset.take(1):
print(x.shape, y)
# (2, 64, 64, 3) tf.Tensor([b'ok' b'not ok'], shape=(2,), dtype=string)
uj5u.com熱心網友回復:
一種可能性是使用range創建索引資料集,然后將陣列和標簽映射在一起。
# array
img = np.random.rand(4, 2, 2, 2)
label = np.array(['ok', 'not ok', 'ok', 'ok'])
# convert to tf constant
img = tf.constant(img)
label = tf.constant(label)
# create dataset with 0 - 3 index
dataset = tf.data.Dataset.range(len(label))
# map dataset
dataset = dataset.map(lambda x: (img[x, :, :, :], label[x]))
輸出:
<MapDataset element_spec=(TensorSpec(shape=(2, 2, 2), dtype=tf.float64, name=None), TensorSpec(shape=(), dtype=tf.string, name=None))>
輸出串列-第二個 idx:
for i in dataset:
print(list(i)[1])
tf.Tensor(b'ok', shape=(), dtype=string)
tf.Tensor(b'not ok', shape=(), dtype=string)
tf.Tensor(b'ok', shape=(), dtype=string)
tf.Tensor(b'ok', shape=(), dtype=string)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/483309.html
