You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Hyperas优化CNN时遇TypeError: bad operand type for unary -: 'list'求助

Let's break down and fix your issues step by step:

1. The Root Cause of TypeError: bad operand type for unary -: 'list'

In your create_model function, you have:

acc = history.history['acc']
# ...
return {'loss': -acc, 'status': STATUS_OK, 'model': model}

history.history['acc'] returns a list of accuracy values (one for each training epoch). You can't apply the unary - operator directly to a list—Hyperas expects a single scalar value for the loss metric.

Fix this by using the accuracy from the last epoch (since that's the final performance we care about):

return {'loss': -acc[-1], 'status': STATUS_OK, 'model': model}

2. Fix Mismatched Input Shapes

Your data preprocessing resizes images to (100, 100), but your first Conv2D layer defines an input shape of (150, 150, 3). This will cause a shape mismatch error. Update the input shape to match your data:

model.add(layers.Conv2D(16, (3, 3), activation='tanh', input_shape=(100, 100, 3)))

3. Correct Model Training & Parameter Definitions

  • Your data() function returns numpy arrays, but you're using model.fit_generator (which is designed for ImageDataGenerator generators). Use model.fit instead for direct numpy input.
  • Your create_model function is defined to take train_generator, validation_generator, but you're passing raw numpy arrays. Update the function signature to match the data returned by data():
def create_model(x_train, y_train, x_val, y_val):
    # ... rest of your model code ...
    # Replace fit_generator with fit
    history = model.fit(x_train, y_train, 
                        steps_per_epoch=4, epochs=2, 
                        validation_data=(x_val, y_val), 
                        validation_steps=7)
    # ... rest of your code ...

4. Uncomment & Fix Hyperas Execution Code

You have the Hyperas optimization code commented out. Uncomment it and make sure it's correctly structured (also remove the direct create_model call, since Hyperas handles this automatically):

# Remove this line: create_model(x_train, y_train, x_val, y_val)

if __name__ == '__main__':
    best_run, best_model = optim.minimize(model=create_model,
                                          data=data,
                                          algo=tpe.suggest,
                                          max_evals=5,
                                          trials=Trials())
    print("Best performing model chosen hyper-parameters:")
    print(best_run)

Additional Improvement: Sync Data-Label Shuffling

Your current shuffle function only shuffles one array at a time, which can misalign your images and their labels. Replace it with a function that shuffles data and labels in sync:

def shuffle_data(x, y, seed=16):
    np.random.seed(seed)
    indices = np.random.permutation(len(x))
    return x[indices], y[indices]

# Use it like this:
train_array, train_tags = shuffle_data(train_array, train_tags)
val_array, val_tags = shuffle_data(val_array, val_tags)

After making all these fixes, your code should run without the TypeError and Hyperas will start optimizing your Dropout rate parameter.

内容的提问来源于stack exchange,提问作者lrdewaal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 08:57:35