model.fit() 类权重在训练模型时不起作用

问题描述 投票:0回答:1

计算classes_weight时用

from sklearn.utils import class_weight
class_weights = class_weight.compute_class_weight(class_weight="balanced",
                     classes=np.unique(masks_reshaped_encoded),y= masks_reshaped_encoded)

我得到了权重,但是当使用 keras model.fit() 时,会显示此错误

history=model.fit(img, msk, epochs=50, verbose=1, validation_split=0.2, shuffle=False,
                  class_weight=class_weights)

AttributeError:'numpy.ndarray'对象没有属性'get'在此处输入图像描述

我正在使用此代码

import pathlib
import tensorflow as tf
import imageio
import numpy as np
import keras
import glob
import random
import os
os.environ["SM_FRAMEWORK"] = "tf.keras"
import segmentation_models as sm
#import cv2
from tqdm import tqdm
from matplotlib import pyplot as plt
from PIL import Image
from model_segmentation import simple_unet_model
from keras.metrics import MeanIoU
from sklearn.preprocessing import LabelEncoder


img = img[...,np.newaxis]
print(img.shape)
print(msk.shape)
#msk = msk[...,np.newaxis]
kernel_initializer =  'he_uniform' #Try others if you want

steps_per_epoch = len(train_img_list)//batch_size
#val_steps_per_epoch = len(val_img_list)//batch_size

model = simple_unet_model(IMG_HEIGHT=128, IMG_WIDTH=128, IMG_CHANNELS=1, num_classes=4)

total_loss = 'binary_crossentropy'
#metrics = ['accuracy', sm.metrics.IOUScore(threshold=0.5)]
metrics = ['accuracy']
optim = 'adam'

model.compile(optimizer = optim, loss=total_loss, metrics= metrics)
print(model.summary())

print(model.input_shape)
print(model.output_shape)

msk = msk.astype(np.uint8)
print(msk.shape)
msk_argmax=np.argmax(msk, axis=3)
masks_reshaped = msk_argmax.reshape(-1,1)
print(masks_reshaped.shape)
masks_reshaped_encoded = masks_reshaped.reshape(-1)
print(masks_reshaped_encoded.shape)

labelencoder = LabelEncoder()
masks_reshaped_encoded = labelencoder.fit_transform(masks_reshaped)
print(masks_reshaped_encoded.shape)

np.unique(masks_reshaped_encoded)

非常感谢您的帮助

python keras image-processing image-segmentation sklearn-pandas
1个回答
0
投票

来自 keras 文档:

class_weight:可选的字典将类索引(整数)映射到 权重(浮点)值,用于对损失函数进行加权(期间 仅培训)。

但是

sklearn.utils.class_weight.compute_class_weight
返回
ndarray
。 所以基本上你需要将收到的权重转换为对类:权重。这个问题可能有帮助

© www.soinside.com 2019 - 2024. All rights reserved.