"""
演示
创建 全0、全1、指定值 张量
涉及到的API:
torch.zeros 和 torch.zeros_like 创建全0张量
torch.ones 和 torch.ones_like 创建全1张量
torch.full 和 torch.full_like 创建全为指定值张量
要掌握:
torch.zeros
用处:
网络参数初始化,偏置参数初始化
"""
# 导包
import torch
# 1.定义函数,演示创建全0张量
def demo01():
# 1.使用torcn.zeros创建全0张量,(3,4)
t1 = torch.zeros(3, 4)
print(f"t1:{t1}, shape: {t1.shape}, dtype: {t1.dtype}")
# 2.创建一个随机张量,(3,5)
t2 = torch.randn(3, 5)
print(f"t2:{t2}, shape: {t2.shape}, dtype: {t2.dtype}")
# 3.使用torch.zeros_like创建相同形状的全0张量
t3 = torch.zeros_like(t2) # (3,5)
print(f"t3:{t3}, shape: {t3.shape}, dtype: {t3.dtype}")
# 2.定义函数,演示创建全1张量
def demo02():
# 1.使用torcn.ones创建全1张量,(3,4)
t1 = torch.ones(3, 4)
print(f"t1:{t1}, shape: {t1.shape}, dtype: {t1.dtype}")
# 2.创建一个随机张量,(3,5)
t2 = torch.randn(3, 5)
print(f"t2:{t2}, shape: {t2.shape}, dtype: {t2.dtype}")
# 3.使用torch.ones_like创建相同形状的全1张量
t3 = torch.ones_like(t2) # (3,5)
print(f"t3:{t3}, shape: {t3.shape}, dtype: {t3.dtype}")
# 3.定义函数,演示创建指定值张量
def demo03():
# 1.使用torcn.full创建指定值张量,(3,4)
t1 = torch.full((3, 4), 3.14)
print(f"t1:{t1}, shape: {t1.shape}, dtype: {t1.dtype}")
# 2.创建一个随机张量,(3,5)
t2 = torch.randn(3, 5)
print(f"t2:{t2}, shape: {t2.shape}, dtype: {t2.dtype}")
# 3.使用torch.full_like创建相同形状的指定值张量
t3 = torch.full_like(t2, 10) # (3,5)
print(f"t3:{t3}, shape: {t3.shape}, dtype: {t3.dtype}")
# 测试
if __name__ == '__main__':
demo01()
demo02()
demo03()