根据操作员的意见进行编辑
可以将输入的特征向量展平为形状
[-1, n_type * n_features]
,应用精心选择的矩阵乘法,并从
[-1, n_type * n_neurons]
到
[-1, n_type, n_neurons]
运算张量是块对角线
[n_type * n_features, n_type * n_neurons]
一个,每个块是
n_type
张量
weights
.
为了构建一个块对角矩阵,我使用了另一个答案(来自
here
)
这个看起来像
inputs = tf.placeholder("float", shape=[None, n_type, n_features])
inputs = tf.reshape(inputs, shape=[-1, n_type * n_features])
weights = tf.Variable(FNN_weight_initializer([n_type, n_features, n_neurons]))
split_weights = tf.split(weights, num_or_size_splits=n_type, axis=1)
split_weights = tf.map_fn(lambda elt : tf.squeeze(elt, axis=0), split_weights)
block_matrix = block_diagonal(split_weights) # from the abovementioned reference
Hidden1 = tf.matmul(inputs, block_matrix)
Hidden1 = tf.reshape(Hidden1, [-1, n_type, n_neurons])
原始答案
根据文件
tf.matmul
(
reference
)你要乘的张量必须是同一个等级。
当等级是
>2
只有最后两个维度需要矩阵乘法兼容,第一个其他维度需要完全匹配。
那么,对于这个问题,“能不能用tf.matmul把rank3张量相乘?”答案是“是的,这是可能的,但从概念上讲,它仍然是第二级乘法”。
因此,需要进行一些整形:
inputs = tf.placeholder("float", shape=[None, n_type, n_features])
inputs = tf.reshape(inputs, shape=[-1, n_type, 1, n_features])
weights = tf.Variable(FNN_weight_initializer([n_type, n_features, n_neurons]))
weights = tf.expand_dims(weights, 0)
weights = tf.tile(weights, [tf.shape(inputs)[0], 1, 1, 1])
Hidden1 = tf.matmul(inputs, weights)
Hidden1 = tf.reshape(Hidden1, [-1, n_type, n_neurons])