How to store CNN extracted features to train a SVM classifier

Issue

Using the 2D CNN shown below to extract features from images, how I can store the extracted features in order to train an SVM to classify the features?

Model:

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(3, 150, 150)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())  # this converts our 3D feature maps to 1D feature vectors
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(4))
model.add(Activation('softmax'))

Extracting features with:

layer_name = 'layer_name'
intermediate_layer_model = Model(inputs=model.input,
                                 outputs=model.get_layer(layer_name).output)
intermediate_output = intermediate_layer_model.predict(data)

Steps:

  • Storing these extracted features from my image dataset in order to train an SVM classifier.

  • Using train_test_split() to split the train and test data

  • Train the classifier:

    clf = svm.SVC()
    clf.fit(X, y)  
    

I need to know how to do this.

Solution

You can try saving and loading them as HDF5 file format. It has several advantages over pickle. It’s much faster to save and load (especially for large arrays).

To do so, you need to install h5py package. Example codes for saving and loading are as follows:

For saving:

import h5py
h5f = h5py.File('your_file_name.h5', 'w')
h5f.create_dataset('layer_model', data=intermediate_layer_model)
h5f.create_dataset('output', data=intermediate_output)
h5f.close()

For loading

import h5py
h5f = h5py.File('your_file_name.h5', 'r')
intermediate_layer_model = h5f['layer_model'][:]
intermediate_output = h5f['output'][:]
h5f.close()

Answered By – Ary

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published