0

I'm trying to train a classification model on 10 different training sets, I tried using a for loop to iterate the sets names in a dictionary then pass them in fit() method in each iteration. Here is the code:

for n in range (1, 11):
    classifier = tf.keras.models.Sequential()
    classifier.add(tf.keras.layers.Dense(units=8, activation='relu'))
    classifier.add(tf.keras.layers.Dense(units=8, activation='relu'))
    classifier.add(tf.keras.layers.Dense(units=5, activation='softmax'))
    classifier.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'])
    X_train_value, Y_train_value = "X_train_{0}".format(n), "Y_train_{0}".format(n)
    classifier_args = {'x':X_train_value,'y':Y_train_value}
    classifier.fit(**classifier_args, batch_size=32, epochs=100)

but I this error:

IndexError: list index out of range
desertnaut
  • 57,590
  • 26
  • 140
  • 166

1 Answers1

0

With dictionary you will have to first create a dictionary with key being the name of the variable as a string and the value being the actual variable. However, this information is already available in vars(), so you can use it rather then creating one.

Use vars()

sample

import tensorflow as tf
import numpy as np

X_train_1 = np.random.randn(10)
X_train_2 = np.random.randn(10)
X_train_3 = np.random.randn(10)

Y_train_1 = np.random.randint(0, 5, size=(10))
Y_train_2 = np.random.randint(0, 5, size=(10))
Y_train_3 = np.random.randint(0, 5, size=(10))

for n in range (1, 4):
    classifier = tf.keras.models.Sequential()
    classifier.add(tf.keras.layers.Dense(units=8, activation='relu'))
    classifier.add(tf.keras.layers.Dense(units=5, activation='softmax'))
    classifier.compile(optimizer = 'adam', 
                       loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'])

    classifier.fit(vars()["X_train_{0}".format(n)], vars()["Y_train_{0}".format(n)], epochs=2)

Output

Epoch 1/2
1/1 [==============================] - 0s 1ms/step - loss: 1.6550 - accuracy: 0.1000
Epoch 2/2
1/1 [==============================] - 0s 2ms/step - loss: 1.6523 - accuracy: 0.1000
Epoch 1/2
1/1 [==============================] - 0s 1ms/step - loss: 1.6760 - accuracy: 0.3000
Epoch 2/2
1/1 [==============================] - 0s 2ms/step - loss: 1.6737 - accuracy: 0.3000
Epoch 1/2
1/1 [==============================] - 0s 1ms/step - loss: 1.5701 - accuracy: 0.2000
Epoch 2/2
1/1 [==============================] - 0s 2ms/step - loss: 1.5681 - accuracy: 0.2000
mujjiga
  • 16,186
  • 2
  • 33
  • 51