尝试创建一个简单的keras模型,其中模型的输出是输入乘以密集层元素。
inputs = tf.keras.Input(shape=256)
weightLayer = tf.keras.layers.Dense(256)
multipled = tf.keras.layers.Dot(axes=1)([inputs,weightLayer])
model = tf.keras.Model(inputs, multipled)
然而,这给了我";非类型对象不可下标";错误我想这是因为点层的输入形状面临问题吗?我该如何解决此问题?
Dense
层必须接收某种输入:
import tensorflow as tf
inputs = tf.keras.layers.Input(shape=256)
weightLayer = tf.keras.layers.Dense(256)
multipled = tf.keras.layers.Dot(axes=1)([inputs, weightLayer(inputs)])
model = tf.keras.Model(inputs, multipled)
否则,只需定义一个权重矩阵,并将其与输入元素相乘即可。例如,通过使用自定义层:
import tensorflow as tf
class WeightedLayer(tf.keras.layers.Layer):
def __init__(self, num_outputs):
super(WeightedLayer, self).__init__()
self.num_outputs = num_outputs
self.dot_layer = tf.keras.layers.Dot(axes=1)
def build(self, input_shape):
self.kernel = self.add_weight("kernel",
shape=[int(input_shape[-1]),
self.num_outputs])
def call(self, inputs):
return self.dot_layer([inputs, self.kernel])
inputs = tf.keras.layers.Input(shape=256)
weighted_layer = WeightedLayer(256)
multipled = weighted_layer(inputs)
model = tf.keras.Model(inputs, multipled)