编辑: 我的第一个答案是认为您的输入是 (299,299,3),而不是您的输出。我很抱歉! “图像预测”相当模糊,但如果您的意图确实是输出一个 3D 张量作为您的y_pred,您可能仍然希望创建一个产生标量的损失函数。这是因为一个样本的损失需要与所有其他样本的误差合并。联合损失允许模型概括其行为。见this wiki snippet。本质上,多维损失函数相当于在随机梯度下降中将批量大小设置为 1。
第一个答案:
通常你希望你的损失函数输出一个数字。如果你在做图像分类,你几乎肯定希望你的损失函数输出一个数字。
假设“图像预测”意味着“图像分类”,您的输入很可能是您的图像,而您的 y_pred 通常是一批长度等于可能类数的一维数组。
您的y_true 将是一批大小与y_pred 相同的one_hot 编码数组。这意味着它们是长度等于图像可以包含的类数的数组。不同之处在于,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)
如果这些都没有帮助,请查看教程或尝试 fast.ai 课程。 fast.ai 课程可能是世界上最好的课程,所以我想说从那里开始。