Python,argparse命令行参数断言错误

如何解决Python,argparse命令行参数断言错误

我使用 argparse 的命令行参数返回 AssertionError。我有两个脚本和一个存储三个数据文件的目录。

脚本:

  • main.py 负责加载数据
  • data.py 对语言数据进行预处理

数据:

  • 三个令牌存储在 C:\Users\archive 路径中

data.py 脚本

**#data.py**
import os
from io import open
import torch

class Dictionary(object):
    def __init__(self):
        self.word2idx = {}
        self.idx2word = []

    def add_word(self,word):
        if word not in self.word2idx:
            self.idx2word.append(word)
            self.word2idx[word] = len(self.idx2word) - 1
        return self.word2idx[word]

    def __len__(self):
        return len(self.idx2word)

class Corpus(object):
    def __init__(self,path):
        self.dictionary = Dictionary()
        self.train = self.tokenize(os.path.join(path,'train.txt'))
        self.valid = self.tokenize(os.path.join(path,'valid.txt'))
        self.test = self.tokenize(os.path.join(path,'test.txt'))

    def tokenize(self,path):
        """Tokenizes a text file."""
        assert os.path.exists(path)
        # Add words to the dictionary
        with open(path,'r',encoding="utf8") as f:
            for line in f:
                words = line.split() + ['<eos>']
                for word in words:
                    self.dictionary.add_word(word)

        # Tokenize file content
        with open(path,encoding="utf8") as f:
            idss = []
            for line in f:
                words = line.split() + ['<eos>']
                ids = []
                for word in words:
                    ids.append(self.dictionary.word2idx[word])
                idss.append(torch.tensor(ids).type(torch.int64))
            ids = torch.cat(idss)

        return ids

ma​​in.py 脚本

**#main.py**
import argparse
import time
import math
import os
import torch
import torch.nn as nn
import torch.onnx

import data

parser = argparse.ArgumentParser(description='PyTorch Wikitext-2 RNN/LSTM/GRU/Transformer Language Model')
parser.add_argument('--data',type=str,default='./data/wikitext-2',help='location of the data corpus')
parser.add_argument('--model',default='LSTM',help='type of recurrent net (RNN_TANH,RNN_RELU,LSTM,GRU,Transformer)')
parser.add_argument('--emsize',type=int,default=200,help='size of word embeddings')
parser.add_argument('--nhid',help='number of hidden units per layer')
parser.add_argument('--nlayers',default=2,help='number of layers')
parser.add_argument('--lr',type=float,default=20,help='initial learning rate')
parser.add_argument('--clip',default=0.25,help='gradient clipping')
parser.add_argument('--epochs',default=40,help='upper epoch limit')
parser.add_argument('--batch_size',Metavar='N',help='batch size')
parser.add_argument('--bptt',default=35,help='sequence length')
parser.add_argument('--dropout',default=0.2,help='dropout applied to layers (0 = no dropout)')
parser.add_argument('--tied',action='store_true',help='tie the word embedding and softmax weights')
parser.add_argument('--seed',default=1111,help='random seed')
parser.add_argument('--cuda',help='use CUDA')
parser.add_argument('--log-interval',help='report interval')
parser.add_argument('--save',default='model.pt',help='path to save the final model')
parser.add_argument('--onnx-export',default='',help='path to export the final model in onnx format')
parser.add_argument('--nhead',help='the number of heads in the encoder/decoder of the transformer model')
parser.add_argument('--dry-run',help='verify the code and the model')

args = parser.parse_args()

# Set the random seed manually for reproducibility.
torch.manual_seed(args.seed)
if torch.cuda.is_available():
    if not args.cuda:
        print("WARNING: You have a CUDA device,so you should probably run with --cuda")

device = torch.device("cuda" if args.cuda else "cpu")

###############################################################################
# Load data
###############################################################################

corpus = data.Corpus(args.data)

当我在终端中运行 main.py 时:

$ python main.py 

断言错误显示如下:

File "main.py",line 67,in <module>
    corpus = data.Corpus(args.data)
File "C:\Users\archive\data.py",line 22,in __init__
    self.train = self.tokenize(os.path.join(path,'train.txt'))
File "C:\Users\archive\data.py",line 28,in tokenize
    assert os.path.exists(path)
AssertionError

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?