当我运行下面粘贴的代码时,模型只是在训练"乘数"=1或=4。在googlecolab中运行相同的代码→仅训练乘数=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
显然,如果使用自定义input_shape
(不是ImageNet的标准224x224x3(和include_top = False
,则有必要添加自定义GlobalAveragePooling和Dense Layer:
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)