0

当我运行下面粘贴的代码时,模型只是针对“乘数”=1 或 =4 进行训练。在 google colab 中运行相同的代码 → 只训练 multiplier=1

我在这里使用 DenseNet 的方式有什么错误吗?

在此先感谢,感谢您的帮助!

import numpy as np
import tensorflow as tf
from tensorflow.keras.applications.densenet import DenseNet201
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.losses import BinaryCrossentropy


random_array = np.random.rand(128,128,3)
image = tf.convert_to_tensor(
    random_array
)
label = tf.constant(0)



model = DenseNet201(
    include_top=False, weights='imagenet', input_tensor=None,
    input_shape=(128, 128, 3), pooling=None, classes=2
)
model.compile(
optimizer=Adam(),
loss=BinaryCrossentropy(),
metrics=['accuracy'],
)


for multiplier in range(1,20):

    print(f"Using multiplier {multiplier}")
    x_train = np.array([image]*multiplier)
    y_train = np.array([label]*multiplier)



    try: 
        model.fit(x=x_train,y=y_train, epochs=2)
    except:
        print("Not training...")
        pass

如果训练没有开始,输出是:

2021-12-01 11:48:40.372387: W tensorflow/core/framework/op_kernel.cc:1680] Invalid argument: required broadcastable shapes
2021-12-01 11:48:40.372660: W tensorflow/core/framework/op_kernel.cc:1680] Invalid argument: required broadcastable shapes
2021-12-01 11:48:40.372734: W tensorflow/core/framework/op_kernel.cc:1680] Invalid argument: required broadcastable shapes
4

1 回答 1

0

input_shape显然,如果使用自定义(不是 ImageNet 的标准 224x224x3),则有必要添加自定义 GlobalAveragePooling 和 Dense 层include_top = False

base_model = DenseNet201(
    include_top=False, weights='imagenet', input_tensor=None,
    input_shape=(128, 128, 3),
    pooling=None, classes=2
)

x= base_model.output
x = GlobalAveragePooling2D(name = "avg_pool")(x)
outputs = Dense(2, activation=tf.nn.softmax, name="predictions")(x)

model = Model(base_model.input, outputs)
于 2021-12-02T11:35:52.190 回答