logits和标签尺寸错误(但没有类似的变量)。FITVGG19 TensorFlow代码

发布于 2025-02-03 01:32:55 字数 2362 浏览 5 评论 0原文

我正在使用转移学习来构建一个具有三个类别的模型。我不知道为什么由于逻辑和标签而导致错误。 这是我的代码,

baseModel = tf.keras.applications.VGG19(input_shape=(128,128,3), include_top=False, weights='imagenet')
baseModel.trainable = False
labels = ['glass', 'paper', 'plastic']
trainGenerator = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg19.preprocess_input, rescale=(1/255.0)) \
    .flow_from_directory(directory=trainDir, target_size=(128,128), classes=['glass', 'paper', 'plastic'], batch_size=10)
testGenerator = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg19.preprocess_input, rescale=(1/255.0)) \
    .flow_from_directory(directory=testDir, target_size=(128,128), classes=['glass', 'paper', 'plastic'], batch_size=10)
validGenerator = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg19.preprocess_input, rescale=(1/255.0)) \
    .flow_from_directory(directory=validDir, target_size=(128,128), classes=['glass', 'paper', 'plastic'], batch_size=10)
images, label = next(trainGenerator)
model.add(Input(shape=(128,128,3)))
model.add(baseModel)
model.compile(optimizer=Adam(learning_rate = 0.0001), 
                   loss='sparse_categorical_crossentropy', 
                   metrics=['sparse_categorical_accuracy'])
history = model.fit(trainGenerator, 
                    epochs=20, 
                    shuffle=True,
                    validation_data=validGenerator 
                    )

这是

InvalidArgumentError:  logits and labels must have the same first dimension, got logits shape [160,3] and labels shape [30]
     [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits
 (defined at C:\Users\ugouc\anaconda3\lib\site-packages\keras\backend.py:5114)
]] [Op:__inference_train_function_4832]

Errors may have originated from an input operation.
Input Source operations connected to node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits:
In[0] sparse_categorical_crossentropy/Reshape_1 (defined at C:\Users\ugouc\anaconda3\lib\site-packages\keras\backend.py:5109)   
In[1] sparse_categorical_crossentropy/Reshape (defined at C:\Users\ugouc\anaconda3\lib\site-packages\keras\backend.py:3561)

当我尝试添加更多层(例如,与relu的密度更平坦和密集)时,我会遇到的错误,我会遇到一个错误,说它不能挤压3到1的尺寸。 请帮忙

I am using transfer learning to build a model that with three categories. I do not know why I am having an error due to logits and labels.
This is my code

baseModel = tf.keras.applications.VGG19(input_shape=(128,128,3), include_top=False, weights='imagenet')
baseModel.trainable = False
labels = ['glass', 'paper', 'plastic']
trainGenerator = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg19.preprocess_input, rescale=(1/255.0)) \
    .flow_from_directory(directory=trainDir, target_size=(128,128), classes=['glass', 'paper', 'plastic'], batch_size=10)
testGenerator = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg19.preprocess_input, rescale=(1/255.0)) \
    .flow_from_directory(directory=testDir, target_size=(128,128), classes=['glass', 'paper', 'plastic'], batch_size=10)
validGenerator = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg19.preprocess_input, rescale=(1/255.0)) \
    .flow_from_directory(directory=validDir, target_size=(128,128), classes=['glass', 'paper', 'plastic'], batch_size=10)
images, label = next(trainGenerator)
model.add(Input(shape=(128,128,3)))
model.add(baseModel)
model.compile(optimizer=Adam(learning_rate = 0.0001), 
                   loss='sparse_categorical_crossentropy', 
                   metrics=['sparse_categorical_accuracy'])
history = model.fit(trainGenerator, 
                    epochs=20, 
                    shuffle=True,
                    validation_data=validGenerator 
                    )

This is the error I am getting

InvalidArgumentError:  logits and labels must have the same first dimension, got logits shape [160,3] and labels shape [30]
     [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits
 (defined at C:\Users\ugouc\anaconda3\lib\site-packages\keras\backend.py:5114)
]] [Op:__inference_train_function_4832]

Errors may have originated from an input operation.
Input Source operations connected to node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits:
In[0] sparse_categorical_crossentropy/Reshape_1 (defined at C:\Users\ugouc\anaconda3\lib\site-packages\keras\backend.py:5109)   
In[1] sparse_categorical_crossentropy/Reshape (defined at C:\Users\ugouc\anaconda3\lib\site-packages\keras\backend.py:3561)

When I try to add more layers (e.g. flatten layer and dense with relu), I get an error saying it cannot squeeze the dimension of 3 to 1.
Please, help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

因为看清所以看轻 2025-02-10 01:32:55

代码

model.add(Input(shape=(128,128,3)))

删除您已经指定输入形状的VGG19模型代码的 。在VGG代码中,对此进行了更改,

baseModel = tf.keras.applications.VGG19(input_shape=(128,128,3), include_top=False, weights='imagenet', poooling='max')

使基本模型的输出可以用作密度层的输入。 之后添加代码。

x=base_model.output
x=BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001 )(x)
x = Dense(256, kernel_regularizer = regularizers.l2(l = 0.016),activity_regularizer=regularizers.l1(0.006),
                bias_regularizer=regularizers.l1(0.006) ,activation='relu')(x)
x=Dropout(rate=.4, seed=123)(x)       
output=Dense(3, activation='softmax')(x)
model=Model(inputs=base_model.input, outputs=output)
lr=.001 # start with this learning rate
model.compile(Adamax(learning_rate=lr), loss='categorical_crossentropy', metrics=['accuracy']) 

然后在测试生成器集Shuffle = false

remove the code

model.add(Input(shape=(128,128,3)))

You have already specified the input shape the the VGG19 model code. In the VGG code change to

baseModel = tf.keras.applications.VGG19(input_shape=(128,128,3), include_top=False, weights='imagenet', poooling='max')

This makes the output of the base model a vector that can be used as input to a dense layer. Then add code after baseModel

x=base_model.output
x=BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001 )(x)
x = Dense(256, kernel_regularizer = regularizers.l2(l = 0.016),activity_regularizer=regularizers.l1(0.006),
                bias_regularizer=regularizers.l1(0.006) ,activation='relu')(x)
x=Dropout(rate=.4, seed=123)(x)       
output=Dense(3, activation='softmax')(x)
model=Model(inputs=base_model.input, outputs=output)
lr=.001 # start with this learning rate
model.compile(Adamax(learning_rate=lr), loss='categorical_crossentropy', metrics=['accuracy']) 

Also in your test generator set shuffle=False

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文