Search code examples
pythontensorflowkerasconv-neural-networkkeras-layer

Conv 1d and its input


I have a numpy array of array with shape (273, 168) so 273 sample and every sample has 168 observation.

I want as output 273 array of 24 observations.

Why my code give me a problem of dim differences?

x = np.random.randint(0,1,(273,168))
y = np.random.randint(0,1,(273,24))


model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv1D(7, activation='relu', kernel_size=(3), input_shape=(168,273)))
model.add(tf.keras.layers.Dropout(0.2))
model.add(tf.keras.layers.Dense(24))


model.compile(loss=tf.losses.MeanSquaredError(),
            optimizer=tf.optimizers.Adam(),
            metrics=[tf.metrics.MeanAbsoluteError()])

model.fit(x,y))

model.predcit(x[42])

Anyone can help me?


Solution

  • If you check the error message that you get, you can see that the required number of dimensions is 3, you are passing just 2 (n_samples, n_features), you need to reshape you data using .reshape(n_samples, 1, n_features) your input_shape is also incorrect.

    Finally, you need to set padding='same', or your input data runs out of dimensions. (You can try running without setting padding to same and see what error you get)

    This code works:

    x = np.random.randint(0,1,(273,168)).reshape(273, 1, 168)
    y = np.random.randint(0,1,(273,24)).reshape(273, 1, 24)
    
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Conv1D(7, activation='relu', kernel_size=(3), padding='same', input_shape=(1,168)))
    model.add(tf.keras.layers.Dropout(0.2))
    model.add(tf.keras.layers.Dense(24))
    
    
    model.compile(loss=tf.losses.MeanSquaredError(),
                optimizer=tf.optimizers.Adam(),
                metrics=[tf.metrics.MeanAbsoluteError()])
    
    model.fit(x,y)