Sora模型已经诞生了,你还不会PyTorch吗?抓紧时间上车,驶入机器学习的快车道
收录于话题
公众号后台回复“111”
领取本篇代码、基因集或示例数据等文件
文件编号:240312
需要租赁服务器的小伙伴可以扫码添加小果,此外小果还提供生信分析,思路设计,文献复现等,有需要的小伙伴欢迎来撩~




import torch#导入机器学习框架
import numpy as np#导入科学计算库
t0=torch.tensor([1,2,3],dtype=torch.int8)#可选int16,int32,int64,float32,float16,float64
print(t0)
#输出:tensor([1, 2, 3], dtype=torch.int8)
print(t0.size())
#输出:torch.Size([3])
array1=np.arange(12).reshape(4,3)#arange生成连续整数的numpy.ndarray,reshape修改形状
print(array1)
'''输出:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
'''
t1=torch.tensor(array1,dtype=torch.float64)
print(t1)
'''输出:tensor([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.],
[ 9., 10., 11.]], dtype=torch.float64)
'''
print(t1.size())
#输出:torch.Size([4, 3])

print(t1.transpose(1,0))#等价T
'''输出:tensor([[ 0., 3., 6., 9.],
[ 1., 4., 7., 10.],
[ 2., 5., 8., 11.]], dtype=torch.float64)
'''
print(torch.empty(2,2))#空数组,使用无用数据填充
'''输出(不唯一):tensor([[-7.6103e+30, 1.5204e-42],
[ 0.0000e+00, 0.0000e+00]])
'''
print(torch.ones(2,3))#生成数据均为1的张量
'''输出:tensor([[1., 1., 1.],
[1., 1., 1.]])
'''
print(torch.zeros(2,1))#生成数据均为0的张量
#输出:tensor([[0.],
# [0.]])
print(torch.rand(1,4))#随机值区间为[0,1)
#输出(不唯一):tensor([[0.3295, 0.8059, 0.1125, 0.3575]])
print(torch.randn(1,4))#随机值的分布式均值为0,方差为1
#输出(不唯一):tensor([[-0.7469, 1.1632, 0.7925, 0.3307]])
print(torch.randint(low=0,high=3,size=[3,2]))#整型数组
'''输出(不唯一):tensor([[2, 2],
[0, 1],
[0, 0]])
'''
t2=torch.arange(24,dtype=torch.float)
print(t2)
#输出:tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
# 18, 19, 20, 21, 22, 23])
t2=t2.reshape(2,3,4)#和resize(2,3,4)相同,但过时
print(t2)
'''输出:tensor([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
'''
print(t2.view(-1))
'''输出:tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23])
'''
print(t2.view(3,-1))
'''输出:tensor([[ 0, 1, 2, 3, 4, 5, 6, 7],
[ 8, 9, 10, 11, 12, 13, 14, 15],
[16, 17, 18, 19, 20, 21, 22, 23]])
'''
print(t2.view(-1,2,4))
'''输出:tensor([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]],
[[16, 17, 18, 19],
[20, 21, 22, 23]]])
'''
print(t2.transpose(0,1))#两个参数,第1维和第2维交换 2*3*4->3*2*4
# '''输出:tensor([[[ 0., 1., 2., 3.],
# [12., 13., 14., 15.]],
#
# [[ 4., 5., 6., 7.],
# [16., 17., 18., 19.]],
#
# [[ 8., 9., 10., 11.],
# [20., 21., 22., 23.]]])
# '''
print(t2.permute(2,0,1))#三个参数,维度交换 2*3*4->4*2*3
'''输出:tensor([[[ 0., 4., 8.],
[12., 16., 20.]],
[[ 1., 5., 9.],
[13., 17., 21.]],
[[ 2., 6., 10.],
[14., 18., 22.]],
[[ 3., 7., 11.],
[15., 19., 23.]]])
'''
print(t2.min(),t2.max())
#输出:tensor(0.) tensor(23.)
print(t2.mean(),t2.std())#均值(只有数据不是整数型才能计算)、方差
#输出:tensor(11.5000) tensor(7.0711)
小果还提供思路设计、定制生信分析、文献思路复现;有需要的小伙伴欢迎直接扫码咨询小果,竭诚为您的科研助力!

定制生信分析
服务器租赁
扫码咨询小果


往期回顾
01 |
02 |
03 |
04 |