I defined a simple two-layer Convolutional network in Keras. When feed only a sample input to check the Tensor size and values for each Convolutional layer, why I get this error?
Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (1, 4, 4)
Below is the simple code:
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
from keras import backend as K
import numpy as np
input_img = Input(shape=(4, 4, 1))
# adapt this if using channels_first image data format
x = Conv2D(2, (2, 2), activation='relu')(input_img)
y = Conv2D(3, (2, 2), activation='relu')(x)
model = Model(input_img, y)
# cnv_ml_1 = Model(input_img, x)
data = np.array([[[5, 12, 1, 8], [2, 10, 3, 6], [4, 7, 9, 1], [5, 7, 5, 6]]])
# data = data.reshape(4, 4, 1)
# print(data)
print(model.predict(data))
print(model.summary())
You need to add batch_size
in your data. In the example, when you reshape the data, you forget to define batch_size
. Here is a simple solution to fix the issue:
import numpy as np
from tensorflow.python.keras import Model, Input
from tensorflow.python.keras.layers import Conv2D
input_img = Input(shape=(4, 4, 1))
# adapt this if using channels_first image data format
x = Conv2D(2, (2, 2), activation='relu', data_format='channels_last')(input_img)
y = Conv2D(3, (2, 2), activation='relu', data_format='channels_last')(x)
model = Model(input_img, y)
cnv_ml_1 = Model(input_img, x)
data = np.array([[[5, 12, 1, 8], [2, 10, 3, 6], [4, 7, 9, 1], [5, 7, 5, 6]]])
data = data.reshape(1, 4, 4, 1) # assume batch size is 1
print(data)
print(model.predict(data))
print(model.summary())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.