我想通过迁移学习创建一个回归模型,但遇到了错误

我的目标是创建一个从单张图片预测两个数值的模型。
因此,我尝试实现迁移学习。然而,我遇到了一个错误。

模型实现如下所示。

# input img shape : (100,100,3)base = VGG16(weights='imagenet',include_top=False, input_shape=(100,100,3)) x = base.outputx = Dense(512, activation='relu')(x)x = Dropout(0.5)(x)output1 = Dense(1, activation='relu')(x)output2 = Dense(1, activation='relu')(x)model=Model(inputs=base.input,outputs=[output1,output2])model.compile(optimizer ='adam',loss = 'mse', metrics = ['mae'])# All data is stored in the listhistory = model.fit([np.array(trainIMG)],[np.array(trainVal1),np.array(trainVal2)],                    epochs=100,batch_size=8,                    validation_data=([np.array(TestIMG)],[np.array(testVal1),np.array(testVal2)])) 

错误↓

WARNING:tensorflow:The following Variables were used a Lambda layer's call (tf.tensordot), butare not present in its tracked objects:  <tf.Variable 'dense/kernel:0' shape=(512, 512) dtype=float32>It is possible that this is intended behavior, but it is more likelyan omission. This is a strong indication that this layer should beformulated as a subclassed Layer rather than a Lambda layer.WARNING:tensorflow:The following Variables were used a Lambda layer's call (tf.nn.bias_add), butare not present in its tracked objects:  <tf.Variable 'dense/bias:0' shape=(512,) dtype=float32>It is possible that this is intended behavior, but it is more likelyan omission. This is a strong indication that this layer should beformulated as a subclassed Layer rather than a Lambda layer.WARNING:tensorflow:The following Variables were used a Lambda layer's call (tf.tensordot_1), butare not present in its tracked objects:  <tf.Variable 'dense_1/kernel:0' shape=(512, 1) dtype=float32>It is possible that this is intended behavior, but it is more likelyan omission. This is a strong indication that this layer should beformulated as a subclassed Layer rather than a Lambda layer.WARNING:tensorflow:The following Variables were used a Lambda layer's call (tf.nn.bias_add_1), butare not present in its tracked objects:  <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32>It is possible that this is intended behavior, but it is more likelyan omission. This is a strong indication that this layer should beformulated as a subclassed Layer rather than a Lambda layer.WARNING:tensorflow:The following Variables were used a Lambda layer's call (tf.tensordot_2), butare not present in its tracked objects:  <tf.Variable 'dense_2/kernel:0' shape=(512, 1) dtype=float32>It is possible that this is intended behavior, but it is more likelyan omission. This is a strong indication that this layer should beformulated as a subclassed Layer rather than a Lambda layer.WARNING:tensorflow:The following Variables were used a Lambda layer's call (tf.nn.bias_add_2), butare not present in its tracked objects:  <tf.Variable 'dense_2/bias:0' shape=(1,) dtype=float32>It is possible that this is intended behavior, but it is more likelyan omission. This is a strong indication that this layer should beformulated as a subclassed Layer rather than a Lambda layer.2021-06-26 19:23:01.524564: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:176] None of the MLIR Optimization Passes are enabled (registered 2)Epoch 1/1002021-06-26 19:23:09.797624: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library cudnn64_8.dll2021-06-26 19:23:10.091894: I tensorflow/stream_executor/cuda/cuda_dnn.cc:359] Loaded cuDNN version 82002021-06-26 19:23:10.416480: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library cublas64_11.dll2021-06-26 19:23:10.669945: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library cublasLt64_11.dll2021-06-26 19:23:11.181791: W tensorflow/core/framework/op_kernel.cc:1755] Invalid argument: required broadcastable shapes at loc(unknown)2021-06-26 19:23:11.182116: W tensorflow/core/framework/op_kernel.cc:1755] Invalid argument: required broadcastable shapes at loc(unknown)Traceback (most recent call last):  File "c:/Users/userA/OneDrive/doc/StudyAI/CNN.py", line 164, in <module>    history = model.fit([np.array(PPG_train)],[np.array(S_IBP_train),np.array(D_IBP_train)],  File "C:\Users\userA\anaconda3\lib\site-packages\keras\engine\training.py", line 1158, in fit    tmp_logs = self.train_function(iterator)  File "C:\Users\userA\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 889, in __call__    result = self._call(*args, **kwds)  File "C:\Users\userA\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 950, in _call    return self._stateless_fn(*args, **kwds)  File "C:\Users\userA\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 3023, in __call__    return graph_function._call_flat(  File "C:\Users\userA\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 1960, in _call_flat    return self._build_call_outputs(self._inference_function.call(  File "C:\Users\userA\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 591, in call    outputs = execute.execute(  File "C:\Users\userA\anaconda3\lib\site-packages\tensorflow\python\eager\execute.py", line 59, in quick_execute    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,tensorflow.python.framework.errors_impl.InvalidArgumentError:  required broadcastable shapes at loc(unknown)         [[node sub (defined at C:\Users\userA\anaconda3\lib\site-packages\keras\losses.py:1301) ]] [Op:__inference_train_function_2222]Errors may have originated from an input operation.Input Source operations connected to node sub: model/tf.nn.relu_1/Relu (defined at C:\Users\userA\anaconda3\lib\site-packages\keras\engine\functional.py:551) ExpandDims (defined at C:\Users\userA\anaconda3\lib\site-packages\keras\engine\data_adapter.py:1414)Function call stack:train_function

回答:

这个错误是因为您指定的损失函数与输出形状不匹配。输出的形状是(3,3,1)(使用model.summary()查看),所以您不能为它们指定mse损失函数。对于通过密集层输入数据,首先需要展平数据。

因此,您应该在第一个密集层之前先展平数据,像这样:

x = base.outputx = tf.keras.layers.Flatten()(x)       # 添加这一行x = Dense(512, activation='relu')(x)x = Dropout(0.5)(x)output1 = Dense(1, activation='relu')(x)output2 = Dense(1, activation='relu')(x)model=Model(inputs=base.input,outputs=[output1,output2])model.compile(optimizer ='adam',loss = 'mse', metrics = ['mae'])

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注