Skip to main content
 首页 » 编程设计

python之帮助新手学习 TensorFlow 中的线性代数(3 阶张量)

2024年09月07日36kuangbin

我怀疑已经有人问过这个问题,尽管在我的搜索中,许多其他问题都有特定的独特问题,这些问题似乎不适用于我的情况(或者解决方案可能超出了我的理解)。

我在 tensorflow 中有一个标准的前馈神经网络,它在大小为 [None, n_features]、权重为 [n_features, n_neurons] 的 rank2 输入张量下表现正确> 这导致隐藏层 tf.matmul(inputs, weight) = [None, n_neurons]。

但是,我想在输入和输出中将我的维度扩展一维。例如,我想要

inputs = tf.placeholder("float", shape=[None, n_type, n_features]) 
weight= tf.Variable(FNN_weight_initializer([n_type, n_features, n_neurons])) 
Hidden1 = tf.matmul(inputs, weight) 

我的最终目标是让 Hidden1 = [None, n_type, n_neurons]。

但是,我没有生成所需的张量形状,而是得到了一个形状为 [n_type, n_type, n_neurons] 的张量。我不是线性代数方面的专家,我尝试了几种维序组合,但都没有成功。甚至可以将 rank3 张量与 tf.matmul 相乘吗?我应该在这里的某个地方进行 reshape 或转置操作吗?

请您参考如下方法:

根据 OP 的评论进行编辑

您可以将输入特征向量展平为 [-1, n_type * n_features] 形状,应用精心选择的矩阵乘法并 reshape [-1, n_type * n_neurons] 的输出] 到 [-1, n_type, n_neurons]

操作张量将是 block 对角线[n_type * n_features, n_type * n_neurons],每个 block 都是权重中的n_type张量之一。

为了构建 block 对角矩阵,我使用了另一个答案(来自 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) 
# each element of split_weights is a tensor of shape : [1, n_features, n_neurons] -> need to squeeze 
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) 
# shape : [None, n_type * n_neurons] 
 
Hidden1 = tf.reshape(Hidden1, [-1, n_type, n_neurons]) 
# shape : [None, n_type, n_neurons] 

原始答案

根据 tf.matmul ( reference ) 的文档,您要相乘的张量需要具有相同的秩。

当秩为>2时,只有最后两个维度需要矩阵乘法兼容,前两个维度需要完全匹配。

因此,对于“是否有可能将 rank3 张量与 tf.matmul 相乘?”这个问题,答案是“是的,有可能,但从概念上讲,它仍然是 rank 2 乘法”。

因此,一些 reshape 是必要的:

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) 
# shape : [1, n_type, n_features, n_neurons] 
 
weights = tf.tile(weights, [tf.shape(inputs)[0], 1, 1, 1]) 
# shape : [None, n_type, n_features, n_neurons] 
 
Hidden1 = tf.matmul(inputs, weights) 
# shape : [None, n_type, 1, n_neurons] 
 
Hidden1 = tf.reshape(Hidden1, [-1, n_type, n_neurons]) 
# shape : [None, n_type, n_neurons]