TensorFlow 两个二阶张量的外积

假设我有一个二阶张量,[[a,b],[c,d]](一般是一个 m×n 矩阵)。

我想通过一个 2×2 的单位矩阵(外积)扩展每一个元素,最终得到

[[a, 0, b, 0],[0,a,0,b],[c,0,d,0],[0,c,0,d]]. 

在 TensorFlow 中实现这个操作的最有效方法是什么?

这种操作在框架中经常出现。


回答:

我想通过两步来完成这个操作。如果我有一个 m×n 矩阵和一个 2×2 的单位矩阵,首先我会将矩阵扩展(重复)为“2m×2n 矩阵”,然后乘以扩展后的单位矩阵(2m×2n 矩阵)。如下所示。

import tensorflow as tf#第一步  在二维中重复张量。#例如 [1,2,3,4]  --> [[1,1,2,2],[1,1,2,2],[3,3,4,4],[3,3,4,4]]#假设 m x n 单位矩阵 例如 [1,2,3],[4,5,6]] , m=2,n=3id_matrix_size=2  # 单位矩阵的大小(例如 2x2 3x3 ...)m=2n=3mytensor=tf.constant([[1,2,3],[4,5,6] ],dtype = tf.float32)#类似于 np.repeat 在 x 维度上。flatten_mytensor=tf.reshape(mytensor,[-1,1])  a=tf.tile(flatten_mytensor,  [1, id_matrix_size])b=tf.reshape( a, [m,-1])#在 y 维度上重复c=tf.tile(b,[1,id_matrix_size])d=tf.reshape(c,[id_matrix_size*m,id_matrix_size*n])#第二步  在二维中重复单位矩阵。 identity_matrix=tf.eye(id_matrix_size) # 单位矩阵 identity_matrix_2D= tf.tile(identity_matrix,[m,n])#第三步  逐元素相乘output = tf.multiply(d,identity_matrix_2D )with tf.Session() as sess:    print(sess.run(output) )#输出 :#[[1. 0. 2. 0. 3. 0.]# [0. 1. 0. 2. 0. 3.]# [4. 0. 5. 0. 6. 0.]# [0. 4. 0. 5. 0. 6.]]

此外,如果需要多次实现这个操作,定义一个函数会更方便。

def Expand_tensor(mytensor,id_matrix_size):    m=mytensor.shape[0]        n=mytensor.shape[1]    #类似于 np.repeat 在 x 维度上。    flatten_mytensor=tf.reshape(mytensor,[-1,1])      a=tf.tile(flatten_mytensor,  [1, id_matrix_size])    b=tf.reshape( a, [m,-1])    #在 y 维度上重复    c=tf.tile(b,[1,id_matrix_size])    d=tf.reshape(c,[id_matrix_size*m,id_matrix_size*n])    #在二维中重复单位矩阵。     identity_matrix=tf.eye(id_matrix_size) # 单位矩阵     identity_matrix_2D= tf.tile(identity_matrix,[m,n])    #逐元素相乘    output = tf.multiply(d,identity_matrix_2D )    return outputmytensor=tf.constant([[1,2,3],[4,5,6] ],dtype = tf.float32)with tf.Session() as sess:    print(sess.run(Expand_tensor(mytensor,2)) )

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注