Pytorch卷积层手动初始化权值的实例
作者:Learn2Learn 时间:2023-08-02 15:38:23
由于研究关系需要自己手动给卷积层初始化权值,但是好像博客上提到的相关文章比较少(大部分都只提到使用nn.init里的按照一定分布初始化方法),自己参考了下Pytorch的官方文档,发现有两种方法吧。
所以mark下。
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
# 第一一个卷积层,我们可以看到它的权值是随机初始化的
w=torch.nn.Conv2d(2,2,3,padding=1)
print(w.weight)
# 第一种方法
print("1.使用另一个Conv层的权值")
q=torch.nn.Conv2d(2,2,3,padding=1) # 假设q代表一个训练好的卷积层
print(q.weight) # 可以看到q的权重和w是不同的
w.weight=q.weight # 把一个Conv层的权重赋值给另一个Conv层
print(w.weight)
# 第二种方法
print("2.使用来自Tensor的权值")
ones=torch.Tensor(np.ones([2,2,3,3])) # 先创建一个自定义权值的Tensor,这里为了方便将所有权值设为1
w.weight=torch.nn.Parameter(ones) # 把Tensor的值作为权值赋值给Conv层,这里需要先转为torch.nn.Parameter类型,否则将报错
print(w.weight)
效果预览
来源:https://blog.csdn.net/u014767662/article/details/83150942
标签:Pytorch,卷积层,初始化,权值
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python学习之字符串常用操作详解
2022-07-14 18:54:48
python 实现客户端与服务端的通信
2023-11-19 01:28:33
![](https://img.aspxhome.com/file/2023/7/101207_0s.png)
Ubuntu安装Go语言运行环境
2024-03-09 11:06:15
python图形用户界面tkinter之按钮Button的使用说明
2022-09-14 06:48:28
![](https://img.aspxhome.com/file/2023/4/106974_0s.png)
浅谈Python中的私有变量
2023-07-21 17:59:46
使用Python脚本将文字转换为图片的实例分享
2022-07-20 14:33:29
![](https://img.aspxhome.com/file/2023/5/72935_0s.png)
asp如何写入超长的字符串?
2010-06-09 18:53:00
Python中的axis参数的具体使用
2021-06-14 19:42:53
![](https://img.aspxhome.com/file/2023/5/92045_0s.png)
由黄钻等级图标处理引发的思考
2009-11-16 12:37:00
![](https://img.aspxhome.com/file/UploadPic/200911/16/20091116124056484s.jpg)
Python对XML文件实现增删改查操作
2023-11-19 20:42:03
python错误处理详解
2023-04-24 11:10:30
python隐藏终端执行cmd命令的方法
2022-01-09 05:19:37
python中apply函数详情
2023-06-03 14:58:15
![](https://img.aspxhome.com/file/2023/1/87941_0s.png)
pytest使用@pytest.mark.parametrize()实现参数化的示例代码
2022-07-17 07:54:01
![](https://img.aspxhome.com/file/2023/8/69508_0s.png)
Django 日志配置按日期滚动的方法
2021-02-02 08:27:01
Python中如何自定义函数
2021-12-12 20:20:58
![](https://img.aspxhome.com/file/2023/2/84972_0s.png)
SQL Server 数据库基本操作语句总结
2024-01-18 05:12:06
Python如何实现感知器的逻辑电路
2021-01-09 00:41:38
![](https://img.aspxhome.com/file/2023/5/91975_0s.png)
Python requests库参数提交的注意事项总结
2021-11-18 19:40:18
![](https://img.aspxhome.com/file/2023/1/76711_0s.png)
用Django实现一个可运行的区块链应用
2022-07-17 22:26:31
![](https://img.aspxhome.com/file/2023/3/101323_0s.jpg)