Keras:TypeError模块不可调用(例如)

时间:2017-05-23 23:10:57

标签: python keras

我正在尝试从https://github.com/maxpumperla/hyperas运行完整示例(复制如下)。

示例中的代码:

from __future__ import print_function

from hyperopt import Trials, STATUS_OK, tpe
from keras.datasets import mnist
from keras.layers.core import Dense, Dropout, Activation
from keras.models import Sequential
from keras.utils import np_utils

from hyperas import optim
from hyperas.distributions import choice, uniform, conditional


def data():
    """
    Data providing function:

    This function is separated from model() so that hyperopt
    won't reload data for each evaluation run.
    """
    (x_train, y_train), (x_test, y_test) = mnist.load_data()
    x_train = x_train.reshape(60000, 784)
    x_test = x_test.reshape(10000, 784)
    x_train = x_train.astype('float32')
    x_test = x_test.astype('float32')
    x_train /= 255
    x_test /= 255
    nb_classes = 10
    y_train = np_utils.to_categorical(y_train, nb_classes)
    y_test = np_utils.to_categorical(y_test, nb_classes)
    return x_train, y_train, x_test, y_test


def model(x_train, y_train, x_test, y_test):
    """
    Model providing function:

    Create Keras model with double curly brackets dropped-in as needed.
    Return value has to be a valid python dictionary with two customary keys:
        - loss: Specify a numeric evaluation metric to be minimized
        - status: Just use STATUS_OK and see hyperopt documentation if not feasible
    The last one is optional, though recommended, namely:
        - model: specify the model just created so that we can later use it again.
    """
    model = Sequential()
    model.add(Dense(512, input_shape=(784,)))
    model.add(Activation('relu'))
    model.add(Dropout({{uniform(0, 1)}}))
    model.add(Dense({{choice([256, 512, 1024])}}))
    model.add(Activation({{choice(['relu', 'sigmoid'])}}))
    model.add(Dropout({{uniform(0, 1)}}))

    # If we choose 'four', add an additional fourth layer
    if conditional({{choice(['three', 'four'])}}) == 'four':
        model.add(Dense(100))

        # We can also choose between complete sets of layers

        model.add({{choice([Dropout(0.5), Activation('linear')])}})
        model.add(Activation('relu'))

    model.add(Dense(10))
    model.add(Activation('softmax'))

    model.compile(loss='categorical_crossentropy', metrics=['accuracy'],
                  optimizer={{choice(['rmsprop', 'adam', 'sgd'])}})

    model.fit(x_train, y_train,
              batch_size={{choice([64, 128])}},
              epochs=1,
              verbose=2,
              validation_data=(x_test, y_test))
    score, acc = model.evaluate(x_test, y_test, verbose=0)
    print('Test accuracy:', acc)
    return {'loss': -acc, 'status': STATUS_OK, 'model': model}


if __name__ == '__main__':
    best_run, best_model = optim.minimize(model=model,
                                          data=data,
                                          algo=tpe.suggest,
                                          max_evals=5,
                                          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)

我正在使用

  • hyperopt:0.0.4
  • keras:2.0.3
  • hyperas:0.2(不是开发版,即0.3)
  • Python 2.7.12,Anaconda

我得到的错误是:

Traceback (most recent call last):
  File "hyperas_test.py", line 82, in <module>
    trials=Trials())
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/hyperas/optim.py", line 32, in minimize
    best_run = base_minimizer(model, data, algo, max_evals, trials, rseed)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/hyperas/optim.py", line 120, in base_minimizer
    rstate=np.random.RandomState(rseed))
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/hyperopt-0.0.4-py2.7.egg/hyperopt/fmin.py", line 306, in fmin
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/hyperopt-0.0.4-py2.7.egg/hyperopt/base.py", line 633, in fmin
TypeError: 'module' object is not callable

__main__部分发生此错误。

部分trials=Trials()看起来是故意调用模块Trials,通过from hyperopt import Trials导入。

知道我做错了吗?

编辑:可能有趣的是,只要我使用Canopy而不是Anaconda,this simpler example运行没问题。

0 个答案:

没有答案