【问题标题】:CNN Keras using Hyperas error: AttributeError: 'str' object has no attribute 'ndim'CNN Keras 使用 Hyperas 错误:AttributeError: 'str' object has no attribute 'ndim'
【发布时间】:2019-07-12 15:55:11
【问题描述】:

模型编译并运行,直到到达代码末尾评估模型的行。我认为错误在于它收到了一个字符串,但没想到会收到一个字符串,但我不知道如何修复它。提前致谢。

def data():

train_data_dir = '/home/bjorn/Downloads/CATS_DOGS2/train'
validation_data_dir = '/home/bjorn/Downloads/CATS_DOGS2/test'
return train_data_dir, validation_data_dir


def model_one(train_data_dir, validation_data_dir):

img_width, img_height = 150, 150

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()

model.add(Conv2D({{choice([32, 64, 128, 256])}}, 3, 3, border_mode='same',
                 input_shape=input_shape, activation={{choice(['relu', 'sigmoid', 'softmax', 'tanh'])}}))
model.add(Conv2D({{choice([32, 64, 128, 256])}}, 3, 3, border_mode='same',
                 activation={{choice(['relu', 'sigmoid', 'softmax', 'tanh'])}}))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D({{choice([32, 64, 128, 256])}}, 3, 3, border_mode='same',
                 activation={{choice(['relu', 'sigmoid', 'softmax', 'tanh'])}}))
model.add(Conv2D({{choice([32, 64, 128, 256])}}, 3, 3, border_mode='same',
                 activation={{choice(['relu', 'sigmoid', 'softmax', 'tanh'])}}))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D({{choice([32, 64, 128, 256])}}, 3, 3, border_mode='same',
                 activation={{choice(['relu', 'sigmoid', 'softmax', 'tanh'])}}))
model.add(Conv2D({{choice([32, 64, 128, 256])}}, 3, 3, border_mode='same',
                 activation={{choice(['relu', 'sigmoid', 'softmax', 'tanh'])}}))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D({{choice([32, 64, 128, 256])}}, 3, 3, border_mode='same',
                 activation={{choice(['relu', 'sigmoid', 'softmax', 'tanh'])}}))
model.add(Conv2D({{choice([32, 64, 128, 256])}}, 3, 3, border_mode='same',
                 activation={{choice(['relu', 'sigmoid', 'softmax', 'tanh'])}}))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense({{choice([32, 64, 128, 256, 512])}},
                activation={{choice(['relu', 'sigmoid', 'softmax', 'tanh'])}}))
model.add(Dropout({{uniform(0, 0.75)}}))

model.add(Dense({{choice([32, 64, 128, 256, 512])}},
                activation={{choice(['relu', 'sigmoid', 'softmax', 'tanh'])}}))
model.add(Dropout({{uniform(0, 0.75)}}))

model.add(Dense(1))
model.add(Activation({{choice(['relu', 'sigmoid', 'softmax', 'tanh'])}}))

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

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.1,
    zoom_range=0.1,
    horizontal_flip=True)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=16,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=16,
    class_mode='binary')

result = model.fit_generator(
    train_generator,
    steps_per_epoch=125,
    epochs=5,
    verbose=2,
    validation_data=validation_generator,
    validation_steps=50)

# get the highest validation accuracy of the training epochs
validation_acc = np.amax(result.history['val_acc'])
print('Best validation acc of epoch:', validation_acc)
return {'loss': -validation_acc, 'status': STATUS_OK, 'model': model}

if __name__ == '__main__':
    best_run, best_model = optim.minimize(model=model_one,
                                          data=data,
                                          algo=tpe.suggest,
                                          max_evals=10,
                                          trials=Trials())

train_data_dir, validation_data_dir = data()
print('Evaluation of best performing model:')
print(best_model.evaluate(validation_data_dir))
print('Best performing model chosen hyper-parameters:')
print(best_run)

最佳性能模型的评估: data = [standardize_single_array(x) for x in data] 文件“/home/bjorn/PycharmProjects/Test/venv/lib/python3.5/site-packages/keras/engine/training_utils.py”,第 92 行,在 data = [standardize_single_array(x) for x in data] 文件“/home/bjorn/PycharmProjects/Test/venv/lib/python3.5/site-packages/keras/engine/training_utils.py”,第 27 行,位于standardize_single_array elif x.ndim == 1: AttributeError: 'str' 对象没有属性 'ndim'

进程以退出代码 1 结束

【问题讨论】:

    标签: python keras conv-neural-network hyperopt hyperas


    【解决方案1】:

    我从未使用过 keras,但据我所知, 很明显 best_model.evaluate(arg) 函数需要一个 numpy 数组作为参数。

    【讨论】:

    • 我添加了这个: print(best_model.evaluate(np.ndarray(shape=(len(validation_data_dir), 150, 150, 3)))) 尝试修复错误,但现在我' m 收到此错误:IndexError: list index out of range。我正在尝试解决此问题,但我真的不知道如何解决。
    • 看来您是 python 新手。我建议你从一门课程中用 Python 做一些基本的作业,这将帮助你解决这些极其常见的错误。 PY4E 是一个很好的免费练习网站。还要检查 Keras 的文档,以确保您以正确的数据类型传递正确的参数。
    猜你喜欢
    • 2020-04-26
    • 1970-01-01
    • 2018-12-01
    • 2017-05-10
    • 1970-01-01
    • 2019-06-09
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    相关资源
    最近更新 更多