CNN训练触发TypeError:float()参数类型异常求解决方案
Hey there, let's dig into your problem step by step and fix those issues one by one!
1. The Direct Cause of Your TypeError: Uncalled flatten() Method
Looking at your generator code, this line is the root of the float() conversion error:
labels.append((np.array(batch_sample[1].flatten)).transpose())
flatten is a method of numpy arrays, not a property. You need to call it with parentheses flatten()—right now you're passing the method object itself instead of the flattened numerical values. Fix it to:
labels.append(np.array(batch_sample[1].flatten()).transpose())
2. Wrong Loss Function for Your Task
You mentioned this is an image detection (regression) task (output corresponds to 1D image size parameters), but you're using sparse_categorical_crossentropy—this loss is designed for classification tasks, not regression. Swap it for a regression-friendly loss function:
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mae'], options=run_opts)
mean_squared_error is the standard choice for regression tasks, and mae (Mean Absolute Error) is a more interpretable metric for evaluating regression performance.
3. Redundant/Incorrect Layer in Model Structure
- The
Activation('softmax')layer added after your lastMaxPooling2Dis completely unnecessary here. Applying softmax to feature maps doesn't make sense for a regression task, and it will distort the feature distribution before flattening. Delete this layer entirely. - Your output
Dense(19316)layer is correct for regression (linear activation is the default, which is what we want for continuous value prediction).
4. Wrong Step Counts in fit_generator
You set steps_per_epoch = len(training_data) and validation_steps = len(val_data)—this will make the training run way more steps than needed. The correct calculation is total samples divided by batch size:
batch_size = 20 steps_per_epoch = len(training_data) // batch_size validation_steps = len(val_data) // batch_size model.fit_generator( train_generator, steps_per_epoch=steps_per_epoch, epochs=nb_epoch, validation_data=validation_generator, validation_steps=validation_steps )
Note: If you're using TensorFlow 2.1 or later, fit_generator() is deprecated—you can directly use model.fit() with your generator input.
5. Small Optimization for Your Generator
You can simplify the generator logic and add data shuffling to improve training stability:
def generator(data_arr, batch_size=10): num_samples = len(data_arr) while True: # Shuffle data each epoch to avoid order bias np.random.shuffle(data_arr) for offset in range(0, num_samples, batch_size): batch_samples = data_arr[offset:offset+batch_size] samples = [] labels = [] for batch_sample in batch_samples: samples.append(batch_sample[0]) labels.append(batch_sample[1].flatten().transpose()) # Simplify dimension expansion X_ = np.array(samples)[..., np.newaxis] Y_ = np.array(labels) yield (X_, Y_)
内容的提问来源于stack exchange,提问作者lr99

