How use extracted features as input to the vgg19 model? - keras

I have extracted the features using AlexNet and want to use it as input to VGG19.
The shape of features is (2144, 3), and the input shape of VGG 19 is (224, 224, 3)
How to reshape the features?
ValueError: Input 0 of layer "model_1" is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(None, 3)

Related

Building a cnn-lstm model, getting this error and have no idea how to go about it

model.add(LSTM(100, input_shape=(156,156, 3), return_sequences=True)) #error
model.add(LSTM(Embedding(8192, 256)))
model.add(LSTM(SpatialDropout1D(0.3)))
model.add(LSTM(256, dropout=0.3, recurrent_dropout=0.3))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(5, activation='softmax'))
ValueError: Input 0 of layer "lstm_10" is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 1)
The shapes of my data:
x_train shape : (1532, 156, 156, 3) y_train shape : (1532,)
x_test shape : (384, 156, 156, 3) y_test shape : (384,)
Trying to build a cnn-lstm model for a project. The LSTM layer as mentioned is throwing an error.

Problem in prediction of my image in my own trained Keras model

I trained my model using transfer learning. Now when I am predicting my image in Colab it shows me an error:
WARNING:tensorflow:Model was constructed with shape (None, 128, 128, 3) for input Tensor("xception_input:0", shape=(None, 128, 128, 3), dtype=float32), but it was called on an input with incompatible shape (None, 275, 3).
WARNING:tensorflow:Model was constructed with shape (None, 128, 128, 3) for input Tensor("input_1:0", shape=(None, 128, 128, 3), dtype=float32), but it was called on an input with incompatible shape (None, 275, 3).
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-142a5ca8cbef> in <module>()
1 import numpy as np
----> 2 classes = np.argmax(model.predict(img), axis=-1)
3 print(classes)
.
.
.
ValueError: Input 0 of layer block1_conv1 is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: [None, 275, 3]
Basically during training, you were feeding a batch of images as input the network, the same will be required at the test/evaluation time. So, the easy solution would be to expand the dimension of img tensor to [1, img.shape].
img_test = tf.expand_dims(img, axis=0)
The message is saying that you trained your model using a shape of
shape=(None, 128, 128, 3)
but when you try to predict from the model you provided an input of
[None, 275, 3]
Obviously, this cannot be used by your model. First of all, you provided a 3dim dimension input but you should have provided a 4dim one. Typically images are (height, width, 3) and if you provide them in batches this becomes (batch_size, height, width, 3) and if you have just one image it becomes:
(1, height, width, 3)
So, you should check the input you provide your model with. With numpy you typically use something like
np.expand_dims(original_image, axis=0)
to go from 3dim to 4dim input.

Tensorflow says Input 0 of layer conv2d is incompatible with the layer: expected ndim=4, found ndim=3

Here's my code:
(x_train, y_train), (x_test, y_test) = mnist.load_data()
def create_model():
model = tf.keras.models.Sequential()
model.add(Conv2D(64, (3, 3), input_shape=x_train.shape[1:], activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dense(10, activation='softmax'))
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
return model
model = create_model()
the input data shape is (60000, 28, 28). its the keras mnist dataset.
and here's the error
ValueError: Input 0 of layer conv2d_1 is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [None, 28, 28]
An I have no idea whats wrong with it.
Input shape
4D tensor with shape: (batch, channels, rows, cols) if data_format is "channels_first" or 4D tensor with shape: (batch, rows, cols, channels) if data_format is "channels_last".
The Input shape is expected as (batch,channels,rows,cols) you have given number of images.
create a variable like image_size=(3,28,28)
and
input_shape = image_size
... This might work for you. or try
input_shape = (3,28,28)
I realized my mistake mnist data has a shape: (sample, width, height) and Conv2D layers require a shape (samples, width, height, depth), so the solution would be to add an extra dimension.
x_train = x_train[..., np.newaxis]
x_test = x_test[..., np.newaxis]

keras pre-trained ResNet50 target shape

I am trying to use ResNet50 Pretrained network for segmentation problem.
I remove the last layer and add my desired layer. But when I try to fit, I get the following error:
ValueError: Error when checking target: expected conv2d_1 to have shape (16, 16, 1) but got array with shape (512, 512, 1)
I have two folders: images and masks. images are RGB and masks are in grayscale.
The shape is 512x512 for all images.
I can not figure in which part am I doing wrong.
Any help will be appreciated.
from keras.applications.resnet50 import ResNet50
image_input=Input(shape=(512, 512, 3))
model = ResNet50(input_tensor=image_input,weights='imagenet',include_top=False)
x = model.output
x = Conv2D(1, (1,1), padding="same", activation="sigmoid")(x)
model = Model(inputs=model.input, outputs=x)
model.summary()
conv2d_1 (Conv2D) (None, 16, 16, 1) 2049 activation_49[0][0]
for layer in model.layers[:-1]:
layer.trainable = False
for layer in model.layers[-1:]:
layer.trainable = True
model.compile(optimizer=Adam(), loss='binary_crossentropy', metrics=['accuracy'])
Your network gives an output of shape (16, 16, 1) but your y (target) has shape (512, 512, 1)
Run the following to see this.
from keras.applications.resnet50 import ResNet50
from keras.layers import Input
image_input=Input(shape=(512, 512, 3))
model = ResNet50(input_tensor=image_input,weights='imagenet',include_top=False)
model.summary()
# Output shows that the ResNet50 network has output of shape (16,16,2048)
from keras.layers import Conv2D
conv2d = Conv2D(1, (1,1), padding="same", activation="sigmoid")
conv2d.compute_output_shape((None, 16, 16, 2048))
# Output shows the shape your network's output will have.
Either your y or the way you use ResNet50 has to change. Read about ResNet50 to see what you are missing.

Keras 2D Dense Layer for Output

I am playing with a model which should take a 8x8 chess board as input, encoded as a 224x224 grey image, and then output a 64x13 one-hot-encoded logistic regression = probabilities of pieces on the squares.
Now, after the Convolutional layers I don't quite know, how to proceed to get a 2D-Dense layer as a result/target.
I tried adding a Dense(64,13) as a layer to my Sequential model, but I get the error "Dense` can accept only 1 positional arguments ('units',)"
Is it even possible to train for 2D-targets?
EDIT1:
Here is the relevant part of my code, simplified:
# X.shape = (10000, 224, 224, 1)
# Y.shape = (10000, 64, 13)
model = Sequential([
Conv2D(8, (3,3), activation='relu', input_shape=(224, 224, 1)),
Conv2D(8, (3,3), activation='relu'),
# some more repetitive Conv + Pooling Layers here
Flatten(),
Dense(64,13)
])
TypeError: Dense can accept only 1 positional arguments ('units',), but you passed the following positional arguments: [64, 13]
EDIT2: As Anand V. Singh suggested, I changed Dense(64, 13) to Dense(832), which works fine. Loss = mse.
Wouldn't it be better to use "sparse_categorical_crossentropy" as loss and 64x1 encoding (instead of 64x13) ?
In Dense you only pass the number of layers you expect as output, if you want (64x13) as output, put the layer dimension as Dense(832) (64x13 = 832) and then reshape later. You will also need to reshape Y so as to accurately calculate loss, which will be used for back propagation.
# X.shape = (10000, 224, 224, 1)
# Y.shape = (10000, 64, 13)
Y = Y.reshape(10000, 64*13)
model = Sequential([
Conv2D(8, (3,3), activation='relu', input_shape=(224, 224, 1)),
Conv2D(8, (3,3), activation='relu'),
# some more repetitive Conv + Pooling Layers here
Flatten(),
Dense(64*13)
])
That should get the job done, if it doesn't post where it fails and we can proceed further.
A Reshape layer allows you to control the output shape.
Flatten(),
Dense(64*13),
Reshape((64,13))#2D

Resources