Я пытаюсь настроить нейронную сеть для визуального ответа на вопрос, но потеря продолжает расходиться. Изменения гиперпараметров Basi c не дали результатов, и я пробовал разные модели тоже безрезультатно. Вот модель, которую я использовал:
word2vec_dim = 30
num_hidden_nodes_mlp = 1024
num_hidden_nodes_lstm = 30
num_layers_lstm = 2
dropout = 0.3
activation_mlp = 'tanh'
num_epochs = 1
image_model = Sequential()
image_model.add(Reshape(input_shape = (320,480,4), target_shape=(320,480,4)))
image_model.add(Conv2D(4,(3,1)))
image_model.add(Conv2D(4,(1,3)))
image_model.add(MaxPooling2D(pool_size=(2, 2)))
image_model.add(Conv2D(4,(3,1)))
image_model.add(Conv2D(4,(1,3)))
image_model.add(MaxPooling2D(pool_size=(2, 2)))
image_model.add(Conv2D(4,(3,1)))
image_model.add(Conv2D(4,(1,3)))
image_model.add(MaxPooling2D(pool_size=(2, 2)))
image_model.add(Conv2D(4,(3,1)))
image_model.add(Conv2D(4,(1,3)))
image_model.add(Flatten())
image_model.add(Dense(num_hidden_nodes_lstm, activation='relu'))
model1 = Model(inputs = image_model.input, outputs = image_model.output)
model1.summary()
language_model = Sequential()
language_model.add(Embedding(len(unique_words)+1, word2vec_dim, input_length=max_lenght))
language_model.add(LSTM(units=num_hidden_nodes_lstm,
return_sequences=True, input_shape=(None, word2vec_dim)))
for i in range(num_layers_lstm-2):
language_model.add(LSTM(units=num_hidden_nodes_lstm, return_sequences=True))
language_model.add(LSTM(units=num_hidden_nodes_lstm, return_sequences=False))
model2 = Model(language_model.input, language_model.output)
model2.summary()
combined = concatenate([image_model.output, language_model.output])
model = Dense(512, activation="tanh", kernel_initializer="uniform")(combined)
#model = Activation('tanh')(model)
model = Dropout(0.3)(model)
model = Dense(512, activation="tanh", kernel_initializer="uniform")(model)
#model = Activation('tanh')(model)
#model = Dropout(0.5)(model)
#model = Dense(1024, activation="tanh", kernel_initializer="uniform")(model)
#model = Activation('tanh')(model)
#model = Dropout(0.5)(model)
model = Dense(13, activation="softmax")(model)
model = Model(inputs=[image_model.input, language_model.input], outputs=model)
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
model.summary()
Здесь вместо учебного кода. Набор данных был разделен на 80/20, размер пакета 64, эпохи невелики, но, поскольку набор данных большой (партии по 3 КБ), потери увеличиваются до достижения 10% от одного. целевой класс words задается одним горячим кодированием, а кодирование вопроса выполняется с использованием однозначного словарного соответствия (с использованием диктионарии для каждого слова, поскольку их немного), оставляя 0 в качестве значения заполнения. У меня есть запятые, знаки вопроса и др. c. жестко.
train_gen=image_generator(batch_size=batch_size)
eval_gen=evaluation_generator(batch_size=batch_size)
model.fit(x=train_gen, epochs=2, verbose=1, validation_data=eval_gen, steps_per_epoch=training_batches ,validation_steps=evaluation_batches, shuffle=True, max_queue_size=10, callbacks=[save])
Я также получаю это предупреждающее сообщение
/opt/conda/lib/python3.6/site-packages/tensorflow_core/python/framework/indexed_slices.py:433: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.
"Converting sparse IndexedSlices to a dense Tensor of unknown shape. "
Epoch 1/2
522/3243 [===>..........................] - ETA: 33:05 - loss: 2825421622922535501824.0000
Я заметил, что модель ответит на все вопросы с тем же классом (я предполагаю, что это является причиной расходящиеся потери).
, где определен image_generator:
def my_hash (word):
for x in range(dictionary_lenght-1):
if word==unique_words[x]:
return (x+1)
print("Error, word not in the vocabulary")
def pad(sequence, lenght, value=0):
for x in range(len(sequence), lenght):
sequence.append(value)
return sequence
def image_generator(batch_size = 32):
zeros=[0]*13
while True:
for x2 in range(training_batches):# Select files (paths/indices) for the batch
input_img_batch = []
input_question_batch = []
output_batch = []
img_name=""
for x in range(batch_size):
temp=[]
img_name=training_data["questions"][x+x2*batch_size]["image_filename"]
question=training_data["questions"][x+x2*batch_size]["question"].replace("?","")
question=hashing_trick(question, dictionary_lenght,hash_function=my_hash)
question=pad(question, max_lenght)
img = Image.open("/kaggle/input/ann-and-dl-vqa/dataset_vqa/train/" + img_name , 'r')
img=img.resize([img_width, img_height])
img=np.asarray(img)#execute the same process as before but the corrispective mask
img=img/255
input_img_batch.append(img)
input_question_batch.append(question)
dummy=zeros
dummy[encode_answer(training_data["questions"][x+x2*batch_size]["answer"])]=1
output_batch.append(dummy)
# Return a tuple of (input,output) to feed the network
batch_x1 = np.array( input_img_batch )
batch_x2 = np.array( input_question_batch )
batch_y = np.array( output_batch )
yield( [batch_x1, batch_x2], batch_y )