import torch
import numpy as np
import torch.nn as nn
import math
print(torch.__version__)
Tensor 为 python 类,是默认张量类型 torch.FloatTensor() 的别名
tensor 为 python 函数,其中data可以是list,tuple,numpy ndarray,scalar等等,从data中数据部分做拷贝,根据原始数据类型生成相应的torch.LongTensor、torch.FloatTensor和torch.DoubleTensor
x = torch.Tensor([1, 2, 3]) # torch.float32
y = torch.tensor([1, 2, 3]) # torch.int64
print(x, type(x), x.dtype, x.shape)
print(y, type(y), y.dtype, y.shape)
tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False) -> Tensor
a = torch.tensor([2, 3])
b = torch.Tensor(2, 3)
print(a, type(a), a.dtype, a.shape)
print(b, type(b), b.dtype, b.shape)
torch.FloatTensor() # 32位浮点型(torch.Tensor默认的数据类型) eg. torch.Tensor([[2,3].[4,8],[7,9]])
torch.DoubleTensor() # 64位浮点类型
torch.ShortTensor() # 16位整型
torch.IntTensor() # 32位整型
torch.LongTensor() # 64位整型
tensor.half() # 转换为半精度类型 dtype=torch.float16
tensor.float()
tensor.double()
tensor.short()
tensor.int()
tensor.long()
## tensor维度 dim=0 表示列,第一维 dim=1 表示行,第二维
## tensor属性 tensor.ndim, tensor.dtype, tensor.shape, tensor.size()
x = torch.randn(2,3,4)
y = x.numpy() # tensor 转换为 numpy
z = torch.from_numpy(y) # numpy 转换为 tensor
r = torch.tensor(y)
print('x =', type(x), x.dtype, x)
print('y =', type(y), y.dtype, y)
print('z =', type(z), z.dtype, z)
print('r =', type(r), r.dtype, r)
Returns the total number of elements in the :attr:
input
tensor.
print(torch.rand(2,3).numel()) # 6
Returns the value of this tensor as a standard Python number.
print(torch.tensor(1).item()) # 1.0
Returns the size of the :attr:
self
tensor.
x = torch.arange(24).reshape(2,3,4)
print(x.size()) # torch.Size([2, 3, 4])
print(x.size(1)) # 3
Returns a tensor filled with uninitialized data.
print('empty =', torch.empty(2, 3, 4))
Returns a 2-D tensor with ones on the diagonal and zeros elsewhere.
print('eye =', torch.eye(2, 3))
print(torch.eye(2)) # 未指定m
Returns a tensor filled with the scalar value
1
.
print('ones =', torch.ones(2, 3, 4))
Returns a tensor filled with the scalar value
0
.
print('zeros =', torch.zeros(2, 3, 4))
Returns a tensor filled with random numbers from a uniform distribution on the interval :math:
[0, 1)
print('rand =', torch.rand(2, 3, 4))
Returns a tensor filled with random numbers from a normal distribution with mean
0
and variance1
(also called the standard normal distribution).
print('randn =', torch.randn(2, 3 ,4))
Returns a tensor filled with random integers generated uniformly between :attr:
low
(inclusive) and :attr:high
(exclusive).
print('randint =', torch.randint(10, (2, 3)))
Returns a random permutation of integers from
0
ton - 1
.
print('randperm =', torch.randperm(10)) # tensor([2, 9, 5, 3, 6, 1, 0, 4, 7, 8])
返回一个从[start, end) 指定步长(默认1)的序列一维张量
print('arange =', torch.arange(0, 10, step=2)) # tensor([0, 2, 4, 6, 8])
返回一个包含在[start, end]上均匀间隔的steps个点
print('linspace =', torch.linspace(0, 100, 10)) # tensor([ 0.0000, 11.1111, 22.2222, 33.3333, 44.4444, 55.5556, 66.6667, 77.7778, 88.8889, 100.0000])
用于创建一个与已知tensor形状相同的tensor
eg. torch.empty_like(input), torch.ones_like(input), torch.zeros_like(input), torch.rand_like(input), torch.randn_like(input), torch.randint_like(input),
用于创建一个与已知tensor数据类型相同的tensor
eg. torch.Tensor.new_tensor(data), torch.Tensor.new_empty(size), torch.Tensor.full_like(size, fill_value), torch.Tensor.new_ones(size), torch.Tensor.new_zeros(size)
Gathers values along an axis specified by
dim
.
x = [
[2, 3, 4, 5, 0, 0],
[1, 4, 3, 0, 0, 9],
[4, 2, 2, 5, 7, 0],
[1, 0, 6, 0, 0, 6]
]
input = torch.tensor(x)
index = torch.LongTensor([[3, 2],[2, 1],[4, 3],[0, 2]]) # index.shape=[4,2] 注意index的类型
print('gather =', torch.gather(input, 1, index))
index = torch.LongTensor([[3, 2, 1, 0, 2, 1], [0, 1, 3, 2, 2, 1]]) # index.shape=[2, 6]
print('gather =', torch.gather(input, 0, index))
返回给定tensor中a至b行中的c至d列,区间是连续的张量。
x = torch.arange(12).reshape(3, 4)
print(x)
print('[:, :] =', x[1:3, 2:], '\n')
Returns a new tensor that is a narrowed version of :attr:
input
tensor.
[start, start+length)
print('narrow =', torch.narrow(x, 0, 1, 2))
print('narrow =', torch.narrow(x, 1, 1, 2), '\n')
Removes a tensor dimension. Returns a tuple of all slices along a given dimension, already without it.
print('unbind =', torch.unbind(x, 0))
print('unbind =', torch.unbind(x, 1), '\n')
Returns a new tensor which indexes the :attr:
input
tensor along dimension :attr:dim
using the entries in :attr:index
which is aLongTensor
.
print('index_select =', torch.index_select(x, 1, torch.LongTensor([2, 1, 0])))
print('index_select =', torch.index_select(x, 0, torch.LongTensor([1, 2, 0])))
Concatenates the given sequence of seq` tensors in the given dimension.
x = torch.arange(6).reshape(2, 3)
print(x)
print('cat =', torch.cat((x,x), 0))
print('cat =', torch.cat((x,x), 1), '\n')
Concatenates a sequence of tensors along a new dimension.
a = torch.stack([x, x, x])
b = torch.stack([x, x, x], 1)
print('stack =', a, a.size())
print('stack =', b, b.size())
Attempts to split a tensor into the specified number of chunks. Each chunk is a view of the input tensor.
a = torch.arange(9).reshape(3, 3)
print(a)
print('chunk =', torch.chunk(a, 2))
print('chunk =', torch.chunk(a, 2, 1), '\n')
Splits the tensor into chunks. Each chunk is a view of the original tensor.
print('split =', torch.split(a, 2))
print('split =', torch.split(a, [1, 2]))
print('split =', torch.split(a, [2, 1], 1))
Returns a tensor with all the dimensions of :attr:
input
of size1
removed.
x = torch.zeros(2, 1, 2, 1, 2)
y = torch.squeeze(x)
z = torch.squeeze(x, 1)
print(x.size())
print(y.size())
print(z.size())
Returns a new tensor with a dimension of size one inserted at the specified position.
x = torch.tensor([1,2,3,4])
print(torch.unsqueeze(x, 0))
print(torch.unsqueeze(x, 1))
Returns a new view of the :attr:
self
tensor with singleton dimensions expanded to a larger size.
x = torch.tensor([[1], [2], [3]])
print(x.expand(3, 4))
print(x.expand(-1, 3))
Expand this tensor to the same size as :attr:
other
.
x = torch.tensor([[2,2], [3,3], [4,4]])
y = torch.tensor([[1], [2], [3]])
print(x)
print(y.expand_as(x))
Repeats this tensor along the specified dimensions.
x = torch.arange(4)
y = x.repeat(2, 3, 4)
print(x, x.size())
print(y, y.size())
Returns a tensor that is a transposed version of :attr:
input
.
x = torch.randn(2, 3)
print(x)
print(torch.transpose(x, 0, 1))
Expects :attr:
input
to be <= 2-D tensor and transposes dimensions 0 and 1.
x = torch.arange(6).reshape(2, 3)
print(x)
print(torch.t(x)) # x.t
Returns a view of the original tensor :attr:
input
with its dimensions permuted.
x = torch.randn(2, 3, 5)
print(x.size())
print(torch.permute(x, (2, 0, 1)).size())
Returns a tensor with the same data and number of elements as :attr:
input
, but with the specified shape.
x = torch.arange(4)
print(torch.reshape(x, (2, 2))) # x.reshape(2,2)
Returns a new tensor with the same data as the :attr:
self
tensor but of a different :attr:shape
.
y = x.view(a, -1) 用于改变维度(x与y共享内存)
y = x.clone().view(a,b) x与y断开联系,创造一个x副本,再进行view
x = torch.arange(16)
y = x.view(2, 8)
print(x)
print(y)
Flattens :attr:
input
by reshaping it into a one-dimensional tensor.
x = torch.arange(1, 9).reshape(2, 4)
y = torch.flatten(x)
print(x)
print(y)
torch.random
torch.manual_seed(seed) -> torch._C.Generator
Sets the seed for generating random numbers. Returns a
torch.Generator
object.
torch.manual_seed(0)
print(torch.rand(10))
Draws binary random numbers (0 or 1) from a Bernoulli distribution.
a = torch.empty(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1]
print(a)
print(torch.bernoulli(a))
a = torch.ones(3, 3) # probability of drawing "1" is 1
print(torch.bernoulli(a))
a = torch.zeros(3, 3) # probability of drawing "1" is 0
print(torch.bernoulli(a))
Returns a tensor where each row contains :attr:
num_samples
indices sampled from the multinomial probability distribution located in the corresponding row of tensor :attr:input
.
weights = torch.tensor([0, 10, 3, 0], dtype=torch.float) # create a tensor of weights
print(torch.multinomial(weights, 2))
print(torch.multinomial(weights, 4, replacement=True))
torch.save(model1,'model1.pt') # 保存整个模型,消耗存储较大
torch.save(model2.state_dict(),'model2.pt') # 保存模型参数,消耗存储较小
model1 = torch.load('model1.pt') # 加载整个模型
model2 = Model()
model2.load_state_dict(torch.load('model2.pt')) # 加载模型参数
torch.load('tensors.pth')
torch.load('tensors.pth', map_location=lambda storage, loc: storage) #把所有的张量加载到CPU中
torch.load('tensors.pth', map_location=lambda storage, loc: storage.cuda(1)) #把所有的张量加载到GPU 1中
torch.load('tensors.pth', map_location={'cuda:1':'cuda:0'}) # 把张量从GPU 1 移动到 GPU 0
x = torch.arange(6).reshape(2, 3)
y = torch.arange(6, 12).reshape(2, 3)
print(x)
print(y)
print(-x) # torch.neg(x)
print(x+y) # torch.add(x, y)
print(x-y) # torch.add(x, -y)
print(x*y) # torch.mul(x, y)
print(x*2) # torch.mul(x, 2)
print(x/y) # torch.div(x, y)
print(x/2) # torch.div(x, 2)
print(x%y) # torch.fmod(x, y)
print(x%2) # torch.fmod(x, 2)
print(x**y) # torch.pow(x, y)
print(x**2) # torch.pow(x, 2)
print(torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2))
print(torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5))
print(torch.exp(torch.tensor([0, 1, math.log(2.)])))
x = torch.randn(5)
print(torch.log(x))
Returns a new tensor with the natural logarithm of (1 + :attr:
input
).
print(torch.log1p(torch.tensor([-2, -1, 0, math.exp(1.)-1])))
Returns a new tensor with the reciprocal of the elements of :attr:
input
.
print(torch.reciprocal(torch.tensor([-1, 1, 0, float("inf"), -float("inf"), 10])))
Returns a new tensor with the square-root of the elements of :attr:
input
.
print(torch.sqrt(torch.tensor([-2, 1, 4, 9, 100, float("inf")])))
Returns a new tensor with the reciprocal of the square-root of each of the elements of :attr:
input
.
print(torch.rsqrt(torch.tensor([-2, 1, 4, 9, 100, float("inf")])))
Computes the absolute value of each element in :attr:
input
.
print(torch.abs(torch.tensor([-1, -2, 3])))
a = torch.randn(4)
print(a)
print(torch.ceil(a))
print(torch.floor(a))
Rounds elements of :attr:
input
to the nearest integer.
print(torch.round(a))
Returns a new tensor with the truncated integer values of the elements of :attr:
input
.
Computes the fractional portion of each element in :attr:
input
.
Clamps all elements in :attr:
input
into the range[
:attr:min
, :attr:max
]
.
a = torch.randn(4)
print(a)
print(torch.trunc(a))
print(torch.frac(a))
print(torch.clamp(a, min=-0.5, max=0.5))
Does a linear interpolation of two tensors :attr:
start
(given by :attr:input
) and :attr:end
based
on a scalar or tensor :attr:weight
and returns the resulting :attr:out
tensor.
st = torch.arange(1., 5.)
ed = torch.Tensor(4).fill_(10)
print(st)
print(ed)
print(torch.lerp(st, ed, 0.5))
torch.sigmoid(input, *, out=None) -> Tensor
torch.sign(input, *, out=None) -> Tensor
a = torch.randn(4)
print(a)
print(torch.sign(a))
a = torch.Tensor([-math.pi, -math.pi/2, -math.pi/3, -math.pi/6, 0, math.pi/6, math.pi/3, math.pi/2, math.pi])
print(torch.sin(a))
print(torch.cos(a))
print(torch.tan(a))
print(torch.asin(a))
print(torch.acos(a))
print(torch.atan(a))
print(torch.atan2(torch.randn(4), torch.randn(4)))
a = torch.randn(4)
print(torch.sinh(a))
print(torch.cosh(a))
print(torch.tanh(a))
Computes the dot product of two 1D tensors. 两个向量(一维张量)相乘
print(torch.dot(torch.tensor([1, 2, 3]), torch.tensor([1, 2, 3])))
Performs a matrix-vector product of the matrix :attr:
input
and the vector :attr:vec
. 矩阵(二维张量)与向量(一维张量)相乘
mat = torch.arange(6).reshape(2, 3)
vec = torch.arange(1, 4)
print(mat)
print(vec)
print(torch.mv(mat, vec))
Performs a matrix multiplication of the matrices :attr:
input
and :attr:mat2
. 两个矩阵(二维张量)相乘
mat1 = torch.arange(6).reshape(2, 3)
mat2 = torch.arange(1, 10).reshape(3, 3)
print(mat1)
print(mat2)
print(torch.mm(mat1, mat2))
Matrix product of two tensors. 两个多维张量相乘
t1 = torch.arange(6).reshape(2,3)
t2 = torch.arange(9).reshape(3,3)
print(t1)
print(t2)
print(torch.matmul(t1, t2))
Performs a batch matrix-matrix product of matrices stored in :attr:
input
and :attr:mat2
.
input = torch.randn(10, 3, 4)
mat2 = torch.randn(10, 4, 5)
res = torch.bmm(input, mat2)
print(res.size())
Returns the sum of all elements in the :attr:
input
tensor.
x = torch.arange(6).reshape(2, 3)
print(x)
print(torch.sum(x))
print(torch.sum(x, dim=0)) # col
print(torch.sum(x, dim=1)) # row
Returns the product of all elements in the :attr:
input
tensor.
x = torch.arange(1, 7).reshape(2,3)
print(x)
print(torch.prod(x))
print(torch.prod(x, dim=0)) # col
print(torch.prod(x, dim=1)) # row
Returns the cumulative product of elements of :attr:
input
in the dimension :attr:dim
.
x = torch.arange(2,8).reshape(2,3)
print(x)
print(torch.cumprod(x,0))
Returns the cumulative sum of elements of :attr:
input
in the dimension :attr:dim
.
x = torch.arange(2,8).reshape(2,3)
print(x)
print(torch.cumsum(x,0))
Returns the p-norm of (:attr:
input
- :attr:other
)
x = torch.randn(4)
y = torch.randn(4)
print(torch.dist(x, y, 3.5))
Returns the matrix norm or vector norm of a given tensor.
a = torch.arange(9, dtype=torch.float)-4
b = a.reshape(3,3)
print(torch.norm(a))
print(torch.norm(b))
Returns the mean value of all elements in the :attr:
input
tensor.
Returns the mean value of each row of the :attr:
input
tensor in the given
dimension :attr:dim
.
x = torch.arange(6, dtype=float).reshape(2,3)
print(x)
print(torch.mean(x))
print(torch.mean(x, 0))
print(torch.mean(x, 1))
If :attr:
unbiased
isTrue
, Bessel’s correction will be used. Otherwise, the sample variance is calculated, without any correction.
x = torch.arange(6, dtype=float).reshape(2, 3)
print(x)
print(torch.var(x))
print(torch.var(x, 0))
print(torch.var(x, 1))
If :attr:
unbiased
isTrue
, Bessel’s correction will be used. Otherwise, the sample deviation is calculated, without any correction.
print(torch.std(x))
print(torch.std(x, 0))
print(torch.std(x, 1))
Returns the median of the values in :attr:
input
.
Returns a namedtuple
(values, indices)
wherevalues
contains the median of each row of :attr:input
in the dimension :attr:dim
, andindices
contains the index of the median values found in the dimension :attr:dim
.
print(torch.median(x))
print(torch.median(x, 0))
print(torch.median(x, 1))
Returns a namedtuple
(values, indices)
wherevalues
is the mode value of each row of the :attr:input
tensor in the given dimension :attr:dim
, i.e. a value which appears most often in that row, andindices
is the index location of each mode value found.
Returns the lower triangular part of the matrix (2-D tensor) or batch of matrices :attr:
input
, the other elements of the result tensor :attr:out
are set to 0.
a = torch.randn(3, 3)
print(a)
print(torch.tril(a))
Fills elements of :attr:
self
tensor with :attr:value
where :attr:mask
is True.
print(torch.eq(torch.Tensor([[1, 2], [3, 4]]), torch.Tensor([[1, 1], [4, 4]])))
print(torch.eq(torch.Tensor([[1, 2], [3, 4]]), 2))
print(torch.equal(torch.tensor([1, 2]), torch.tensor([1, 2])))
print(torch.ge(torch.Tensor([[1, 2], [3, 4]]), torch.Tensor([[1, 1], [4, 4]])))
print(torch.ge(torch.Tensor([[1, 2], [3, 4]]), 2))
print(torch.gt(torch.Tensor([[1, 2], [3, 4]]), torch.Tensor([[1, 1], [4, 4]])))
print(torch.gt(torch.Tensor([[1, 2], [3, 4]]), 2))
torch.le(input, other, *, out=None) -> Tensor
torch.lt(input, other, *, out=None) -> Tensor
torch.kthvalue(input, k, dim=None, keepdim=False, *, out=None) -> (Tensor, LongTensor)
a = torch.arange(1, 9)
print(a)
print(torch.kthvalue(a, 4))
x = torch.arange(1, 9).reshape(2, 4)
print(x)
print(torch.kthvalue(x, 2, 0, True))
print(torch.kthvalue(x, 3, 1, True))
torch.max(input) -> Tensor
torch.max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor)
torch.max(input, other, *, out=None) -> Tensor
torch.min(input) -> Tensor
torch.min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor)
torch.min(input, other, *, out=None) -> Tensor
torch.ne(input, other, *, out=None) -> Tensor
print(torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])))
print(torch.ne(torch.tensor([[1, 2], [3, 4]]), 2))
x = torch.randn(3, 4)
print(x)
print(torch.sort(x))
print(torch.sort(x, 0))
print(torch.sort(x, 1))
Returns the :attr:
k
largest elements of the given :attr:input
tensor along a given dimension.