我正在用 python 开发这个程序,但一直收到这个错误
AttributeError Traceback (most recent call last)
<ipython-input-17-334b6c50bab3> in <module>()
30
31 args = parser.parse_known_args()
---> 32 root = args.data_dir
33 save = args.save_dir
34 learningrate = args.learning_rate
AttributeError: 'tuple' object has no attribute 'data_dir'
我一直在想办法解决这个问题,想知道是否有人可以帮忙?
谢谢你!
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from torch import tensor
from torch import optim
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision import datasets, transforms
import torchvision.models as models
from collections import OrderedDict
import json
import PIL
from PIL import Image
import argparse
import Utilities3
parser = argparse.ArgumentParser(description='train3.py')
parser.add_argument('data_dir', type=str, \
help='Path of the Image Dataset (with train, valid and test folders)')
parser.add_argument('--save_dir', type=str, \
help='Directory to save checkpoints')
parser.add_argument('--arch', type=str, \
help='Models architeture. Default is densenet121. Choose one at https://pytorch.org/docs/master/torchvision/models.html')
parser.add_argument('--learning_rate', type=float, \
help='Learning rate. Default is 0.01')
parser.add_argument('--hidden_units', type=int, \
help='Hidden units. Default is 200')
parser.add_argument('--epochs', type=int, \
help='Number of epochs. Default is 3')
parser.add_argument('--gpu', action='store_true', \
help='Use GPU for inference if available')
parser.add_argument('--save_every', type=int, \
help='Number of steps to save the checkpoint. Default is 50')
args = parser.parse_known_args()
root = args.data_dir
save = args.save_dir
learningrate = args.learning_rate
structure = args.arch
dropout = args.dropout
hidden_layer = args.hidden_units
device = args.gpu
epochs = args.epochs
def main():
training_loader, validation_loader, testing_loader = Utilities3.load_data(root)
model, optimizer, criterion = Utilities3.network_construct(structure, dropout, hidden_layer, learningrate, device)
Utilities3.do_deep_learning(model, optimizer, criterion, epochs, 40, training_loader, device)
Utilities3.save_checkpoint(model, path, structure, hidden_layer, dropout, learningrate)
print("Training is finish")
if __name__== "__main__":
main()
答案1
您确定需要使用吗parse_known_args
?
如果是这样,您必须像这样更改root
和其他变量的分配:
root = args[0].data_dir
如果您选择parse_known_args
错误,只需使用parse_args
,问题就解决了。
您可以阅读argparse
(https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.parse_known_args) 其中写道:
相反,它返回一个包含填充的命名空间和剩余参数字符串列表的两项元组。
因此,您需要访问元组中的第一个项,因为[0]
Python 是从零开始的。
breakpoint()
或者您可以通过插入或(取决于您的 Python 版本)设置断点import pdb;pdb.set_trace()
并检查的值args
。
如果您需要进一步的建议,请告诉我,我会更新答案。