How to store CNN extracted features to train a SVM classifier

Question:

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.

Asked By: user9165727

||

Answers:

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 article will help you extract features using a CNN model.

https://www.kdnuggets.com/2018/12/solve-image-classification-problem-quickly-easily.html/2

You’ll have the extracted features of all the images in a numpy array. Then you can decide to store it as a CSV file or any other file format like HDF5.

Answered By: Ini-Abasi Affiah