importosfromioimportopenimporttorchclassDictionary(object):def__init__(self):self.word2idx={}self.idx2word=[]defadd_word(self,word):ifwordnotinself.word2idx:self.idx2word.append(word)self.word2idx[word]=len(self.idx2word)-1returnself.word2idx[word]def__len__(self):returnlen(self.idx2word)classCorpus(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'))deftokenize(self,path):"""Tokenizes a text file."""assertos.path.exists(path)# Add words to the dictionarywithopen(path,'r',encoding="utf8")asf:forlineinf:words=line.split()+['<eos>']forwordinwords:self.dictionary.add_word(word)# Tokenize file contentwithopen(path,'r',encoding="utf8")asf:idss=[]forlineinf:words=line.split()+['<eos>']ids=[]forwordinwords:ids.append(self.dictionary.word2idx[word])idss.append(torch.tensor(ids).type(torch.int64))ids=torch.cat(idss)returnids
defbatchify(data,bsz):# Work out how cleanly we can divide the dataset into bsz parts.nbatch=data.size(0)//bsz# Trim off any extra elements that wouldn't cleanly fit (remainders).data=data.narrow(0,0,nbatch*bsz)# Evenly divide the data across the bsz batches.data=data.view(bsz,-1).t().contiguous()returndata
importtorch.nnasnnimporttorch.nn.functionalasFclassLanguageLSTM(nn.Module):"""Container module with an encoder, a recurrent module, and a decoder."""def__init__(self,rnn_type,ntoken,ninp,nhid,nlayers,dropout=0.5,tie_weights=False):super(LanguageLSTM,self).__init__()self.ntoken=ntokenself.drop=nn.Dropout(dropout)self.encoder=nn.Embedding(ntoken,ninp)self.rnn=getattr(nn,rnn_type)(ninp,nhid,nlayers,dropout=dropout)self.decoder=nn.Linear(nhid,ntoken)self.init_weights()self.rnn_type=rnn_typeself.nhid=nhidself.nlayers=nlayersdefinit_weights(self):initrange=0.1nn.init.uniform_(self.encoder.weight,-initrange,initrange)nn.init.zeros_(self.decoder.bias)nn.init.uniform_(self.decoder.weight,-initrange,initrange)defforward(self,input,hidden):emb=self.drop(self.encoder(input))output,hidden=self.rnn(emb,hidden)output=self.drop(output)decoded=self.decoder(output)decoded=decoded.view(-1,self.ntoken)returnF.log_softmax(decoded,dim=1),hiddendefinit_hidden(self,bsz):weight=next(self.parameters())return(weight.new_zeros(self.nlayers,bsz,self.nhid),weight.new_zeros(self.nlayers,bsz,self.nhid))
– <unk> , a year then with the software . It usually was sold for nearly half the day time . For this reason , the Nevermind run surpassed and a new group of canned <unk> . It had benefited from the unhealthy content , which have been leveled on the <unk> 's gates through the design the effects products associated with other birds and tested stewardship of those articles , ranging from an upright system with <unk> <unk> .