使用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 usingmodel.fit_generator(which is designed forImageDataGeneratorgenerators). Usemodel.fitinstead for direct numpy input. - Your
create_modelfunction is defined to taketrain_generator, validation_generator, but you're passing raw numpy arrays. Update the function signature to match the data returned bydata():
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

