Проблема оптимизации байесовского гиперпараметра Кераса - PullRequest
0 голосов
/ 06 февраля 2019

Я пытаюсь создать оптимизированную модель, которая использует эту базу данных: https://www.kaggle.com/aaron7sun/stocknews

Я попытался выполнить следующие инструкции: Как использовать hyperopt для оптимизации гиперпараметров в сети глубокого обучения Keras?

В литературе выясняется, что байесовская оптимизация является лучшим решением на данный момент.Но когда я пытаюсь реализовать это, я продолжаю получать эту ошибку:

TypeError: объект «генератора» не может быть подписан

Может кто-нибудь дать мне более подробную информацию о том, кака почему это не работает?

from __future__ import print_function


import numpy as np
import tensorflow as tf
import random as rn

np.random.seed(1)

rn.seed(2)
session_conf = tf.ConfigProto(intra_op_parallelism_threads=1,
                              inter_op_parallelism_threads=1)
from keras import backend as K
tf.set_random_seed(2)
sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
K.set_session(sess)


from hyperopt import Trials, STATUS_OK, tpe
from hyperas import optim
from hyperas.distributions import choice, uniform

def data():
    from keras.utils import to_categorical
    from keras.preprocessing.sequence import pad_sequences
    from keras.preprocessing.text import Tokenizer
    import pandas as pd
    DJIA = pd.read_csv("Combined_News_DJIA.csv")
    start_train = '2008-08-08'
    end_train = '2014-12-31'
    start_val = '2015-01-02'
    end_val = '2016-07-01'
    max_sequence_length = 110
    vocab_size = 3000
    # create training and testing dataframe on 80 % and 20 % respectively
    Training_dataframe = DJIA[(DJIA['Date'] >= start_train) & (DJIA['Date'] <= end_train)]
    Testing_dataframe = DJIA[(DJIA['Date'] >= start_val) & (DJIA['Date'] <= end_val)]

    attrib = DJIA.columns.values

    x_train = Training_dataframe.loc[:, attrib[2:len(attrib)]]
    y_train = Training_dataframe.iloc[:, 1]

    x_test = Testing_dataframe.loc[:, attrib[2:len(attrib)]]
    y_test = Testing_dataframe.iloc[:, 1]

    # merge the 25 news together to form a single signal
    merged_x_train = x_train.apply(lambda x: ''.join(str(x.values)), axis=1)
    merged_x_test = x_test.apply(lambda x: ''.join(str(x.values)), axis=1)

    # ===============
    # pre-process
    # ===============

    # remove stopwords in the training and testing set
    train_without_sw = []
    test_without_sw = []
    train_temporary = list(merged_x_train)
    test_temporary = list(merged_x_test)
    stop_words = ['I', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll",
                  "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', "she's",
                  'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their', 'theirs',
                  'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', 'am', 'is',
                  'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did',
                  'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at',
                  'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after',
                  'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again',
                  'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both',
                  'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same',
                  'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've",
                  'now', 'd', 'll', 'm', 'o', 're', 've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn',
                  "didn't", 'doesn', "doesn't", 'hadn', "hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't",
                  'ma', 'mightn', "mightn't", 'mustn', "mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn',
                  "shouldn't", 'wasn', "wasn't", 'weren', "weren't", 'won', "won't", 'wouldn', "wouldn't"]

    for i in train_temporary:
        f = i.split(' ')
        for j in f:
            if j in stop_words:
                f.remove(j)
        s1 = ""
        for k in f:
            s1 += k + " "
        train_without_sw.append(s1)
    merged_x_train = train_without_sw

    for i in test_temporary:
        f = i.split(' ')
        for j in f:
            if j in stop_words:
                f.remove(j)
        s1 = ""
        for k in f:
            s1 += k + " "
        test_without_sw.append(s1)
    merged_x_test = test_without_sw

    # tokenize and create sequences
    tokenizer = Tokenizer(num_words=vocab_size)
    tokenizer.fit_on_texts(merged_x_train)
    x_train = tokenizer.texts_to_sequences(merged_x_train)
    x_test = tokenizer.texts_to_sequences(merged_x_test)

    word_index = tokenizer.word_index
    input_dim = len(word_index) + 1
    print('Found %s unique tokens.' % len(word_index))

    x_train = pad_sequences(x_train, maxlen=max_sequence_length)
    x_test = pad_sequences(x_test, maxlen=max_sequence_length)

    y_train = to_categorical(y_train)
    y_test = to_categorical(y_test)

    return x_train, y_train, x_test, y_test


def model(x_train, y_train, x_test, y_test):
    from keras.models import Sequential
    from keras.layers import Dense, ELU, Dropout, LSTM, Embedding
    max_sequence_length = 110
    vocab_size = 3000
    embedding_dim = 256
    verbose = 2
    model = Sequential()
    model.add(Embedding(vocab_size, embedding_dim, input_length=max_sequence_length, mask_zero=True))
    model.add(LSTM({{choice([32, 64,126, 256, 512, 1024])}}, recurrent_dropout={{uniform(0, .5)}}, return_sequences=False))
    model.add(ELU())
    model.add(Dropout({{uniform(0, .5)}}))
    model.add(Dense(2, activation='softmax'))
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=["binary_accuracy"])
    model.fit(x_train, y_train, batch_size={{choice([16, 32, 64, 128])}},
              validation_data=(x_test, y_test), verbose=verbose, shuffle=True, epochs=5)

    score, acc = model.evaluate(x_test, y_test, verbose=2)
    print('Test accuracy:', acc)
    return {'loss': -acc, 'status': STATUS_OK, 'model': model}

if __name__ == '__main__':
    import gc; gc.collect()

    with K.get_session(): ## TF session
        best_run, best_model = optim.minimize(model=model,
                                              data=data,
                                              algo=tpe.suggest,
                                              max_evals=2,
                                              trials=Trials())
        X_train, Y_train, X_test, Y_test = data()
        print("Evalutation of best performing model:")
        print(best_model.evaluate(X_test, Y_test))
        print("Best performing model chosen hyper-parameters:")
        print(best_run)

Заранее большое спасибо за терпение

...