Keras Lambda:函数无法返回可调用张量

时间:2018-09-26 16:16:33

标签: python tensorflow machine-learning lambda keras

为复杂的预测任务构建特殊的神经网络。由于其复杂性,我想将分类任务实现为伪回归。正常分类并不能真正起作用。

我的想法是添加一个图层,以将 Dense(1)中的一个单一值转换为类别矩阵之类的张量。以下是我对Lambda和后端类的实现。

from tensorflow import convert_to_tensor, float32
from keras import backend as K
from tensorflow.keras.utils import to_categorical 


def Kaname(p):    #0<p<1 (sigmoid output)
    critical_p=round(float(K.get_value(K.sum(p))),4)
    #categorize to {0,1,2,3,4} depending on the inner value of the tensor.
    if round(abs(critical_p-0.5),4)<round(0.1,4):
        nnn=2
    elif critical_p<round(0.5,4):
        if critical_p<=round(0.2,4):
            nnn=0
        elif critical_p<=round(0.4,4):
            nnn=1
    elif critical_p>round(0.5,4):
        if critical_p>=round(0.8,4):
            nnn=4
        elif critical_p>=round(0.6,4):
            nnn=3

    a=to_categorical(nnn,num_division+1)
    a=np.array(a).reshape(-1,5)
    a=convert_to_tensor(a,dtype=float32)
    return a 
    #should return callable tensor for prediction. The max will lead the predicted category.


def test_model(num_division):
    model=Sequential()
    model.add(Conv1D(32, 3, padding='valid', input_shape=(12, 1), activation='sigmoid'))
    model.add(Flatten())
    model.add(Dense(16,activation="sigmoid"))
    model.add(Dense(1,activation="sigmoid"))

    #Original Lambda Layer
    #model.add(Lambda(Kaname(num_division+1),output_shape=(1, 5)))

    #Revised
    model.add(Lambda(Kaname,output_shape=(1, 5)))
    model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])
    return model

没有Lambda,模型可以正常工作。但是,Lambda似乎无法正常工作。

Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1278, in _do_call
    return fn(*args)
  File "/usr/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1263, in _run_fn
    options, feed_dict, fetch_list, target_list, run_metadata)
  File "/usr/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1350, in _call_tf_sessionrun
    run_metadata)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'conv1d_1_input' with dtype float and shape [?,12,1]
         [[Node: conv1d_1_input = Placeholder[dtype=DT_FLOAT, shape=[?,12,1], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "cnn_classify.py", line 264, in <module>
    model=model_generation(function_name)
  File "cnn_classify.py", line 240, in model_generation
    model=eval('%s'%abc)(num_division)
  File "cnn_classify.py", line 204, in simplified_test_model
    model.add(Lambda(Kaname,output_shape=(1, 5)))
  File "/usr/lib64/python3.6/site-packages/keras/engine/sequential.py", line 185, in add
    output_tensor = layer(self.outputs[0])
  File "/usr/lib64/python3.6/site-packages/keras/engine/base_layer.py", line 457, in __call__
    output = self.call(inputs, **kwargs)
  File "/usr/lib64/python3.6/site-packages/keras/layers/core.py", line 682, in call
    return self.function(inputs, **arguments)
  File "cnn_classify.py", line 167, in Kaname
    critical_p=round(float(K.get_value(K.sum(p))),4)
  File "/usr/lib64/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 2377, in get_value
    return x.eval(session=get_session())
  File "/usr/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 680, in eval
    return _eval_using_default_session(self, feed_dict, self.graph, session)
  File "/usr/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 4951, in _eval_using_default_session
    return session.run(tensors, feed_dict)
  File "/usr/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 877, in run
     run_metadata_ptr)
  File "/usr/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1100, in _run
    feed_dict_tensor, options, run_metadata)
  File "/usr/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1272, in _do_run
    run_metadata)
  File "/usr/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1291, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'conv1d_1_input' with dtype float and shape [?,12,1]
         [[Node: conv1d_1_input = Placeholder[dtype=DT_FLOAT, shape=[?,12,1], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

是否不可能从单值张量创建分类张量?如果用Keras不可能,那么我是否可以控制回归等分类模型? Google并没有帮助我,所以我需要您的帮助。谢谢。

0 个答案:

没有答案