Keras int_shape在自定义丢失函数中返回None

时间:2018-05-25 21:54:03

标签: keras loss-function

我尝试使用下面代码演示的K.int_shape()在自定义丢失函数中获取批量大小。

from keras import layers, Input, Model
import keras.backend as K
import numpy as np

train_X=np.random.random([100, 5])
train_Y=train_X.sum(axis=1)

inputs=Input(shape=(5,), dtype='float32', name='posts')
outputs=layers.Dense(1, activation='relu')(inputs)
model = Model(inputs, outputs)#, net_qc])
model.summary()

def myloss(y_true, y_pred):
    n=K.int_shape(y_pred)[0]
    return K.sum(y_pred)/n

model.compile(optimizer='adam', loss=myloss)
model.fit(train_X, train_Y, epochs=10, batch_size=10)

以下错误消息表明K.int_shape返回None。我已经尝试了几件没有成功的事情,真的很感激一些帮助。

Traceback (most recent call last):
  File "./test_intshape.py", line 21, in <module>
    model.compile(optimizer='adam', loss=myloss)
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/keras/engine/training.py", line 830, in compile
    sample_weight, mask)
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/keras/engine/training.py", line 429, in weighted
    score_array = fn(y_true, y_pred)
  File "./test_intshape.py", line 19, in myloss
    return K.sum(y_pred)/n
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py", line 820, in binary_op_wrapper
    y = ops.convert_to_tensor(y, dtype=x.dtype.base_dtype, name="y")
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 639, in convert_to_tensor
    as_ref=False)
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 704, in internal_convert_to_tensor
    ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/framework/constant_op.py", line 113, in _constant_tensor_conversion_function
    return constant(v, dtype=dtype, name=name)
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/framework/constant_op.py", line 102, in constant
    tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape, verify_shape=verify_shape))
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/framework/tensor_util.py", line 360, in make_tensor_proto
    raise ValueError("None values not supported.")
ValueError: None values not supported.

1 个答案:

答案 0 :(得分:1)

这是预期的行为,因为K.int_shape()不会返回符号张量,而是返回当前已知的形状。那么你只能在运行时知道批量大小,在构建图形时它将是None。您正在寻找的是K.shape(),它将返回将在运行时设置批量大小的符号张量,即:

n = K.shape(y_pred)[0]