小灰灰深度学习day4——数据操作之张量(torch)

发布时间 2023-05-29 23:33:08作者: 啥都不会的灰太狼

震惊了!!!在python中, y = x + y;与 y += x;竟然有区别,且看如下代码:

import torch
'''
x = torch.arange(12)
print(x)
#reshape可以改变张量的形状而不改变元素的数量和元素值
X = x.reshape(-1,3)
print(X)

#shape属性可以访问元素的张量的形状
print(X.shape)

#numel()得到张量中元素的总数
print(X.numel())

#张量元素设全0
x = torch.zeros((2, 3, 4))
print(x)

#张量内元素全为1
x = torch.ones((2, 3, 4))
print(x)

#创建形状为(3, 4),每个元素都从均值为0,标准差为1的标准高斯分布(正态分布)中随机取样
x = torch.randn(3, 4)
print(x)

#还可以直接赋值
x = torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
print(x)
x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])
#对应每个元素之间做运算
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x ** y) #  **是求幂运算

#求指数
print(torch.exp(x))

x = torch.arange(12, dtype=torch.float32).reshape(3, 4)
y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
print(torch.cat((x, y), dim = 0)) #按照第0维度拼接 (即按照x拼接)
print(torch.cat((x, y), dim = 1)) #按照第1维度拼接 (即按照y拼接)

#利用逻辑符号构成二元张量
print(x == y)

#求一个张量内所有元素的和
print(x.sum())

#形状不同,会有广播机制,将张量复制放大(3, 1)->(3, 2),(1, 2)->(3, 2)
#维度数相同的张量才能广播。
a = torch.arange(3).reshape(3, 1)
b = torch.arange(2).reshape(1, 2)
print(a)
print(b)
print(a + b)
print(a * b)

x = torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
#输出最后一行
print(x[-1])

#修改某一个元素————索引
x[1, 2] = 9
print(x)

#修改某一些元素(这里修改1到2行)————切片
x[0:2, :] = 9
print(x)
'''
'''
#有关节省内存 先看反例
x = [2]
y = [1]
before = id(y)
y = y + x
print(id(y) == before)
#这样当数组很大时,比较浪费空间
'''
'''
#为了节省空间我们这么做
x = [2]
y = [1]
before = id(x)
x += y
print(id(x) == before)
'''
'''
x = torch.tensor([2])
y = torch.tensor([1])
z = torch.zeros_like(y)
print(id(z))
z[:] = x + y
print(id(z))
'''
'''
#numpy和torch共享底层内存,所以他们之间转化起来很容易
import numpy as np
a = np.array([1, 2]) 
b = torch.tensor(a)
print(type(a))
print(type(b))

#将大小为1的张量转换为python标量,我们可以调用item函数或python的内置函数
a = torch.tensor([3.5])
print(a)
print(a.item())
print(float(a))
print(int(a))
#深度学习存储和操作数据的主要接口是张量(n维数组)。它提供了各种功能,包括基本数学,
#运算,广播,索引,切片,内存节省,和转换为其他Python对象
'''