代码可在https://github.com/Yablon/pytorch-practices.git下载how_to_use_tensor.ipynb
# coding: utf-8
# In[1]:
#开始练习pytorch中对tensor的使用
from __future__ import print_function
import torch as t
#__future__这个模块是将python3版本的一些特性导入到2版本中。
#导入print_function后,print的用法就和python3中一样了
# In[2]:
#使用Tensor函数新建tensor,方式复杂多变,例子如下
#指定tensor的形状
a = t.Tensor(2,3)
a #数值没有初始化,所以取决于内存的状态
# In[3]:
#用list的数据创建tensor
b = t.Tensor([[1,2,3],[4,5,6]])
b
# In[4]:
b.tolist() #tolist这个函数把tensor变为list,list就是列表
# In[5]:
#tensor.size返回torch.Size的对象,注意后边S是大写,它是tuple的子类,但使用方式与tuple略有区别
#tuple是元组的意思,元组的元素不能修改,但元组元素的元素可以修改;例tuple = (1,2,3)
b_size = b.size()
b_size
# In[6]:
b.numel() #b中元素的个数,等价于b.nelement()
# In[7]:
#创建一个和b形状一样的tensor,跟matlab里边差不多
c = t.Tensor(b_size)
# In[8]:
d = t.Tensor((2,3))
c, d #可以看出tuplet和list差不多
# In[9]:
#you can use tensor.shape to see the shape of tensor.
#tensor.shape equals to tensor.size, that is similar to matlab
#my sougou is broken, so I use my tough English to comment here.
c.shape
# In[10]:
get_ipython().run_line_magic('pinfo2', 'c.shape')
# In[11]:
#if you use t.Tensor(*sizes) to new a tensor,
#the storage will not be allocated immediately,
#when you use it, system allowcates it.
#other operations will allocate the storage immediately
#examples
t.ones(2,3)
# In[12]:
t.zeros(2,3)
# In[13]:
t.arange(1, 6, 2)
# In[14]:
t.linspace(1,10,3)
# In[15]:
t.randn(2,3)
# In[16]:
t.randperm(5) #random sequence of length 5
# In[17]:
t.eye(2,3)
# In[18]:

本文档通过实例代码详细介绍了如何在PyTorch中使用Tensor,包括创建、操作和运算,适合初学者进行Tensor应用的练习。完整代码可在GitHub项目<https://github.com/Yablon/pytorch-practices>的how_to_use_tensor.ipynb找到。
最低0.47元/天 解锁文章
1456

被折叠的 条评论
为什么被折叠?



