可调用神经网络与全连接层

2019-08-02  本文已影响0人  钢笔先生

Time: 2019-08-02

全连接层的输入

全连接层的输入是一个向量,权重是一个二维矩阵,矩阵在前,每行表示当前层的神经元们和输入元素的连接权重。

fc.png
in_features = torch.tensor([1,2,3,4], dtype=torch.float32)

weight_matrix = torch.tensor(
        [
            [1,2,3,4],
            [2,3,4,5],
            [3,4,5,6]
        ],
    dtype=torch.float32
)

weight_matrix.matmul(in_features) # 3x4 x 4x1 ==  3x1
# tensor([30., 40., 50.])

可以看作是输入形状为4x1, 当前层有3个神经元。

用PyTorch来实现就是:

fc = nn.Linear(in_features=4, out_features=3)

# 使用计算: 对输入值进行操作
fc(in_features)
# tensor([-1.2031,  2.6481, -0.0190], grad_fn=<AddBackward0>)

手动修改fc层的权重

fc.weight
'''
Parameter containing:
tensor([[-0.2965, -0.0901, -0.3543,  0.1393],
        [ 0.2594,  0.4917,  0.0977,  0.3502],
        [-0.0267,  0.3842, -0.1950, -0.1272]], requires_grad=True)
'''

# 指定fc计算不带bias
fc = nn.Linear(in_features=4, out_features=3, bias=False)

# 手动修改
fc.weight = nn.Parameter(weight_matrix)
fc(in_features)
# tensor([30., 40., 50.], grad_fn=<SqueezeBackward3>)

可以得到和手动设计的一模一样的结果~~~

多做一些验证试验,可以快速掌握PyTorch。

层的调用方式

layer(input)
__call__(input)

可以将层当做函数使用,一定是层实现了__call__函数,在nn.Module中确实看到了__call__的实现。

这些都是Python数据模型的内容,也侧面反映了PyTorch实现得很好,非常Pythonic。

END.

上一篇 下一篇

猜你喜欢

热点阅读