首先是test出错部分代码
def Test(model, dataLoader):
totalNum = 0
rightNum = 0
badlist = []
for circle, input in enumerate(dataLoader, 0):
totalNum += 1
x, label = input
if t.cuda.is_available():
x = x.cuda()
label = label.cuda()
temp = label.detach().cpu().numpy().astype(np.int32)
realLabel = LabeltoStr(temp[0])
#realLabel = LabeltoStr([label[0][0], label[0][1], label[0][2], label[0][3]])
# realLabel = LabeltoStr(int(i) for i in label.squeeze().tolist())
print(label)
print(realLabel)
y1, y2, y3, y4 = model(x)
y1, y2, y3, y4 = y1.topk(1, dim=1)[1].view(1, 1), y2.topk(1, dim=1)[1].view(1, 1), \
y3.topk(1, dim=1)[1].view(1, 1), y4.topk(1, dim=1)[1].view(1, 1)
y = t.cat((y1, y2, y3, y4), dim=1)
# print(x,label,y)
decLabel = LabeltoStr([y[0][0], y[0][1], y[0][2], y[0][3]])
# decLabel = LabeltoStr(int(i) for i in y.squeeze().tolist())
print("real: %s -> %s , %s" % (realLabel, decLabel, str(realLabel == decLabel)))
if realLabel == decLabel:
rightNum += 1
else:
badlist.append([realLabel,decLabel])
for itm in badlist:
print("False: ", itm[0], "=>", itm[1])
print("\n total %s, right %s, wrong %s." % (totalNum, rightNum, totalNum-rightNum))
LabeltoStr函数如下:
def LabeltoStr(Label):
Str = ""
for i in Label:
if i <= 9:
Str += chr(ord('0') + i)
elif i <= 35:
Str += chr(ord('a') + i - 10)
else:
Str += chr(ord('A') + i - 36)
return Str
报错截图
解决方法
把tensor转化成数据再转化成字符串
temp = label.detach().cpu().numpy().astype(np.int32)
realLabel = LabeltoStr(temp[0])
结果预测结果全为false,而且每个label都为test
tensor([[29., 14., 28., 29.]], device='cuda:0')
test
real: test -> hh22 , False
之后是train代码 ,最后准确率为0,测试集准确率也为0