【问题标题】:Keras custom metric gives incorrect tensor shapeKeras 自定义指标给出了不正确的张量形状
【发布时间】:2016-10-07 20:39:25
【问题描述】:

我想通过定义我自己的自定义指标(使用 Theano 后端)来监控 y_pred 的维度

def shape_test(y_true, y_pred):
    return K.shape(y_pred)[0]

我假设自定义度量函数中y_pred 的维度等于小批量大小。但是,我得到奇怪的输出。请参阅下面的一个可重现的小示例。

#imports and definitions
import numpy
numpy.random.seed(1234)
import keras.backend as K
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD

neuron_num=20
dim_input=2
#batch size will be important below!
batch_size=2048
TT=int(1e4)

#sample data
X=numpy.random.randn(TT,dim_input)
eps=numpy.random.randn(TT)
Y=0.3*X[:,0]+0.5*X[:,1]+eps
x={"is":X[:(TT/2),:],"os":X[(TT/2+1):,:]}
y={"is":Y[:(TT/2)],"os":Y[(TT/2+1):]}

这是上面给出的自定义指标

def shape_test(y_true, y_pred):
    return K.shape(y_pred)[0]

现在定义一个简单的神经网络

sgd=SGD(lr=1e-2,nesterov=True)

model=Sequential()
model.add(Dense(neuron_num,
                input_dim=x["is"].shape[1],
                init="glorot_normal",
                activation="tanh"))
model.add(Dense(neuron_num,init="glorot_normal",activation="tanh"))
model.add(Dense(1,init="glorot_normal",activation="linear"))
model.compile(loss="mean_squared_error",
              optimizer=sgd,
              metrics=["mean_squared_error",shape_test])

model.fit(x["is"],
          y["is"],
          validation_data=(x["os"],y["os"]),
          nb_epoch=1,
          batch_size=batch_size,
          verbose=False).history

这给了

#{'loss': [1.834826689338684],
# 'mean_squared_error': [1.834826689338684],
# 'shape_test': [1841],
# 'val_loss': [1.4931119817522769],
# 'val_mean_squared_error': [1.4931119817522769],
# 'val_shape_test': [1841.1716343268654]}

我本来希望看到 'shape_test': [2048] 而不是 'shape_test': [1841],因为批量大小是 2048。

这看起来很奇怪。这可能是一个错误吗? 我正在使用Python 2.7.6Keras==1.0.8Theano==0.8.2 和 CPU。

【问题讨论】:

    标签: python python-2.7 theano keras


    【解决方案1】:

    使用neuron_num=2000verbose=True,这是我通过您的示例能够产生的结果:

    Epoch 1/1
    2048/5000 [========>............] - ETA: 9s - loss: 1.4507 - shape_test: 2048.000
    4096/5000 [=================>...] - ETA: 3s - loss: 1.3577 - shape_test: 2048.000
    5000/5000 [=====================] - 26s - loss: 1.3087 - shape_test: 1841.1648 - val_shape_test: 1841.1716
    

    如您所见,您的形状函数似乎工作正常。但由于 batch_size 不是训练集大小的除数,所以最后一批只包含 904 个示例。我现在似乎无法猜测 Keras 是如何提出 1841 的,但它可能并不复杂。

    batch_size=2500 的另一个尝试看起来更好:

    2500/5000 [==========>..........] - ETA: 9s - loss: 1.4292 - shape_test: 2500.0000
    5000/5000 [=====================] - 24s - loss: 1.3311 - shape_test: 2500.0000 - val_shape_test: 2499.5001
    

    【讨论】:

    • 感谢您的帮助!我忘记了小批量是没有替换的。是的,最后一个值 904 看起来仍然很有趣,但它可能并不重要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 2022-12-01
    • 1970-01-01
    相关资源
    最近更新 更多