用指定的Tensor数据来初始化model的参数

很多时候我们都想用自己的参数(数据)来初始化我们的model,代码如下:

>>> model=torch.nn.Linear(10,5)
>>> for ii in model.modules():
...     ii.weight=torch.nn.Parameter(torch.randn(10,5))
...
>>> a=torch.randn(10,5)
>>> a
tensor([[-0.8402, -1.3473,  0.9593, -0.1408,  0.2504],
        [-0.5642,  0.5420, -1.6001, -0.9807,  0.6935],
        [ 0.5199,  0.7962,  0.1486,  2.1762, -0.1486],
        [-0.9331,  0.7782,  0.7501, -0.0087, -0.3033],
        [-0.9602,  2.0800,  0.9486,  0.9825,  1.8542],
        [-0.7316, -0.7301,  0.8184, -1.1840,  1.1499],
        [-2.6392,  0.4696, -1.0079,  0.6272, -0.0083],
        [ 1.0821, -0.3723,  1.3923, -0.6589, -0.4807],
        [ 0.2141, -0.2910,  2.6941,  0.3908,  0.0870],
        [ 0.3787, -3.2251,  1.6406, -0.4179, -0.4480]])
>>> for ii in model.modules():
...     ii.weight=torch.nn.Parameter(a)
...
>>> for ii in model.modules():
...     print(ii.weight)
...
Parameter containing:
tensor([[-0.8402, -1.3473,  0.9593, -0.1408,  0.2504],
        [-0.5642,  0.5420, -1.6001, -0.9807,  0.6935],
        [ 0.5199,  0.7962,  0.1486,  2.1762, -0.1486],
        [-0.9331,  0.7782,  0.7501, -0.0087, -0.3033],
        [-0.9602,  2.0800,  0.9486,  0.9825,  1.8542],
        [-0.7316, -0.7301,  0.8184, -1.1840,  1.1499],
        [-2.6392,  0.4696, -1.0079,  0.6272, -0.0083],
        [ 1.0821, -0.3723,  1.3923, -0.6589, -0.4807],
        [ 0.2141, -0.2910,  2.6941,  0.3908,  0.0870],
        [ 0.3787, -3.2251,  1.6406, -0.4179, -0.4480]], requires_grad=True)
>>> for ii in model.modules():
...     print(ii.bias)
...
Parameter containing:
tensor([-0.3115, -0.0643, -0.0982,  0.1830, -0.1755], requires_grad=True)
>>>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值