繁体   English   中英

如何处理在Keras的自定义层中发生的此代码错误?

[英]How can I deal with this code error which happens in my custom layer in Keras?

我想在Keras中创建一个自定义图层。 在此示例中,我使用变量将张量相乘,但出现以下错误:

在/keras/engine/training_arrays.py,第304行中,在predict_loop中outs [i] [batch_start:batch_end] = batch_out ValueError:无法将输入数组从形状(36)广播到形状(2)中。

其实我已经检查了这个文件,但是我什么也没得到。 我的自定义层有问题吗?

#the definition of mylayer.


 from keras import backend as K
 import keras
 from keras.engine.topology import Layer

class mylayer(Layer):
def __init__(self, output_dim, **kwargs):
    self.output_dim = output_dim
    super(mylayer, self).__init__(**kwargs)

def build(self, input_shape):
    self.kernel = self.add_weight(name = 'kernel',
                                  shape=(1,),dtype='float32',trainable=True,initializer='uniform')
    super(mylayer, self).build(input_shape)

def call(self, inputs, **kwargs):
    return self.kernel * inputs[0]
def compute_output_shape(self, input_shape):
    return (input_shape[0], input_shape[1])


#the test of mylayer.

from mylayer import mylayer
from tensorflow import keras as K
import numpy as np
from keras.layers import Input, Dense, Flatten
from keras.models import Model

x_train = np.random.random((2, 3, 4, 3))
y_train = np.random.random((2, 36))
print(x_train)

x = Input(shape=(3, 4, 3))
y = Flatten()(x)
output = mylayer((36, ))(y)

model = Model(inputs=x, outputs=output)

model.summary()

 model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
model.fit(x_train, y_train, epochs=2)

hist = model.predict(x_train,batch_size=2)

print(hist)

print(model.get_layer(index=1).get_weights())


#So is there some wrong in my custom error?

特别是,当我训练该网时,没关系,但是当我尝试使用“ prdict”时,这是错误的。

您的self.kernel * inputs[0]形状为(36,) ,但您的期望为(?,36) 更改:

def call(self, inputs, **kwargs):
    return self.kernel * inputs

如果要输出mylayer的权重,则应设置index=2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM