簡體   English   中英

檢查輸入時出錯:期望flatten_input具有3維,但數組的形狀為(無,100、100、1)

[英]Error when checking input: expected flatten_input to have 3 dimensions, but got array with shape (None, 100, 100, 1)

我想使用TensorFlow / Keras將圖片分為兩類,自拍和非自拍。

我已經將樣本收集到兩個文件系統文件夾中,每個類別一個。

在使用從文件系統加載圖片后,按照MNIST時尚的官方教程(這也是圖片分類問題),我在下面進行了培訓,如https://stackoverflow.com/a/52417770/226958所示

不幸的是,我得到一個錯誤:

1.10.1
Tensor("IteratorGetNext:0", shape=(?, 100, 100, 1), dtype=float32)
Tensor("IteratorGetNext:1", shape=(?,), dtype=int32)
Traceback (most recent call last):
  File "run.py", line 50, in <module>
    model.fit(images, labels, epochs=1, steps_per_epoch=60000)
  File "/home/nico/.local/lib/python2.7/site-packages/tensorflow/python/keras/engine/training.py", line 1278, in fit
    validation_split=validation_split)
  File "/home/nico/.local/lib/python2.7/site-packages/tensorflow/python/keras/engine/training.py", line 878, in _standardize_user_data
    exception_prefix='input')
  File "/home/nico/.local/lib/python2.7/site-packages/tensorflow/python/keras/engine/training_utils.py", line 182, in standardize_input_data
    'with shape ' + str(data_shape))
ValueError: Error when checking input: expected flatten_input to have 3 dimensions, but got array with shape (None, 100, 100, 1)

這是源代碼:

import tensorflow as tf
print(tf.__version__)

out_shape = tf.convert_to_tensor([100, 100])
batch_size = 2

image_paths, labels = ["selfies-data/1", "selfies-data/2"], [1, 2]
epoch_size = len(image_paths)
image_paths = tf.convert_to_tensor(image_paths, dtype=tf.string)
labels = tf.convert_to_tensor(labels)

# The images loading part is from https://stackoverflow.com/a/52417770/226958
dataset = tf.data.Dataset.from_tensor_slices((image_paths, labels))
dataset = dataset.repeat().shuffle(epoch_size)

def map_fn(path, label):
    # path/label represent values for a single example
    image = tf.image.decode_jpeg(tf.read_file(path))

    # some mapping to constant size - be careful with distorting aspec ratios
    image = tf.image.resize_images(image, out_shape)
    image = tf.image.rgb_to_grayscale(image)
    # color normalization - just an example
    image = tf.to_float(image) * (2. / 255) - 1
    return image, label

# num_parallel_calls > 1 induces intra-batch shuffling
dataset = dataset.map(map_fn, num_parallel_calls=8)
dataset = dataset.batch(batch_size)
dataset = dataset.prefetch(1)

images, labels = dataset.make_one_shot_iterator().get_next()

# All of the following is from https://www.tensorflow.org/tutorials/keras/basic_classification
from tensorflow import keras

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(100, 100)),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(10, activation=tf.nn.softmax)
])

model.compile(optimizer=tf.train.AdamOptimizer(),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

print(images)
print(labels)
model.fit(images, labels, epochs=epoch_size, steps_per_epoch=60000)

盡管我已經閱讀了類似的問題,但沒有這個None問題。

如何使Keras適應我的輸入,或轉換我的輸入以使Keras接受它?

1)圖像具有一個通道,因此必須在輸入shape參數中反映出來:

keras.layers.Flatten(input_shape=(100, 100, 1))

2)要使用tf.data API加載文件,您首先需要獲取圖片文件名及其對應的標簽:

image_paths, lbls = ["selfies-data/1", "selfies-data/2"], [0., 1.]

labels = []
file_names = []
for d, l in zip(image_paths, lbls):
    # get the list all the images file names
    name = [os.path.join(d,f) for f in os.listdir(d)]
    file_names.extend(name)
    labels.extend([l] * len(name))

file_names = tf.convert_to_tensor(file_names, dtype=tf.string)
labels = tf.convert_to_tensor(labels)

dataset = tf.data.Dataset.from_tensor_slices((file_names, labels))

# the rest is the same 

您可能還需要擴展labels的尺寸,以使其具有(?, 1)的形狀(而不是(?,) )。 為此,您可以map_fn下行放在map_fn函數中:

labels = tf.expand_dims(labels, axis=-1)

3)如果您有兩個班級,那么為什么最后一層有10個單元? 這是一個二進制分類問題,因此使最后一層具有一個通過sigmoid激活的單元。 最后,將損失更改為binary_crossentropy

       # ... 
       keras.layers.Dense(1, activation=tf.nn.sigmoid)
])

model.compile(optimizer=tf.train.AdamOptimizer(),
              loss='binary_crossentropy',
              metrics=['accuracy'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM