Я пытаюсь построить сложную модель нейронной сети, чтобы попытаться получить высокий показатель val_a cc. Как работает эта модель, я обучил две разные модели с разными архитектурами и сохранил их. Я собираю эти две модели вместе и создаю еще одну архитектуру нейронной сети для вывода. (Код создан по этой ссылке: https://machinelearningmastery.com/stacking-ensemble-for-deep-learning-neural-networks/ (непосредственно переходите к интегрированному стекированию sub-topi c)
dir_name = '/content/drive/My Drive/'
layer_name = ['twitter_3.h5','fasttext_3.h5'] # models trained on different architectures and embeddings
#load models and give layers different names
for i in layer_name:
model = load_model(dir_name+i)
f=0
for layer in model.layers:
layer.trainable = False
layer.name = 'ensemble'+i+'_'+layer.name
f+=1
#append all loaded models in a list
all_models = []
for i in layer_name:
model = load_model(dir_name+i)
all_models.append(model)
# list of input and outputs in an array
ensemble_visible = [model.input for model in all_models]
ensemble_outputs = [model.output for model in all_models]
#Stratified k fold for sampling different batches
folds = StratifiedKFold(n_splits = 5, shuffle = True, random_state=25)
oof = np.empty([len(X_t),len(list_classes)])
sub_preds = np.zeros([len(X_te),len(list_classes)])
foldwise_auc = []
#build and train model
for fold_, (trn_idx, val_idx) in enumerate(folds.split(y[:,0], y[:,0])): #StratifiedKFold expects array of shape (n,)
if fold_ == 1:
break
X_train, y_train = X_t[trn_idx], y[trn_idx]
X_val, y_val = X_t[val_idx], y[val_idx]
print("Running fold %d" % fold_)
ra_val = RocAucEvaluation(validation_data=(X_val, y_val), interval=1)
earlystop = EarlyStopping(monitor='val_loss', mode="min", patience=5, verbose=1)
def build_model(ensemble_outputs,ensemble_visible,lr = 0.0, lr_d = 0.0, units = 0, dr = 0.0):
merge = concatenate(ensemble_outputs)
hidden = Dense(12, activation='relu')(merge)
output = Dense(6, activation='sigmoid')(hidden)
model = Model(inputs=ensemble_visible, outputs=output)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
#model = Model(inputs = inp, outputs = x)
#model.compile(loss = "binary_crossentropy", optimizer = Adam(lr = lr, decay = lr_d), metrics = ["accuracy"])
X = [X_train for _ in range(2)]
X_v = [X_val for _ in range(2)]
model.summary()
model.fit([np.asarray(X_train),np.asarray(X_train)],y_train, batch_size = 2048, epochs = 1, validation_data = ([np.asarray(X_val),np.asarray(X_val)], y_val),verbose = 1, callbacks = [ra_val, earlystop])
return model
modelx = build_model(ensemble_outputs,ensemble_visible,lr = 1e-3, lr_d = 0, units = 144, dr = 0.2)
pred = modelx.predict([np.asarray(X_val),np.asarray(X_val)], batch_size = 1024, verbose = 1)
oof[val_idx] = pred
sub_preds += modelx.predict([X_te,X_te], batch_size=1024, verbose=1) / n_splits
auc=0
for i in range(len(list_classes)):
auc += roc_auc_score(y[:,i], oof[:,i]) / len(list_classes)
print("AUC for full run: %.6f" % auc)
validation = pd.DataFrame(oof, columns = list_classes)
validation.to_csv('Ensemble', index=False)
submission = pd.concat([test['id'], pd.DataFrame(sub_preds, columns = list_classes)], axis=1)
submission.to_csv('sEnsemble_Submission', index=False)
Но когда я пытаюсь передать ввод через модель, он работает в течение одной эпохи, а затем выдает следующую ошибку:
Train on 127656 samples, validate on 31915 samples
Epoch 1/1
127656/127656 [==============================] - 45s 350us/step - loss: 0.3582 - acc: 0.9896 - val_loss: 0.3224 - val_acc: 0.9943
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-50-4d274c66b613> in <module>()
27 return model
28
---> 29 modelx = build_model(ensemble_outputs,ensemble_visible,lr = 1e-3, lr_d = 0, units = 144, dr = 0.2)
30
31 pred = modelx.predict([np.asarray(X_val),np.asarray(X_val)], batch_size = 1024, verbose = 1)
ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 2 array(s), but instead got the following list of 1 arrays: [array([[ 0, 0, 0, ..., 2086, 33, 9],
[ 0, 0, 0, ..., 131, 1700, 70116],
[ 0, 0, 0, ..., 3240, 6513, 28],
...,
[ 0, ...
В нем говорится, что ожидается увидеть два массива, но я передаю два массива, как видно из кода. Может кто-нибудь помочь мне понять это?