Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Keras中张量元素的有效乘法_Python_Tensorflow_Keras - Fatal编程技术网

Python Keras中张量元素的有效乘法

Python Keras中张量元素的有效乘法,python,tensorflow,keras,Python,Tensorflow,Keras,我有一个Keras中的张量,形状如下 x = (None, 14, 14, 32) 这是我的网络中卷积层的权重 我需要将张量的元素相乘,即自乘,然后将所有值相加 让我们考虑一个更简单的例子,如果我有以下张量 x = Tensor([1,2,3],[4,5,6]) 然后我需要计算x*x,输出应该是 1*4 + 1*5 + 1*6 + 2*4 + 2*5 + 2*6 + 3*4 + 3*5 + 3*6 作为一个幼稚的实现,我尝试了以下方法 flattened_unpacked

我有一个Keras中的张量,形状如下

x = (None, 14, 14, 32)
这是我的网络中卷积层的权重

我需要将张量的元素相乘,即自乘,然后将所有值相加

让我们考虑一个更简单的例子,如果我有以下张量

x = Tensor([1,2,3],[4,5,6])
然后我需要计算x*x,输出应该是

1*4 + 1*5 + 1*6 + 2*4 + 2*5 + 2*6 + 3*4 + 3*5 + 3*6
作为一个幼稚的实现,我尝试了以下方法

        flattened_unpacked = tf.unstack(tf.reshape(tf.gather(x,0), [-1]))
        list1 = []
        list2 = []
        for elem in flattened_unpacked:
            list1.append(elem)
            list2.append(elem)       
        res = [i * j for j in list1 for i in list2]  
        sum_res = sum(res)

但它很快就在Google Colab上耗尽了内存。是否有一种有效的方法来执行此乘法?

您可以使用
broadcast\u to
使数组大小与矩阵乘法兼容。请参阅文档

看看给出的示例,您正试图对这两个矩阵进行矩阵乘法。
矩阵1:形状3x3

array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])
矩阵2:形状3x1

array([[4],
       [5],
       [6]])
并计算得到的3x1矩阵的和

这可以通过以下方式实现:
步骤1:矩阵乘法:

x = tf.matmul(tf.broadcast_to(tf.constant([[1], [2], [3]]), shape = (3,3)), tf.constant([[4], [5], [6]]))
array([[15],
       [30],
       [45]])
90
输出:

x = tf.matmul(tf.broadcast_to(tf.constant([[1], [2], [3]]), shape = (3,3)), tf.constant([[4], [5], [6]]))
array([[15],
       [30],
       [45]])
90
步骤2:添加元素

tf.reduce_sum(x)
输出:

x = tf.matmul(tf.broadcast_to(tf.constant([[1], [2], [3]]), shape = (3,3)), tf.constant([[4], [5], [6]]))
array([[15],
       [30],
       [45]])
90