首页 > 解决方案 > 为什么 Tensorflow/Keras 说我的标签和形状必须具有相同的尺寸?

问题描述

每当我使用 model.fit 训练模型时,都会出现值错误

ValueError: Dimensions must be equal, but are 2662 and 64 for 'loss/output_1_loss/mul' (op: 'Mul') with input shapes: [2662,1], [2662,64,64,128].

我使用的是 64x64 3 通道图像,但是,我不知道 128 来自哪里。有谁知道如何解决这个错误?

附上代码:

import tensorflow as tf
import glob
data = "*data\\*training\\*\\*"
filelist = glob.glob(str(data))
classes = ('classa','classb','classc','classd')
batchsize = 10
steps = (int(input("Enter Steps: "))/10)
def generator(file):
    f = tf.io.read_file(file)
    f = tf.image.decode_jpeg(f)
    f = tf.cast(f, tf.float32)
    f = tf.expand_dims(f,0)
    print(tf.shape(f))
    l = file.split('\\')
    l = l[2]
    l_label = classes.index(l)
    r1 = tf.constant(l_label)
    return f, r1
def todataset():
    array1 = []
    array2 = []
    for file in filelist:
        push_to_array1, push_to_array2 = generator(file)
        array1.append(push_to_array1)
        array2.append(push_to_array2)
    dataseta = tf.data.Dataset.from_tensors(array1)
    datasetb = tf.data.Dataset.from_tensors(array2)
    print(dataseta.element_spec)
    print(datasetb.element_spec)
    return(tf.data.Dataset.zip((dataseta,datasetb)))

dataset = todataset().shuffle(10000)
print(dataset.element_spec)

model = tf.keras.models.Sequential([
    tf.keras.layers.ConvLSTM2D(128, (2,2), padding="same")
])

model.compile(optimizer='adam', loss=tf.keras.losses.CategoricalCrossentropy(), metrics=['accuracy'], batch_size = batchsize)


model.fit(dataset, epochs=10, steps_per_epoch = steps)
model.save('MyModel.h5')

标签: pythonpython-3.xtensorflowkeras

解决方案


推荐阅读