1. 在jupyter notebook里写Python代码时,运行如何直接跳行,新增一个代码框
- Ctrl+Enter 运行当前单元格,焦点还在当前单元格
- Shift+Enter 运行当前单元格, 焦点跳到下一个单元格
- Alt+Enter 运行当前单元格, 在下方插入一个新的单元格
2. torch.rand_like报错
import torch
import numpy as np
data = [[1,2],[3,4]]
x_rand = torch.rand_like(x_data)
print(f"Rand Tensor:\n{x_rand}\n")
报错:“RuntimeError: "check_uniform_bounds" not implemented for 'Int'”
纠错:
import torch
import numpy as np
data = [[1,2],[3,4]]
x_rand = torch.rand_like(x_data,dtype=torch.float)
print(f"Rand Tensor:\n{x_rand}\n")
3. Jupyter Notebook 查看帮助文档
- 使用help查看文档:help(torch.cat)
- 使用?查看文档:torch.cat?
- 使用Shift+Tab快捷键查看文档:将光标置于cat上,点击Shift+Tab
4. torch.cat报错
import torch
tensor = torch.ones(4,4)
tensor[:,2] = 0
print(tensor)
t1 = torch.cat(tensor,tensor,tensor,dim=1)
print(t1)
报错:
TypeError: cat() received an invalid combination of arguments - got (Tensor, Tensor, Tensor, dim=int), but expected one of: * (tuple of Tensors tensors, int dim, *, Tensor out) didn't match because some of the keywords were incorrect: dim * (tuple of Tensors tensors, name dim, *, Tensor out) didn't match because some of the keywords were incorrect: dim
纠错1:
import torch
tensor = torch.ones(4,4)
tensor[:,2] = 0
print(tensor)
t1 = torch.cat((tensor,tensor,tensor),dim=1)
print(t1)
纠错2:
import torch
tensor = torch.ones(4,4)
tensor[:,2] = 0
print(tensor)
t1 = torch.cat([tensor,tensor,tensor],dim=1)
print(t1)
5. 函数后面莫忘记加括号
z = y * y * 3
out = z.mean()
out.backward()
6.pytorch张量复制clone()和detach()
https://blog.csdn.net/Answer3664/article/details/104417013/
https://blog.csdn.net/m0_46653437/article/details/112547756/
https://blog.csdn.net/guofei_fly/article/details/104486708/
-
clone
clone()函数可以返回一个完全相同的tensor,新的tensor开辟新的内存,但是仍然留在计算图中。
clone
操作在不共享数据内存的同时支持梯度回溯,所以常用在神经网络中某个单元需要重复使用的场景下。
-
detach
detach()函数可以返回一个完全相同的tensor,新的tensor开辟与旧的tensor共享内存,新的tensor会脱离计算图,不会牵扯梯度计算。此外,一些原地操作(in-place, such as resize_ / resize_as_ / set_ / transpose_) 在两者任意一个执行都会引发错误。detach
操作在共享数据内存的脱离计算图,所以常用在神经网络中仅要利用张量数值,而不需要追踪导数的场景下。
7.
pred = x_tensor * w + b
plt.scatter(x, y)
plt.plot(x, pred)
plt.legend(['y=-3x+4','network'])
报错:
RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.
纠错:
x = np.linspace(0, 10, 100)
y = -3 * x + 4 + np.random.randint(-2, 2, size=100)
pred = x_tensor * w + b
plt.scatter(x, y)
plt.plot(x, pred.data.numpy())
plt.legend(['y=-3x+4', 'Network'])