如何在Keras/tensorflow中向输入张量添加恒定张量 [英] How to add a constant tensor to Input tensor in Keras/tensorflow

查看:567
本文介绍了如何在Keras/tensorflow中向输入张量添加恒定张量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的CNN,输入的形状为(5,5,3).第一步,我想向输入添加一个常数张量. 使用下面的代码,我得到 AttributeError:'NoneType'对象没有属性'_inbound_nodes'

I have a simple CNN with inputs of shape (5,5,3). As a first step I want to add a constant tensor to the input. With the code below, I get AttributeError: 'NoneType' object has no attribute '_inbound_nodes'

我尝试了

const_change = Input(tensor=tf.constant([ ...

const_change = Input(tensor=K.variable([ ...

,但似乎没有任何效果.任何帮助都将受到高度赞赏.

but nothing seems to work. Any help is highly appreciated.

from __future__ import print_function

import tensorflow as tf
import numpy as np
import keras
from keras import backend as K
from keras.models import Model
from keras.layers import Input
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense

# Python 2.7.10
# keras version 2.2.0
# tf.VERSION '1.8.0'

raw_input = Input(shape=(5, 5, 3))

const_change = tf.constant([
        [[5.0,0.0,0.0],[0.0,0.0,-3.0],[-10.0,0.0,0.0],[0.0,0.0,4.0],[-20.0,0.0,0.0]],
        [[-15.0,0.0,12.0],[0.0,4.0,0.0],[-3.0,0.0,10.0],[-18.0,0.0,0.0],[20.0,0.0,-6.0]],
        [[0.0,0.0,6.0],[0.0,-2.0,-6.0],[0.0,0.0,2.0],[0.0,0.0,-9.0],[7.0,-6.0,0.0]],
        [[-3.0,4.0,0.0],[11.0,-12.0,0.0],[0.0,0.0,0.0],[0.0,0.0,7.0],[0.0,0.0,2.0]],
        [[0.0,0.0,0.0],[0.0,1.0,-2.0],[4.0,0.0,3.0],[0.0,0.0,0.0],[0.0,0.0,0.0]]])

cnn_layer1 = Conv2D(32, (4, 4), activation='relu')
cnn_layer2 = MaxPooling2D(pool_size=(2, 2))

cnn_layer3 = Dense(128, activation='relu')
cnn_layer4 = Dropout(0.1)
cnn_output = Dense(4, activation='softmax')

proc_input = keras.layers.Add()([raw_input, const_change])
# proc_input = keras.layers.add([raw_input, const_change])  -> leads to the same error (see below)
lay1 = cnn_layer1(proc_input)
lay2 = cnn_layer2(lay1)
lay3 = Flatten()(lay2)
lay4 = cnn_layer3(lay3)
lay5 = cnn_layer4(lay4)
lay_out = cnn_output(lay5)

model = Model(inputs=raw_input, outputs=lay_out)
# -> AttributeError: 'NoneType' object has no attribute '_inbound_nodes'

推荐答案

const_change也应该像raw_input一样是Input.您可以创建另一个名为const_input的输入层,并将raw_inputconst_input一起输入到模型中.

The const_change should be also Input just like raw_input. You can create another input layer named const_input, and feed raw_input and const_input together into model.

...
const_input = Input(tensor=const_change)
...
proc_input = keras.layers.Add()[raw_input, const_input]
...
model = Model(inputs=[raw_input, const_input], outputs=lay_out)

这篇关于如何在Keras/tensorflow中向输入张量添加恒定张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆