Skip to main content
 首页 » 编程设计

python之如何在 Tensorflow 中对 3D 特征向量应用线性变换

2024年09月07日30xing901022

假设有一个具有以下维度的张量 (32, 20, 3) 其中 batch_size = 32,num_steps = 20 和 < strong>features = 3。这些特征取自具有以下格式的 .csv 文件:

feat1, feat2, feat3 
200, 100, 0 
5.5, 200, 0.5 
23.2, 1, 9.3 

每一行都被转换为 3 维向量(numpy 数组):[200, 100, 0], [5.5, 200, 0.5], [23.2, 1, 9.3].

我们想在循环神经网络中使用这些特征,但直接将它们输入 rnn 是不行的,我们想先通过对批处理样本中的每个 3-dim 向量应用线性变换来处理这些特征向量,然后将输入张量 reshape 为 (32, 20, 100)。

这在 Torch 中很容易完成,例如通过:nn.MapTable():add(nn.Linear(3, 100)) 应用于大小为 的输入批处理张量20 x 32 x 3(num_steps 和 batch_size 在 Torch 中切换)。我们将其分成 20 个数组,每个数组的大小为 32x3

  1 : DoubleTensor - size: 32x3 
  2 : DoubleTensor - size: 32x3 
  3 : DoubleTensor - size: 32x3 
  ... 

并使用 nn.Linear(3, 100) 将它们转换为 32x100 向量。然后我们将它们打包回 20 x 32 x 100 张量。我们如何在 TensorFlow 中实现相同的操作?

请您参考如下方法:

可以 reshape 为 [batchsize*num_steps, features] 使用具有 100 个输出的 Tensorflow 线性层,然后 reshape 回来是否可行?

reshaped_tensor = tf.reshape(your_input, [batchsize*num_steps, features]) 
linear_out = tf.layers.dense(inputs=reshaped_tensor, units=100) 
reshaped_back = tf.reshape(linear_out, [batchsize, num_steps, features]