keras 中损失函数的输出形状应该是什么?

Dik*_*rAz 6 deep-learning keras tensorflow

例如,如果我正在做图像预测并且我的网络输出是形状张量,[299, 299, 3]我该如何编写 loss function loss(y_true, y_pred)。我应该期望y_truey_pred有形状[batch_size, 299, 299, 3]和损失函数的输出为形状的阵列[batch_size]或其他什么东西?

sae*_*h_g 0

编辑: 我的第一个答案是认为你的输入是(299,299,3),而不是你的输出。我很抱歉!“图像预测”相当模糊,但如果您的意图确实是输出 3D 张量作为y_pred,您仍然可能想要创建一个产生标量的损失函数。这是因为样本的损失需要与所有其他样本的误差合并。联合损失允许模型概括其行为。请参阅此维基片段。本质上,多维损失函数相当于在随机梯度下降中将批量大小设置为 1。

第一个答案:
通常您希望损失函数输出单个数字。如果您正在进行图像分类,您几乎肯定希望损失函数输出单个数字。

假设“图像预测”意味着“图像分类”,您的输入很可能是您的图像,并且您y_pred通常是一批长度等于可能类别数量的一维数组。

y_true将得到一批与 大小相同的 one_hot 编码数组y_pred。这意味着它们是长度等于图像所属类数的数组。不同之处在于,y_true向量除相应图像类别索引处的单个 1 外全部包含零。

例如,如果您的图像只有狗、猫或羊,则有 3 种可能的类别。我们任意说 0 表示狗,1 表示猫,2 表示羊。那么如果图像是一只羊,则对应的y_true将为[0,0,1]。如果图像是猫,y_true则为 [0,1,0]。如果你的图像是一只熊,你的分类器将会感到困惑......

y_pred至于损失函数,通常您会以某种方式计算出每个函数与对应函数的差距有多大y_true,并对批次中的所有差异进行求和。这会产生一个代表该批次总损失的数字。

Keras 可以很好地为您处理损失函数。当您拥有模型时,您可以调用model.compile(loss='some_loss_fxn_here', optimizer='some_optimizer_here')并指定要用作字符串的损失函数。您可能会想使用'categorical_crossentropy'.

鉴于您提出问题的方式,您可能需要在担心所有这些问题之前创建一个模型。

你可以尝试这样的事情:

from keras.models import Sequential, Model
from keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout
from keras.layers.normalization import BatchNormalization

def conv_block(x, depth, filt_shape=(3,3), padding='same', act='relu'):
    x = Conv2D(depth, filt_shape, padding=padding, activation=act)(x)
    x = BatchNormalization()(x)
    pool_filt, pool_stride = (2,2), (2,2)
    return MaxPooling2D(pool_filt, strides=pool_stride, padding='same')(x)

# Don't forget to preprocess your images!
inputs = Input(shape(299,299,3))
layer1 = conv_block(inputs, 64) # shape = [batch_size,150,150,64]
layer1 = Dropout(.05)(layer1) # Note early dropout should be low
layer2 = conv_block(layer1, 64) # shape = [batch_size,75,75,64]
layer2 = Dropout(.1)(layer2)
layer3 = conv_block(layer2, 64) # shape = [batch_size,38,38,64]
layer3 = Dropout(.2)(layer3)
layer4 = conv_block(layer3, 64) # shape = [batch_size,19,19,64]
layer4 = Dropout(.25)(layer4)
layer5 = conv_block(layer4, 64) # shape = [batch_size,10,10,30]

flat_layer = Flatten()(layer5) # shape = [batch_size, 3000]
flat_layer = Dropout(.4)(flat_layer)

def dense_block(x, output_dim, act='relu'):
    x = Dense(output_dim, activation=act)(x)
    return BatchNormalization()(x)

layer6 = dense_block(flat_layer, 300)
layer7 = dense_block(layer6, 50)

n_labels = 10 # change this number depending on the number of image classes
outputs = dense_block(layer7, n_labels, 'softmax')

model = Model(inputs=inputs, outputs=outputs)
model.compile(loss='categorical_crossentropy', optimizer='adam')

# Be sure to make your own images and y_trues arrays!
model.fit(x=images,y=y_trues,batch_size=124)
Run Code Online (Sandbox Code Playgroud)

如果这些都没有帮助,请查看教程或尝试fast.ai课程。fast.ai 课程可能是世界上最好的课程,所以我建议从那里开始。

  • 感谢您的详细回答。尽管我更多地寻找 Keras 行为的解释,而不是一般的深度学习。目前还不清楚如何使用 Keras 进行结构化预测(比图像预测更成熟的术语)。 (3认同)