文章目录
Q.1 vscode相对路径问题
文件结构如下:
————model
————A.py
————E(class or func)
————B.py
————F(class or func)
————__init__.py
————utils
————utilss
————C.py
————G(class or func)
————D.py
————H(class or func)
————train.py
运行A.py
调用B.py中的F
from B import F
调用D.py
import sys, os
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import D
注意,下图所示方式容易出错
import sys
sys.path.append("..")
import D
调用D.py中的H时
基于上述,在A.py中写D.H()
调用C.py
import sys, os
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from utils.utills import C
调用C.py中的G时
基于上述,在A.py中写C.G()
运行D.py
导入A.py
A.py没有调用同级目录下的其他文件(如B.py)
在model下A.py同级新建空的__init__文件,再在D.py文件中写from model import A
A.py又调用B.py文件
在model下A.py同级新建空的__init__文件,再在A.py中写:
import sys
sys.path.append("..")
import model.B as B
或from . import B
二选一
然后在D.py文件中写from model import A
不然会报错ModuleNotFoundError: No module named 'B'
A.py又调用C.py文件
在A.py中写from utils.utills import C
,因为此时的绝对路径是D
Q2.数据类型的问题
查看模型的两个输出是否相等
直接判断报错
if (out1==out2):
print("true")
报错RuntimeError: Boolean value of Tensor with more than one value is ambiguous
,可能出现情况有:
- 将含有两个及以上的布尔值的张量用在了 if 判断条件里:
a = torch.tensor([True, False])
if a:
print(1)
改为
if a is not None:
print(1)
需要注意的是,如果 a 只含一个布尔值,则判断不会出现错误:
a = torch.tensor([True])
if a:
print(1)
- 使用交叉熵损失时没有先实例化:
inputs = torch.randn(6, 4)
target = torch.randint(4, (6, ))
loss = nn.CrossEntropyLoss(inputs, target)
应先实例化再计算损失:
criterion = nn.CrossEntropyLoss()
loss = criterion(inputs, target)
- 对含有两个及以上的布尔值张量执行了 or、and、not 这样的操作:
a = torch.tensor([True, False])
b = torch.tensor([False, True])
""" 以下三种操作都会报错 """
print(a or b)
print(a and b)
print(not a)
需要注意的是,如果 a 和 b 都只含一个布尔值,则不会出现错误:
a = torch.tensor([True])
b = torch.tensor([False])
print(a or b)
# tensor([True])
print(a and b)
# tensor([False])
print(not a)
# False
- Pytorch 跑模型报错
if labels:
loss = self.loss_fn(out, labels)
return out, loss
else:
return out
if labels 那一行报错。这一行代码想判断labels是否为空。
因为labels是torch.tensor类型,不能直接转换成bool值。需要改成:
if labels is not None:
if (labels):
查看类型
print(type(out1))
,输出<class 'list'>
。list不能直接查看是否相等
使用eq()
import operator
print(operator.eq(out1,out2))
还是报错RuntimeError: Boolean value of Tensor with more than one value is ambiguous
print(out1.eq(out2))
报错AttributeError: 'list' object has no attribute 'eq'
使用list转换成tensor
tensor=torch.tensor(out1)
报错ValueError: only one element tensors can be converted to Python scalars
,可能出现的情况:
因为要转换的list里面的元素包含多维的tensor,一般list 转 torch.tensor只需要tensor=torch.tensor(out1)
,但是要转换的list里面的元素包含多维的tensor,应该使用val= torch.tensor([item.cpu().detach().numpy() for item in out1]).cuda()
这是由于 gpu上的 tensor 不能直接转为 numpy; 须要先在 cpu 上完成操做,再回到 gpu 上。
运行后继续报错ValueError: expected sequence of length 9 at dim 2 (got 2)
说明长度一不一样,一个有9个元素,另一个只有2个。
使用list转换成numpy
ndarray1 = np.array(out1)
报错RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.
但是out1是list,怎么能用tensor.detach().numpy()
呢?
使用debug查询out的具体值
发现out是由多个高维tensor组成的list
编写对比程序
for i in range(len(out)):
if out1[i]==out2[i]:
print("true")
报错RuntimeError: Boolean value of Tensor with more than one value is ambiguous
修改后
for i in range(len(out)):
if out[i].equal(outs[i]):
print("true")
成功!