我正在一个项目中,需要预测图像中是否有车辆。为此,我使用的是已经在Caffe中训练过的模型,我已将权重转换为Keras,并基于prototxt定义了图层。 正确加载权重并以适当的形状定义要预测的图像后,我将其传递给了预测函数,导致矩阵大小不兼容的错误。 设置模型时,我可能会犯错,但是经过数小时的研究和寻找解决方案后,我无法解决它。
import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Dropout, Flatten, Conv2D, MaxPooling2D, Dropout, BatchNormalization
from tensorflow.keras.initializers import glorot_uniform, Constant
import numpy as np
np.random.seed(1000)
model = Sequential()
model.add(Conv2D(filters=16, activation='relu', input_shape=(224, 224, 3), kernel_size=(11, 11), strides=(4,4)))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
model.add(Conv2D(filters=20, activation='relu', kernel_size=(5, 5), strides=(1, 1)))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
model.add(Conv2D(filters=30, activation='relu', kernel_size=(3, 3), strides=(1, 1)))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
model.add(Flatten())
model.add(Dense(48, activation='relu', input_shape=(224*224*3,)))
model.add(Dense(2, activation='softmax'))
model.summary()
model.load_weights('CNRPARK-EXT-Keras.h5')
import cv2
imgPath = "../dataset150x150/A/"
imgBusyPath = imgPath + "busy/"
img = cv2.imread(imgBusyPath + "20150703_0805_8.jpg")
import matplotlib.pyplot as plt
%matplotlib inline
plt.imshow(img)
img = cv2.resize(img, (224, 224))
img = img.reshape(-1, 224, 224, 3)
img.shape
model.predict(img)
执行预测时生成错误:
InvalidArgumentError Traceback (most recent call last)
<ipython-input-10-a59b8e0bb15a> in <module>
----> 1 model.predict(img)
/opt/anaconda3/envs/PFG/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training.py in predict(self, x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing)
906 max_queue_size=max_queue_size,
907 workers=workers,
--> 908 use_multiprocessing=use_multiprocessing)
909
910 def reset_metrics(self):
/opt/anaconda3/envs/PFG/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_arrays.py in predict(self, model, x, batch_size, verbose, steps, callbacks, **kwargs)
721 verbose=verbose,
722 steps=steps,
--> 723 callbacks=callbacks)
/opt/anaconda3/envs/PFG/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_arrays.py in model_iteration(model, inputs, targets, sample_weights, batch_size, epochs, verbose, callbacks, val_inputs, val_targets, val_sample_weights, shuffle, initial_epoch, steps_per_epoch, validation_steps, validation_freq, mode, validation_in_fit, prepared_feed_values_from_dataset, steps_name, **kwargs)
392
393 # Get outputs.
--> 394 batch_outs = f(ins_batch)
395 if not isinstance(batch_outs, list):
396 batch_outs = [batch_outs]
/opt/anaconda3/envs/PFG/lib/python3.7/site-packages/tensorflow_core/python/keras/backend.py in __call__(self, inputs)
3474
3475 fetched = self._callable_fn(*array_vals,
-> 3476 run_metadata=self.run_metadata)
3477 self._call_fetch_callbacks(fetched[-len(self._fetches):])
3478 output_structure = nest.pack_sequence_as(
/opt/anaconda3/envs/PFG/lib/python3.7/site-packages/tensorflow_core/python/client/session.py in __call__(self, *args, **kwargs)
1470 ret = tf_session.TF_SessionRunCallable(self._session._session,
1471 self._handle, args,
-> 1472 run_metadata_ptr)
1473 if run_metadata:
1474 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
InvalidArgumentError: Matrix size-incompatible: In[0]: [1,270], In[1]: [480,48]
[[{{node dense/MatMul}}]]