0

如何将外部产品(先前的特征向量及其本身)包含在链接器中作为层,尤其是以与批处理兼容的方式?

4

2 回答 2

1

F.matmul也很方便。

根据输入形状,您可以将其与F.expand_dims(当然F.reshape也可以)或使用transa/transb参数结合使用。

详细请参考函数官方文档

代码

import chainer.functions as F
import numpy as np

print("---")
x = np.array([[[1], [2], [3]], [[4], [5], [6]]], 'f')
y = np.array([[[1, 2, 3]], [[4, 5, 6]]], 'f')
print(x.shape)
print(y.shape)
z = F.matmul(x, y)
print(z)


print("---")
x = np.array([[[1], [2], [3]], [[4], [5], [6]]], 'f')
y = np.array([[[1], [2], [3]], [[4], [5], [6]]], 'f')
print(x.shape)
print(y.shape)
z = F.matmul(x, y, transb=True)
print(z)


print("---")
x = np.array([[1, 2, 3], [4, 5, 6]], 'f')
y = np.array([[1, 2, 3], [4, 5, 6]], 'f')
print(x.shape)
print(y.shape)
z = F.matmul(
    F.expand_dims(x, -1),
    F.expand_dims(y, -1),
    transb=True)
print(z)

输出

---
(2, 3, 1)
(2, 1, 3)
variable([[[  1.   2.   3.]
           [  2.   4.   6.]
           [  3.   6.   9.]]

          [[ 16.  20.  24.]
           [ 20.  25.  30.]
           [ 24.  30.  36.]]])
---
(2, 3, 1)
(2, 3, 1)
variable([[[  1.   2.   3.]
           [  2.   4.   6.]
           [  3.   6.   9.]]

          [[ 16.  20.  24.]
           [ 20.  25.  30.]
           [ 24.  30.  36.]]])
---
(2, 3)
(2, 3)
variable([[[  1.   2.   3.]
           [  2.   4.   6.]
           [  3.   6.   9.]]

          [[ 16.  20.  24.]
           [ 20.  25.  30.]
           [ 24.  30.  36.]]])
于 2017-11-22T20:19:39.500 回答
0

您可以使用F.reshapeandF.broadcast_to来显式处理数组。

假设您有h形状为(小批量、特征)的二维数组。如果要计算 and 的外积h,请h尝试以下代码。这是你想做的吗?

import numpy as np
from chainer import functions as F


def outer_product(h):
    s0, s1 = h.shape
    h1 = F.reshape(h, (s0, s1, 1))
    h1 = F.broadcast_to(h1, (s0, s1, s1))
    h2 = F.reshape(h, (s0, 1, s1))
    h2 = F.broadcast_to(h2, (s0, s1, s1))
    h_outer = h1 * h2
    return h_outer

# test code
h = np.arange(12).reshape(3, 4).astype(np.float32)
h_outer = outer_product(h)
print(h.shape)
print(h_outer.shape, h_outer.data)
于 2017-11-22T08:39:51.223 回答