第二章节学习
**
import torch
import numpy as np
x = torch.arange(12)
print(x)
output: tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
# 2行3列
x = x.reshape(2, -1)
print(x)
tensor([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]])
# 轴0-2 轴1-3 轴2-4
zeros = torch.zeros((2, 3, 4))
print(zeros)
tensor([[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]],
[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]])
# 随机生成
randn = torch.randn(2, 3)
print(randn)
# 运算符 + - * / **(次方)
x = torch.tensor([1, 2, 3], dtype=torch.float)
y = torch.tensor([1, 2, 3], dtype=torch.float)
x + y, x - y, x * y, x / y, x ** y
# x^e 若dtype不是Long 会报错
torch.exp(x)
# 张量连接dimension维度 dim=0为轴0 dim=0为轴1 dim=0时候张量轴-0的长度相加 为1时轴1的长度相加
x = torch.arange(4, dtype=torch.float32).reshape(2, 2)
y = torch.tensor([[1, 1], [2, 2]], dtype=torch.float32)
print(x)
print(y)
print(torch.cat((x, y), dim=0))
print(torch.cat((x, y), dim=1))
# 广播机制
# 当两个张量的长宽不一样的时候 广播机可以将矩阵扩大 将一个矩阵复制另外一个矩阵的列 另外一个矩阵肤质一个矩阵的行 然后进行元素相加
x = torch.arange(3).reshape((3, 1))
y = torch.arange(2).reshape((1, 2))
print(x, y)
# 进行相加3 * 1 * 1 * 2 = 3 * 2所以是3行2列的张量
print(x + y)
张量广播机制的相关知识连接
**https://zhuanlan.zhihu.com/p/60365398**
**https://www.cnblogs.com/jiaxin359/p/9021726.html**
x = torch.arange(4, dtype=torch.float32).reshape(2, 2)
# 对张量进行求和
x.sum()
# 判断两个张量之间是否相等 x == y 若相等那么相同元素的位置为True 1 否则为False 0
x = torch.arange(4, dtype=torch.float32).reshape(2, 2)
y = torch.tensor([[1, 1], [2, 2]], dtype=torch.float32)
x == y
# 索引和切片 -1是最后一个元素的索引
x = torch.arange(4, dtype=torch.float32).reshape(2, 2)
print(x[-1])
print(x[0:2])
# 将指定元素写入矩阵中
x[1, 1] = 100
print(x)
# 给多个元素赋相同的数值 ::表示轴1的所有元素
# 此时为0 1 行的全部列的数值修改为200
x[0:2, :] = 200
print(x)
# id()函数显示变量的内存分配地址
z = torch.zeros_like(x)
print('z的内存地址:', id(z))
z[:] = x + x
print('z的内存地址:', id(z))
# 将其他对象转换为python对象
# numpy张量是在cpu上运行 torch是在GPU上运行 进行了加速的作用 二者之间可以进行相互转换
A = x.numpy()
B = torch.tensor(A)
type(A), type(B)
# numpy -> tensor
np_data=np.arange(6).reshape((2,3))
torch_data=torch.from_numpy(np_data)
print(torch_data)
#torch ->numpy
tensor2array=torch_data.numpy()
print(tensor2array)
# 作业1
# 将本节中的条件语句X == Y更改为X < Y或X > Y,然后看看你可以得到什么样的张量。
# 1:True 0: False
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]])
X>Y, X<Y
output: (tensor([[0, 0, 0, 0],
[1, 1, 1, 1],
[1, 1, 1, 1]], dtype=torch.uint8),
tensor([[1, 0, 1, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=torch.uint8))
# 作业2
# 用其他形状(例如三维张量)替换广播机制中按元素操作的两个张量。结果是否与预期相同?
# 轴-0 轴-1 轴-2都会进行赋值
# 广播机制 1.两个数组的后维(最末尾开始算起的维度)的轴长度相等
# 2.其中一方的长度为1
a = torch.arange(6).reshape((3, 1, 2))
b = torch.arange(4).reshape((1, 2, 2))
c = a + b
print(c)
output:tensor([[[0, 2],
[2, 4]],
[[2, 4],
[4, 6]],
[[4, 6],
[6, 8]]])
**