3-4 tensor 创建

import torch

# 1 直接定义
a=torch.Tensor([[1,2],[3,4]])
print(a)
print(a.type())#type 有括号
tensor([[1., 2.],
        [3., 4.]])
torch.FloatTensor
# 2 通过shape定义,值随机
a=torch.Tensor(2,3)  # 无括号
print(a)
print(a.shape)   
tensor([[ 0.0000e+00, -1.1152e-01,  5.2672e-08],
        [ 2.5959e-09,  4.2000e-08,  5.4373e+22]])
torch.Size([2, 3])
# 3 特殊tensor创建
a=torch.ones(2,3)  # 无括号
print(a)
print(a.shape) 

a=torch.zeros(2,3)  # 无括号
print(a)
print(a.shape)

a=torch.eye(2,3)  # 无括号
print(a)
print(a.shape)
tensor([[1., 1., 1.],
        [1., 1., 1.]])
torch.Size([2, 3])
tensor([[0., 0., 0.],
        [0., 0., 0.]])
torch.Size([2, 3])
tensor([[1., 0., 0.],
        [0., 1., 0.]])
torch.Size([2, 3])
# 4 相同尺寸tensor创建
b=torch.Tensor(2,3)  # 无括号
b=torch.ones_like(b)  #zeros_like  ;eye_like
print(b)
print(b.shape)
tensor([[1., 1., 1.],
        [1., 1., 1.]])
torch.Size([2, 3])
# 5 随机tensor创建
a=torch.rand(2,3) #(shape)
print(a)
print(a.shape)

a=torch.rand(2,3) #(shape)
print(a)
print(a.shape)

a=torch.normal(mean=0.0,std=torch.rand(5))
print(a)
print(a.shape)

a=torch.normal(mean=torch.rand(5),std=torch.rand(5))
print(a)
print(a.shape)

c=torch.Tensor(2,2).uniform_(-1,1) #先定义尺寸  unniform后面有个_!!!
print(c)
print(c.shape)

a=torch.arange(0,10,1)   #包前不包尾
print(a)
print(a.shape)

a=torch.linspace(2,10,3)#(起,终,数字个数)  等间隔的N个数字
print(a)
print(a.shape)

a=torch.randperm(10)  #打乱序列   不含10
print(a)
print(a.shape)
tensor([[0.9852, 0.2455, 0.0777],
        [0.7583, 0.9628, 0.6174]])
torch.Size([2, 3])
tensor([[0.0693, 0.2986, 0.3640],
        [0.9512, 0.7760, 0.7952]])
torch.Size([2, 3])
tensor([-0.7132, -0.0136, -0.2727, -0.3336,  0.8283])
torch.Size([5])
tensor([0.8153, 0.1946, 0.4179, 0.1585, 0.2395])
torch.Size([5])
tensor([[-0.8261,  0.1895],
        [-0.5835,  0.7373]])
torch.Size([2, 2])
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
torch.Size([10])
tensor([ 2.,  6., 10.])
torch.Size([3])
tensor([9, 1, 2, 4, 5, 8, 6, 3, 7, 0])
torch.Size([10])
# 6 numpy对比
import numpy as np
a=np.array([[1,2],[3.0,4]]) 
print(a)
print(a.shape)
[[1. 2.]
 [3. 4.]]
(2, 2)






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值