TinyML Gesture TensorFlow Training Tutorial Error

I'm trying to work through the first tutorial with my Nano BLE 33 Sense and have gotten to the Jupyter notebook portion where you're supposed to be training the model - but when I try to run the code in the 'Run with Test Data' section I keep getting the error:

ValueError                                Traceback (most recent call last)
<ipython-input-25-797f8421ff49> in <cell line: 11>()
      9 plt.clf()
     10 plt.title('Training data predicted vs actual values')
---> 11 plt.plot(inputs_test, outputs_test, 'b.', label='Actual')
     12 plt.plot(inputs_test, predictions, 'r.', label='Predicted')
     13 plt.show()

3 frames
/usr/local/lib/python3.9/dist-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs, return_kwargs, ambiguous_fmt_datakey)
    520         ncx, ncy = x.shape[1], y.shape[1]
    521         if ncx > 1 and ncy > 1 and ncx != ncy:
--> 522             raise ValueError(f"x has {ncx} columns but y has {ncy} columns")
    523         if ncx == 0 or ncy == 0:
    524             return []

ValueError: x has 714 columns but y has 2 columns

I've tried with 2 different data sets but can't work out where to change the array size and how. Would appreciate your help!

This is the code it's trying to run:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf

print(f"TensorFlow version = {tf.__version__}\n")

# Set a fixed random seed value, for reproducibility, this will allow us to get
# the same random numbers each time the notebook is run
SEED = 1337
np.random.seed(SEED)
tf.random.set_seed(SEED)

# the list of gestures that data is available for
GESTURES = [
    "punch",
    "flex",
]

SAMPLES_PER_GESTURE = 119

NUM_GESTURES = len(GESTURES)

# create a one-hot encoded matrix that is used in the output
ONE_HOT_ENCODED_GESTURES = np.eye(NUM_GESTURES)

inputs = []
outputs = []

# read each csv file and push an input and output
for gesture_index in range(NUM_GESTURES):
  gesture = GESTURES[gesture_index]
  print(f"Processing index {gesture_index} for gesture '{gesture}'.")
  
  output = ONE_HOT_ENCODED_GESTURES[gesture_index]
  
  df = pd.read_csv("/content/" + gesture + ".csv")
  
  # calculate the number of gesture recordings in the file
  num_recordings = int(df.shape[0] / SAMPLES_PER_GESTURE)
  
  print(f"\tThere are {num_recordings} recordings of the {gesture} gesture.")
  
  for i in range(num_recordings):
    tensor = []
    for j in range(SAMPLES_PER_GESTURE):
      index = i * SAMPLES_PER_GESTURE + j
      # normalize the input data, between 0 to 1:
      # - acceleration is between: -4 to +4
      # - gyroscope is between: -2000 to +2000
      tensor += [
          (df['aX'][index] + 4) / 8,
          (df['aY'][index] + 4) / 8,
          (df['aZ'][index] + 4) / 8,
          (df['gX'][index] + 2000) / 4000,
          (df['gY'][index] + 2000) / 4000,
          (df['gZ'][index] + 2000) / 4000
      ]

    inputs.append(tensor)
    outputs.append(output)

# convert the list to numpy array
inputs = np.array(inputs)
outputs = np.array(outputs)

print("Data set parsing and preparation complete.")

# build the model and train it
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(50, activation='relu')) # relu is used for performance
model.add(tf.keras.layers.Dense(15, activation='relu'))
model.add(tf.keras.layers.Dense(NUM_GESTURES, activation='softmax')) # softmax is used, because we only expect one gesture to occur per input
model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])
history = model.fit(inputs_train, outputs_train, epochs=600, batch_size=1, validation_data=(inputs_validate, outputs_validate))

# use the model to predict the test inputs
predictions = model.predict(inputs_test)

# print the predictions and the expected ouputs
print("predictions =\n", np.round(predictions, decimals=3))
print("actual =\n", outputs_test)

# Plot the predictions along with to the test data
plt.clf()
plt.title('Training data predicted vs actual values')
plt.plot(inputs_test, outputs_test, 'b.', label='Actual')
plt.plot(inputs_test, predictions, 'r.', label='Predicted')
plt.show()

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.