我怎么能得到一个与keras巧合的百分比

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

我有我的模型和偏见,当我预测我的图像时,我会得到一个这样的矢量

[0 , 0 , 0 , 1]

我需要这样的东西

[.48, .52, .08, .97]

我的培训代码是:

entrenamiento_datagen = ImageDataGenerator(
rescale=1. / 255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1. / 255)

entrenamiento_generador = entrenamiento_datagen.flow_from_directory(
data_entrenamiento,
target_size=(altura, longitud),
batch_size=batch_size,
class_mode='categorical')

validacion_generador = test_datagen.flow_from_directory(
data_validacion,
target_size=(altura, longitud),
batch_size=batch_size,
class_mode='categorical')

cnn = Sequential()
cnn.add(Convolution2D(filtrosConv1, tamano_filtro1, padding ="same",input_shape=(longitud, altura, 3), activation='relu'))
cnn.add(MaxPooling2D(pool_size=tamano_pool))

cnn.add(Convolution2D(filtrosConv2, tamano_filtro2, padding ="same"))
cnn.add(MaxPooling2D(pool_size=tamano_pool))

cnn.add(Flatten())
cnn.add(Dense(256, activation='relu'))
cnn.add(Dropout(0.5))
cnn.add(Dense(clases, activation='sigmoid'))

cnn.compile(loss='categorical_crossentropy',
        optimizer=optimizers.Adam(lr=lr),
        metrics=['accuracy'])

我的分类代码是:

ongitud, altura = 150, 150
modelo = './modelo/modelo.h5'
pesos_modelo = './modelo/pesos.h5'
with CustomObjectScope({'GlorotUniform': glorot_uniform()}):
cnn = load_model(modelo)
cnn.load_weights(pesos_modelo)

def predict(file):
  x = load_img(file, target_size=(longitud, altura))
  x = img_to_array(x)
  x = np.expand_dims(x, axis=0)
  array = cnn.predict_proba(x[0:1])
  print(array)

我尝试过使用predict(),predict_proba()但是没有用

python tensorflow keras
2个回答
1
投票

您应该使用binary_crossentropy而不是categorical_crossentropy:

  • categorical_crossentropy用于多类问题,即为每个样本选择多个类中的一个类。它返回0到1之间的数字向量,总和为1。
  • binary_crossentropy用于多标签问题,即为每个样本分配可能多于一个标签。它返回一个数字向量,每个数字在0和1之间。

0
投票

对于每个图像,如果4个标签中只有一个是正确的(类似于ImageNet),那么最后一层中的激活应该是softmax。

cnn.add(Dense(clases, activation='softmax'))

这样,概率之和将等于1,您可以选择概率最高的类。例如这是使用cnn.predict()或cnn.predict_proba()的输出(两个输出都相同)。

[0.09843186 0.613065 0.19164166 0.09686147]

在这种情况下,cnn.predict_classes()将给出类[1]。

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