Build a basic model for arrays of arrays data samples

Hi all, I’m trying to build a “simple” model to predict basic arm movements. Every movement as described as an array of a variable length, which contains sub-arrays of fixed length = 3 (i.e. something like this: [[1,2,3],[4,5,6], … , [100,102,103]]).

I’ve tried to build a model this way, but I guess something is wrong because I’m getting error when i try to make the prediction (the training seems ok):

import numpy as np
import tensorflow as tf

# Create the model
model = tf.keras.Sequential([
    tf.keras.layers.Dense(3, activation='relu', input_shape=(None, 9)),  # Adjusted input shape
    tf.keras.layers.Dense(2, activation='softmax')
])

# Compile the model
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# Train the model
data = np.array([[[2, 3, 5], [6, 8, 9], [10, 11, 12]], [[2, 1, 3], [3, 5, 6], [4, 5, 2]]])
labels = np.array([0, 1])  # One label for each group of arrays

# Reshape the data to combine all groups into one sample
data = np.reshape(data, (2, -1))

model.fit(data, labels, epochs=10)



to_predict = np.array([[2,14,3],[3,56,6]])

predictions = model.predict(to_predict)
print(predictions)

Hi @Quiquoqua48, You should add padding to to_predict array so that it should match the input_shape of the model.

to_predict = np.array([[2,14,3],[3,56,6]])
x=np.pad(to_predict,((0, 0), (0, 6)), 'constant', constant_values=0)
predictions = model.predict(x)
print(predictions)

Now you can make predictions using that. Please refer to this gist for working code example.

Thank you for your answer! It solve the prediction problem, but I’ve another problem now, I think that the model as now doesn’t make what I guessed… I’ll try to explain, maybe you can help me:

the result, i.e. [[0.5 0.5 ], [0.49962947 0.50037056]], if I correctly understand, considers [2,14,3] and [3,56,6] as different input to calculate the prediction on, while I would like to have a prediction on [[2,14,3],[3,56,6]] as single data (also [[2,14,3],[3,56,6],[3,4,6]] should be ok… my problem is not the length, but the fact that I need to have a percent result for one list of arrays considered as one single sample). Is there a way to perform that?

Hi @Quiquoqua48, As you have defined the model input_shape as (None , 9), while making predictions the model will accept the same shape. Even when you try to make predictions using [[2,14,3],[3,56,6],[3,4,6]] you will get an error because the 2nd dimension has only 3 elements but the model accepts 9 elements. To make predictions make sure that the 2nd dimensions should have 9 elements. Thank You.