使用keras的多分类任务 [英] Multiclassification task using keras

查看:259
本文介绍了使用keras的多分类任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一幅图像中对多个对象进行分类(不是检测!)是问题所在。

Classification (not detection!) of several objects in one image is the problem. How can I do this using keras.

例如,如果我有6个类(狗,猫,鸟,...)和两个不同的对象(猫和鸟),则该如何使用keras做到这一点。图片。标签的格式为:[0,1,1,0,0,0]建议使用哪种度量,损失函数和优化器?我想使用CNN。

For example if I have 6 classes (dogs,cats,birds,...) and two different objects (a cat and a bird) in this image. The label would be of the form: [0,1,1,0,0,0] Which metric, loss function and optimizer is recommended? I would like to use CNN.

推荐答案

关键字是 多标签分类
在输出层中,您有多个神经元,每个神经元代表您的一个类。

The keyword is "multilabel classification". In the output layer you have multiple neurons, each neuron representing one of your classes.

现在,您应为每个神经元分别使用二进制分类。
因此,如果您有3个类别,则网络的输出可能为[0.1,0.8,0.99],这意味着:第一个类别对图像的真实性为10%,第二个类别对80的真实性%,最后一个类别为99%。因此,网络决定对于一个输入图像,两个类别必须同时为真!

Now you should use a binary classification for each neuron independently. So if you have 3 classes, the output of your network could be [0.1, 0.8, 0.99] which means the following: The first class is true for your image with the probability 10 %, the second is true with 80 % and the last class is true with 99 %. So the network decided for two classes to be true at the same time for a single input image!

很容易将其实现到Keras / Tensorflow中。
您可以在最后一层中使用一些binary_crossentropy作为损失函数,并使用Sigmoid函数作为激活。因此,对于每个输出神经元,您将获得间隔(0,1)中的值。
作为指标,您可以使用准确性,它可以告诉您以正确的方式(相对频率)分类了多少张图像。

It's pretty easy to implement this into Keras/Tensorflow. You could use some binary_crossentropy as your loss function and Sigmoid Function as the activation in your last layer. Therefore you get values in the interval (0, 1) for every output neuron. As the metric you could use accuracy, which tells you how many images are classified in the right way (as relative frequency).

请参阅下面的示例:

from tensorflow.keras.layers import *
from tensorflow.keras.activations import *
from tensorflow.keras.models import *
from tensorflow.keras.optimizers import *
import numpy as np

# put your data right here:
num_classes = 3 # here I'm assuming 3 classes, e.g. dog, cat and bird
x_train = np.zeros((100, 128, 128, 3)) # I'm just using zeros to simplify the example
y_train = np.zeros((100, num_classes))

model = Sequential()
# put your conv layer / conv blocks here:
model.add(Conv2D(32, kernel_size=3, activation='relu', input_shape=(128, 128, 3)))
model.add(Flatten())
model.add(Dense(units=num_classes, activation='sigmoid'))
    
model.compile(
        loss="binary_crossentropy",
        optimizer=Adam(0.005),
        metrics=["accuracy"])
training_history = model.fit(x=x_train, y=y_train, epochs=5)

我正在使用Tensorflow 2.2.0。
希望对您有所帮助:)

I'm using Tensorflow 2.2.0. I hope this will help you :)

这篇关于使用keras的多分类任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆