text stringlengths 0 93.6k |
|---|
from torch.autograd import Variable |
from blocks import softmax, ResBlock |
class PredictNetwork(nn.Module): |
def __init__(self, ninp, nout, nslots, dropout, nlayers=1): |
super(PredictNetwork, self).__init__() |
self.ninp = ninp |
self.nout = nout |
self.nslots = nslots |
self.nlayers = nlayers |
self.drop = nn.Dropout(dropout) |
self.projector_pred = nn.Sequential(nn.Dropout(dropout), |
nn.Linear(ninp, ninp), |
nn.Dropout(dropout)) |
if nlayers > 0: |
self.res = ResBlock(ninp*2, nout, dropout, nlayers) |
else: |
self.res = None |
self.ffd = nn.Sequential(nn.Dropout(dropout), |
nn.Linear(ninp * 2, nout), |
nn.BatchNorm1d(nout), |
nn.Tanh() |
) |
def forward(self, input, input_memory): |
input = torch.cat([input, input_memory], dim=1) |
if self.nlayers > 0: |
input = self.res(input) |
output = self.ffd(input) |
return output |
def attention(self, input, memory, gate_time): |
key = self.projector_pred(input) |
# select memory to use |
logits = torch.bmm(memory, key[:, :, None]).squeeze(2) |
logits = logits / math.sqrt(self.ninp) |
attention = softmax(logits, gate_time) |
selected_memory_h = (memory * attention[:, :, None]).sum(dim=1) |
memory = torch.cat([input[:, None, :], memory[:, :-1, :]], dim=1) |
return selected_memory_h, memory, attention |
def init_hidden(self, bsz): |
weight = next(self.parameters()).data |
self.ones = Variable(weight.new(bsz, 1).zero_() + 1.) |
return Variable(weight.new(bsz, self.nslots, self.ninp).zero_()) |
# <FILESEP> |
# gz: 即gzip。通常仅仅能压缩一个文件。与tar结合起来就能够实现先打包,再压缩。 |
# tar: linux系统下的打包工具。仅仅打包。不压缩 |
# tgz:即tar.gz。先用tar打包,然后再用gz压缩得到的文件 |
# zip: 不同于gzip。尽管使用相似的算法,能够打包压缩多个文件。只是分别压缩文件。压缩率低于tar。 |
# rar:打包压缩文件。最初用于DOS,基于window操作系统。 |
import gzip |
import os |
import tarfile |
import zipfile |
import rarfile |
# 根据输入的字符串确定解压方式 |
def decompress_path(file_path, file_name, way): |
if way == 'auto': |
decompress_to = file_path |
# 因为解压后是很多文件,预先建立同名目录 |
elif way is not '': |
if os.path.isdir(way): |
pass |
else: |
os.mkdir(way) |
decompress_to = way + '/' |
else: |
if os.path.isdir(file_name + '_files'): |
pass |
else: |
os.mkdir(file_name + '_files') |
decompress_to = file_name + '_files/' |
return decompress_to |
# gz |
# 因为gz一般仅仅压缩一个文件,全部常与其它打包工具一起工作。比方能够先用tar打包为XXX.tar,然后在压缩为XXX.tar.gz |
# 解压gz,事实上就是读出当中的单一文件 |
def un_gz(file_path, file_name, way): |
"""ungz zip file""" |
f_name = (file_path + '/' + file_name).replace('.gz', '') |
# 获取文件的名称,去掉 |
g_file = gzip.GzipFile(file_path + '/' + file_name) |
# 创建gzip对象 |
open(f_name, 'w+').write(g_file.read()) |
# gzip对象用read()打开后,写入open()建立的文件里。 |
g_file.close() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.