python - 从 tensorflow 中的向量构造成对矩阵

标签 python numpy tensorflow matrix

假设我有一个 1*3 向量 [[1,3,5]] (或者像 [1,3,5] 这样的列表,如果你使用),如何生成 9*2 矩阵:[[1,1],[1,3],[1,5],[3,1],[3,3],[3,5 ],[5,1],[5,3],[5,5]]

新矩阵中的元素是原矩阵中元素的两两组合。

此外,原始矩阵可以包含零,就像这样[[0,1],[0,3],[0,5]]

实现应该推广到任何维度的向量。

非常感谢!

最佳答案

您可以使用tf.meshgrid()tf.transpose()生成两个矩阵。然后 reshape 并连接它们。

import tensorflow as tf

a = tf.constant([[1,3,5]])

A,B=tf.meshgrid(a,tf.transpose(a))
result = tf.concat([tf.reshape(B,(-1,1)),tf.reshape(A,(-1,1))],axis=-1)

with tf.Session() as sess:
    print(sess.run(result))

[[1 1]
 [1 3]
 [1 5]
 [3 1]
 [3 3]
 [3 5]
 [5 1]
 [5 3]
 [5 5]]

关于python - 从 tensorflow 中的向量构造成对矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55153745/

相关文章:

python - 元组第一个值的唯一元组列表

python - 计算字符串中给出的电路的总电阻

Python - 连接或堆叠两个以上不同形状的数组

Tensorflow 对象检测 : visualization_export_dir in eval_config not saving eval images

python - NumPy:计算两个数组之间按行交叉的大小

python - 如何使用 Drive API 在 Google 电子表格中获取工作表列表(名称和 "gid")?

python - 推断 numpy 数组中的 NaN 值

python - 尽可能高效地在 Python 中叠加混合模式(Numpy、OpenCV)

python - 错误 - 没有名为 '_pywrap_tensorflow' 的模块

python - Tensorflow 2.0.0-alpha0 : tf. logging.set_verbosity