Here is the error in full:
Exception: Error when checking model input: expected convolution2d_input_1 to have shape (None, 3, 224, 224) but got array with shape (20, 3, 244, 244)
Everything works until the final model.fit_generator(...) chunk of code. I am using a theano backend.
I'm pretty new to keras, so I'm not sure exactly how to proceed. Checking the documentation I can see that the None in layers.convolutional.Convolution2D corresponds to the number of batches (or samples)? Substituting input_shape=(20,3,244,244) yielded the following error Exception: Input 0 is incompatible with layer conv1_1: expected ndim=4, found ndim=5. Using 23000 instead of 20 yielded the same error.
Any help is appreciated.
Below is my code:
# ======================
# load data
# ======================
# Set relevant paths for dir structure
current_dir = "/home/ubuntu/nbs/"
DATA_HOME_DIR = current_dir + 'lesson1/data/redux'
path = DATA_HOME_DIR + '/'
train_path = DATA_HOME_DIR + '/train/'
valid_path = DATA_HOME_DIR + '/valid/'
test_path = DATA_HOME_DIR + '/test/'
nb_train_samples = 23000
nb_validation_samples = 2000
nb_epoch = 4
# ======================
# import stuff
# ======================
import numpy as np
from keras.utils.data_utils import get_file
from keras import backend as K
from keras.layers.normalization import BatchNormalization
from keras.models import Sequential
from keras.layers.core import Flatten, Dense, Dropout, Lambda
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.layers.pooling import GlobalAveragePooling2D
from keras.optimizers import SGD, RMSprop, Adam
from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator
# ======================
# define model
# ======================
def vgg():
model = Sequential()
model.add(Convolution2D(64, 3, 3,input_shape=(3,224,224), activation='relu', name='conv1_1'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_2'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_1'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_2'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_1'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_2'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_3'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_1'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_2'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_3'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_1'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_2'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_3'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(Flatten())
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1000, activation='softmax'))
return model
model = vgg()
print model.summary()
#### load weights
fname = 'vgg16.h5'
model.load_weights(get_file(fname, 'http://www.platform.ai/models/'+fname, cache_subdir='models'))
print "successfully created model and loaded weights"
#### Finetune model
model.pop()
for layer in model.layers: layer.trainable=False
model.add(Dense(batches.nb_class, activation='softmax'))
#### Compile model
model.compile(optimizer=Adam(lr=0.01),
loss='categorical_crossentropy', metrics=['accuracy'])
train_datagen = ImageDataGenerator(
rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_path,
target_size=(244,244),
batch_size = 20,
class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(
valid_path,
target_size=(244,244),
batch_size=20,
class_mode='categorical')
model.fit_generator(
train_generator,
samples_per_epoch=nb_train_samples,
nb_epoch=nb_epoch,
validation_data=validation_generator,
nb_val_samples=nb_validation_samples)
There is a mismatch between the expected size of the images and the actual one. Your model expects images of size 224 x 224 and according to the attached error message actual size is 244 x 244.
Related
I want to apply GridSearchCV on the autoencoder model. The code of the atuoencoder and GridSearchCV is added below please tell me how I change this code to run GridSearchCV successfully.
autoencoder = Sequential()
# Encoder Layers
autoencoder.add(Conv2D(16, (3, 3), activation='relu', padding='same', input_shape=x_train.shape[1:]))
autoencoder.add(MaxPooling2D((2, 2), padding='same'))
autoencoder.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
autoencoder.add(MaxPooling2D((2, 2), padding='same'))
autoencoder.add(Conv2D(8, (3, 3), strides=(2,2), activation='relu', padding='same'))
# Flatten encoding for visualization
autoencoder.add(Flatten())
autoencoder.add(Reshape((4, 4, 8)))
# Decoder Layers
autoencoder.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
autoencoder.add(UpSampling2D((2, 2)))
autoencoder.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
autoencoder.add(UpSampling2D((2, 2)))
autoencoder.add(Conv2D(16, (3, 3), activation='relu'))
autoencoder.add(UpSampling2D((2, 2)))
autoencoder.add(Conv2D(1, (3, 3), activation='sigmoid', padding='same'))
autoencoder.summary()
I want to apply GridSearch on the above autoencoder code
from sklearn.model_selection import GridSearchCV
from keras.wrappers.scikit_learn import KerasClassifier
model_classifier = KerasClassifier(autoencoder, verbose=1, batch_size=10, epochs=10)
# define the grid search parameters
batch_size = [10]
loss = ['mean_squared_error', 'binary_crossentropy']
optimizer = [Adam, SGD, RMSprop]
learning_rate = [0.001]
epochs = [3, 5]
param_grid = dict(optimizer=optimizer, learning_rate=learning_rate)
grid = GridSearchCV(cv=[(slice(None), slice(None))], estimator=model_classifier, param_grid=param_grid, n_jobs=1)
grid_result = grid.fit(x_train, x_train)
print("training Successfully completed")
I have solved this by hard code. I applied for lop on every parameter and get the result.
For best parameter selection I have find the parameter on which I have got high results.
i am trying to use VGG16 pretrained in Keras, but i keep getting this error:
ValueError: Error when checking target: expected block5_pool to have 4 dimensions, but got array with shape (6, 1)
What is the error mean?
Error when checking target: expected block5_pool to have 4 dimensions,
but got array with shape (6, 1)
This the my actual code:
from keras import applications
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
# dimensions of our images.
img_width, img_height = 224, 224
train_data_dir = 'database/train'
validation_data_dir = 'database/validation'
nb_train_samples = 2000
nb_validation_samples = 26
epochs = 50
batch_size = 20
if K.image_data_format() == 'channels_first':
input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)
model = applications.VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
print('VGG-16 Model loaded.')
top_model = Sequential()
top_model.add(ZeroPadding2D((1,1),input_shape=input_shape))
top_model.add(Conv2D(64, (3, 3), activation='relu'))
top_model.add(ZeroPadding2D((1,1)))
top_model.add(Conv2D(64, (3, 3), activation='relu'))
top_model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))
top_model.add(ZeroPadding2D((1,1)))
top_model.add(Conv2D(128, (3, 3), activation='relu'))
top_model.add(ZeroPadding2D((1,1)))
top_model.add(Conv2D(128, (3, 3), activation='relu'))
top_model.add(MaxPooling2D((2,2), strides=(2,2)))
top_model.add(ZeroPadding2D((1,1)))
top_model.add(Conv2D(256, (3, 3), activation='relu'))
top_model.add(ZeroPadding2D((1,1)))
top_model.add(Conv2D(256, (3, 3), activation='relu'))
top_model.add(ZeroPadding2D((1,1)))
top_model.add(Conv2D(256, (3, 3), activation='relu'))
top_model.add(MaxPooling2D((2,2), strides=(2,2)))
top_model.add(ZeroPadding2D((1,1)))
top_model.add(Conv2D(512, (3, 3), activation='relu'))
top_model.add(ZeroPadding2D((1,1)))
top_model.add(Conv2D(512, (3, 3), activation='relu'))
top_model.add(ZeroPadding2D((1,1)))
top_model.add(Conv2D(512, (3, 3), activation='relu'))
top_model.add(MaxPooling2D((2,2), strides=(2,2)))
top_model.add(ZeroPadding2D((1,1)))
top_model.add(Conv2D(512, (3, 3), activation='relu'))
top_model.add(ZeroPadding2D((1,1)))
top_model.add(Conv2D(512, (3, 3), activation='relu'))
top_model.add(ZeroPadding2D((1,1)))
top_model.add(Conv2D(512, (3, 3), activation='relu'))
top_model.add(MaxPooling2D((2,2), strides=(2,2)))
top_model.add(Flatten())
top_model.add(Dense(4096, activation='relu'))
top_model.add(Dropout(0.5))
top_model.add(Dense(12))
top_model.add(Activation('softmax'))
# note that it is necessary to start with a fully-trained
# classifier, including the top classifier,
# in order to successfully do fine-tuning
# top_model.load_weights('./vgg16_face_weights.h5')
# add the model on top of the convolutional base
model.add_update(top_model)
# set the first 25 layers (up to the last conv block)
# to non-trainable (weights will not be updated)
for layer in model.layers[:25]:
layer.trainable = False
model.compile(loss='sparse_categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
rescale=1. / 255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
model.fit_generator(
train_generator,
steps_per_epoch=nb_train_samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=nb_validation_samples // batch_size)
model.save_weights('first_try.h5')
The terminal run:
VGG-16 Model loaded.
Found 46 images belonging to 12 classes.
Found 26 images belonging to 12 classes.
Epoch 1/50
Traceback (most recent call last):
File "C:/Users/w024029h/PycharmProjects/keras_pretrained/pretrained.py", line 113, in <module>
validation_steps=nb_validation_samples // batch_size)
File "C:\Users\w024029h\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "C:\Users\w024029h\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\engine\training.py", line 2230, in fit_generator
class_weight=class_weight)
File "C:\Users\w024029h\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\engine\training.py", line 1877, in train_on_batch
class_weight=class_weight)
File "C:\Users\w024029h\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\engine\training.py", line 1480, in _standardize_user_data
exception_prefix='target')
File "C:\Users\w024029h\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\engine\training.py", line 113, in _standardize_input_data
'with shape ' + str(data_shape))
ValueError: Error when checking target: expected block5_pool to have 4 dimensions, but got array with shape (6, 1)
I had this same error before. I resolved it by changing the class_mode on the data generators from 'binary' to None
According to the keras docs, setting the class_mode to 'binary' will return a 1-D array.
By changing the class_mode=None, no labels are returned and the generator will only yield batches of image data. This is what you are expecting with your model and this works well with the fit_generator() method. However, when using class_mode None, the data still needs to reside in a subdirectory of directory for it to work correctly.
This page was useful to me
^look at flow_from_directory()
Hope this helps!
Hello guys I am trying to make pretrained VGG16 on Keras
But it keeps give me error:
ValueError: Error when checking target: expected activation_1 to have
shape (2622,) but got array with shape (1,)
I was trying to create the model based on this poster : Link
Also, I took the pre-trained weight from here. This weight can be read on here
This my code:
from keras import applications
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential, Model
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense, ZeroPadding2D
from keras import backend as K
# dimensions of our images.
img_width, img_height = 224, 224
train_data_dir = 'database/train'
validation_data_dir = 'database/validation'
nb_train_samples = 2000
nb_validation_samples = 800
epochs = 50
batch_size = 16
if K.image_data_format() == 'channels_first':
input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)
# build the VGG16 network
model = applications.VGG16(weights='imagenet', include_top=False)
print('VGG Pretrained Model loaded.')
model = Sequential()
model.add(ZeroPadding2D((1, 1), input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(256, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(256, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(256, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(512, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(512, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(512, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(512, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(512, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(512, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(Conv2D(4096, (7, 7), activation='relu'))
model.add(Dropout(0.5))
model.add(Conv2D(4096, (1, 1), activation='relu'))
model.add(Dropout(0.5))
model.add(Conv2D(2622, (1, 1)))
model.add(Flatten())
model.add(Activation('softmax'))
# model.load_weights('./vgg16_face_weights.h5')
#
# vgg_face_descriptor = Model(inputs=model.layers[0].input, outputs=model.layers[-2].output)
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
rescale=1. / 224,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 224)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
model.fit_generator(
train_generator,
steps_per_epoch=nb_train_samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=nb_validation_samples // batch_size)
model.save_weights('first_try.h5')
You probably have only one folder inside 'database/train' and 'database/validation'.
Please make sure you have 2622 folders in the two folders so that keras can generate the label correctly.
Following is an example showing that the label should have shape of (batch_size, 2622).
# the above remains the same
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
import numpy as np
classes = 2622
batch_size = 4
y = np.zeros((batch_size, classes))
for i in range(batch_size):
y[i, np.random.choice(classes)] = 1
model.fit(x=np.random.random((batch_size,)+input_shape), y=y, batch_size=batch_size)
model.save_weights('first_try.h5')
EDIT:
To change the last Conv2D layer from 2622 filters to 12 filters while maintaining the loaded weights, here is a workaround:
#define model and load_weights
#......
#build a new model based on the last model
conv = Conv2D(12, (1, 1))(model.layers[-4].output)
flatten = Flatten()(conv)
softmax = Activation('softmax')(flatten)
final_model = Model(inputs=model.input, outputs=softmax)
Ref:Cannot add layers to saved Keras Model. 'Model' object has no attribute 'add'
I am working on the some kind of the 2D Regression Deep network with keras, but the network has constant output for every datasets, even I test with handmade dataset in this code I feed the network with a constant 2d values and the output is linear valu of the X (2*X/100) but the out put is constant.
import resource
import glob
import gc
rsrc = resource.RLIMIT_DATA
soft, hard = resource.getrlimit(rsrc)
print ('Soft limit starts as :', soft)
resource.setrlimit(rsrc, (4 * 1024 * 1024 * 1024, hard)) # limit to four giga bytes
soft, hard = resource.getrlimit(rsrc)
print ('Soft limit changed to :', soft)
from keras.models import Sequential
import keras.optimizers
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization
from keras.layers import Convolution2D, MaxPooling2D,AveragePooling2D
import numpy as np
import random
from keras.utils import plot_model
sample_size = 1
batch_size = 50
input_shape = (int(720 / 4), int(1280 / 4), sample_size * 5)
# model
model = Sequential()
model.add(BatchNormalization(input_shape=input_shape))
model.add(Convolution2D(128, (3, 3), activation='relu', dim_ordering="tf", padding="same",kernel_initializer='random_uniform'))
model.add(Convolution2D(128, (3, 3), activation='sigmoid', dim_ordering="tf", padding="same",kernel_initializer='random_uniform'))
model.add(AveragePooling2D(pool_size=(4, 4), dim_ordering="tf"))
model.add(Convolution2D(256, (3, 3), activation='sigmoid', dim_ordering="tf", padding="same",kernel_initializer='random_uniform'))
model.add(Convolution2D(256, (3, 3), activation='sigmoid', dim_ordering="tf", padding="same",kernel_initializer='random_uniform'))
model.add(AveragePooling2D(pool_size=(4, 4), dim_ordering="tf"))
model.add(Convolution2D(512, (3, 3), activation='sigmoid', dim_ordering="tf", padding="same",kernel_initializer='random_uniform'))
model.add(Convolution2D(512, (3, 3), activation='sigmoid', dim_ordering="tf", padding="same",kernel_initializer='random_uniform'))
model.add(AveragePooling2D(pool_size=(4, 4), dim_ordering="tf"))
model.add(Flatten())
model.add(Dense(4096, activation='relu',kernel_initializer='random_uniform'))
#model.add(Dropout(0.5))
model.add(Dense(512, activation='sigmoid',kernel_initializer='random_uniform'))
model.add(Dense(1, activation='sigmoid',kernel_initializer='random_uniform'))
model.compile(loss='mean_absolute_error',
optimizer='adam',
metrics=['mae','mse'])
model.summary()
plot_model(model,to_file='model.png')
def generate_tr(batch_size, is_training=False):
x=np.linspace(0, 10, num=5000).reshape(-1, 1)
counter = 0
print 'start'
while 1:
samples=np.zeros((batch_size, 720/4, 1280/4, 5))
labels=[]
for t in range (batch_size):
i = int(random.randint(0, 4999))
for b in range(sample_size):
samples[t, :,:,b*5:b*5+5] = np.random.rand(720/4,1280/4,5)/10+x[i]
labels.append((2*x[i])/100)
counter += 1
print counter #, labels
yield ((samples), np.asarray(labels))
tt = model.fit_generator(generate_tr(batch_size, True), steps_per_epoch=100, epochs=10,
use_multiprocessing=False, verbose=2)
score = model.predict_generator(generate_tr(batch_size, True), steps=30)
the output is always average of all of the values (here is .10)
do you know why?
How do I create a VGG-16 sequence for my data?
The data has the following :
model = Sequential()
model.add(ZeroPadding2D((1, 1), input_shape=(3, img_width, img_height))) model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_1')) model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_2'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_1')) model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_2'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_1')) model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_2'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_3')) model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_1')) model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_2'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_3')) model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_1')) model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_2'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_3')) model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(Flatten())
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1000, activation='softmax'))
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(optimizer=sgd, loss='categorical_crossentropy')
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=32)
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=32)
model.fit_generator(
train_generator,
samples_per_epoch=2000,
nb_epoch=1,
verbose=1,
validation_data=validation_generator,
nb_val_samples=800)
json_string = model.to_json()
open('my_model_architecture.json','w').write(json_string)
model.save_weights('Second_try.h5')
I got an error:
Exception: Error when checking model target: expected dense_3 to have
shape (None, 32) but got array with shape (32, 2)
How do I change Dense to make it work?
I have 10 species,
I have solved the problem by
changing:
model.add(Dense(1000, activation='softmax'))
to:
model.add(Dense(10, activation='softmax'))
then it works.
Here instead of 1000 you should have the total number of classes because it's the output layer.
model.add(Dense(1000, activation='softmax'))
Also shape of labels (or Y_train/Y_test) should be (total number of classes, total number records).
This helped me resolve similar kind of error.