我正在處理影像并想為我的模型構建自定義層。我想將每個像素乘以權重并為其添加偏差(x.w b)。我知道 flatten 可以解決這個問題,但我在計算方面還有其他任務,我可能還需要對其中一些進行轉置。我的問題,我可以將每個輸入和 wight 的 2D 形式相乘,并為我的自定義密集層添加二維偏差嗎?我試過了,但 shape 只接受一維輸入并給出單位輸出 shape=(input_dim, units) 的數量。我希望 input_dim 對于權重和偏差都是 2D 的!
密集類(layers.Layer):
def __init__(self, units):
super(Dense, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
name="w",
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=True,
)
self.b = self.add_weight(
name="b", initializer="random_normal", trainable=True, shape=(input_shape[-1], self.units),
)
def call(self, inputs):
return tf.matmul(inputs, self.w) self.b
uj5u.com熱心網友回復:
IIUC,這取決于您想要的輸出。你可以嘗試這樣的事情:
import tensorflow as tf
class Dense2D(tf.keras.layers.Layer):
def __init__(self, units):
super(Dense2D, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
name="w",
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=True,
)
self.b = self.add_weight(
name="b", initializer="random_normal", trainable=True, shape=(input_shape[1], input_shape[-1]),
)
def call(self, inputs):
return tf.matmul(inputs, self.w) self.b
dense2d = Dense2D(units = 10)
samples = 1
x = tf.random.normal((samples, 5, 10))
print(dense2d(x).shape)
# (1, 5, 10)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/456246.html
上一篇:將影像拼接在一起
下一篇:Keras早期停止和監控
