我正在创建一个自定义图层,其权重需要在激活之前乘以逐个元素。当输出和输入的形状相同时,我可以使它工作。当我将一阶数组作为输入,将二阶数组作为输出时,会发生问题。tensorflow.multiply支持广播,但是当我尝试在Layer.call(x,self.kernel)中使用它来将x与self.kernel变量相乘时,它抱怨它们是不同的形状,说:
ValueError: Dimensions must be equal, but are 4 and 3 for 'my_layer_1/Mul' (op: 'Mul') with input shapes: [?,4], [4,3].
这是我的代码:
from keras import backend as K
from keras.engine.topology import Layer
import tensorflow as tf
from keras.models import Sequential
import numpy as np
class MyLayer(Layer):
def __init__(self, output_dims, **kwargs):
self.output_dims = output_dims
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
# Create a trainable weight variable for this layer.
self.kernel = self.add_weight(name='kernel',
shape=self.output_dims,
initializer='ones',
trainable=True)
super(MyLayer, self).build(input_shape) # Be sure to call this somewhere!
def call(self, x):
#multiply wont work here?
return K.tf.multiply(x, self.kernel)
def compute_output_shape(self, input_shape):
return (self.output_dims)
mInput = np.array([[1,2,3,4]])
inShape = (4,)
net = Sequential()
outShape = (4,3)
l1 = MyLayer(outShape, input_shape= inShape)
net.add(l1)
net.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])
p = net.predict(x=mInput, batch_size=1)
print(p)
编辑:给定输入形状(4,)和输出形状(4,3),权重矩阵应与输出形状相同,并用1进行初始化。因此,在上面的代码中,输入为[1,2,3,4],权重矩阵应为[[1,1,1,1],[1,1,1,1],[1,1,1
,1]],输出应类似于[[1,2,3,4],[1,2,3,4],[1,2,3,4]]
乘法之前,您需要重复元素以增加形状。您可以使用K.repeat_elements
它。(import keras.backend as K
)
class MyLayer(Layer):
#there are some difficulties for different types of shapes
#let's use a 'repeat_count' instead, increasing only one dimension
def __init__(self, repeat_count,**kwargs):
self.repeat_count = repeat_count
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
#first, let's get the output_shape
output_shape = self.compute_output_shape(input_shape)
weight_shape = (1,) + output_shape[1:] #replace the batch size by 1
self.kernel = self.add_weight(name='kernel',
shape=weight_shape,
initializer='ones',
trainable=True)
super(MyLayer, self).build(input_shape) # Be sure to call this somewhere!
#here, we need to repeat the elements before multiplying
def call(self, x):
if self.repeat_count > 1:
#we add the extra dimension:
x = K.expand_dims(x, axis=1)
#we replicate the elements
x = K.repeat_elements(x, rep=self.repeat_count, axis=1)
#multiply
return x * self.kernel
#make sure we comput the ouptut shape according to what we did in "call"
def compute_output_shape(self, input_shape):
if self.repeat_count > 1:
return (input_shape[0],self.repeat_count) + input_shape[1:]
else:
return input_shape
问题内容: 我正在尝试创建一个简单的加权损失函数。 假设我的输入尺寸为100 * 5,输出尺寸也为100 *5。我也有一个相同尺寸的权重矩阵。 类似于以下内容: 定义自定义损失函数 定义模型 使用现有指标进行测试可以正常工作 使用我们的自定义损失功能进行测试不起作用 它给出以下堆栈跟踪: 数字32是哪里来的? 使用权重作为Keras张量测试损失函数 似乎可以完成此功能。因此,可能暗示将Keras张
本文向大家介绍在keras里实现自定义上采样层,包括了在keras里实现自定义上采样层的使用技巧和注意事项,需要的朋友参考一下 Keras里的UpSampling2D层不是中的双线性内插,而是简单的重复图像。这点和pytorch不一样,pytorch默认使用的是双线性内插。 同样:这里仍然使用的是keras而不是tf.keras. keras里UpSampling2D的部分定义说明如下: 可以看出
使用Ember.Component子类自定义元素,并将tagName属性设置为它。 语法 (Syntax) import Ember from 'ember'; export default Ember.Component.extend ({ tagName: 'tag_name' }); 例子 (Example) 下面给出的示例指定使用tagName属性自定义组件的元素。 创建一个名为p
对于简单的定制操作,我们或许可以通过使用 layers.core.Lambda 层来完成。但对于任何具有可训练权重的定制层,你应该自己来实现。 from keras import backend as K from keras.engine.topology import Layer import numpy as np class MyLayer(Layer): def __init
深度学习的一个魅力在于神经网络中各式各样的层,例如全连接层和后面章节中将要介绍的卷积层、池化层与循环层。虽然Gluon提供了大量常用的层,但有时候我们依然希望自定义层。本节将介绍如何使用NDArray来自定义一个Gluon的层,从而可以被重复调用。 不含模型参数的自定义层 我们先介绍如何定义一个不含模型参数的自定义层。事实上,这和“模型构造”一节中介绍的使用Block类构造模型类似。下面的Cent
问题内容: 由于在TensorFlow 2.0中,他们计划统一keras下的所有高级API(我不太熟悉)并完全删除Sessions,我想知道: 如何创建具有自定义渐变的自定义keras图层? 我看过(非常有限)在keras中创建自定义图层的指南,但是它没有描述如果我们希望操作具有自定义渐变应该怎么做。 问题答案: 首先,在keras下对API(如您所称的)的“统一”并不能阻止您像在TensorFl