Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build 1D Convolutional Neural Network in keras python?

I am solving a classification problem using CNN. I have data.csv file (15000 samples/rows & 271 columns), where 1st column is a class label(total 4 classes) and other 270 columns are features(6 different signals of length 45 concatenated i.e 6X45=270).

Problem: I want to provide single sample of length 270 as vector(6 X 45, all 6 signals have different meaning) but I am getting error in dimensions when reshaped a single sample to (6 rows, 45 colums) in convolution.
My CNN model:

X, y = load_data()   
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
num_classes = 4

X_train = X_train.reshape(X_train.shape[0], 6, 45).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 6, 45).astype('float32') 

model = Sequential()
model.add(Conv1D(filters=32, kernel_size=5, input_shape=(6, 45)))
model.add(MaxPooling1D(pool_size=5 ))
model.add(Flatten())
model.add(Dense(1000, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))  

How to reshape my data that CNN treats every single sample as 6 signals of 45 length and convolve with kernal of window 5.

like image 769
Arslan Avatar asked Apr 24 '18 15:04

Arslan


People also ask

Can we use CNN for 1D data?

You can certainly use a CNN to classify a 1D signal.

What is a 1D convolutional layer?

A 1-D convolutional layer applies sliding convolutional filters to 1-D input. The layer convolves the input by moving the filters along the input and computing the dot product of the weights and the input, then adding a bias term.

How do you calculate 1D convolution?

`To calculate 1D convolution by hand, you slide your kernel over the input, calculate the element-wise multiplications and sum them up.


1 Answers

You need to reshape your data like

X_train.reshape(num_of_examples, num_of_features, num_of_signals)

and change your input_shape in model to (45, 6). See the example code below,

X = np.random.randn(4000,270)
y = np.ones((4000,1))
y[0:999] = 2
y[1000:1999] = 3
y[2000:2999] = 0

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
num_classes = 4

X_train = X_train.reshape(X_train.shape[0], 45, 6).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 45, 6).astype('float32') 

model = Sequential()
model.add(Conv1D(filters=32, kernel_size=5, input_shape=(45, 6)))
model.add(MaxPooling1D(pool_size=5 ))
model.add(Flatten())
model.add(Dense(1000, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
like image 110
user8190410 Avatar answered Nov 11 '22 18:11

user8190410