python - 如何在 keras CNN 中使用 sample_weight?
问题描述
在将 keras 用于 CNN 图像分类器时,我在使用 sample_weight 时遇到问题。我有以下模型:
input_shape = (256, 256, 3)
model = Sequential()
model.add(keras.Input(shape=input_shape))
model.add(Conv2D(64,3,padding="same", activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())
model.add(Conv2D(128, 3, padding="same", activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())
model.add(Conv2D(256, 3, padding="same", activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())
model.add(Conv2D(512, 3, padding="same", activation="relu"))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.4))
model.add(Flatten())
model.add(Dense(512,activation="relu"))
model.add(BatchNormalization())
model.add(Dense(1024,activation="relu"))
model.add(BatchNormalization())
model.add(Dense(29, activation="softmax"))
model.build()
model.summary()
我发现样本重量如下:
from sklearn.utils.class_weight import compute_class_weight
from tensorflow.keras.utils import get_custom_objects
labelsForWeight = pd.read_csv(data_dir_labels_t)
def get_sample_weights(labels):
# paramts: y is class labels as integers
label = labels.astype(int)
label = label.values
class_weight = compute_class_weight('balanced', np.unique(label), np.ravel(label))
print("Real class weights are {}".format(class_weight),np.unique(label))
print("value_counts",np.unique(label,return_counts=True))
sample_weights = label.copy().astype(float)
for i in range(29):
sample_weights = np.where(sample_weights == i, class_weight[int(i)],class_weight)
sampleWeights = sample_weights[0, :]
return sampleWeights
sampleWeights = get_sample_weights(labelsForWeight)
其中 sampleWeight 是一个带有标签长度的数组。
NEXT 我正在使用增强数据训练模型:
aug = ImageDataGenerator(
rotation_range=20,
zoom_range=0.15,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.15,
horizontal_flip=True,
vertical_flip=True,
fill_mode="nearest")
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adam(),
metrics=['accuracy'])
K.set_value(model.optimizer.learning_rate, 0.0001)
history = model.fit(aug.flow(trainImg, trainLabels, batch_size=32), epochs=25, validation_data=(valImg, valLabels), sample_weight=sampleWeights)
我可以轻松地训练模型,但是当使用 sample_weight 我得到:
ValueError: `sample_weight` argument is not supported when using `keras.utils.Sequence` as input.
该怎么办?
解决方案
推荐阅读
- python - 仅屏蔽非 NaN 值(Python)
- amazon-web-services - 为什么来自另一个 vpc 实例的入站规则中的安全组不起作用?
- node.js - Speech-to-Text API 无法通过“未找到请求的实体”错误
- excel - 接收 KeyNotFoundError 字典键未找到:使用 .click 方法时的状态
- google-cloud-platform - 如何使用服务帐户获取 application_default_credentials?
- python - 如果在 python 中找不到文件,有没有办法抛出异常?
- spring - 具有基本身份验证和 cors 的 Spring Boot
- android - 从适配器打开的 DialogFragment 获取上下文
- python - 有没有办法在 django 中添加模型值?
- python-3.x - 我正在尝试按列在列表中添加列表。有没有办法将它们与列表中缺少的变量相加?