Как обучить модель LSTM с несколькими отдельными обучающими данными?

#python #machine-learning #keras #neural-network #lstm

#python #машинное обучение #keras #нейронная сеть #lstm

Вопрос:

У меня есть данные о продажах, которые 100 продавцов совершили за 1 год.

И я хочу, чтобы ОДНА модель предсказывала все 100 продаж мужских продаж позже.

Вот мой код:

 model=Sequential()

y_train=sells_men_sell[1] # sells_men_sell[1] is a 1d array that contains the first sells  man's sells record

x_train=sells_men_data[1] # sells_men_sell[1] is a array that contains the first sells  man's sells record for training
#, each value in the array(sells_men_sell) contains the sells record for the past 30 days.

model.add(LSTM(50, input_shape=(x_train.shape[1], x_train.shape[2])))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(x_train, y_train, batch_size=1, epoch=1)
  

Я знаю, что прогнозировать 100 продаж в одной модели звучит странно, но я делаю это для проекта.

Что мне делать с моим кодом?

Должен ли я добавить следующий код после model.fit(x_train, y_train, batch_size=1, epoch=1) ?

 y_train1=sells_men_sell[2] # sells_men_sell[2] is a 1d array that contains the second sells  man's sells record

x_train1=sells_men_data[2] # sells_men_sell[2] is a array that contains the second sells man's sells record for training

model.add(LSTM(50, input_shape=(x_train1.shape[1], x_train1.shape[2])))
model.fit(x_train1, y_train1, batch_size=1, epoch=1)
  

Комментарии:

1. Должна ли ваша модель иметь 100 различных входных слоев?

2. Аникет Боте, вы имеете в виду добавить 100 слоев LSTM в модель?

3. Проверьте ответ ниже. Это то, что вы хотите. Я дал ответ, основанный на вашем названии.

4. Не могли бы вы немного объяснить, что именно вы хотите, чтобы я мог изменить свой ans.

Ответ №1:

Ваша модель может иметь несколько входов, а также несколько выходов. Для достижения этой цели вы можете использовать функциональный API.
Я поделился небольшим примером того, как вы можете этого добиться. Вы можете адаптировать пример для вашего случая использования.

Код:

 # imports
import tensorflow as tf
import pandas as pd 
import numpy as np

# genration of dummy data
x1 = np.random.randint(100, size =(5, 5, 5), dtype = np.int16)
x2 = np.random.randint(100, size =(5, 4, 4), dtype = np.int16)
y1 = np.random.randint(2, size =(5,), dtype = np.int16)
y2 = np.random.randint(2, size =(5,), dtype = np.int16)

# creation of model
def create_model3():
    input1 = tf.keras.Input(shape=(5,5,), name = 'I1')
    input2 = tf.keras.Input(shape=(4,4,), name = 'I2')
    
    hidden1 = tf.keras.layers.LSTM(units = 4)(input1)
    hidden2 = tf.keras.layers.LSTM(units = 4)(input2)
    merge = tf.keras.layers.concatenate([hidden1, hidden2])
    hidden3 = tf.keras.layers.Dense(units = 3, activation='relu')(merge)
    output1 = tf.keras.layers.Dense(units = 2, activation='softmax', name ='O1')(hidden3)
    output2 = tf.keras.layers.Dense(units = 2, activation='softmax', name = 'O2')(hidden3)
    
    model = tf.keras.models.Model(inputs = [input1,input2], outputs = [output1,output2])
    
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    return model



model = create_model3()
tf.keras.utils.plot_model(model, 'my_first_model.png', show_shapes=True)

# training the model
history = model.fit(
    x = {'I1':x1, 'I2':x2}, 
    y = {'O1':y1, 'O2': y2},
    batch_size = 32,
    epochs = 10,
    verbose = 1,
    callbacks = None,
#     validation_data = [(val_data,new_val_data),(val_labels, new_val_labels)]
)
  

Сгенерированная модель выглядит следующим образом.

Моя модель