code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import matplotlib
matplotlib.use('Agg')
import argparse
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
parser = argparse.ArgumentParser()
parser.add_argument('-in', '--input', help="Full path to the input csv file")
parser.add_argument('-outdir', '--output', help="Full path to the output directory")
parser.add_argument('-sn', '--fitres', help="Full path to the SNANA fitres file")
# Execute the parse_args() method
args = parser.parse_args()
input_file = args.input
output_dir = args.output
fitres = args.fitres
## Load the spec-observed SNe
specSN = pd.read_csv(input_file)
specSN['snid'] = specSN['snid'].astype(int)
specSN['redshift'] = specSN['redshift'].astype(float)
f = open(output_dir+('/liveSNmetrics.txt'), 'w')
def round_sigfigs(num, sig_figs):
if num != 0:
return np.round(num, -int(np.floor(np.log10(abs(num))) - (sig_figs - 1)))
else:
return 0 # Can't take the log of 0
def plotnz(data, outdir):
nia, bins, patch = plt.hist(data['redshift'][data['sntype']==1], bins=np.arange(0,1.3,0.05), histtype='step', label='SNe Ia: '+str(round_sigfigs(len(data['redshift'][data['sntype']==1]),2)), lw=1.5)
#plt.hist(data['redshift'][np.isin(data['sntype'],np.array([21,25]))], bins=np.arange(0,1.3,0.05), histtype='step', label='Type II SNe: '+str(round_sigfigs(len(data['redshift'][np.isin(data['sntype'],np.array([21,25]))]),2)), lw=1.5)
ncc, bins, patch = plt.hist(data['redshift'][np.isin(data['sntype'],np.array([20,23,32,33,35]))], bins=np.arange(0,1.3,0.05), histtype='step', label='CCSNe: '+str(round_sigfigs(len(data['redshift'][np.isin(data['sntype'],np.array([20,21,25,23,32,33,35]))]),2)), lw=1.5)
nslsne, bins, patch =plt.hist(data['redshift'][np.isin(data['sntype'],np.array([70]))], bins=np.arange(0,1.3,0.05), histtype='step', label='SLSNe: '+str(round_sigfigs(len(data['redshift'][np.isin(data['sntype'],np.array([70]))]),2)), lw=1.5)
ncart, bins, patch =plt.hist(data['redshift'][np.isin(data['sntype'],np.array([50]))], bins=np.arange(0,1.3,0.05), histtype='step', label='CaRT: '+str(round_sigfigs(len(data['redshift'][np.isin(data['sntype'],np.array([50]))]),2)), lw=1.5)
nbg, bins, patch =plt.hist(data['redshift'][np.isin(data['sntype'],np.array([11,12]))], bins=np.arange(0,1.3,0.05), histtype='step', label='SN 91bg/Iax: '+str(round_sigfigs(len(data['redshift'][np.isin(data['sntype'],np.array([11,12]))]),2)), lw=1.5)
#plt.hist(data['redshift'][np.isin(data['sntype'],np.array([60]))], bins=np.arange(0,1.3,0.05), histtype='step', label='KNe', lw=1.5)
ntde, bins, patch =plt.hist(data['redshift'][np.isin(data['sntype'],np.array([80]))], bins=np.arange(0,1.3,0.05), histtype='step', label='TDEs: '+str(round_sigfigs(len(data['redshift'][np.isin(data['sntype'],np.array([80]))]),2)), lw=1.5)
np.savetxt(outdir+'/nzHistogramLiveSNe.csv', np.column_stack((0.5*(bins[1:]+bins[:-1]),nia,ncc,nslsne,ncart,nbg,ntde)), delimiter=',', header='zbin,n_ia,n_cc,n_slsne,n_cart,n_bgiax,ntde', fmt='%.3f')
# plt.hist(data['redshift'][np.isin(data['sntype'],np.array([21,25]))], bins=np.arange(0,1.3,0.05), histtype='step', label=index2type[i])
plt.xlim(-0.01,1.2)
#plt.ylim(3,3e4)
plt.xlabel('Redshift')
plt.ylabel('Number of SNe in bin')
plt.yscale('log')
#plt.legend(loc='lower left',mode='expand',framealpha=0.95, fontsize='small', bbox_to_anchor=(0,1.02,1,0.2), ncol=1)
plt.legend(loc='upper right',framealpha=0.95, fontsize='small',ncol=1)
plt.savefig(str(outdir)+'/numberRedshiftBinsLive.pdf', dpi=300, bbox_inches='tight')
print('Total number of unique SNe: ', len(np.unique(data['snid'])))
f.write('Total number of SNe: '+str(len(np.unique(data['snid'])))+'\n')
f.write('Total number of SN Ia: '+str(len(np.unique(data['snid'][data['sntype']==1])))+'\n')
f.write('Total number of CCSNe: '+str(len(np.unique(data['snid'][np.isin(data['sntype'],np.array([20,23,32,33,35]))])))+'\n')
f.write('Total number of SLSNe: '+str(len(np.unique(data['snid'][np.isin(data['sntype'],np.array([70]))])))+'\n')
f.write('Total number of CaRT: '+str(len(np.unique(data['snid'][np.isin(data['sntype'],np.array([50]))])))+'\n')
f.write('Total number of 91bg/Iax: '+str(len(np.unique(data['snid'][np.isin(data['sntype'],np.array([11,12]))])))+'\n')
f.write('Total number of TDE: '+str(len(np.unique(data['snid'][np.isin(data['sntype'],np.array([80]))])))+'\n')
print(specSN.dtypes)
plotnz(specSN, output_dir)
f.close()
| [
"numpy.unique",
"argparse.ArgumentParser",
"pandas.read_csv",
"matplotlib.use",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.arange",
"numpy.column_stack",
"numpy.array",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.yscale",
"matplotlib.pyplot.legend"
] | [((18, 39), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (32, 39), False, 'import matplotlib\n'), ((138, 163), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (161, 163), False, 'import argparse\n'), ((582, 605), 'pandas.read_csv', 'pd.read_csv', (['input_file'], {}), '(input_file)\n', (593, 605), True, 'import pandas as pd\n'), ((3168, 3188), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-0.01)', '(1.2)'], {}), '(-0.01, 1.2)\n', (3176, 3188), True, 'import matplotlib.pyplot as plt\n'), ((3213, 3235), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Redshift"""'], {}), "('Redshift')\n", (3223, 3235), True, 'import matplotlib.pyplot as plt\n'), ((3240, 3274), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of SNe in bin"""'], {}), "('Number of SNe in bin')\n", (3250, 3274), True, 'import matplotlib.pyplot as plt\n'), ((3279, 3296), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (3289, 3296), True, 'import matplotlib.pyplot as plt\n'), ((3422, 3494), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""', 'framealpha': '(0.95)', 'fontsize': '"""small"""', 'ncol': '(1)'}), "(loc='upper right', framealpha=0.95, fontsize='small', ncol=1)\n", (3432, 3494), True, 'import matplotlib.pyplot as plt\n'), ((2866, 2953), 'numpy.column_stack', 'np.column_stack', (['(0.5 * (bins[1:] + bins[:-1]), nia, ncc, nslsne, ncart, nbg, ntde)'], {}), '((0.5 * (bins[1:] + bins[:-1]), nia, ncc, nslsne, ncart, nbg,\n ntde))\n', (2881, 2953), True, 'import numpy as np\n'), ((1049, 1072), 'numpy.arange', 'np.arange', (['(0)', '(1.3)', '(0.05)'], {}), '(0, 1.3, 0.05)\n', (1058, 1072), True, 'import numpy as np\n'), ((1523, 1546), 'numpy.arange', 'np.arange', (['(0)', '(1.3)', '(0.05)'], {}), '(0, 1.3, 0.05)\n', (1532, 1546), True, 'import numpy as np\n'), ((1787, 1810), 'numpy.arange', 'np.arange', (['(0)', '(1.3)', '(0.05)'], {}), '(0, 1.3, 0.05)\n', (1796, 1810), True, 'import numpy as np\n'), ((2032, 2055), 'numpy.arange', 'np.arange', (['(0)', '(1.3)', '(0.05)'], {}), '(0, 1.3, 0.05)\n', (2041, 2055), True, 'import numpy as np\n'), ((2277, 2300), 'numpy.arange', 'np.arange', (['(0)', '(1.3)', '(0.05)'], {}), '(0, 1.3, 0.05)\n', (2286, 2300), True, 'import numpy as np\n'), ((2668, 2691), 'numpy.arange', 'np.arange', (['(0)', '(1.3)', '(0.05)'], {}), '(0, 1.3, 0.05)\n', (2677, 2691), True, 'import numpy as np\n'), ((3631, 3654), 'numpy.unique', 'np.unique', (["data['snid']"], {}), "(data['snid'])\n", (3640, 3654), True, 'import numpy as np\n'), ((1488, 1518), 'numpy.array', 'np.array', (['[20, 23, 32, 33, 35]'], {}), '([20, 23, 32, 33, 35])\n', (1496, 1518), True, 'import numpy as np\n'), ((1764, 1778), 'numpy.array', 'np.array', (['[70]'], {}), '([70])\n', (1772, 1778), True, 'import numpy as np\n'), ((2009, 2023), 'numpy.array', 'np.array', (['[50]'], {}), '([50])\n', (2017, 2023), True, 'import numpy as np\n'), ((2251, 2269), 'numpy.array', 'np.array', (['[11, 12]'], {}), '([11, 12])\n', (2259, 2269), True, 'import numpy as np\n'), ((2645, 2659), 'numpy.array', 'np.array', (['[80]'], {}), '([80])\n', (2653, 2659), True, 'import numpy as np\n'), ((3701, 3724), 'numpy.unique', 'np.unique', (["data['snid']"], {}), "(data['snid'])\n", (3710, 3724), True, 'import numpy as np\n'), ((3779, 3823), 'numpy.unique', 'np.unique', (["data['snid'][data['sntype'] == 1]"], {}), "(data['snid'][data['sntype'] == 1])\n", (3788, 3823), True, 'import numpy as np\n'), ((1641, 1679), 'numpy.array', 'np.array', (['[20, 21, 25, 23, 32, 33, 35]'], {}), '([20, 21, 25, 23, 32, 33, 35])\n', (1649, 1679), True, 'import numpy as np\n'), ((1905, 1919), 'numpy.array', 'np.array', (['[70]'], {}), '([70])\n', (1913, 1919), True, 'import numpy as np\n'), ((2149, 2163), 'numpy.array', 'np.array', (['[50]'], {}), '([50])\n', (2157, 2163), True, 'import numpy as np\n'), ((2401, 2419), 'numpy.array', 'np.array', (['[11, 12]'], {}), '([11, 12])\n', (2409, 2419), True, 'import numpy as np\n'), ((2785, 2799), 'numpy.array', 'np.array', (['[80]'], {}), '([80])\n', (2793, 2799), True, 'import numpy as np\n'), ((3922, 3952), 'numpy.array', 'np.array', (['[20, 23, 32, 33, 35]'], {}), '([20, 23, 32, 33, 35])\n', (3930, 3952), True, 'import numpy as np\n'), ((4052, 4066), 'numpy.array', 'np.array', (['[70]'], {}), '([70])\n', (4060, 4066), True, 'import numpy as np\n'), ((4169, 4183), 'numpy.array', 'np.array', (['[50]'], {}), '([50])\n', (4177, 4183), True, 'import numpy as np\n'), ((4290, 4308), 'numpy.array', 'np.array', (['[11, 12]'], {}), '([11, 12])\n', (4298, 4308), True, 'import numpy as np\n'), ((4409, 4423), 'numpy.array', 'np.array', (['[80]'], {}), '([80])\n', (4417, 4423), True, 'import numpy as np\n')] |
import torch
import torch.nn as nn
from torch.utils.data import Dataset
from torch.autograd import Variable
import os
import cv2
import numpy as np
from torchvision import datasets, models, transforms
label_len = 36
# vocab="<,.+:-?$ <aAàÀảẢãÃáÁạẠăĂằẰẳẲẵẴắẮặẶâÂầẦẩẨẫẪấẤậẬbBcCdDđĐeEèÈẻẺẽẼéÉẹẸêÊềỀểỂễỄếẾệỆfFgGhHiIìÌỉỈĩĨíÍịỊjJkKlLmMnNoOòÒỏỎõÕóÓọỌôÔồỒổỔỗỖốỐộỘơƠờỜởỞỡỠớỚợỢpPqQrRsStTuUùÙủỦũŨúÚụỤưƯừỪửỬữỮứỨựỰvVwWxXyYỳỲỷỶỹỸýÝỵỴzZ0123456789!>"
vocab='<aAàÀảẢãÃáÁạẠăĂằẰẳẲẵẴắẮặẶâÂầẦẩẨẫẪấẤậẬbBcCdDđĐeEèÈẻẺẽẼéÉẹẸêÊềỀểỂễỄếẾệỆfFgGhHiIìÌỉỈĩĨíÍịỊjJkKlLmMnNoOòÒỏỎõÕóÓọỌôÔồỒổỔỗỖốỐộỘơƠờỜởỞỡỠớỚợỢpPqQrRsStTuUùÙủỦũŨúÚụỤưƯừỪửỬữỮứỨựỰvVwWxXyYỳỲỷỶỹỸýÝỵỴzZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ >'
# start symbol <
# end symbol >
char2token = {"PAD":0}
token2char = {0:"PAD"}
for i, c in enumerate(vocab):
char2token[c] = i+1
token2char[i+1] = c
def illegal(label):
if len(label) > label_len-1:
return True
for l in label:
if l not in vocab[1:-1]:
return True
return False
class ListDataset(Dataset):
def __init__(self, fname):
self.lines = []
# if not isinstance(fname, list):
# fname = [fname]
# for f in fname:
lines = open('train_line_annotation.txt','r',encoding='utf8').readlines()
self.lines += [i for i in lines if not illegal(i.strip('\n').split('\t')[1])]
def __len__(self):
return len(self.lines)
def __getitem__(self, index):
'''
line: image path\tlabel
'''
line = self.lines[index]
img_path, label_y_str = line.strip('\n').split('\t')
img = cv2.imread(img_path) / 255.
img=cv2.resize(img,(500,40))
# cv2.imshow('s',img)
# cv2.waitKey(0)
# Channels-first
img = np.transpose(img, (2, 0, 1))
# As pytorch tensor
img = torch.from_numpy(img).float()
label = np.zeros(label_len, dtype=int)
for i, c in enumerate('<'+label_y_str):
label[i] = char2token[c]
label = torch.from_numpy(label)
label_y = np.zeros(label_len, dtype=int)
for i, c in enumerate(label_y_str+'>'):
label_y[i] = char2token[c]
label_y = torch.from_numpy(label_y)
return img, label_y, label
def subsequent_mask(size):
"Mask out subsequent positions."
attn_shape = (1, size, size)
subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')
return torch.from_numpy(subsequent_mask) == 0
def make_std_mask(tgt, pad):
"Create a mask to hide padding and future words."
tgt_mask = (tgt != pad).unsqueeze(-2)
tgt_mask = tgt_mask & Variable(
subsequent_mask(tgt.size(-1)).type_as(tgt_mask.data))
return tgt_mask
class Batch:
"Object for holding a batch of data with mask during training."
def __init__(self, imgs, trg_y, trg, pad=0):
self.imgs = Variable(imgs.cuda(), requires_grad=False)
self.src_mask = Variable(torch.from_numpy(np.ones([imgs.size(0), 1, 96], dtype=np.bool)).cuda())
if trg is not None:
self.trg = Variable(trg.cuda(), requires_grad=False)
self.trg_y = Variable(trg_y.cuda(), requires_grad=False)
self.trg_mask = \
self.make_std_mask(self.trg, pad)
self.ntokens = (self.trg_y != pad).data.sum()
@staticmethod
def make_std_mask(tgt, pad):
"Create a mask to hide padding and future words."
tgt_mask = (tgt != pad).unsqueeze(-2)
tgt_mask = tgt_mask & Variable(
subsequent_mask(tgt.size(-1)).type_as(tgt_mask.data))
return Variable(tgt_mask.cuda(), requires_grad=False)
class FeatureExtractor(nn.Module):
def __init__(self, submodule, name):
super(FeatureExtractor, self).__init__()
self.submodule = submodule
self.name = name
def forward(self, x):
for name, module in self.submodule._modules.items():
x = module(x)
if name is self.name:
b = x.size(0)
c = x.size(1)
return x.view(b, c, -1).permute(0, 2, 1)
return None
if __name__=='__main__':
listdataset = ListDataset('your-lines')
dataloader = torch.utils.data.DataLoader(listdataset, batch_size=2, shuffle=False, num_workers=0)
for epoch in range(1):
for batch_i, (imgs, labels_y, labels) in enumerate(dataloader):
continue
| [
"numpy.ones",
"torch.from_numpy",
"numpy.zeros",
"torch.utils.data.DataLoader",
"cv2.resize",
"numpy.transpose",
"cv2.imread"
] | [((4235, 4323), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['listdataset'], {'batch_size': '(2)', 'shuffle': '(False)', 'num_workers': '(0)'}), '(listdataset, batch_size=2, shuffle=False,\n num_workers=0)\n', (4262, 4323), False, 'import torch\n'), ((1653, 1679), 'cv2.resize', 'cv2.resize', (['img', '(500, 40)'], {}), '(img, (500, 40))\n', (1663, 1679), False, 'import cv2\n'), ((1772, 1800), 'numpy.transpose', 'np.transpose', (['img', '(2, 0, 1)'], {}), '(img, (2, 0, 1))\n', (1784, 1800), True, 'import numpy as np\n'), ((1889, 1919), 'numpy.zeros', 'np.zeros', (['label_len'], {'dtype': 'int'}), '(label_len, dtype=int)\n', (1897, 1919), True, 'import numpy as np\n'), ((2021, 2044), 'torch.from_numpy', 'torch.from_numpy', (['label'], {}), '(label)\n', (2037, 2044), False, 'import torch\n'), ((2064, 2094), 'numpy.zeros', 'np.zeros', (['label_len'], {'dtype': 'int'}), '(label_len, dtype=int)\n', (2072, 2094), True, 'import numpy as np\n'), ((2200, 2225), 'torch.from_numpy', 'torch.from_numpy', (['label_y'], {}), '(label_y)\n', (2216, 2225), False, 'import torch\n'), ((2452, 2485), 'torch.from_numpy', 'torch.from_numpy', (['subsequent_mask'], {}), '(subsequent_mask)\n', (2468, 2485), False, 'import torch\n'), ((1613, 1633), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (1623, 1633), False, 'import cv2\n'), ((1843, 1864), 'torch.from_numpy', 'torch.from_numpy', (['img'], {}), '(img)\n', (1859, 1864), False, 'import torch\n'), ((2399, 2418), 'numpy.ones', 'np.ones', (['attn_shape'], {}), '(attn_shape)\n', (2406, 2418), True, 'import numpy as np\n')] |
#!/usr/bin/env python
import pandas as pd
import numpy as np
from scipy.sparse import csc_matrix
import os, sys
import functools as fct
# import from parent directory
nb_dir = os.path.split(os.getcwd())[0]
if nb_dir not in sys.path:
print('Appending directory as path: {}'.format(nb_dir))
sys.path.append(nb_dir)
import pmRecUtils as rutils
import logUtils as lutils
def partialcase_to_fm_format(caseid, partialcase, cid_list, \
activity_list, negative_samples, seed, \
normalize, pred_id):
x_datalist = list()
x_row_inds = list()
x_col_inds = list()
x_shape = np.zeros(shape=(2,))
y_datalist = list()
pred_id_list = list()
if partialcase.shape[0] <= 2:
# not enough events to make a step
return np.asarray(x_datalist), np.asarray(x_row_inds), \
np.asarray(x_col_inds), np.asarray(x_shape), \
np.asarray(y_datalist), np.asarray(pred_id_list)
# there should negative samples + 1 rows
if negative_samples >= 0 and \
negative_samples < activity_list.shape[0]:
num_of_rows = negative_samples + 1
else:
num_of_rows = activity_list.shape[0]
x_shape[0] = num_of_rows
x_shape[1] = cid_list.shape[0] + activity_list.shape[0] * 2
x_shape = x_shape.astype(np.int)
# make into 2-steps
subpartialcase = partialcase[:-1]
to_predict = partialcase[-1]
possible = activity_list
# pick negative samples
if negative_samples > -1:
rand_negatives = filter(lambda s: s != to_predict, possible)
# need to check if negative_samples is larger than len(rand_negatives)
rand_negatives = list(rand_negatives)
random_sz = negative_samples
if negative_samples > len(rand_negatives):
# use the size of rand_negatives if this is bigger
random_sz = len(rand_negatives)
rand_negatives = np.random.choice(list(rand_negatives), \
size=random_sz, \
replace=False)
samples = np.append(rand_negatives, [to_predict,])
else:
samples = filter(lambda s: s != to_predict, possible)
samples = np.append(list(samples), [to_predict,])
# create block for cid
cid_repeat = np.asarray([caseid,]).repeat(len(samples))
cid_datalist, cid_row_inds, cid_col_inds, cid_shape = \
rutils.single_to_fm_format(cid_repeat, cid_list)
# create block for taken acts
taken_repeat = np.asarray([subpartialcase,]).repeat(len(samples), axis=0)
taken_datalist, taken_row_inds, taken_col_inds, taken_shape = \
rutils.multiple_to_fm_format(taken_repeat, activity_list)
# create block for samples
# print('Samples: {}'.format(samples))
next_datalist, next_row_inds, next_col_inds, next_shape = \
rutils.single_to_fm_format(samples, activity_list)
# shift taken columns by |cid_list|
taken_col_inds = taken_col_inds + cid_list.shape[0]
# shift next columns by |cid_list| + |activity_list|
next_col_inds = next_col_inds + cid_list.shape[0] + activity_list.shape[0]
x_datalist = np.concatenate((cid_datalist, taken_datalist, next_datalist))
x_row_inds = np.concatenate((cid_row_inds, taken_row_inds, next_row_inds))
x_col_inds = np.concatenate((cid_col_inds, taken_col_inds, next_col_inds))
x_row_inds = x_row_inds.astype(np.int)
x_col_inds = x_col_inds.astype(np.int)
y_datalist = np.asarray([np.int(step) for step in samples == to_predict], \
dtype=np.int)
pred_id_list = np.ones(len(y_datalist)) * pred_id
return x_datalist, x_row_inds, x_col_inds, x_shape, \
y_datalist, pred_id_list
def case_to_fm_format(caseid, case, cid_list, activity_list, \
minpartialsz, negative_samples, seed, \
normalize, pred_id):
# create objects to be returned
x_datalist = list()
x_row_inds = list()
x_col_inds = list()
x_shape = np.zeros(shape=(2,), dtype=np.int)
y_datalist = list()
pred_id_list = list()
# need to have minpartialsz plus one to predict
if case.shape[0] <= minpartialsz:
return np.asarray(x_datalist), np.asarray(x_row_inds), \
np.asarray(x_col_inds), x_shape, \
np.asarray(y_datalist), np.asarray(pred_id_list)
for ind in range(minpartialsz, case.shape[0] + 1):
partialcase = case[:ind]
# print('building for partial case: {}'.format(partialcase))
x_datalist_i, x_row_inds_i, x_col_inds_i, x_shape_i, \
y_datalist_i, pred_id_list_i = \
partialcase_to_fm_format(caseid, partialcase, \
cid_list, activity_list, \
negative_samples, seed, \
normalize, pred_id)
# shift by rows if necessary
if len(x_datalist) == 0:
x_datalist = x_datalist_i
x_row_inds = x_row_inds_i
x_col_inds = x_col_inds_i
x_shape = x_shape_i
y_datalist = y_datalist_i
pred_id_list = pred_id_list_i
else:
x_row_inds_i += x_shape[0]
x_datalist = np.concatenate((x_datalist, x_datalist_i))
x_row_inds = np.concatenate((x_row_inds, x_row_inds_i))
x_col_inds = np.concatenate((x_col_inds, x_col_inds_i))
x_shape = np.asarray((x_shape[0] + x_shape_i[0], x_shape[1]))
y_datalist = np.concatenate((y_datalist, y_datalist_i))
pred_id_list = np.concatenate((pred_id_list, pred_id_list_i))
# update pred_id
if len(pred_id_list) > 0:
pred_id = pred_id_list[-1] + 1
return x_datalist, x_row_inds, x_col_inds, x_shape, \
y_datalist, pred_id_list
def log_to_fm_format(log, cid_list, activity_list, \
minpartialsz=3, negative_samples=3, seed=123, \
normalize=True, pred_id=0):
# create objects to be returned
x_datalist = list()
x_row_inds = list()
x_col_inds = list()
x_shape = np.zeros(2, dtype=np.int)
y_datalist = list()
pred_id_list = list()
log_caseids = log['caseId'].unique()
log_caseids.sort()
np.random.seed(seed=seed)
for cid in log_caseids:
# print('Building for case: {}'.format(cid))
case = log[(log['caseId']==cid)]['activity'].values
x_datalist_i, x_row_inds_i, x_col_inds_i, x_shape_i, \
y_datalist_i, pred_id_list_i = \
case_to_fm_format(cid, case, cid_list, activity_list, \
minpartialsz, negative_samples, \
seed, normalize, pred_id)
if len(x_datalist) == 0:
x_datalist = x_datalist_i
x_row_inds = x_row_inds_i
x_col_inds = x_col_inds_i
x_shape = x_shape_i
y_datalist = y_datalist_i
pred_id_list = pred_id_list_i
else:
# shift by rows
x_row_inds_i += x_shape[0]
x_datalist = np.concatenate((x_datalist, x_datalist_i))
x_row_inds = np.concatenate((x_row_inds, x_row_inds_i))
x_col_inds = np.concatenate((x_col_inds, x_col_inds_i))
x_shape = np.asarray((x_shape[0] + x_shape_i[0], x_shape[1]))
y_datalist = np.concatenate((y_datalist, y_datalist_i))
pred_id_list = np.concatenate((pred_id_list, pred_id_list_i))
# update pred_id
if len(pred_id_list) > 0:
pred_id = pred_id_list[-1] + 1
return x_datalist, x_row_inds, x_col_inds, x_shape, \
y_datalist, pred_id_list
| [
"pmRecUtils.single_to_fm_format",
"numpy.asarray",
"os.getcwd",
"numpy.append",
"numpy.zeros",
"pmRecUtils.multiple_to_fm_format",
"numpy.int",
"numpy.random.seed",
"numpy.concatenate",
"sys.path.append"
] | [((298, 321), 'sys.path.append', 'sys.path.append', (['nb_dir'], {}), '(nb_dir)\n', (313, 321), False, 'import os, sys\n'), ((647, 667), 'numpy.zeros', 'np.zeros', ([], {'shape': '(2,)'}), '(shape=(2,))\n', (655, 667), True, 'import numpy as np\n'), ((2448, 2496), 'pmRecUtils.single_to_fm_format', 'rutils.single_to_fm_format', (['cid_repeat', 'cid_list'], {}), '(cid_repeat, cid_list)\n', (2474, 2496), True, 'import pmRecUtils as rutils\n'), ((2690, 2747), 'pmRecUtils.multiple_to_fm_format', 'rutils.multiple_to_fm_format', (['taken_repeat', 'activity_list'], {}), '(taken_repeat, activity_list)\n', (2718, 2747), True, 'import pmRecUtils as rutils\n'), ((2898, 2948), 'pmRecUtils.single_to_fm_format', 'rutils.single_to_fm_format', (['samples', 'activity_list'], {}), '(samples, activity_list)\n', (2924, 2948), True, 'import pmRecUtils as rutils\n'), ((3201, 3262), 'numpy.concatenate', 'np.concatenate', (['(cid_datalist, taken_datalist, next_datalist)'], {}), '((cid_datalist, taken_datalist, next_datalist))\n', (3215, 3262), True, 'import numpy as np\n'), ((3280, 3341), 'numpy.concatenate', 'np.concatenate', (['(cid_row_inds, taken_row_inds, next_row_inds)'], {}), '((cid_row_inds, taken_row_inds, next_row_inds))\n', (3294, 3341), True, 'import numpy as np\n'), ((3359, 3420), 'numpy.concatenate', 'np.concatenate', (['(cid_col_inds, taken_col_inds, next_col_inds)'], {}), '((cid_col_inds, taken_col_inds, next_col_inds))\n', (3373, 3420), True, 'import numpy as np\n'), ((4071, 4105), 'numpy.zeros', 'np.zeros', ([], {'shape': '(2,)', 'dtype': 'np.int'}), '(shape=(2,), dtype=np.int)\n', (4079, 4105), True, 'import numpy as np\n'), ((6224, 6249), 'numpy.zeros', 'np.zeros', (['(2)'], {'dtype': 'np.int'}), '(2, dtype=np.int)\n', (6232, 6249), True, 'import numpy as np\n'), ((6371, 6396), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'seed'}), '(seed=seed)\n', (6385, 6396), True, 'import numpy as np\n'), ((191, 202), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (200, 202), False, 'import os, sys\n'), ((2117, 2156), 'numpy.append', 'np.append', (['rand_negatives', '[to_predict]'], {}), '(rand_negatives, [to_predict])\n', (2126, 2156), True, 'import numpy as np\n'), ((813, 835), 'numpy.asarray', 'np.asarray', (['x_datalist'], {}), '(x_datalist)\n', (823, 835), True, 'import numpy as np\n'), ((837, 859), 'numpy.asarray', 'np.asarray', (['x_row_inds'], {}), '(x_row_inds)\n', (847, 859), True, 'import numpy as np\n'), ((879, 901), 'numpy.asarray', 'np.asarray', (['x_col_inds'], {}), '(x_col_inds)\n', (889, 901), True, 'import numpy as np\n'), ((903, 922), 'numpy.asarray', 'np.asarray', (['x_shape'], {}), '(x_shape)\n', (913, 922), True, 'import numpy as np\n'), ((942, 964), 'numpy.asarray', 'np.asarray', (['y_datalist'], {}), '(y_datalist)\n', (952, 964), True, 'import numpy as np\n'), ((966, 990), 'numpy.asarray', 'np.asarray', (['pred_id_list'], {}), '(pred_id_list)\n', (976, 990), True, 'import numpy as np\n'), ((2333, 2353), 'numpy.asarray', 'np.asarray', (['[caseid]'], {}), '([caseid])\n', (2343, 2353), True, 'import numpy as np\n'), ((2551, 2579), 'numpy.asarray', 'np.asarray', (['[subpartialcase]'], {}), '([subpartialcase])\n', (2561, 2579), True, 'import numpy as np\n'), ((3537, 3549), 'numpy.int', 'np.int', (['step'], {}), '(step)\n', (3543, 3549), True, 'import numpy as np\n'), ((4264, 4286), 'numpy.asarray', 'np.asarray', (['x_datalist'], {}), '(x_datalist)\n', (4274, 4286), True, 'import numpy as np\n'), ((4288, 4310), 'numpy.asarray', 'np.asarray', (['x_row_inds'], {}), '(x_row_inds)\n', (4298, 4310), True, 'import numpy as np\n'), ((4330, 4352), 'numpy.asarray', 'np.asarray', (['x_col_inds'], {}), '(x_col_inds)\n', (4340, 4352), True, 'import numpy as np\n'), ((4381, 4403), 'numpy.asarray', 'np.asarray', (['y_datalist'], {}), '(y_datalist)\n', (4391, 4403), True, 'import numpy as np\n'), ((4405, 4429), 'numpy.asarray', 'np.asarray', (['pred_id_list'], {}), '(pred_id_list)\n', (4415, 4429), True, 'import numpy as np\n'), ((5334, 5376), 'numpy.concatenate', 'np.concatenate', (['(x_datalist, x_datalist_i)'], {}), '((x_datalist, x_datalist_i))\n', (5348, 5376), True, 'import numpy as np\n'), ((5402, 5444), 'numpy.concatenate', 'np.concatenate', (['(x_row_inds, x_row_inds_i)'], {}), '((x_row_inds, x_row_inds_i))\n', (5416, 5444), True, 'import numpy as np\n'), ((5470, 5512), 'numpy.concatenate', 'np.concatenate', (['(x_col_inds, x_col_inds_i)'], {}), '((x_col_inds, x_col_inds_i))\n', (5484, 5512), True, 'import numpy as np\n'), ((5535, 5586), 'numpy.asarray', 'np.asarray', (['(x_shape[0] + x_shape_i[0], x_shape[1])'], {}), '((x_shape[0] + x_shape_i[0], x_shape[1]))\n', (5545, 5586), True, 'import numpy as np\n'), ((5612, 5654), 'numpy.concatenate', 'np.concatenate', (['(y_datalist, y_datalist_i)'], {}), '((y_datalist, y_datalist_i))\n', (5626, 5654), True, 'import numpy as np\n'), ((5682, 5728), 'numpy.concatenate', 'np.concatenate', (['(pred_id_list, pred_id_list_i)'], {}), '((pred_id_list, pred_id_list_i))\n', (5696, 5728), True, 'import numpy as np\n'), ((7215, 7257), 'numpy.concatenate', 'np.concatenate', (['(x_datalist, x_datalist_i)'], {}), '((x_datalist, x_datalist_i))\n', (7229, 7257), True, 'import numpy as np\n'), ((7283, 7325), 'numpy.concatenate', 'np.concatenate', (['(x_row_inds, x_row_inds_i)'], {}), '((x_row_inds, x_row_inds_i))\n', (7297, 7325), True, 'import numpy as np\n'), ((7351, 7393), 'numpy.concatenate', 'np.concatenate', (['(x_col_inds, x_col_inds_i)'], {}), '((x_col_inds, x_col_inds_i))\n', (7365, 7393), True, 'import numpy as np\n'), ((7416, 7467), 'numpy.asarray', 'np.asarray', (['(x_shape[0] + x_shape_i[0], x_shape[1])'], {}), '((x_shape[0] + x_shape_i[0], x_shape[1]))\n', (7426, 7467), True, 'import numpy as np\n'), ((7493, 7535), 'numpy.concatenate', 'np.concatenate', (['(y_datalist, y_datalist_i)'], {}), '((y_datalist, y_datalist_i))\n', (7507, 7535), True, 'import numpy as np\n'), ((7563, 7609), 'numpy.concatenate', 'np.concatenate', (['(pred_id_list, pred_id_list_i)'], {}), '((pred_id_list, pred_id_list_i))\n', (7577, 7609), True, 'import numpy as np\n')] |
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from tensorflow.python.keras.layers import Flatten
from tensorflow.python.keras.layers import Dense
from tensorflow.python.keras.layers import Dropout
from tensorflow.python.keras.layers import Input
from tensorflow.python.keras.models import Model
from scipy import stats
import tensorflow as tf
import gc
import numpy as np
import random
import math
nb_total_epoch = 100
nb_autoencoder_epoch = 100
nb_frozen_epoch = 200
batch_size = 16
use_existing = False
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
def test_loss(prediction, ground_truth):
return np.sqrt(np.mean((prediction - ground_truth) ** 2))
def make_discriminator_model(input_size):
inputs = Input(shape=(input_size, 1))
x = inputs
x = Dense(256, activation="relu")(x)
x = Dense(128, activation="relu")(x)
x = Flatten()(x)
output = Dense(1)(x)
model = Model(inputs, output, name="discriminator")
return model
def make_generator_model(input_size):
inputs = Input(shape=(input_size, 1))
x = inputs
x = Dense(128, activation="relu")(x)
x = Dense(128, activation="relu")(x)
# x = Flatten()(x)
output = Dense(1)(x)
model = Model(inputs, output, name="generator")
return model
def discriminator_loss(real_output, fake_output):
real_loss = cross_entropy(tf.ones_like(real_output), real_output)
fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)
total_loss = real_loss + fake_loss
return total_loss
generator_optimizer = tf.keras.optimizers.Adam(0.00001)
discriminator_optimizer = tf.keras.optimizers.Adam(0.00001)
def train_step(generator, generator2, discriminator, input_profiles, target_profiles):
with tf.GradientTape() as tape, tf.GradientTape() as disc_tape:
reconstruction = generator(input_profiles, training=True)
reconstruction2 = generator2(reconstruction, training=True)
correspondence_loss = tf.reduce_mean(
tf.math.squared_difference(target_profiles, reconstruction))
reconstruction_loss = tf.reduce_mean(
tf.math.squared_difference(input_profiles, reconstruction2))
real_output = discriminator(target_profiles, training=True)
fake_output = discriminator(reconstruction, training=True)
disc_loss = discriminator_loss(real_output, fake_output)
gen_loss = generator_loss(fake_output)
total_loss = correspondence_loss + reconstruction_loss + 0.01 * gen_loss
gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)
discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator,
discriminator.trainable_variables))
gradients = tape.gradient(total_loss, generator.trainable_variables)
generator_optimizer.apply_gradients(zip(gradients, generator.trainable_variables))
def generator_loss(fake_output):
return cross_entropy(tf.ones_like(fake_output), fake_output)
def get_generators(input_size, data):
cells = list(data.cell_types)
generators = {}
generators[cells[0]] = make_generator_model(input_size)
generators[cells[1]] = make_generator_model(input_size)
discriminators = {}
discriminators[cells[0]] = make_discriminator_model(input_size)
discriminators[cells[1]] = make_discriminator_model(input_size)
count = 0
e = 0
while e < nb_total_epoch:
print("Epoch " + str(e) + " ------------------------------------------------------")
for pert in data.train_perts:
cell = random.choice(list(data.cell_types))
other_cell = list(data.cell_types - {cell})[0]
input_profile = np.asarray([data.train_data[i]
for i, p in enumerate(data.train_meta) if p[1] == pert and p[0] == other_cell])
target_profile = np.asarray([data.train_data[i]
for i, p in enumerate(data.train_meta) if p[1] == pert and p[0] == cell])
train_step(generators[cell], generators[other_cell], discriminators[cell], input_profile, target_profile)
val_cor_sum = 0.0
val_count = 0
seen_perts = []
disc_fake = 0
disc_real = 0
for i in range(len(data.val_data)):
val_meta_object = data.val_meta[i]
if val_meta_object[1] in seen_perts:
continue
closest, closest_profile, mean_profile, all_profiles = data.get_profile(data.val_data,
data.meta_dictionary_pert_val[
val_meta_object[1]],
val_meta_object)
if closest_profile is None:
continue
seen_perts.append(val_meta_object[1])
val_count = val_count + 1
cell = val_meta_object[0]
predictions = []
for p in all_profiles:
predictions.append(generators[cell].predict(np.asarray([p])))
special_decoded = np.mean(np.asarray(predictions), axis=0)
val_cor_sum = val_cor_sum + stats.pearsonr(special_decoded.flatten(), data.val_data[i].flatten())[0]
if discriminators[cell].predict(special_decoded)[0, 0] > 0.5:
disc_fake = disc_fake + 1
if discriminators[cell].predict(np.asarray([data.val_data[i]]))[0, 0] > 0.5:
disc_real = disc_real + 1
val_cor = val_cor_sum / val_count
print("Validation pcc: " + str(val_cor))
print("Evaluated:" + str(val_count))
print("Discriminator real correct:" + str(disc_real) + ", fake wrongly: " + str(disc_fake))
if e == 0:
best_val_cor = val_cor
else:
if val_cor < best_val_cor:
count = count + 1
else:
best_val_cor = val_cor
count = 0
if count > 4:
break
e = e + 1
return generators | [
"numpy.mean",
"tensorflow.python.keras.models.Model",
"tensorflow.keras.losses.BinaryCrossentropy",
"tensorflow.math.squared_difference",
"numpy.asarray",
"tensorflow.keras.optimizers.Adam",
"tensorflow.python.keras.layers.Dense",
"tensorflow.python.keras.layers.Flatten",
"tensorflow.GradientTape",
... | [((616, 668), 'tensorflow.keras.losses.BinaryCrossentropy', 'tf.keras.losses.BinaryCrossentropy', ([], {'from_logits': '(True)'}), '(from_logits=True)\n', (650, 668), True, 'import tensorflow as tf\n'), ((1649, 1680), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', (['(1e-05)'], {}), '(1e-05)\n', (1673, 1680), True, 'import tensorflow as tf\n'), ((1709, 1740), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', (['(1e-05)'], {}), '(1e-05)\n', (1733, 1740), True, 'import tensorflow as tf\n'), ((830, 858), 'tensorflow.python.keras.layers.Input', 'Input', ([], {'shape': '(input_size, 1)'}), '(shape=(input_size, 1))\n', (835, 858), False, 'from tensorflow.python.keras.layers import Input\n'), ((1014, 1057), 'tensorflow.python.keras.models.Model', 'Model', (['inputs', 'output'], {'name': '"""discriminator"""'}), "(inputs, output, name='discriminator')\n", (1019, 1057), False, 'from tensorflow.python.keras.models import Model\n'), ((1128, 1156), 'tensorflow.python.keras.layers.Input', 'Input', ([], {'shape': '(input_size, 1)'}), '(shape=(input_size, 1))\n', (1133, 1156), False, 'from tensorflow.python.keras.layers import Input\n'), ((1314, 1353), 'tensorflow.python.keras.models.Model', 'Model', (['inputs', 'output'], {'name': '"""generator"""'}), "(inputs, output, name='generator')\n", (1319, 1353), False, 'from tensorflow.python.keras.models import Model\n'), ((730, 771), 'numpy.mean', 'np.mean', (['((prediction - ground_truth) ** 2)'], {}), '((prediction - ground_truth) ** 2)\n', (737, 771), True, 'import numpy as np\n'), ((882, 911), 'tensorflow.python.keras.layers.Dense', 'Dense', (['(256)'], {'activation': '"""relu"""'}), "(256, activation='relu')\n", (887, 911), False, 'from tensorflow.python.keras.layers import Dense\n'), ((923, 952), 'tensorflow.python.keras.layers.Dense', 'Dense', (['(128)'], {'activation': '"""relu"""'}), "(128, activation='relu')\n", (928, 952), False, 'from tensorflow.python.keras.layers import Dense\n'), ((964, 973), 'tensorflow.python.keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (971, 973), False, 'from tensorflow.python.keras.layers import Flatten\n'), ((990, 998), 'tensorflow.python.keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (995, 998), False, 'from tensorflow.python.keras.layers import Dense\n'), ((1180, 1209), 'tensorflow.python.keras.layers.Dense', 'Dense', (['(128)'], {'activation': '"""relu"""'}), "(128, activation='relu')\n", (1185, 1209), False, 'from tensorflow.python.keras.layers import Dense\n'), ((1221, 1250), 'tensorflow.python.keras.layers.Dense', 'Dense', (['(128)'], {'activation': '"""relu"""'}), "(128, activation='relu')\n", (1226, 1250), False, 'from tensorflow.python.keras.layers import Dense\n'), ((1290, 1298), 'tensorflow.python.keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (1295, 1298), False, 'from tensorflow.python.keras.layers import Dense\n'), ((1453, 1478), 'tensorflow.ones_like', 'tf.ones_like', (['real_output'], {}), '(real_output)\n', (1465, 1478), True, 'import tensorflow as tf\n'), ((1523, 1549), 'tensorflow.zeros_like', 'tf.zeros_like', (['fake_output'], {}), '(fake_output)\n', (1536, 1549), True, 'import tensorflow as tf\n'), ((1841, 1858), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (1856, 1858), True, 'import tensorflow as tf\n'), ((1868, 1885), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (1883, 1885), True, 'import tensorflow as tf\n'), ((3090, 3115), 'tensorflow.ones_like', 'tf.ones_like', (['fake_output'], {}), '(fake_output)\n', (3102, 3115), True, 'import tensorflow as tf\n'), ((2093, 2152), 'tensorflow.math.squared_difference', 'tf.math.squared_difference', (['target_profiles', 'reconstruction'], {}), '(target_profiles, reconstruction)\n', (2119, 2152), True, 'import tensorflow as tf\n'), ((2213, 2272), 'tensorflow.math.squared_difference', 'tf.math.squared_difference', (['input_profiles', 'reconstruction2'], {}), '(input_profiles, reconstruction2)\n', (2239, 2272), True, 'import tensorflow as tf\n'), ((5344, 5367), 'numpy.asarray', 'np.asarray', (['predictions'], {}), '(predictions)\n', (5354, 5367), True, 'import numpy as np\n'), ((5288, 5303), 'numpy.asarray', 'np.asarray', (['[p]'], {}), '([p])\n', (5298, 5303), True, 'import numpy as np\n'), ((5650, 5680), 'numpy.asarray', 'np.asarray', (['[data.val_data[i]]'], {}), '([data.val_data[i]])\n', (5660, 5680), True, 'import numpy as np\n')] |
import os
import numpy as np
from .config import Config
class model:
def __init__(self, config, *args):
if len(args) == 1:
file = args[0]
if os.path.exists(file):
self.load(file)
else:
print(file)
elif len(args) == 2:
if type(args[1]) == bool:
m, wCopy = args
self.NTag = m.NTag
if wCopy:
self.W = m.W.copy()
else:
self.W = np.zeros_like(m.W)
else:
X, fGen = args
self.NTag = X.NTag
if config.random == 0:
self.W = np.zeros(fGen.NCompleteFeature)
elif config.random == 1:
self.W = np.random.random(size=(fGen.NCompleteFeature,)) * 2 - 1
else:
raise Exception("invalid argument")
else:
raise Exception("invalid argument")
def load(self, file):
with open(file, encoding="utf-8") as f:
txt = f.read()
txt = txt.replace("\r", "")
ary = txt.split(Config.lineEnd)
self.NTag = int(ary[0])
wsize = int(ary[1])
self.W = np.zeros(wsize)
for i in range(2, wsize):
self.W[i - 2] = float(ary[i])
def save(self, file):
with open(file, "w", encoding="utf-8") as f:
f.write(str(self.NTag) + "\n")
f.write(str(self.W.shape[0]) + "\n")
for im in self.W:
f.write("%.4f\n" % im)
| [
"numpy.random.random",
"os.path.exists",
"numpy.zeros",
"numpy.zeros_like"
] | [((1254, 1269), 'numpy.zeros', 'np.zeros', (['wsize'], {}), '(wsize)\n', (1262, 1269), True, 'import numpy as np\n'), ((179, 199), 'os.path.exists', 'os.path.exists', (['file'], {}), '(file)\n', (193, 199), False, 'import os\n'), ((530, 548), 'numpy.zeros_like', 'np.zeros_like', (['m.W'], {}), '(m.W)\n', (543, 548), True, 'import numpy as np\n'), ((701, 732), 'numpy.zeros', 'np.zeros', (['fGen.NCompleteFeature'], {}), '(fGen.NCompleteFeature)\n', (709, 732), True, 'import numpy as np\n'), ((803, 850), 'numpy.random.random', 'np.random.random', ([], {'size': '(fGen.NCompleteFeature,)'}), '(size=(fGen.NCompleteFeature,))\n', (819, 850), True, 'import numpy as np\n')] |
from __future__ import annotations
from copy import deepcopy
from typing import Tuple, Callable
import numpy as np
from IMLearn import BaseEstimator
def cross_validate(estimator: BaseEstimator, X: np.ndarray, y: np.ndarray,
scoring: Callable[[np.ndarray, np.ndarray, ...], float],
cv: int = 5) -> Tuple[float, float]:
"""
Evaluate metric by cross-validation for given estimator
Parameters
----------
estimator: BaseEstimator
Initialized estimator to use for fitting the data
X: ndarray of shape (n_samples, n_features)
Input data to fit
y: ndarray of shape (n_samples, )
Responses of input data to fit to
scoring: Callable[[np.ndarray, np.ndarray, ...], float]
Callable to use for evaluating the performance of the cross-validated model.
When called, the scoring function receives the true- and predicted values for each sample
and potentially additional arguments. The function returns the score for given input.
cv: int
Specify the number of folds.
Returns
-------
train_score: float
Average train score over folds
validation_score: float
Average validation score over folds
"""
X_parts = np.array_split(X, cv)
y_parts = np.array_split(y, cv)
train_sum, validation_sum = 0, 0
for k in range(cv):
X_k_fold = np.concatenate(
[part for j, part in enumerate(X_parts) if k != j])
y_k_fold = np.concatenate(
[part for j, part in enumerate(y_parts) if k != j])
estimator.fit(X_k_fold, y_k_fold)
train_sum += scoring(y_k_fold, estimator.predict(X_k_fold))
validation_sum += scoring(y_parts[k], estimator.predict(X_parts[k]))
return train_sum / cv, validation_sum / cv
| [
"numpy.array_split"
] | [((1175, 1196), 'numpy.array_split', 'np.array_split', (['X', 'cv'], {}), '(X, cv)\n', (1189, 1196), True, 'import numpy as np\n'), ((1208, 1229), 'numpy.array_split', 'np.array_split', (['y', 'cv'], {}), '(y, cv)\n', (1222, 1229), True, 'import numpy as np\n')] |
import shutil
import struct
from collections import defaultdict
from pathlib import Path
import lmdb
import numpy as np
import torch.utils.data
from tqdm import tqdm
class AvazuDataset(torch.utils.data.Dataset):
"""
Avazu Click-Through Rate Prediction Dataset
Dataset preparation
Remove the infrequent features (appearing in less than threshold instances) and treat them as a single feature
:param dataset_path: avazu train path
:param cache_path: lmdb cache path
:param rebuild_cache: If True, lmdb cache is refreshed
:param min_threshold: infrequent feature threshold
Reference
https://www.kaggle.com/c/avazu-ctr-prediction
"""
def __init__(self, dataset_path=None, cache_path='.avazu', rebuild_cache=False, min_threshold=4):
self.NUM_FEATS = 22
self.min_threshold = min_threshold
if rebuild_cache or not Path(cache_path).exists():
shutil.rmtree(cache_path, ignore_errors=True)
if dataset_path is None:
raise ValueError('create cache: failed: dataset_path is None')
self.__build_cache(dataset_path, cache_path)
self.env = lmdb.open(cache_path, create=False, lock=False, readonly=True)
with self.env.begin(write=False) as txn:
self.length = txn.stat()['entries'] - 1
self.field_dims = np.frombuffer(txn.get(b'field_dims'), dtype=np.uint32)
def __getitem__(self, index):
with self.env.begin(write=False) as txn:
np_array = np.frombuffer(
txn.get(struct.pack('>I', index)), dtype=np.uint32).astype(dtype=np.long)
return np_array[1:], np_array[0]
def __len__(self):
return self.length
def __build_cache(self, path, cache_path):
feat_mapper, defaults = self.__get_feat_mapper(path)
with lmdb.open(cache_path, map_size=int(1e11)) as env:
field_dims = np.zeros(self.NUM_FEATS, dtype=np.uint32)
for i, fm in feat_mapper.items():
field_dims[i - 1] = len(fm) + 1
with env.begin(write=True) as txn:
txn.put(b'field_dims', field_dims.tobytes())
for buffer in self.__yield_buffer(path, feat_mapper, defaults):
with env.begin(write=True) as txn:
for key, value in buffer:
txn.put(key, value)
def __get_feat_mapper(self, path):
feat_cnts = defaultdict(lambda: defaultdict(int))
with open(path) as f:
f.readline()
pbar = tqdm(f, mininterval=1, smoothing=0.1)
pbar.set_description('Create avazu dataset cache: counting features')
for line in pbar:
values = line.rstrip('\n').split(',')
if len(values) != self.NUM_FEATS + 2:
continue
for i in range(1, self.NUM_FEATS + 1):
feat_cnts[i][values[i + 1]] += 1
feat_mapper = {i: {feat for feat, c in cnt.items() if c >= self.min_threshold} for i, cnt in feat_cnts.items()}
feat_mapper = {i: {feat: idx for idx, feat in enumerate(cnt)} for i, cnt in feat_mapper.items()}
defaults = {i: len(cnt) for i, cnt in feat_mapper.items()}
return feat_mapper, defaults
def __yield_buffer(self, path, feat_mapper, defaults, buffer_size=int(1e5)):
item_idx = 0
buffer = list()
with open(path) as f:
f.readline()
pbar = tqdm(f, mininterval=1, smoothing=0.1)
pbar.set_description('Create avazu dataset cache: setup lmdb')
for line in pbar:
values = line.rstrip('\n').split(',')
if len(values) != self.NUM_FEATS + 2:
continue
np_array = np.zeros(self.NUM_FEATS + 1, dtype=np.uint32)
np_array[0] = int(values[1])
for i in range(1, self.NUM_FEATS + 1):
np_array[i] = feat_mapper[i].get(values[i+1], defaults[i])
buffer.append((struct.pack('>I', item_idx), np_array.tobytes()))
item_idx += 1
if item_idx % buffer_size == 0:
yield buffer
buffer.clear()
yield buffer
| [
"pathlib.Path",
"tqdm.tqdm",
"struct.pack",
"numpy.zeros",
"lmdb.open",
"collections.defaultdict",
"shutil.rmtree"
] | [((1206, 1268), 'lmdb.open', 'lmdb.open', (['cache_path'], {'create': '(False)', 'lock': '(False)', 'readonly': '(True)'}), '(cache_path, create=False, lock=False, readonly=True)\n', (1215, 1268), False, 'import lmdb\n'), ((964, 1009), 'shutil.rmtree', 'shutil.rmtree', (['cache_path'], {'ignore_errors': '(True)'}), '(cache_path, ignore_errors=True)\n', (977, 1009), False, 'import shutil\n'), ((1973, 2014), 'numpy.zeros', 'np.zeros', (['self.NUM_FEATS'], {'dtype': 'np.uint32'}), '(self.NUM_FEATS, dtype=np.uint32)\n', (1981, 2014), True, 'import numpy as np\n'), ((2620, 2657), 'tqdm.tqdm', 'tqdm', (['f'], {'mininterval': '(1)', 'smoothing': '(0.1)'}), '(f, mininterval=1, smoothing=0.1)\n', (2624, 2657), False, 'from tqdm import tqdm\n'), ((3563, 3600), 'tqdm.tqdm', 'tqdm', (['f'], {'mininterval': '(1)', 'smoothing': '(0.1)'}), '(f, mininterval=1, smoothing=0.1)\n', (3567, 3600), False, 'from tqdm import tqdm\n'), ((2525, 2541), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (2536, 2541), False, 'from collections import defaultdict\n'), ((3876, 3921), 'numpy.zeros', 'np.zeros', (['(self.NUM_FEATS + 1)'], {'dtype': 'np.uint32'}), '(self.NUM_FEATS + 1, dtype=np.uint32)\n', (3884, 3921), True, 'import numpy as np\n'), ((924, 940), 'pathlib.Path', 'Path', (['cache_path'], {}), '(cache_path)\n', (928, 940), False, 'from pathlib import Path\n'), ((4136, 4163), 'struct.pack', 'struct.pack', (['""">I"""', 'item_idx'], {}), "('>I', item_idx)\n", (4147, 4163), False, 'import struct\n'), ((1609, 1633), 'struct.pack', 'struct.pack', (['""">I"""', 'index'], {}), "('>I', index)\n", (1620, 1633), False, 'import struct\n')] |
#Aici este citirea exact ca la svm si la naive bayes doar ca testez parametri diferite pentru mlpclassifier.
#Rezultatul nu a trecut de 0.72 din ce imi amintesc (stiu ca era mai slaba solutia decat svm si nu am notat-o).
#Am luat MLPCLASSIFIER-ul din laborator si m-am jucat cu valorile ce erau oferite in documentatia din laboratul 7.
import numpy as np
import glob
from sklearn.neural_network import MLPClassifier
import matplotlib.pyplot as plt
def load_train_data():
train_images = []
for image in glob.glob("./train/*.png"):
train_images.append(plt.imread(image))
images = np.array(train_images)
return images
def load_validation_data():
validation_images = []
for image in glob.glob("./validation/*.png"):
validation_images.append(plt.imread(image))
images = np.array(validation_images)
return images
def load_test_data():
test_images = []
for image in glob.glob("./test/*.png"):
test_images.append(plt.imread(image))
images = np.array(test_images)
return images
loaded_train_images = load_train_data()
print(len(loaded_train_images))
loaded_validation_images = load_validation_data()
loaded_test_images = load_test_data()
# print(train_image[0])
length_train, train_x_axis, train_y_axis = loaded_train_images.shape
length_validation, validation_x_axis, validation_y_axis = loaded_validation_images.shape
length_test, test_x_axis, test_y_axis = loaded_test_images.shape
label_train = []
train_name_files = []
f = open("train.txt", "r")
for line in f:
separator = line.split(",")
train_name_files.append(separator[0])
label_train.append(int(separator[1]))
f.close()
print(len(label_train))
label_validation = []
validation_name_files = []
f = open("validation.txt", "r")
for line in f:
separator = line.split(",")
validation_name_files.append(separator[0])
label_validation.append(int(separator[1]))
f.close()
test_name_files = []
f = open("test.txt", "r")
#ignore_first_line = f.readline()
for line in f:
test_name_files.append(line[0:10])
f.close()
load_reshaped_train = loaded_train_images.reshape(length_train, train_x_axis*train_y_axis)
load_reshaped_validation = loaded_validation_images.reshape(length_validation, validation_x_axis*validation_y_axis)
load_reshaped_test = loaded_test_images.reshape(length_test, test_x_axis*test_y_axis)
def train_and_eval(clf):
clf.fit(load_reshaped_train, label_train)
return clf.score(load_reshaped_validation, label_validation)
#Aici am doar cateva din modele testate
# clf = MLPClassifier(hidden_layer_sizes=(1), activation='tanh',
# learning_rate_init=0.01, momentum=0)
# print(train_and_eval(clf))
#
# clf = MLPClassifier(hidden_layer_sizes=(10), activation='tanh',
# learning_rate_init=0.01, momentum=0)
# print(train_and_eval(clf))
#
# clf = MLPClassifier(hidden_layer_sizes=(100, 100), activation='relu',
# learning_rate_init=0.01, momentum=0,
# max_iter=2000)
# print(train_and_eval(clf))
#
# clf = MLPClassifier(hidden_layer_sizes=(100, 100), activation='relu',
# learning_rate_init=0.01, momentum=0.9,
# max_iter=2000)
# print(train_and_eval(clf))
#
#
# clf = MLPClassifier(hidden_layer_sizes=(100, 100), activation='relu',
# learning_rate_init=0.01, momentum=0.9,
# max_iter=2000, alpha=0.005)
# print(train_and_eval(clf))
#
# clf = MLPClassifier(hidden_layer_sizes=(30, 30,30), activation='relu',
# learning_rate_init=0.05,
# max_iter=2000, alpha=0.005)
# print(train_and_eval(clf))
#
# clf = MLPClassifier(hidden_layer_sizes=(100, 100, 100), activation='relu',
# learning_rate_init=0.001,
# max_iter=2000, alpha=0.005)
# print(train_and_eval(clf))
#
# clf = MLPClassifier(hidden_layer_sizes=(50,50), activation='relu',
# learning_rate_init=0.1,
# max_iter=2000, alpha=0.005)
# print(train_and_eval(clf))
#
# clf = MLPClassifier(hidden_layer_sizes=(10,10,10), activation='relu',
# learning_rate_init=0.05,
# max_iter=2000, alpha=0.005)
# print(train_and_eval(clf))
#
# clf = MLPClassifier(hidden_layer_sizes=(50,100,50), activation='relu',
# learning_rate_init=0.001,
# max_iter=2000, alpha=0.005)
# print(train_and_eval(clf))
#
# clf = MLPClassifier(hidden_layer_sizes=(100,), activation='relu',
# learning_rate_init=0.1,
# max_iter=2000, alpha=0.005)
# print(train_and_eval(clf))
# 0.1108
# 0.451
# 0.3454
# 0.4824
# 0.4986
# 0.1066
# 0.6682
# 0.1122
# 0.2158
# 0.704
# 0.104
#Fac matricea de confuzie pentru penultimul model
clf = MLPClassifier(hidden_layer_sizes=(50,100,50), activation='relu',
learning_rate_init=0.001, #rata de invatare este cea default
max_iter=2000, alpha=0.005) #numarul maxim de epoci si parametrul pentru regularizarea L2
print("Accuracy =", train_and_eval(clf))
predictions = clf.predict(load_reshaped_validation)
def confusion_matrix(label_true, label_predicted): # aici afisez matricea de confuzie
num_classes = max(max(label_true), max(label_predicted)) + 1 # iau numarul de clase posibile, puteam sa ii dau 9 eu
conf_matrix = np.zeros((num_classes, num_classes)) # face o matrice 9x9 initializata cu 0
for i in range(len(label_true)): # iau i = numarul de labeluri date (de imagini)
conf_matrix[int(label_true[i]), int(label_predicted[i])] += 1 # daca prezicerea este corecta crestem valoarea pe diagonala principala, daca nu in afara ei ( [i][j] i -> ce trebuia prezis si j-> ce a prezis)
return conf_matrix
print(confusion_matrix(label_validation, predictions))
# g = open("sample_submission.txt", "w")
# sample_sub = clf.predict(load_reshaped_test)
# print(len(sample_sub), len(test_name_files))
# g.write("id,label\n")
# for i in range (len(sample_sub)):
# g.write(str(test_name_files[i]) + "," + str(sample_sub[i]) + '\n')
#
# g.close() | [
"sklearn.neural_network.MLPClassifier",
"matplotlib.pyplot.imread",
"numpy.array",
"numpy.zeros",
"glob.glob"
] | [((4970, 5094), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {'hidden_layer_sizes': '(50, 100, 50)', 'activation': '"""relu"""', 'learning_rate_init': '(0.001)', 'max_iter': '(2000)', 'alpha': '(0.005)'}), "(hidden_layer_sizes=(50, 100, 50), activation='relu',\n learning_rate_init=0.001, max_iter=2000, alpha=0.005)\n", (4983, 5094), False, 'from sklearn.neural_network import MLPClassifier\n'), ((523, 549), 'glob.glob', 'glob.glob', (['"""./train/*.png"""'], {}), "('./train/*.png')\n", (532, 549), False, 'import glob\n'), ((613, 635), 'numpy.array', 'np.array', (['train_images'], {}), '(train_images)\n', (621, 635), True, 'import numpy as np\n'), ((734, 765), 'glob.glob', 'glob.glob', (['"""./validation/*.png"""'], {}), "('./validation/*.png')\n", (743, 765), False, 'import glob\n'), ((834, 861), 'numpy.array', 'np.array', (['validation_images'], {}), '(validation_images)\n', (842, 861), True, 'import numpy as np\n'), ((948, 973), 'glob.glob', 'glob.glob', (['"""./test/*.png"""'], {}), "('./test/*.png')\n", (957, 973), False, 'import glob\n'), ((1036, 1057), 'numpy.array', 'np.array', (['test_images'], {}), '(test_images)\n', (1044, 1057), True, 'import numpy as np\n'), ((5558, 5594), 'numpy.zeros', 'np.zeros', (['(num_classes, num_classes)'], {}), '((num_classes, num_classes))\n', (5566, 5594), True, 'import numpy as np\n'), ((580, 597), 'matplotlib.pyplot.imread', 'plt.imread', (['image'], {}), '(image)\n', (590, 597), True, 'import matplotlib.pyplot as plt\n'), ((801, 818), 'matplotlib.pyplot.imread', 'plt.imread', (['image'], {}), '(image)\n', (811, 818), True, 'import matplotlib.pyplot as plt\n'), ((1003, 1020), 'matplotlib.pyplot.imread', 'plt.imread', (['image'], {}), '(image)\n', (1013, 1020), True, 'import matplotlib.pyplot as plt\n')] |
import tensorflow as tf
import numpy as np
from thermal_barrierlife_prediction.load_data import read_data
class Estimator:
"""
Estimator class. Contains all necessary methods for data loading,
model initialization, training, evaluation and prediction.
"""
def prepare_data(
self,
csv_file_path='../data/train-orig.csv',
tiff_folder_path='../data/train/', # for validation: '../data/valid'
mixup: bool = False,
for_training=True,
data_ratio_mixup=2,
alpha_mixup=0.2,
# if True, standardization parameters will be computed, if False then apply parameters computed from training data
):
"""
Prepares the necessary data input for the model.
"""
self.data = read_data(
csv_file_path=csv_file_path,
tiff_folder_path=tiff_folder_path,
)
# Mixup
if mixup:
self.mixup_data(data_ratio_produce=data_ratio_mixup, alpha=alpha_mixup)
### augment, do whatever you want (distinguish between train and validation setting!)
def train(
self,
val_samples=[],
batch_size=8,
epochs=20
):
"""
Trains the model.
"""
self.val_samples = val_samples
self.train_idx = np.argwhere([sample not in self.val_samples for sample in self.data['sample']]).ravel()
self.val_idx = np.argwhere([sample in self.val_samples for sample in self.data['sample']]).ravel() \
if len(val_samples) > 0 else None
X_train = self.data['greyscale'][self.train_idx]
X_train_cov = self.data['magnification'][self.train_idx].reshape(-1, 1)
y_train = self.data['lifetime'][self.train_idx]
if len(val_samples) > 0:
validation_data = ((self.data['greyscale'][self.val_idx],
self.data['magnification'][self.val_idx].reshape(-1, 1)),
self.data['lifetime'][self.val_idx])
else:
validation_data = None
self.history = self.model.training_model.fit(
x=(X_train, X_train_cov),
y=y_train,
shuffle=True,
epochs=epochs,
batch_size=batch_size,
validation_data=validation_data,
verbose=2,
).history
def mixup_data(self, data_ratio_produce=2, alpha=0.2):
"""
Make mixup data, add to original data, and save in estimator's data object
:param data_ratio_produce: Prudouce int(X_train.shape[0]*data_ratio_produce) samples
:param alpha: Beta distn param for sampling mixing weights
"""
real_samples_idx = np.argwhere(self.data['real']).ravel()
n_training_samples = real_samples_idx.shape[0]
# Make random mixup samples
n_samples = int(n_training_samples * data_ratio_produce)
data_new = dict()
for key in self.data:
data_new[key] = []
for i in range(n_samples):
# Mixup ratio
lam = np.random.beta(alpha, alpha)
# Should not happen, but just in case to detect bugs
if lam < 0 or lam > 1:
raise ValueError('Lam not between 0 and 1')
# Images to choose for mixup, choose only from real samples
idxs = np.random.choice(real_samples_idx, 2, replace=False)
idx0 = idxs[0]
idx1 = idxs[1]
# Make mixup data
data_new['greyscale'].append(
self.data['greyscale'][idx0] * lam + self.data['greyscale'][idx1] * (1 - lam))
data_new['sample'].append(
'_'.join([str(self.data['sample'][idx0]), str(lam), str(str(self.data['sample'][idx1])), str(1 - lam)]))
data_new['lifetime'].append(
self.data['lifetime'][idx0] * lam + self.data['lifetime'][idx1] * (1 - lam))
data_new['magnification'].append(
self.data['magnification'][idx0] * lam + self.data['magnification'][idx1] * (1 - lam))
data_new['uncertainty'].append(
self.data['uncertainty'][idx0] * lam + self.data['uncertainty'][idx1] * (1 - lam))
data_new['image_id'].append(
'_'.join(
[str(self.data['image_id'][idx0]), str(lam), str(self.data['image_id'][idx1]), str(1 - lam)]))
data_new['real'].append(0)
# Add mixup to data
for key in self.data.keys():
if len(data_new[key]) != n_samples:
raise ValueError('Mixup data for %s not of corect length' % key)
# Do not use np concat as it is slow - filling an array is quicker
# data_temp = np.empty((self.data[key].shape[0] + len(data_new[key]), *self.data[key].shape[1:]),
# dtype=self.data[key].dtype)
# for i in range(self.data[key].shape[0]):
# data_temp[i] = self.data[key][i]
# # Add new data after old one (array positions starting after positions of original data)
# for i in range(len(data_new[key])):
# data_temp[i+self.data[key].shape[0]] = data_new[key][i]
# self.data[key] = data_temp
self.data[key] = np.concatenate([self.data[key], data_new[key]])
def _compile_model(
self,
):
"""
Prepares the losses and metrics and compiles the model.
"""
self.model.training_model.compile(
loss=tf.keras.losses.mean_squared_error,
optimizer='adam',
metrics=[
tf.keras.metrics.mean_squared_error,
tf.keras.metrics.mean_absolute_error
],
)
def predict(self,
val_data: dict = None,
val_samples=None,
val_idx=None
):
'''
predicts a set of input samples. If both samples and idx are None then use saved val_idx.
Only one of samples and idx can be non-None.
'''
if val_data is not None:
data = (val_data['greyscale'], val_data['magnification'].reshape(-1, 1))
else:
if val_samples is not None and val_idx is not None:
raise ValueError('Only one of sample names or idx can be non-None')
if val_samples is not None:
val_idx = np.argwhere([sample in val_samples for sample in self.data['sample']]).ravel()
# Use saved index if not specified by samples or idx
if val_idx is None:
print('Using saved val samples')
val_idx = self.val_idx.copy()
data = (self.data['greyscale'][val_idx], self.data['magnification'][val_idx])
y_pred = self.model.training_model.predict(data)
return y_pred.flatten()
def compute_gradients_input(
self,
image_ids,
plot=True,
):
"""
Computes and plots gradients with respect to input data.
"""
if not isinstance(image_ids, list):
image_ids = [image_ids]
predictions = []
gradients = []
for image_id in image_ids:
input_raw = self.data['greyscale'][np.argwhere(self.data['image_id'] == image_id)]
input_X = tf.convert_to_tensor(input_raw.astype('float32'))
input_X = tf.expand_dims(input_X, 0)
with tf.GradientTape(persistent=True) as g:
g.watch(input_X)
pred = self.model.training_model(input_X)
grad = g.gradient(pred, input_X).numpy()[0]
predictions.append(pred.numpy()[0, 0])
gradients.append(grad)
if plot:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].matshow(np.abs(grad), cmap='gray', vmax=np.sort(np.abs(grad).flatten())[-10000])
ax[1].matshow(input_raw, cmap='gray', vmin=0, vmax=255)
ax[0].axis('off')
ax[1].axis('off')
plt.tight_layout()
return predictions, gradients
| [
"thermal_barrierlife_prediction.load_data.read_data",
"numpy.abs",
"numpy.random.beta",
"numpy.random.choice",
"tensorflow.GradientTape",
"numpy.argwhere",
"numpy.concatenate",
"matplotlib.pyplot.tight_layout",
"tensorflow.expand_dims",
"matplotlib.pyplot.subplots"
] | [((810, 883), 'thermal_barrierlife_prediction.load_data.read_data', 'read_data', ([], {'csv_file_path': 'csv_file_path', 'tiff_folder_path': 'tiff_folder_path'}), '(csv_file_path=csv_file_path, tiff_folder_path=tiff_folder_path)\n', (819, 883), False, 'from thermal_barrierlife_prediction.load_data import read_data\n'), ((3116, 3144), 'numpy.random.beta', 'np.random.beta', (['alpha', 'alpha'], {}), '(alpha, alpha)\n', (3130, 3144), True, 'import numpy as np\n'), ((3396, 3448), 'numpy.random.choice', 'np.random.choice', (['real_samples_idx', '(2)'], {'replace': '(False)'}), '(real_samples_idx, 2, replace=False)\n', (3412, 3448), True, 'import numpy as np\n'), ((5328, 5375), 'numpy.concatenate', 'np.concatenate', (['[self.data[key], data_new[key]]'], {}), '([self.data[key], data_new[key]])\n', (5342, 5375), True, 'import numpy as np\n'), ((7455, 7481), 'tensorflow.expand_dims', 'tf.expand_dims', (['input_X', '(0)'], {}), '(input_X, 0)\n', (7469, 7481), True, 'import tensorflow as tf\n'), ((1363, 1449), 'numpy.argwhere', 'np.argwhere', (["[(sample not in self.val_samples) for sample in self.data['sample']]"], {}), "([(sample not in self.val_samples) for sample in self.data[\n 'sample']])\n", (1374, 1449), True, 'import numpy as np\n'), ((2755, 2785), 'numpy.argwhere', 'np.argwhere', (["self.data['real']"], {}), "(self.data['real'])\n", (2766, 2785), True, 'import numpy as np\n'), ((7313, 7359), 'numpy.argwhere', 'np.argwhere', (["(self.data['image_id'] == image_id)"], {}), "(self.data['image_id'] == image_id)\n", (7324, 7359), True, 'import numpy as np\n'), ((7499, 7531), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {'persistent': '(True)'}), '(persistent=True)\n', (7514, 7531), True, 'import tensorflow as tf\n'), ((7870, 7905), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(10, 5)'}), '(1, 2, figsize=(10, 5))\n', (7882, 7905), True, 'import matplotlib.pyplot as plt\n'), ((8165, 8183), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (8181, 8183), True, 'import matplotlib.pyplot as plt\n'), ((1474, 1551), 'numpy.argwhere', 'np.argwhere', (["[(sample in self.val_samples) for sample in self.data['sample']]"], {}), "([(sample in self.val_samples) for sample in self.data['sample']])\n", (1485, 1551), True, 'import numpy as np\n'), ((7936, 7948), 'numpy.abs', 'np.abs', (['grad'], {}), '(grad)\n', (7942, 7948), True, 'import numpy as np\n'), ((6458, 6530), 'numpy.argwhere', 'np.argwhere', (["[(sample in val_samples) for sample in self.data['sample']]"], {}), "([(sample in val_samples) for sample in self.data['sample']])\n", (6469, 6530), True, 'import numpy as np\n'), ((7976, 7988), 'numpy.abs', 'np.abs', (['grad'], {}), '(grad)\n', (7982, 7988), True, 'import numpy as np\n')] |
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn import metrics
import numpy as np
import pickle
import cv2 as cv
from tensorflow import keras
from keras import optimizers
from tensorflow.keras import layers
from feature_extractor import get_pos_neg_samples_from_pickle
from annotation_parser import parseDataset
from calc_hog import calculate_Hog_OPENCV as calculate_Hog
def getTrainingData():
positives, negatives = get_pos_neg_samples_from_pickle()
data = np.array(positives + negatives, dtype='float32')
labels = np.zeros(len(data),dtype='str')
labels[:len(positives)] = 1
labels[len(positives):] = 0
X_train, X_test, y_train, y_test = train_test_split(data, labels, random_state=0)
return (X_train, X_test, y_train, y_test)
def getTrainedModel():
X_train, X_test, y_train, y_test = getTrainingData()
# # convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train)
y_test = keras.utils.to_categorical(y_test)
"""## Build the model"""
model = keras.Sequential(
[
keras.Input(shape=(X_train.shape[1])),
layers.Dense(10, activation="relu"),
layers.Dense(10, activation="relu"),
layers.Dropout(0.5),
layers.Dense(2, activation="softmax"),
]
)
model.summary()
"""## Train the model"""
batch_size = 2000
epochs = 25
#opt = optimizers.gradient_descent_v2.SGD(momentum=0.1)
opt = optimizers.adam_v2.Adam()
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"]) #keras.metrics.Precision(), keras.metrics.Recall(),
model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)
return model
def finalClassifier(clfPicklePath, X_train, y_train):
# Takes the fitted classifier and the data it used
# Using a sliding window we check all negative images for false-positives with the classifier
# All false-positives are then added to the dataset as negatives and we then train a new classifier on the extended dataset
# Returns newly trained/fitted calssifier
old_x = X_train
old_y = y_train
classifier = pickle.load(open(clfPicklePath, 'rb'))
positives, negatives = parseDataset('INRIAPerson/Train/')
step_x = 8
step_y = 16
for n, neg in enumerate(negatives):
print("Total_imgs/current_img: ",len(negatives),"/", n)
if n > 200: break
frame_raw = cv.imread(neg)
if frame_raw is None:
print("empty negative.png")
continue
for i in range(5):
fx=(1-i*0.2)
fy=(1-i*0.2)
frame = cv.resize(frame_raw, (0,0), fx=fx, fy=fy)
y_len,x_len,_= frame.shape
scalex = int(x_len / step_x)
scaley = int(y_len / step_y)
for y in range(scaley):
if (y)*step_y + 128 > frame.shape[0]:
continue
for x in range(scalex):
if ((x)*step_x + 64) > frame.shape[1]:
continue
cropped_image=frame[(y*step_y):((y)*step_y + 128),
(x*step_x):((x)*step_x + 64)]
feature, notUsedVariableBecauseItIsUseless = calculate_Hog(cropped_image)
if clfPicklePath == 'model_nonlinear_svm.pickle':
pred = classifier.predict_proba([feature])
if pred[0,1] > 0.75:
X_train = np.append(X_train, [feature], axis=0)
y_train = np.append(y_train,0)
elif clfPicklePath == 'model_linear_svm.pickle':
pred = classifier.predict([feature])
if pred != '0':
X_train = np.append(X_train, [feature], axis=0)
y_train = np.append(y_train,0)
print("oldx & oldy",old_x.shape, old_y.shape)
print("newx & newy",X_train.shape, y_train.shape)
print("y diff (new pictures added)",y_train.shape[0]-old_y.shape[0])
pickle.dump([X_train,y_train], open("N200__new_X_y_trainWithHardExamples.pickle", 'wb'))
clfHardExamples = svm.LinearSVC(max_iter=10000, C=0.01)
clfHardExamples.fit(X_train, y_train)
return clfHardExamples
if __name__ == '__main__':
# get NN model
model = getTrainedModel()
"""## Evaluate the trained model"""
X_train, X_test, y_train, y_test = getTrainingData()
#reorder data to fit Keras
y_test = keras.utils.to_categorical(y_test)
score = model.evaluate(X_test, y_test, verbose=0)
print("Test loss:", score[0])
print("Test accuracy:", score[1])
pred = model.predict(X_test)
#calculate and print metrics for NN
TP = 0
FP = 0
FN = 0
for i, p in enumerate(pred):
if y_test[i,1]:
if p[1] > p[0]:
TP += 1
else:
FN += 1
else:
if p[1] > p[0]:
FP += 1
print('TP: ', TP, ', FP: ', FP, ', FN: ', FN)
precision = TP/(TP + FP)
recall = TP/(TP+FN)
print('Precision: ', precision, ', recall: ', recall)
# fit linear SVM, predict and print metrics
X_train, X_test, y_train, y_test = getTrainingData()
clf = svm.LinearSVC(max_iter=10000, C=0.01)
clf.fit(X_train, y_train)
pickle.dump(clf, open('model_linear_svm.pickle', 'wb'))
y_pred = clf.predict(X_test)
print("linear SVM classification report:")
print(metrics.classification_report(y_test, y_pred))
print("linear SVM confusion matrix:")
print(metrics.confusion_matrix(y_pred, y_test))
# fit linear SVM again but with hard examples and predict and print metics
hardExamples = True
if hardExamples == True:
new_clf = finalClassifier('model_linear_svm.pickle' ,X_train, y_train)
pickle.dump(new_clf, open('new_model_linear_svm.pickle', 'wb'))
new_y_pred = new_clf.predict(X_test)
print("NEW linear SVM classification report:")
print(metrics.classification_report(y_test, new_y_pred))
print("NEW linear SVM confusion matrix:")
print(metrics.confusion_matrix(new_y_pred, y_test))
# fit non-linear SVM, predict and print metrics
X_train, X_test, y_train, y_test = getTrainingData()
clf = svm.SVC(probability=True)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("non linear SVM classification report:")
print(metrics.classification_report(y_test, y_pred))
print("non linear SVM confusion matrix:")
print(metrics.confusion_matrix(y_pred, y_test))
pickle.dump(clf, open('model_nonlinear_svm.pickle', 'wb'))
| [
"tensorflow.keras.utils.to_categorical",
"sklearn.svm.SVC",
"sklearn.metrics.confusion_matrix",
"annotation_parser.parseDataset",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.classification_report",
"sklearn.svm.LinearSVC",
"tensorflow.keras.layers.Dropout",
"numpy.append",
"numpy.... | [((468, 501), 'feature_extractor.get_pos_neg_samples_from_pickle', 'get_pos_neg_samples_from_pickle', ([], {}), '()\n', (499, 501), False, 'from feature_extractor import get_pos_neg_samples_from_pickle\n'), ((513, 561), 'numpy.array', 'np.array', (['(positives + negatives)'], {'dtype': '"""float32"""'}), "(positives + negatives, dtype='float32')\n", (521, 561), True, 'import numpy as np\n'), ((710, 756), 'sklearn.model_selection.train_test_split', 'train_test_split', (['data', 'labels'], {'random_state': '(0)'}), '(data, labels, random_state=0)\n', (726, 756), False, 'from sklearn.model_selection import train_test_split\n'), ((955, 990), 'tensorflow.keras.utils.to_categorical', 'keras.utils.to_categorical', (['y_train'], {}), '(y_train)\n', (981, 990), False, 'from tensorflow import keras\n'), ((1004, 1038), 'tensorflow.keras.utils.to_categorical', 'keras.utils.to_categorical', (['y_test'], {}), '(y_test)\n', (1030, 1038), False, 'from tensorflow import keras\n'), ((1518, 1543), 'keras.optimizers.adam_v2.Adam', 'optimizers.adam_v2.Adam', ([], {}), '()\n', (1541, 1543), False, 'from keras import optimizers\n'), ((2284, 2318), 'annotation_parser.parseDataset', 'parseDataset', (['"""INRIAPerson/Train/"""'], {}), "('INRIAPerson/Train/')\n", (2296, 2318), False, 'from annotation_parser import parseDataset\n'), ((4301, 4338), 'sklearn.svm.LinearSVC', 'svm.LinearSVC', ([], {'max_iter': '(10000)', 'C': '(0.01)'}), '(max_iter=10000, C=0.01)\n', (4314, 4338), False, 'from sklearn import svm\n'), ((4659, 4693), 'tensorflow.keras.utils.to_categorical', 'keras.utils.to_categorical', (['y_test'], {}), '(y_test)\n', (4685, 4693), False, 'from tensorflow import keras\n'), ((5418, 5455), 'sklearn.svm.LinearSVC', 'svm.LinearSVC', ([], {'max_iter': '(10000)', 'C': '(0.01)'}), '(max_iter=10000, C=0.01)\n', (5431, 5455), False, 'from sklearn import svm\n'), ((6453, 6478), 'sklearn.svm.SVC', 'svm.SVC', ([], {'probability': '(True)'}), '(probability=True)\n', (6460, 6478), False, 'from sklearn import svm\n'), ((2502, 2516), 'cv2.imread', 'cv.imread', (['neg'], {}), '(neg)\n', (2511, 2516), True, 'import cv2 as cv\n'), ((5637, 5682), 'sklearn.metrics.classification_report', 'metrics.classification_report', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (5666, 5682), False, 'from sklearn import metrics\n'), ((5740, 5780), 'sklearn.metrics.confusion_matrix', 'metrics.confusion_matrix', (['y_pred', 'y_test'], {}), '(y_pred, y_test)\n', (5764, 5780), False, 'from sklearn import metrics\n'), ((6603, 6648), 'sklearn.metrics.classification_report', 'metrics.classification_report', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (6632, 6648), False, 'from sklearn import metrics\n'), ((6706, 6746), 'sklearn.metrics.confusion_matrix', 'metrics.confusion_matrix', (['y_pred', 'y_test'], {}), '(y_pred, y_test)\n', (6730, 6746), False, 'from sklearn import metrics\n'), ((1121, 1156), 'tensorflow.keras.Input', 'keras.Input', ([], {'shape': 'X_train.shape[1]'}), '(shape=X_train.shape[1])\n', (1132, 1156), False, 'from tensorflow import keras\n'), ((1172, 1207), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['(10)'], {'activation': '"""relu"""'}), "(10, activation='relu')\n", (1184, 1207), False, 'from tensorflow.keras import layers\n'), ((1221, 1256), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['(10)'], {'activation': '"""relu"""'}), "(10, activation='relu')\n", (1233, 1256), False, 'from tensorflow.keras import layers\n'), ((1270, 1289), 'tensorflow.keras.layers.Dropout', 'layers.Dropout', (['(0.5)'], {}), '(0.5)\n', (1284, 1289), False, 'from tensorflow.keras import layers\n'), ((1303, 1340), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['(2)'], {'activation': '"""softmax"""'}), "(2, activation='softmax')\n", (1315, 1340), False, 'from tensorflow.keras import layers\n'), ((2719, 2761), 'cv2.resize', 'cv.resize', (['frame_raw', '(0, 0)'], {'fx': 'fx', 'fy': 'fy'}), '(frame_raw, (0, 0), fx=fx, fy=fy)\n', (2728, 2761), True, 'import cv2 as cv\n'), ((6176, 6225), 'sklearn.metrics.classification_report', 'metrics.classification_report', (['y_test', 'new_y_pred'], {}), '(y_test, new_y_pred)\n', (6205, 6225), False, 'from sklearn import metrics\n'), ((6291, 6335), 'sklearn.metrics.confusion_matrix', 'metrics.confusion_matrix', (['new_y_pred', 'y_test'], {}), '(new_y_pred, y_test)\n', (6315, 6335), False, 'from sklearn import metrics\n'), ((3352, 3380), 'calc_hog.calculate_Hog_OPENCV', 'calculate_Hog', (['cropped_image'], {}), '(cropped_image)\n', (3365, 3380), True, 'from calc_hog import calculate_Hog_OPENCV as calculate_Hog\n'), ((3601, 3638), 'numpy.append', 'np.append', (['X_train', '[feature]'], {'axis': '(0)'}), '(X_train, [feature], axis=0)\n', (3610, 3638), True, 'import numpy as np\n'), ((3677, 3698), 'numpy.append', 'np.append', (['y_train', '(0)'], {}), '(y_train, 0)\n', (3686, 3698), True, 'import numpy as np\n'), ((3908, 3945), 'numpy.append', 'np.append', (['X_train', '[feature]'], {'axis': '(0)'}), '(X_train, [feature], axis=0)\n', (3917, 3945), True, 'import numpy as np\n'), ((3984, 4005), 'numpy.append', 'np.append', (['y_train', '(0)'], {}), '(y_train, 0)\n', (3993, 4005), True, 'import numpy as np\n')] |
import cv2 as cv
import numpy as np
def contrast_brightness(image, c, b):
h, w = image.shape
blank = np.zeros([h, w], image.dtype)
dst = cv.addWeighted(image, c, blank, 1-c, b)
return dst
def delate_then_erode(img, times, dilate, erode):
dst = img
for i in range(times):
kerneld = cv.getStructuringElement(cv.MORPH_RECT, (1, dilate))
dst = cv.dilate(dst, kerneld)
kernele = cv.getStructuringElement(cv.MORPH_RECT, (erode, 1))
dst = cv.erode(dst, kernele)
return dst
def show(name, image):
cv.namedWindow(name, cv.WINDOW_NORMAL)
cv.imshow(name, image)
def contrast_boost_add(image, n=3):
dst = image
m = dst
for i in range(n):
dst = cv.add(m, dst)
return dst
def process(path):
# 将路径的照片文件转化成多维数组
global src
src = cv.imread(path)
# 源图片展示
# show("input image", src)
dst = src
'''灰度化,降色彩通道为1'''
dst = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
# mask = numpy.zeros(src.shape) # 黑色掩膜
mask = np.ones(src.shape) # 白色掩膜
'''增强对比度'''
dst = contrast_boost_add(dst, 2)
show("zengqiang", dst)
'''寻找最大值和最小值'''
minVal, maxVal, minIdx, maxIdx = cv.minMaxLoc(dst)
# dst = cv.medianBlur(dst, 5)
dst = cv.GaussianBlur(dst, (5, 5), 3)
dst = cv.normalize(dst, dst=mask, alpha=minVal,
beta=maxVal, norm_type=cv.NORM_MINMAX)
'''二值化处理'''
_, threshold = cv.threshold(dst, 100, 255, cv.THRESH_BINARY)
show("th", threshold)
'''RIO·提取局部并进行处理,中间包括对比度增强与二值化'''
# dst = Region_One_process(dst, 5, 5, contrast_boost_in)
dst = cv.adaptiveThreshold(
dst, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 101, -1)
show("erzhihuachuli", dst)
'''加法去黑边'''
dst = cv.add(dst, threshold)
show("processed", dst)
'''降噪处理·滤波操作'''
dst = cv.medianBlur(dst, 13)
# show("gaosilvbo", dst)
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
dst = cv.morphologyEx(dst, cv.MORPH_OPEN, kernel=kernel) # 开操作降噪
# show("kaicaozuo", dst)
dst = cv.filter2D(dst, -1, kernel=kernel)
show("dst", dst)
# '''Canny检测'''
# edges = cv.Canny(dst, 10, 1000)
# show("edges", edges)
def houghP(src, dst, minLineLength):
'''累计概率霍夫'''
# line_lst = []
edges = cv.Canny(dst, 10, 1000)
background = src.copy()
lines = cv.HoughLinesP(edges, 0.6, np.pi / 180, threshold=minLineLength,
minLineLength=minLineLength, maxLineGap=10)
for x1, y1, x2, y2 in lines[:, 0]:
line = cv.line(background, (x1, y1), (x2, y2), (0, 255, 0), 2)
# line_lst.append(line)
return background
def hough(src, dst):
'''霍夫直线检测'''
dst = delate_then_erode(dst, 20, 6, 3)
kerneld = cv.getStructuringElement(cv.MORPH_RECT, (20, 1))
dst = cv.dilate(dst, kerneld)
show("erode", dst)
res = cv.Canny(dst, 10, 1000)
lines = cv.HoughLines(res, 1, np.pi/180, 50)
background = src.copy()
for line in lines:
rho = line[0][0] # 第一个元素是距离rho
theta = line[0][1] # 第二个元素是角度theta
if (3 > theta > 2.984):
# 该直线与第一行的交点
pt1 = (int(rho / np.cos(theta)), 0)
# 该直线与最后一行的焦点
pt2 = (int(
(rho - background.shape[0] * np.sin(theta)) / np.cos(theta)), background.shape[0])
# 绘制一条白线
if(pt1[0] > 50 and pt1[0] < 500):
cv.line(background, pt1, pt2, (255, 255, 255), 2)
return background
houghP_img = houghP(
np.zeros([src.shape[0], src.shape[1], 3], src.dtype), dst, 50)
hough_img = hough(
np.zeros([src.shape[0], src.shape[1], 3], src.dtype), dst)
# return dst
return cv.add(hough_img, houghP_img)
show("img", process("D:\\study\\opencv\\detection\\1450000.bmp"))
while True:
c = cv.waitKey(50)
if c == 27:
break
cv.destroyAllWindows()
| [
"cv2.normalize",
"cv2.filter2D",
"cv2.imshow",
"cv2.HoughLines",
"cv2.destroyAllWindows",
"numpy.sin",
"cv2.threshold",
"cv2.erode",
"cv2.line",
"cv2.medianBlur",
"cv2.minMaxLoc",
"cv2.addWeighted",
"cv2.waitKey",
"cv2.add",
"numpy.ones",
"cv2.morphologyEx",
"numpy.cos",
"cv2.cvtCo... | [((4146, 4168), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (4166, 4168), True, 'import cv2 as cv\n'), ((117, 146), 'numpy.zeros', 'np.zeros', (['[h, w]', 'image.dtype'], {}), '([h, w], image.dtype)\n', (125, 146), True, 'import numpy as np\n'), ((158, 199), 'cv2.addWeighted', 'cv.addWeighted', (['image', 'c', 'blank', '(1 - c)', 'b'], {}), '(image, c, blank, 1 - c, b)\n', (172, 199), True, 'import cv2 as cv\n'), ((581, 619), 'cv2.namedWindow', 'cv.namedWindow', (['name', 'cv.WINDOW_NORMAL'], {}), '(name, cv.WINDOW_NORMAL)\n', (595, 619), True, 'import cv2 as cv\n'), ((625, 647), 'cv2.imshow', 'cv.imshow', (['name', 'image'], {}), '(name, image)\n', (634, 647), True, 'import cv2 as cv\n'), ((863, 878), 'cv2.imread', 'cv.imread', (['path'], {}), '(path)\n', (872, 878), True, 'import cv2 as cv\n'), ((975, 1010), 'cv2.cvtColor', 'cv.cvtColor', (['src', 'cv.COLOR_BGR2GRAY'], {}), '(src, cv.COLOR_BGR2GRAY)\n', (986, 1010), True, 'import cv2 as cv\n'), ((1068, 1086), 'numpy.ones', 'np.ones', (['src.shape'], {}), '(src.shape)\n', (1075, 1086), True, 'import numpy as np\n'), ((1241, 1258), 'cv2.minMaxLoc', 'cv.minMaxLoc', (['dst'], {}), '(dst)\n', (1253, 1258), True, 'import cv2 as cv\n'), ((1305, 1336), 'cv2.GaussianBlur', 'cv.GaussianBlur', (['dst', '(5, 5)', '(3)'], {}), '(dst, (5, 5), 3)\n', (1320, 1336), True, 'import cv2 as cv\n'), ((1348, 1433), 'cv2.normalize', 'cv.normalize', (['dst'], {'dst': 'mask', 'alpha': 'minVal', 'beta': 'maxVal', 'norm_type': 'cv.NORM_MINMAX'}), '(dst, dst=mask, alpha=minVal, beta=maxVal, norm_type=cv.NORM_MINMAX\n )\n', (1360, 1433), True, 'import cv2 as cv\n'), ((1492, 1537), 'cv2.threshold', 'cv.threshold', (['dst', '(100)', '(255)', 'cv.THRESH_BINARY'], {}), '(dst, 100, 255, cv.THRESH_BINARY)\n', (1504, 1537), True, 'import cv2 as cv\n'), ((1679, 1772), 'cv2.adaptiveThreshold', 'cv.adaptiveThreshold', (['dst', '(255)', 'cv.ADAPTIVE_THRESH_GAUSSIAN_C', 'cv.THRESH_BINARY', '(101)', '(-1)'], {}), '(dst, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.\n THRESH_BINARY, 101, -1)\n', (1699, 1772), True, 'import cv2 as cv\n'), ((1840, 1862), 'cv2.add', 'cv.add', (['dst', 'threshold'], {}), '(dst, threshold)\n', (1846, 1862), True, 'import cv2 as cv\n'), ((1925, 1947), 'cv2.medianBlur', 'cv.medianBlur', (['dst', '(13)'], {}), '(dst, 13)\n', (1938, 1947), True, 'import cv2 as cv\n'), ((1994, 2041), 'cv2.getStructuringElement', 'cv.getStructuringElement', (['cv.MORPH_RECT', '(3, 3)'], {}), '(cv.MORPH_RECT, (3, 3))\n', (2018, 2041), True, 'import cv2 as cv\n'), ((2053, 2103), 'cv2.morphologyEx', 'cv.morphologyEx', (['dst', 'cv.MORPH_OPEN'], {'kernel': 'kernel'}), '(dst, cv.MORPH_OPEN, kernel=kernel)\n', (2068, 2103), True, 'import cv2 as cv\n'), ((2154, 2189), 'cv2.filter2D', 'cv.filter2D', (['dst', '(-1)'], {'kernel': 'kernel'}), '(dst, -1, kernel=kernel)\n', (2165, 2189), True, 'import cv2 as cv\n'), ((3973, 4002), 'cv2.add', 'cv.add', (['hough_img', 'houghP_img'], {}), '(hough_img, houghP_img)\n', (3979, 4002), True, 'import cv2 as cv\n'), ((4098, 4112), 'cv2.waitKey', 'cv.waitKey', (['(50)'], {}), '(50)\n', (4108, 4112), True, 'import cv2 as cv\n'), ((331, 383), 'cv2.getStructuringElement', 'cv.getStructuringElement', (['cv.MORPH_RECT', '(1, dilate)'], {}), '(cv.MORPH_RECT, (1, dilate))\n', (355, 383), True, 'import cv2 as cv\n'), ((399, 422), 'cv2.dilate', 'cv.dilate', (['dst', 'kerneld'], {}), '(dst, kerneld)\n', (408, 422), True, 'import cv2 as cv\n'), ((442, 493), 'cv2.getStructuringElement', 'cv.getStructuringElement', (['cv.MORPH_RECT', '(erode, 1)'], {}), '(cv.MORPH_RECT, (erode, 1))\n', (466, 493), True, 'import cv2 as cv\n'), ((509, 531), 'cv2.erode', 'cv.erode', (['dst', 'kernele'], {}), '(dst, kernele)\n', (517, 531), True, 'import cv2 as cv\n'), ((758, 772), 'cv2.add', 'cv.add', (['m', 'dst'], {}), '(m, dst)\n', (764, 772), True, 'import cv2 as cv\n'), ((2410, 2433), 'cv2.Canny', 'cv.Canny', (['dst', '(10)', '(1000)'], {}), '(dst, 10, 1000)\n', (2418, 2433), True, 'import cv2 as cv\n'), ((2484, 2596), 'cv2.HoughLinesP', 'cv.HoughLinesP', (['edges', '(0.6)', '(np.pi / 180)'], {'threshold': 'minLineLength', 'minLineLength': 'minLineLength', 'maxLineGap': '(10)'}), '(edges, 0.6, np.pi / 180, threshold=minLineLength,\n minLineLength=minLineLength, maxLineGap=10)\n', (2498, 2596), True, 'import cv2 as cv\n'), ((2926, 2974), 'cv2.getStructuringElement', 'cv.getStructuringElement', (['cv.MORPH_RECT', '(20, 1)'], {}), '(cv.MORPH_RECT, (20, 1))\n', (2950, 2974), True, 'import cv2 as cv\n'), ((2990, 3013), 'cv2.dilate', 'cv.dilate', (['dst', 'kerneld'], {}), '(dst, kerneld)\n', (2999, 3013), True, 'import cv2 as cv\n'), ((3057, 3080), 'cv2.Canny', 'cv.Canny', (['dst', '(10)', '(1000)'], {}), '(dst, 10, 1000)\n', (3065, 3080), True, 'import cv2 as cv\n'), ((3098, 3136), 'cv2.HoughLines', 'cv.HoughLines', (['res', '(1)', '(np.pi / 180)', '(50)'], {}), '(res, 1, np.pi / 180, 50)\n', (3111, 3136), True, 'import cv2 as cv\n'), ((3786, 3838), 'numpy.zeros', 'np.zeros', (['[src.shape[0], src.shape[1], 3]', 'src.dtype'], {}), '([src.shape[0], src.shape[1], 3], src.dtype)\n', (3794, 3838), True, 'import numpy as np\n'), ((3882, 3934), 'numpy.zeros', 'np.zeros', (['[src.shape[0], src.shape[1], 3]', 'src.dtype'], {}), '([src.shape[0], src.shape[1], 3], src.dtype)\n', (3890, 3934), True, 'import numpy as np\n'), ((2689, 2744), 'cv2.line', 'cv.line', (['background', '(x1, y1)', '(x2, y2)', '(0, 255, 0)', '(2)'], {}), '(background, (x1, y1), (x2, y2), (0, 255, 0), 2)\n', (2696, 2744), True, 'import cv2 as cv\n'), ((3672, 3721), 'cv2.line', 'cv.line', (['background', 'pt1', 'pt2', '(255, 255, 255)', '(2)'], {}), '(background, pt1, pt2, (255, 255, 255), 2)\n', (3679, 3721), True, 'import cv2 as cv\n'), ((3391, 3404), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (3397, 3404), True, 'import numpy as np\n'), ((3537, 3550), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (3543, 3550), True, 'import numpy as np\n'), ((3520, 3533), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (3526, 3533), True, 'import numpy as np\n')] |
import pyk4a
from pyk4a import Config, PyK4A, ColorResolution
import cv2
import numpy as np
k4a = PyK4A(Config(color_resolution=ColorResolution.RES_720P,
depth_mode=pyk4a.DepthMode.NFOV_UNBINNED,
synchronized_images_only=True, ))
k4a.connect()
# getters and setters directly get and set on device
k4a.whitebalance = 4500
assert k4a.whitebalance == 4500
k4a.whitebalance = 4510
assert k4a.whitebalance == 4510
while 1:
img_color = k4a.get_capture(color_only=True)
# img_color, img_depth = k4a.get_capture() # Would also fetch the depth image
if np.any(img_color):
cv2.imshow('k4a', img_color[:, :, :3])
key = cv2.waitKey(10)
if key != -1:
cv2.destroyAllWindows()
break
k4a.disconnect()
| [
"pyk4a.Config",
"numpy.any",
"cv2.imshow",
"cv2.destroyAllWindows",
"cv2.waitKey"
] | [((106, 233), 'pyk4a.Config', 'Config', ([], {'color_resolution': 'ColorResolution.RES_720P', 'depth_mode': 'pyk4a.DepthMode.NFOV_UNBINNED', 'synchronized_images_only': '(True)'}), '(color_resolution=ColorResolution.RES_720P, depth_mode=pyk4a.\n DepthMode.NFOV_UNBINNED, synchronized_images_only=True)\n', (112, 233), False, 'from pyk4a import Config, PyK4A, ColorResolution\n'), ((599, 616), 'numpy.any', 'np.any', (['img_color'], {}), '(img_color)\n', (605, 616), True, 'import numpy as np\n'), ((626, 664), 'cv2.imshow', 'cv2.imshow', (['"""k4a"""', 'img_color[:, :, :3]'], {}), "('k4a', img_color[:, :, :3])\n", (636, 664), False, 'import cv2\n'), ((679, 694), 'cv2.waitKey', 'cv2.waitKey', (['(10)'], {}), '(10)\n', (690, 694), False, 'import cv2\n'), ((729, 752), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (750, 752), False, 'import cv2\n')] |
# Copyright 2019 <NAME> and <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
################# LIBRARIES ###############################
import warnings
warnings.filterwarnings("ignore")
import numpy as np, os, sys, pandas as pd, csv, copy
import torch, torch.nn as nn, matplotlib.pyplot as plt, random
from torch.utils.data import Dataset
from PIL import Image
from torchvision import transforms
from tqdm import tqdm
import pretrainedmodels.utils as utils
import auxiliaries as aux
"""============================================================================"""
################ FUNCTION TO RETURN ALL DATALOADERS NECESSARY ####################
def give_dataloaders(dataset, opt):
"""
Args:
dataset: string, name of dataset for which the dataloaders should be returned.
opt: argparse.Namespace, contains all training-specific parameters.
Returns:
dataloaders: dict of dataloaders for training, testing and evaluation on training.
"""
#Dataset selection
if opt.dataset=='cub200':
datasets = give_CUB200_datasets(opt)
elif opt.dataset=='cars196':
datasets = give_CARS196_datasets(opt)
elif opt.dataset=='online_products':
datasets = give_OnlineProducts_datasets(opt)
elif opt.dataset=='in-shop':
datasets = give_InShop_datasets(opt)
elif opt.dataset=='vehicle_id':
datasets = give_VehicleID_datasets(opt)
else:
raise Exception('No Dataset >{}< available!'.format(dataset))
#Move datasets to dataloaders.
dataloaders = {}
for key,dataset in datasets.items():
is_val = dataset.is_validation
dataloaders[key] = torch.utils.data.DataLoader(dataset, batch_size=opt.bs, num_workers=opt.kernels, shuffle=not is_val, pin_memory=True, drop_last=not is_val)
return dataloaders
"""============================================================================"""
################# FUNCTIONS TO RETURN TRAIN/VAL PYTORCH DATASETS FOR CUB200, CARS196, STANFORD ONLINE PRODUCTS, IN-SHOP CLOTHES, PKU VEHICLE-ID ####################################
def give_CUB200_datasets(opt):
"""
This function generates a training, testing and evaluation dataloader for Metric Learning on the CUB-200-2011 dataset.
For Metric Learning, the dataset classes are sorted by name, and the first half used for training while the last half is used for testing.
So no random shuffling of classes.
Args:
opt: argparse.Namespace, contains all traininig-specific parameters.
Returns:
dict of PyTorch datasets for training, testing and evaluation.
"""
image_sourcepath = opt.source_path+'/images'
#Find available data classes.
image_classes = sorted([x for x in os.listdir(image_sourcepath) if '._' not in x], key=lambda x: int(x.split('.')[0]))
#Make a index-to-labelname conversion dict.
conversion = {int(x.split('.')[0]):x.split('.')[-1] for x in image_classes}
#Generate a list of tuples (class_label, image_path)
image_list = {int(key.split('.')[0]):sorted([image_sourcepath+'/'+key+'/'+x for x in os.listdir(image_sourcepath+'/'+key) if '._' not in x]) for key in image_classes}
image_list = [[(key,img_path) for img_path in image_list[key]] for key in image_list.keys()]
image_list = [x for y in image_list for x in y]
#Image-dict of shape {class_idx:[list of paths to images belong to this class] ...}
image_dict = {}
for key, img_path in image_list:
key = key-1
if not key in image_dict.keys():
image_dict[key] = []
image_dict[key].append(img_path)
keys = sorted(list(image_dict.keys()))
#Following "Deep Metric Learning via Lifted Structured Feature Embedding", we use the first half of classes for training.
train,test = keys[:len(keys)//2], keys[len(keys)//2:]
train_image_dict, val_image_dict = {key:image_dict[key] for key in train},{key:image_dict[key] for key in test}
train_dataset = BaseTripletDataset(train_image_dict, opt, samples_per_class=opt.samples_per_class)
val_dataset = BaseTripletDataset(val_image_dict, opt, is_validation=True)
eval_dataset = BaseTripletDataset(train_image_dict, opt, is_validation=True)
train_dataset.conversion = conversion
val_dataset.conversion = conversion
eval_dataset.conversion = conversion
return {'training':train_dataset, 'testing':val_dataset, 'evaluation':eval_dataset}
def give_CARS196_datasets(opt):
"""
This function generates a training, testing and evaluation dataloader for Metric Learning on the CARS196 dataset.
For Metric Learning, the dataset classes are sorted by name, and the first half used for training while the last half is used for testing.
So no random shuffling of classes.
Args:
opt: argparse.Namespace, contains all traininig-specific parameters.
Returns:
dict of PyTorch datasets for training, testing and evaluation.
"""
image_sourcepath = opt.source_path+'/images'
#Find available data classes.
image_classes = sorted([x for x in os.listdir(image_sourcepath)])
#Make a index-to-labelname conversion dict.
conversion = {i:x for i,x in enumerate(image_classes)}
#Generate a list of tuples (class_label, image_path)
image_list = {i:sorted([image_sourcepath+'/'+key+'/'+x for x in os.listdir(image_sourcepath+'/'+key)]) for i,key in enumerate(image_classes)}
image_list = [[(key,img_path) for img_path in image_list[key]] for key in image_list.keys()]
image_list = [x for y in image_list for x in y]
#Image-dict of shape {class_idx:[list of paths to images belong to this class] ...}
image_dict = {}
for key, img_path in image_list:
key = key
# key = key-1
if not key in image_dict.keys():
image_dict[key] = []
image_dict[key].append(img_path)
keys = sorted(list(image_dict.keys()))
#Following "Deep Metric Learning via Lifted Structured Feature Embedding", we use the first half of classes for training.
train,test = keys[:len(keys)//2], keys[len(keys)//2:]
train_image_dict, val_image_dict = {key:image_dict[key] for key in train},{key:image_dict[key] for key in test}
train_dataset = BaseTripletDataset(train_image_dict, opt, samples_per_class=opt.samples_per_class)
val_dataset = BaseTripletDataset(val_image_dict, opt, is_validation=True)
eval_dataset = BaseTripletDataset(train_image_dict, opt, is_validation=True)
train_dataset.conversion = conversion
val_dataset.conversion = conversion
eval_dataset.conversion = conversion
return {'training':train_dataset, 'testing':val_dataset, 'evaluation':eval_dataset}
def give_OnlineProducts_datasets(opt):
"""
This function generates a training, testing and evaluation dataloader for Metric Learning on the Online-Products dataset.
For Metric Learning, training and test sets are provided by given text-files, Ebay_train.txt & Ebay_test.txt.
So no random shuffling of classes.
Args:
opt: argparse.Namespace, contains all traininig-specific parameters.
Returns:
dict of PyTorch datasets for training, testing and evaluation.
"""
image_sourcepath = opt.source_path+'/images'
#Load text-files containing classes and imagepaths.
training_files = pd.read_table(opt.source_path+'/Info_Files/Ebay_train.txt', header=0, delimiter=' ')
test_files = pd.read_table(opt.source_path+'/Info_Files/Ebay_test.txt', header=0, delimiter=' ')
#Generate Conversion dict.
conversion = {}
for class_id, path in zip(training_files['class_id'],training_files['path']):
conversion[class_id] = path.split('/')[0]
for class_id, path in zip(test_files['class_id'],test_files['path']):
conversion[class_id] = path.split('/')[0]
#Generate image_dicts of shape {class_idx:[list of paths to images belong to this class] ...}
train_image_dict, val_image_dict = {},{}
for key, img_path in zip(training_files['class_id'],training_files['path']):
key = key-1
if not key in train_image_dict.keys():
train_image_dict[key] = []
train_image_dict[key].append(image_sourcepath+'/'+img_path)
for key, img_path in zip(test_files['class_id'],test_files['path']):
key = key-1
if not key in val_image_dict.keys():
val_image_dict[key] = []
val_image_dict[key].append(image_sourcepath+'/'+img_path)
### Uncomment this if super-labels should be used to generate resp.datasets
# super_conversion = {}
# for super_class_id, path in zip(training_files['super_class_id'],training_files['path']):
# conversion[super_class_id] = path.split('/')[0]
# for key, img_path in zip(training_files['super_class_id'],training_files['path']):
# key = key-1
# if not key in super_train_image_dict.keys():
# super_train_image_dict[key] = []
# super_train_image_dict[key].append(image_sourcepath+'/'+img_path)
# super_train_dataset = BaseTripletDataset(super_train_image_dict, opt, is_validation=True)
# super_train_dataset.conversion = super_conversion
train_dataset = BaseTripletDataset(train_image_dict, opt, samples_per_class=opt.samples_per_class)
val_dataset = BaseTripletDataset(val_image_dict, opt, is_validation=True)
eval_dataset = BaseTripletDataset(train_image_dict, opt, is_validation=True)
train_dataset.conversion = conversion
val_dataset.conversion = conversion
eval_dataset.conversion = conversion
return {'training':train_dataset, 'testing':val_dataset, 'evaluation':eval_dataset}
# return {'training':train_dataset, 'testing':val_dataset, 'evaluation':eval_dataset, 'super_evaluation':super_train_dataset}
def give_InShop_datasets(opt):
"""
This function generates a training, testing and evaluation dataloader for Metric Learning on the In-Shop Clothes dataset.
For Metric Learning, training and test sets are provided by one text file, list_eval_partition.txt.
So no random shuffling of classes.
Args:
opt: argparse.Namespace, contains all traininig-specific parameters.
Returns:
dict of PyTorch datasets for training, testing (by query and gallery separation) and evaluation.
"""
#Load train-test-partition text file.
data_info = np.array(pd.read_table(opt.source_path+'/Eval/list_eval_partition.txt', header=1, delim_whitespace=True))[1:,:]
#Separate into training dataset and query/gallery dataset for testing.
train, query, gallery = data_info[data_info[:,2]=='train'][:,:2], data_info[data_info[:,2]=='query'][:,:2], data_info[data_info[:,2]=='gallery'][:,:2]
#Generate conversions(id verson)
# use_train_image_num = 10000
# use_val_image_num = int(use_train_image_num/3)
# np.random.seed(0)
# train_idx = np.random.choice(len(train), size=use_train_image_num, replace = False)
# train = train[train_idx]
# query_idx = np.random.choice(len(query), size=use_val_image_num, replace = False)
# query = query[query_idx]
# gallery_idx = np.random.choice(len(gallery), size=use_val_image_num, replace = False)
# gallery = gallery[gallery_idx]
#Generate conversions
lab_conv = {x:i for i,x in enumerate(np.unique(np.array([int(x.split('_')[-1]) for x in train[:,1]])))}
train[:,1] = np.array([lab_conv[int(x.split('_')[-1])] for x in train[:,1]])
lab_conv = {x:i for i,x in enumerate(np.unique(np.array([int(x.split('_')[-1]) for x in np.concatenate([query[:,1], gallery[:,1]])])))}
query[:,1] = np.array([lab_conv[int(x.split('_')[-1])] for x in query[:,1]])
gallery[:,1] = np.array([lab_conv[int(x.split('_')[-1])] for x in gallery[:,1]])
#Generate Image-Dicts for training, query and gallery of shape {class_idx:[list of paths to images belong to this class] ...}
train_image_dict = {}
for img_path, key in train:
if not key in train_image_dict.keys():
train_image_dict[key] = []
train_image_dict[key].append(opt.source_path+'/'+img_path)
query_image_dict = {}
for img_path, key in query:
if not key in query_image_dict.keys():
query_image_dict[key] = []
query_image_dict[key].append(opt.source_path+'/'+img_path)
gallery_image_dict = {}
for img_path, key in gallery:
if not key in gallery_image_dict.keys():
gallery_image_dict[key] = []
gallery_image_dict[key].append(opt.source_path+'/'+img_path)
### Uncomment this if super-labels should be used to generate resp.datasets
# super_train_image_dict, counter, super_assign = {},0,{}
# for img_path, _ in train:
# key = '_'.join(img_path.split('/')[1:3])
# if key not in super_assign.keys():
# super_assign[key] = counter
# counter += 1
# key = super_assign[key]
#
# if not key in super_train_image_dict.keys():
# super_train_image_dict[key] = []
# super_train_image_dict[key].append(opt.source_path+'/'+img_path)
# super_train_dataset = BaseTripletDataset(super_train_image_dict, opt, is_validation=True)
train_dataset = BaseTripletDataset(train_image_dict, opt, samples_per_class=opt.samples_per_class)
eval_dataset = BaseTripletDataset(train_image_dict, opt, is_validation=True)
query_dataset = BaseTripletDataset(query_image_dict, opt, is_validation=True)
gallery_dataset = BaseTripletDataset(gallery_image_dict, opt, is_validation=True)
return {'training':train_dataset, 'testing_query':query_dataset, 'evaluation':eval_dataset, 'testing_gallery':gallery_dataset}
# return {'training':train_dataset, 'testing_query':query_dataset, 'evaluation':eval_dataset, 'testing_gallery':gallery_dataset, 'super_evaluation':super_train_dataset}
def give_VehicleID_datasets(opt):
"""
This function generates a training, testing and evaluation dataloader for Metric Learning on the PKU Vehicle dataset.
For Metric Learning, training and (multiple) test sets are provided by separate text files, train_list and test_list_<n_classes_2_test>.txt.
So no random shuffling of classes.
Args:
opt: argparse.Namespace, contains all traininig-specific parameters.
Returns:
dict of PyTorch datasets for training, testing and evaluation.
"""
#Load respective text-files
train = np.array(pd.read_table(opt.source_path+'/train_test_split/train_list.txt', header=None, delim_whitespace=True))
small_test = np.array(pd.read_table(opt.source_path+'/train_test_split/test_list_800.txt', header=None, delim_whitespace=True))
medium_test = np.array(pd.read_table(opt.source_path+'/train_test_split/test_list_1600.txt', header=None, delim_whitespace=True))
big_test = np.array(pd.read_table(opt.source_path+'/train_test_split/test_list_2400.txt', header=None, delim_whitespace=True))
#Generate conversions
lab_conv = {x:i for i,x in enumerate(np.unique(train[:,1]))}
train[:,1] = np.array([lab_conv[x] for x in train[:,1]])
lab_conv = {x:i for i,x in enumerate(np.unique(np.concatenate([small_test[:,1], medium_test[:,1], big_test[:,1]])))}
small_test[:,1] = np.array([lab_conv[x] for x in small_test[:,1]])
medium_test[:,1] = np.array([lab_conv[x] for x in medium_test[:,1]])
big_test[:,1] = np.array([lab_conv[x] for x in big_test[:,1]])
#Generate Image-Dicts for training and different testings of shape {class_idx:[list of paths to images belong to this class] ...}
train_image_dict = {}
for img_path, key in train:
if not key in train_image_dict.keys():
train_image_dict[key] = []
train_image_dict[key].append(opt.source_path+'/image/{:07d}.jpg'.format(img_path))
small_test_dict = {}
for img_path, key in small_test:
if not key in small_test_dict.keys():
small_test_dict[key] = []
small_test_dict[key].append(opt.source_path+'/image/{:07d}.jpg'.format(img_path))
medium_test_dict = {}
for img_path, key in medium_test:
if not key in medium_test_dict.keys():
medium_test_dict[key] = []
medium_test_dict[key].append(opt.source_path+'/image/{:07d}.jpg'.format(img_path))
big_test_dict = {}
for img_path, key in big_test:
if not key in big_test_dict.keys():
big_test_dict[key] = []
big_test_dict[key].append(opt.source_path+'/image/{:07d}.jpg'.format(img_path))
train_dataset = BaseTripletDataset(train_image_dict, opt, samples_per_class=opt.samples_per_class)
eval_dataset = BaseTripletDataset(train_image_dict, opt, is_validation=True)
val_small_dataset = BaseTripletDataset(small_test_dict, opt, is_validation=True)
val_medium_dataset = BaseTripletDataset(medium_test_dict, opt, is_validation=True)
val_big_dataset = BaseTripletDataset(big_test_dict, opt, is_validation=True)
return {'training':train_dataset, 'testing_set1':val_small_dataset, 'testing_set2':val_medium_dataset, \
'testing_set3':val_big_dataset, 'evaluation':eval_dataset}
################## BASIC PYTORCH DATASET USED FOR ALL DATASETS ##################################
class BaseTripletDataset(Dataset):
"""
Dataset class to provide (augmented) correctly prepared training samples corresponding to standard DML literature.
This includes normalizing to ImageNet-standards, and Random & Resized cropping of shapes 224 for ResNet50 and 227 for
GoogLeNet during Training. During validation, only resizing to 256 or center cropping to 224/227 is performed.
"""
def __init__(self, image_dict, opt, samples_per_class=8, is_validation=False):
"""
Dataset Init-Function.
Args:
image_dict: dict, Dictionary of shape {class_idx:[list of paths to images belong to this class] ...} providing all the training paths and classes.
opt: argparse.Namespace, contains all training-specific parameters.
samples_per_class: Number of samples to draw from one class before moving to the next when filling the batch.
is_validation: If is true, dataset properties for validation/testing are used instead of ones for training.
Returns:
Nothing!
"""
#Define length of dataset
self.n_files = np.sum([len(image_dict[key]) for key in image_dict.keys()])
self.is_validation = is_validation
self.pars = opt
self.image_dict = image_dict
self.avail_classes = sorted(list(self.image_dict.keys()))
#Convert image dictionary from classname:content to class_idx:content, because the initial indices are not necessarily from 0 - <n_classes>.
self.image_dict = {i:self.image_dict[key] for i,key in enumerate(self.avail_classes)}
self.avail_classes = sorted(list(self.image_dict.keys()))
#Init. properties that are used when filling up batches.
if not self.is_validation:
self.samples_per_class = samples_per_class
#Select current class to sample images from up to <samples_per_class>
self.current_class = np.random.randint(len(self.avail_classes))
self.classes_visited = [self.current_class, self.current_class]
self.n_samples_drawn = 0
#Data augmentation/processing methods.
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])
transf_list = []
if not self.is_validation:
transf_list.extend([transforms.RandomResizedCrop(size=224) if opt.arch=='resnet50' else transforms.RandomResizedCrop(size=227),
transforms.RandomHorizontalFlip(0.5)])
else:
transf_list.extend([transforms.Resize(256),
transforms.CenterCrop(224) if opt.arch=='resnet50' else transforms.CenterCrop(227)])
transf_list.extend([transforms.ToTensor(), normalize])
self.transform = transforms.Compose(transf_list)
#Convert Image-Dict to list of (image_path, image_class). Allows for easier direct sampling.
self.image_list = [[(x,key) for x in self.image_dict[key]] for key in self.image_dict.keys()]
self.image_list = [x for y in self.image_list for x in y]
#Flag that denotes if dataset is called for the first time.
self.is_init = True
def ensure_3dim(self, img):
"""
Function that ensures that the input img is three-dimensional.
Args:
img: PIL.Image, image which is to be checked for three-dimensionality (i.e. if some images are black-and-white in an otherwise coloured dataset).
Returns:
Checked PIL.Image img.
"""
if len(img.size)==2:
img = img.convert('RGB')
return img
def __getitem__(self, idx):
"""
Args:
idx: Sample idx for training sample
Returns:
tuple of form (sample_class, torch.Tensor() of input image)
"""
if self.is_init:
self.current_class = self.avail_classes[idx%len(self.avail_classes)]
self.is_init = False
if not self.is_validation:
if self.samples_per_class==1:
return self.image_list[idx][-1], self.transform(self.ensure_3dim(Image.open(self.image_list[idx][0])))
if self.n_samples_drawn==self.samples_per_class:
#Once enough samples per class have been drawn, we choose another class to draw samples from.
#Note that we ensure with self.classes_visited that no class is chosen if it had been chosen
#previously or one before that.
counter = copy.deepcopy(self.avail_classes)
for prev_class in self.classes_visited:
if prev_class in counter: counter.remove(prev_class)
self.current_class = counter[idx%len(counter)]
self.classes_visited = self.classes_visited[1:]+[self.current_class]
self.n_samples_drawn = 0
class_sample_idx = idx%len(self.image_dict[self.current_class])
self.n_samples_drawn += 1
out_img = self.transform(self.ensure_3dim(Image.open(self.image_dict[self.current_class][class_sample_idx])))
return self.current_class,out_img
else:
return self.image_list[idx][-1], self.transform(self.ensure_3dim(Image.open(self.image_list[idx][0])))
def __len__(self):
return self.n_files
| [
"torchvision.transforms.Compose",
"torchvision.transforms.CenterCrop",
"os.listdir",
"copy.deepcopy",
"numpy.unique",
"PIL.Image.open",
"torch.utils.data.DataLoader",
"torchvision.transforms.RandomResizedCrop",
"torchvision.transforms.Resize",
"torchvision.transforms.RandomHorizontalFlip",
"nump... | [((739, 772), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (762, 772), False, 'import warnings\n'), ((7958, 8048), 'pandas.read_table', 'pd.read_table', (["(opt.source_path + '/Info_Files/Ebay_train.txt')"], {'header': '(0)', 'delimiter': '""" """'}), "(opt.source_path + '/Info_Files/Ebay_train.txt', header=0,\n delimiter=' ')\n", (7971, 8048), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((8064, 8153), 'pandas.read_table', 'pd.read_table', (["(opt.source_path + '/Info_Files/Ebay_test.txt')"], {'header': '(0)', 'delimiter': '""" """'}), "(opt.source_path + '/Info_Files/Ebay_test.txt', header=0,\n delimiter=' ')\n", (8077, 8153), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((15741, 15785), 'numpy.array', 'np.array', (['[lab_conv[x] for x in train[:, 1]]'], {}), '([lab_conv[x] for x in train[:, 1]])\n', (15749, 15785), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((15929, 15978), 'numpy.array', 'np.array', (['[lab_conv[x] for x in small_test[:, 1]]'], {}), '([lab_conv[x] for x in small_test[:, 1]])\n', (15937, 15978), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((16001, 16051), 'numpy.array', 'np.array', (['[lab_conv[x] for x in medium_test[:, 1]]'], {}), '([lab_conv[x] for x in medium_test[:, 1]])\n', (16009, 16051), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((16074, 16121), 'numpy.array', 'np.array', (['[lab_conv[x] for x in big_test[:, 1]]'], {}), '([lab_conv[x] for x in big_test[:, 1]])\n', (16082, 16121), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((2251, 2395), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'opt.bs', 'num_workers': 'opt.kernels', 'shuffle': '(not is_val)', 'pin_memory': '(True)', 'drop_last': '(not is_val)'}), '(dataset, batch_size=opt.bs, num_workers=opt.\n kernels, shuffle=not is_val, pin_memory=True, drop_last=not is_val)\n', (2278, 2395), False, 'import torch, torch.nn as nn, matplotlib.pyplot as plt, random\n'), ((15128, 15236), 'pandas.read_table', 'pd.read_table', (["(opt.source_path + '/train_test_split/train_list.txt')"], {'header': 'None', 'delim_whitespace': '(True)'}), "(opt.source_path + '/train_test_split/train_list.txt', header=\n None, delim_whitespace=True)\n", (15141, 15236), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((15258, 15368), 'pandas.read_table', 'pd.read_table', (["(opt.source_path + '/train_test_split/test_list_800.txt')"], {'header': 'None', 'delim_whitespace': '(True)'}), "(opt.source_path + '/train_test_split/test_list_800.txt',\n header=None, delim_whitespace=True)\n", (15271, 15368), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((15391, 15502), 'pandas.read_table', 'pd.read_table', (["(opt.source_path + '/train_test_split/test_list_1600.txt')"], {'header': 'None', 'delim_whitespace': '(True)'}), "(opt.source_path + '/train_test_split/test_list_1600.txt',\n header=None, delim_whitespace=True)\n", (15404, 15502), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((15525, 15636), 'pandas.read_table', 'pd.read_table', (["(opt.source_path + '/train_test_split/test_list_2400.txt')"], {'header': 'None', 'delim_whitespace': '(True)'}), "(opt.source_path + '/train_test_split/test_list_2400.txt',\n header=None, delim_whitespace=True)\n", (15538, 15636), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((20172, 20247), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (20192, 20247), False, 'from torchvision import transforms\n'), ((20794, 20825), 'torchvision.transforms.Compose', 'transforms.Compose', (['transf_list'], {}), '(transf_list)\n', (20812, 20825), False, 'from torchvision import transforms\n'), ((11044, 11145), 'pandas.read_table', 'pd.read_table', (["(opt.source_path + '/Eval/list_eval_partition.txt')"], {'header': '(1)', 'delim_whitespace': '(True)'}), "(opt.source_path + '/Eval/list_eval_partition.txt', header=1,\n delim_whitespace=True)\n", (11057, 11145), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((3328, 3356), 'os.listdir', 'os.listdir', (['image_sourcepath'], {}), '(image_sourcepath)\n', (3338, 3356), False, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((5688, 5716), 'os.listdir', 'os.listdir', (['image_sourcepath'], {}), '(image_sourcepath)\n', (5698, 5716), False, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((15700, 15722), 'numpy.unique', 'np.unique', (['train[:, 1]'], {}), '(train[:, 1])\n', (15709, 15722), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((20734, 20755), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (20753, 20755), False, 'from torchvision import transforms\n'), ((22532, 22565), 'copy.deepcopy', 'copy.deepcopy', (['self.avail_classes'], {}), '(self.avail_classes)\n', (22545, 22565), False, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((3692, 3732), 'os.listdir', 'os.listdir', (["(image_sourcepath + '/' + key)"], {}), "(image_sourcepath + '/' + key)\n", (3702, 3732), False, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((5957, 5997), 'os.listdir', 'os.listdir', (["(image_sourcepath + '/' + key)"], {}), "(image_sourcepath + '/' + key)\n", (5967, 5997), False, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((15836, 15905), 'numpy.concatenate', 'np.concatenate', (['[small_test[:, 1], medium_test[:, 1], big_test[:, 1]]'], {}), '([small_test[:, 1], medium_test[:, 1], big_test[:, 1]])\n', (15850, 15905), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((20479, 20515), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', (['(0.5)'], {}), '(0.5)\n', (20510, 20515), False, 'from torchvision import transforms\n'), ((20564, 20586), 'torchvision.transforms.Resize', 'transforms.Resize', (['(256)'], {}), '(256)\n', (20581, 20586), False, 'from torchvision import transforms\n'), ((23057, 23122), 'PIL.Image.open', 'Image.open', (['self.image_dict[self.current_class][class_sample_idx]'], {}), '(self.image_dict[self.current_class][class_sample_idx])\n', (23067, 23122), False, 'from PIL import Image\n'), ((20339, 20377), 'torchvision.transforms.RandomResizedCrop', 'transforms.RandomResizedCrop', ([], {'size': '(224)'}), '(size=224)\n', (20367, 20377), False, 'from torchvision import transforms\n'), ((20407, 20445), 'torchvision.transforms.RandomResizedCrop', 'transforms.RandomResizedCrop', ([], {'size': '(227)'}), '(size=227)\n', (20435, 20445), False, 'from torchvision import transforms\n'), ((20620, 20646), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (20641, 20646), False, 'from torchvision import transforms\n'), ((20676, 20702), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(227)'], {}), '(227)\n', (20697, 20702), False, 'from torchvision import transforms\n'), ((23262, 23297), 'PIL.Image.open', 'Image.open', (['self.image_list[idx][0]'], {}), '(self.image_list[idx][0])\n', (23272, 23297), False, 'from PIL import Image\n'), ((22139, 22174), 'PIL.Image.open', 'Image.open', (['self.image_list[idx][0]'], {}), '(self.image_list[idx][0])\n', (22149, 22174), False, 'from PIL import Image\n'), ((12206, 12250), 'numpy.concatenate', 'np.concatenate', (['[query[:, 1], gallery[:, 1]]'], {}), '([query[:, 1], gallery[:, 1]])\n', (12220, 12250), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n')] |
"""
Copyright 2020, <NAME>, <EMAIL>, All rights reserved.
Borrowed from https://github.com/sidhantagar/ConnectX under the MIT license.
"""
import numpy as np
import random
max_score = None
def score_move_a(grid, col, mark, config, start_score, n_steps=1):
global max_score
next_grid, pos = drop_piece(grid, col, mark, config)
row, col = pos
score = get_heuristic_optimised(grid,next_grid,mark,config, row, col,start_score)
valid_moves = [col for col in range (config.columns) if next_grid[0][col]==0]
#Since we have just dropped our piece there is only the possibility of us getting 4 in a row and not the opponent.
#Thus score can only be +infinity.
scores = []
if len(valid_moves)==0 or n_steps ==0 or score == float("inf"):
return score
else :
for col in valid_moves:
current = score_move_b(next_grid,col,mark,config,n_steps-1,score)
scores.append(current)
if max_score != None:
if current < max_score:
break
score = min(scores)
#print (scores)
return score
def score_move_b(grid, col, mark, config,n_steps, start_score):
next_grid, pos = drop_piece(grid,col,(mark%2)+1,config)
row, col = pos
score = get_heuristic_optimised(grid,next_grid,mark,config, row, col,start_score)
valid_moves = [col for col in range (config.columns) if next_grid[0][col]==0]
#The converse is true here.
#Since we have just dropped opponent piece there is only the possibility of opponent getting 4 in a row and not us.
#Thus score can only be -infinity.
if len(valid_moves)==0 or n_steps ==0 or score == float ("-inf"):
return score
else :
scores = [score_move_a(next_grid,col,mark,config,n_steps-1) for col in valid_moves]
score = max(scores)
return score
def drop_piece(grid, col, mark, config):
next_grid = grid.copy()
for row in range(config.rows-1, -1, -1):
if next_grid[row][col] == 0:
break
next_grid[row][col] = mark
return next_grid,(row,col)
def get_heuristic(grid, mark, config):
score = 0
num = count_windows(grid,mark,config)
for i in range(config.inarow):
#num = count_windows (grid,i+1,mark,config)
if (i==(config.inarow-1) and num[i+1] >= 1):
return float("inf")
score += (4**(i))*num[i+1]
num_opp = count_windows (grid,mark%2+1,config)
for i in range(config.inarow):
if (i==(config.inarow-1) and num_opp[i+1] >= 1):
return float ("-inf")
score-= (2**((2*i)+1))*num_opp[i+1]
return score
def get_heuristic_optimised(grid, next_grid, mark, config, row, col, start_score):
score = 0
num1 = count_windows_optimised(grid,mark,config,row,col)
num2 = count_windows_optimised(next_grid,mark,config,row,col)
for i in range(config.inarow):
if (i==(config.inarow-1) and (num2[i+1]-num1[i+1]) >= 1):
return float("inf")
score += (4**(i))*(num2[i+1]-num1[i+1])
num1_opp = count_windows_optimised(grid,mark%2+1,config,row,col)
num2_opp = count_windows_optimised(next_grid,mark%2+1,config,row,col)
for i in range(config.inarow):
if (i==(config.inarow-1) and num2_opp[i+1]-num1_opp[i+1] >= 1):
return float ("-inf")
score-= (2**((2*i)+1))*(num2_opp[i+1]-num1_opp[i+1])
score+= start_score
#print (num1,num2,num1_opp,num2_opp)
return score
def check_window(window, piece, config):
if window.count((piece%2)+1)==0:
return window.count(piece)
else:
return -1
def count_windows(grid, piece, config):
num_windows = np.zeros(config.inarow+1)
# horizontal
for row in range(config.rows):
for col in range(config.columns-(config.inarow-1)):
window = list(grid[row, col:col+config.inarow])
type_window = check_window(window, piece, config)
if type_window != -1:
num_windows[type_window] += 1
# vertical
for row in range(config.rows-(config.inarow-1)):
for col in range(config.columns):
window = list(grid[row:row+config.inarow, col])
type_window = check_window(window, piece, config)
if type_window != -1:
num_windows[type_window] += 1
# positive diagonal
for row in range(config.rows-(config.inarow-1)):
for col in range(config.columns-(config.inarow-1)):
window = list(grid[range(row, row+config.inarow), range(col, col+config.inarow)])
type_window = check_window(window, piece, config)
if type_window != -1:
num_windows[type_window] += 1
# negative diagonal
for row in range(config.inarow-1, config.rows):
for col in range(config.columns-(config.inarow-1)):
window = list(grid[range(row, row-config.inarow, -1), range(col, col+config.inarow)])
type_window = check_window(window, piece, config)
if type_window != -1:
num_windows[type_window] += 1
return num_windows
def count_windows_optimised(grid, piece, config, row, col):
num_windows = np.zeros(config.inarow+1)
# horizontal
for acol in range(max(0,col-(config.inarow-1)),min(col+1,(config.columns-(config.inarow-1)))):
window = list(grid[row, acol:acol+config.inarow])
type_window = check_window(window, piece, config)
if type_window != -1:
num_windows[type_window] += 1
# vertical
for arow in range(max(0,row-(config.inarow-1)),min(row+1,(config.rows-(config.inarow-1)))):
window = list(grid[arow:arow+config.inarow, col])
type_window = check_window(window, piece, config)
if type_window != -1:
num_windows[type_window] += 1
# positive diagonal
for arow, acol in zip(range(row-(config.inarow-1),row+1),range(col-(config.inarow-1),col+1)):
if (arow>=0 and acol>=0 and arow<=(config.rows-config.inarow) and acol<=(config.columns-config.inarow)):
window = list(grid[range(arow, arow+config.inarow), range(acol, acol+config.inarow)])
type_window = check_window(window, piece, config)
if type_window != -1:
num_windows[type_window] += 1
# negative diagonal
for arow,acol in zip(range(row,row+config.inarow),range(col,col-config.inarow,-1)):
if (arow >= (config.inarow-1) and acol >=0 and arow <= (config.rows-1) and acol <= (config.columns-config.inarow)):
window = list(grid[range(arow, arow-config.inarow, -1), range(acol, acol+config.inarow)])
type_window = check_window(window, piece, config)
if type_window != -1:
num_windows[type_window] += 1
return num_windows
def agent(obs, config):
global max_score
max_score = None
valid_moves = [c for c in range(config.columns) if obs.board[0][c] == 0]
grid = np.asarray(obs.board).reshape(config.rows, config.columns)
scores = {}
start_score = get_heuristic(grid, obs.mark, config)
for col in valid_moves:
scores[col] = score_move_a(grid, col, obs.mark, config,start_score,1)
if max_score == None or max_score < scores[col]:
max_score = scores[col]
print ("Optimised:",scores)
max_cols = [key for key in scores.keys() if scores[key] == max(scores.values())]
return random.choice(max_cols) | [
"numpy.zeros",
"random.choice",
"numpy.asarray"
] | [((3675, 3702), 'numpy.zeros', 'np.zeros', (['(config.inarow + 1)'], {}), '(config.inarow + 1)\n', (3683, 3702), True, 'import numpy as np\n'), ((5178, 5205), 'numpy.zeros', 'np.zeros', (['(config.inarow + 1)'], {}), '(config.inarow + 1)\n', (5186, 5205), True, 'import numpy as np\n'), ((7398, 7421), 'random.choice', 'random.choice', (['max_cols'], {}), '(max_cols)\n', (7411, 7421), False, 'import random\n'), ((6940, 6961), 'numpy.asarray', 'np.asarray', (['obs.board'], {}), '(obs.board)\n', (6950, 6961), True, 'import numpy as np\n')] |
import tensorflow as tf
import numpy as np
slim = tf.contrib.slim
# custom layers
def deconv_layer(net, up_scale, n_channel, method='transpose'):
nh = tf.shape(net)[-3] * up_scale
nw = tf.shape(net)[-2] * up_scale
if method == 'transpose':
net = slim.conv2d_transpose(net, n_channel, (up_scale, up_scale), (
up_scale, up_scale), activation_fn=None, padding='VALID')
elif method == 'transpose+conv':
net = slim.conv2d_transpose(net, n_channel, (up_scale, up_scale), (
up_scale, up_scale), activation_fn=None, padding='VALID')
net = slim.conv2d(net, n_channel, (3, 3), (1, 1))
elif method == 'transpose+conv+relu':
net = slim.conv2d_transpose(net, n_channel, (up_scale, up_scale), (
up_scale, up_scale), padding='VALID')
net = slim.conv2d(net, n_channel, (3, 3), (1, 1))
elif method == 'bilinear':
net = tf.image.resize_images(net, [nh, nw])
else:
raise Exception('Unrecognised Deconvolution Method: %s' % method)
return net
# arg scopes
def hourglass_arg_scope_torch(weight_decay=0.0001,
batch_norm_decay=0.997,
batch_norm_epsilon=1e-5,
batch_norm_scale=True):
"""Defines the default ResNet arg scope.
Args:
is_training: Whether or not we are training the parameters in the batch
normalization layers of the model.
weight_decay: The weight decay to use for regularizing the model.
batch_norm_decay: The moving average decay when estimating layer activation
statistics in batch normalization.
batch_norm_epsilon: Small constant to prevent division by zero when
normalizing activations by their variance in batch normalization.
batch_norm_scale: If True, uses an explicit `gamma` multiplier to scale the
activations in the batch normalization layer.
Returns:
An `arg_scope` to use for the resnet models.
"""
batch_norm_params = {
'decay': batch_norm_decay,
'epsilon': batch_norm_epsilon,
'scale': batch_norm_scale,
'updates_collections': tf.GraphKeys.UPDATE_OPS,
}
with slim.arg_scope(
[slim.conv2d],
weights_regularizer=slim.l2_regularizer(weight_decay),
weights_initializer=slim.variance_scaling_initializer(),
activation_fn=None,
normalizer_fn=None,
normalizer_params=None):
with slim.arg_scope([slim.batch_norm], **batch_norm_params):
with slim.arg_scope([slim.max_pool2d], padding='VALID') as arg_sc:
return arg_sc
def hourglass_arg_scope_tf(weight_decay=0.0001,
batch_norm_decay=0.997,
batch_norm_epsilon=1e-5,
batch_norm_scale=True):
"""Defines the default ResNet arg scope.
Args:
is_training: Whether or not we are training the parameters in the batch
normalization layers of the model.
weight_decay: The weight decay to use for regularizing the model.
batch_norm_decay: The moving average decay when estimating layer activation
statistics in batch normalization.
batch_norm_epsilon: Small constant to prevent division by zero when
normalizing activations by their variance in batch normalization.
batch_norm_scale: If True, uses an explicit `gamma` multiplier to scale the
activations in the batch normalization layer.
Returns:
An `arg_scope` to use for the resnet models.
"""
batch_norm_params = {
'decay': batch_norm_decay,
'epsilon': batch_norm_epsilon,
'scale': batch_norm_scale,
'updates_collections': tf.GraphKeys.UPDATE_OPS,
}
with slim.arg_scope(
[slim.conv2d],
weights_regularizer=slim.l2_regularizer(weight_decay),
weights_initializer=slim.variance_scaling_initializer(),
activation_fn=tf.nn.relu,
normalizer_fn=slim.batch_norm,
normalizer_params=batch_norm_params):
with slim.arg_scope([slim.batch_norm], **batch_norm_params):
with slim.arg_scope([slim.max_pool2d], padding='SAME') as arg_sc:
return arg_sc
# bottleneck_inception_SE
def bottleneck_inception_SE_module(
inputs,
out_channel=256,
res=None,
scope='inception_block'):
min_channel = out_channel // 8
with tf.variable_scope(scope):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv2d(inputs, min_channel * 3,
[1, 1], scope='Conv2d_1x1')
with tf.variable_scope('Branch_1'):
branch_1 = slim.conv2d(inputs, min_channel *
3 / 2, [1, 1], scope='Conv2d_1x1')
branch_1 = slim.conv2d(
branch_1, min_channel * 3, [3, 3], scope='Conv2d_3x3')
with tf.variable_scope('Branch_2'):
branch_2 = slim.conv2d(inputs, min_channel //
3, [1, 1], scope='Conv2d_1x1')
branch_2 = slim.conv2d(
branch_2, min_channel, [3, 3], scope='Conv2d_3x3')
with tf.variable_scope('Branch_3'):
branch_3 = slim.max_pool2d(inputs, [3, 3], 1, scope='MaxPool_3x3')
branch_3 = slim.conv2d(
branch_3, min_channel, [1, 1], scope='Conv2d_1x1')
net = tf.concat(
axis=3, values=[branch_0, branch_1, branch_2, branch_3])
se_branch = tf.reduce_mean(net, axis=[1, 2])
se_branch = slim.fully_connected(se_branch, out_channel // 16)
se_branch = slim.fully_connected(
se_branch, out_channel, activation_fn=tf.sigmoid)
net = net * se_branch[:,None,None,:]
if res:
inputs = slim.conv2d(inputs, res, (1, 1),
scope='bn_res'.format(scope))
net += inputs
return net
# bottle neck modules
def bottleneck_inception_module(
inputs,
out_channel=256,
res=None,
scope='inception_block'):
min_channel = out_channel // 8
with tf.variable_scope(scope):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv2d(inputs, min_channel * 3,
[1, 1], scope='Conv2d_1x1')
with tf.variable_scope('Branch_1'):
branch_1 = slim.conv2d(inputs, min_channel *
3 / 2, [1, 1], scope='Conv2d_1x1')
branch_1 = slim.conv2d(
branch_1, min_channel * 3, [3, 3], scope='Conv2d_3x3')
with tf.variable_scope('Branch_2'):
branch_2 = slim.conv2d(inputs, min_channel //
3, [1, 1], scope='Conv2d_1x1')
branch_2 = slim.conv2d(
branch_2, min_channel, [3, 3], scope='Conv2d_3x3')
with tf.variable_scope('Branch_3'):
branch_3 = slim.max_pool2d(inputs, [3, 3], 1, scope='MaxPool_3x3')
branch_3 = slim.conv2d(
branch_3, min_channel, [1, 1], scope='Conv2d_1x1')
net = tf.concat(
axis=3, values=[branch_0, branch_1, branch_2, branch_3])
if res:
inputs = slim.conv2d(inputs, res, (1, 1),
scope='bn_res'.format(scope))
net += inputs
return net
def bottleneck_module(inputs, out_channel=256, res=None, scope=''):
with tf.variable_scope(scope):
net = slim.stack(inputs, slim.conv2d, [
(out_channel // 2, [1, 1]), (out_channel // 2, [3, 3]), (out_channel, [1, 1])], scope='conv')
if res:
inputs = slim.conv2d(inputs, res, (1, 1),
scope='bn_res'.format(scope))
net += inputs
return net
# recursive hourglass definition
def hourglass_module(inputs, depth=0, deconv='bilinear', bottleneck='bottleneck'):
bm_fn = globals()['%s_module' % bottleneck]
with tf.variable_scope('depth_{}'.format(depth)):
# buttom up layers
net = slim.max_pool2d(inputs, [2, 2], scope='pool')
net = slim.stack(net, bm_fn, [
(256, None), (256, None), (256, None)], scope='buttom_up')
# connecting layers
if depth > 0:
net = hourglass_module(net, depth=depth - 1, deconv=deconv)
else:
net = bm_fn(
net, out_channel=512, res=512, scope='connecting')
# top down layers
net = bm_fn(net, out_channel=512,
res=512, scope='top_down')
net = deconv_layer(net, 2, 512, method=deconv)
# residual layers
net += slim.stack(inputs, bm_fn,
[(256, None), (256, None), (512, 512)], scope='res')
return net
def hourglass(inputs,
scale=1,
regression_channels=2,
classification_channels=22,
deconv='bilinear',
bottleneck='bottleneck'):
"""Defines a lightweight resnet based model for dense estimation tasks.
Args:
inputs: A `Tensor` with dimensions [num_batches, height, width, depth].
scale: A scalar which denotes the factor to subsample the current image.
output_channels: The number of output channels. E.g., for human pose
estimation this equals 13 channels.
Returns:
A `Tensor` of dimensions [num_batches, height, width, output_channels]."""
out_shape = tf.shape(inputs)[1:3]
if scale > 1:
inputs = tf.pad(inputs, ((0, 0), (1, 1), (1, 1), (0, 0)))
inputs = slim.layers.avg_pool2d(
inputs, (3, 3), (scale, scale), padding='VALID')
output_channels = regression_channels + classification_channels
with slim.arg_scope(hourglass_arg_scope_tf()):
# D1
net = slim.conv2d(inputs, 64, (7, 7), 2, scope='conv1')
net = bottleneck_module(net, out_channel=128,
res=128, scope='bottleneck1')
net = slim.max_pool2d(net, [2, 2], scope='pool1')
# D2
net = slim.stack(net, bottleneck_module, [
(128, None), (128, None), (256, 256)], scope='conv2')
# hourglasses (D3,D4,D5)
with tf.variable_scope('hourglass'):
net = hourglass_module(
net, depth=4, deconv=deconv, bottleneck=bottleneck)
# final layers (D6, D7)
net = slim.stack(net, slim.conv2d, [(512, [1, 1]), (256, [1, 1]),
(output_channels, [1, 1])
], scope='conv3')
net = deconv_layer(net, 4, output_channels, method=deconv)
net = slim.conv2d(net, output_channels, 1, scope='conv_last')
regression = slim.conv2d(
net, regression_channels, 1, activation_fn=None
) if regression_channels else None
logits = slim.conv2d(
net, classification_channels, 1, activation_fn=None
) if classification_channels else None
return regression, logits
def StackedHourglassTorch(inputs, out_channels=16, deconv='bilinear'):
net = inputs
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.Sequential'):
net = tf.pad(net, np.array([[0, 0], [3, 3], [3, 3], [0, 0]]))
net = slim.conv2d(net, 64, (7, 7), (2, 2),
activation_fn=None, padding='VALID')
net = slim.batch_norm(net)
net = slim.nn.relu(net)
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net0 = net
with tf.name_scope('nn.Sequential'):
net0 = slim.batch_norm(net0)
net0 = slim.nn.relu(net0)
net0 = tf.pad(net0, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0 = slim.conv2d(
net0, 64, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0 = slim.batch_norm(net0)
net0 = slim.nn.relu(net0)
net0 = tf.pad(net0, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net0 = slim.conv2d(
net0, 64, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net0 = slim.batch_norm(net0)
net0 = slim.nn.relu(net0)
net0 = tf.pad(net0, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0 = slim.conv2d(
net0, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net1 = net
with tf.name_scope('nn.Sequential'):
net1 = tf.pad(net1, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net1 = slim.conv2d(
net1, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net = tf.add_n([net0, net1])
net = tf.pad(net, np.array([[0, 0], [0, 0], [0, 0], [0, 0]]))
net = slim.max_pool2d(net, (2, 2), (2, 2))
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net0 = net
with tf.name_scope('nn.Sequential'):
net0 = slim.batch_norm(net0)
net0 = slim.nn.relu(net0)
net0 = tf.pad(net0, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0 = slim.conv2d(
net0, 64, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0 = slim.batch_norm(net0)
net0 = slim.nn.relu(net0)
net0 = tf.pad(net0, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net0 = slim.conv2d(
net0, 64, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net0 = slim.batch_norm(net0)
net0 = slim.nn.relu(net0)
net0 = tf.pad(net0, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0 = slim.conv2d(
net0, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net1 = net
net = tf.add_n([net0, net1])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net0 = net
with tf.name_scope('nn.Sequential'):
net0 = slim.batch_norm(net0)
net0 = slim.nn.relu(net0)
net0 = tf.pad(net0, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0 = slim.conv2d(
net0, 64, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0 = slim.batch_norm(net0)
net0 = slim.nn.relu(net0)
net0 = tf.pad(net0, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net0 = slim.conv2d(
net0, 64, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net0 = slim.batch_norm(net0)
net0 = slim.nn.relu(net0)
net0 = tf.pad(net0, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0 = slim.conv2d(
net0, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net1 = net
net = tf.add_n([net0, net1])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net0 = net
with tf.name_scope('nn.Sequential'):
net0 = slim.batch_norm(net0)
net0 = slim.nn.relu(net0)
net0 = tf.pad(net0, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0 = slim.conv2d(
net0, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0 = slim.batch_norm(net0)
net0 = slim.nn.relu(net0)
net0 = tf.pad(net0, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net0 = slim.conv2d(
net0, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net0 = slim.batch_norm(net0)
net0 = slim.nn.relu(net0)
net0 = tf.pad(net0, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0 = slim.conv2d(
net0, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net1 = net
with tf.name_scope('nn.Sequential'):
net1 = tf.pad(net1, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net1 = slim.conv2d(
net1, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net = tf.add_n([net0, net1])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net0 = net
with tf.name_scope('nn.Sequential'):
net0 = tf.pad(net0, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0 = slim.max_pool2d(net0, (2, 2), (2, 2))
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net00 = net0
with tf.name_scope('nn.Sequential'):
net00 = slim.batch_norm(net00)
net00 = slim.nn.relu(net00)
net00 = tf.pad(net00, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00 = slim.conv2d(
net00, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00 = slim.batch_norm(net00)
net00 = slim.nn.relu(net00)
net00 = tf.pad(net00, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net00 = slim.conv2d(
net00, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net00 = slim.batch_norm(net00)
net00 = slim.nn.relu(net00)
net00 = tf.pad(net00, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00 = slim.conv2d(
net00, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net01 = net0
net0 = tf.add_n([net00, net01])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net00 = net0
with tf.name_scope('nn.Sequential'):
net00 = slim.batch_norm(net00)
net00 = slim.nn.relu(net00)
net00 = tf.pad(net00, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00 = slim.conv2d(
net00, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00 = slim.batch_norm(net00)
net00 = slim.nn.relu(net00)
net00 = tf.pad(net00, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net00 = slim.conv2d(
net00, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net00 = slim.batch_norm(net00)
net00 = slim.nn.relu(net00)
net00 = tf.pad(net00, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00 = slim.conv2d(
net00, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net01 = net0
net0 = tf.add_n([net00, net01])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net00 = net0
with tf.name_scope('nn.Sequential'):
net00 = slim.batch_norm(net00)
net00 = slim.nn.relu(net00)
net00 = tf.pad(net00, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00 = slim.conv2d(
net00, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00 = slim.batch_norm(net00)
net00 = slim.nn.relu(net00)
net00 = tf.pad(net00, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net00 = slim.conv2d(
net00, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net00 = slim.batch_norm(net00)
net00 = slim.nn.relu(net00)
net00 = tf.pad(net00, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00 = slim.conv2d(
net00, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net01 = net0
net0 = tf.add_n([net00, net01])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net00 = net0
with tf.name_scope('nn.Sequential'):
net00 = tf.pad(net00, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00 = slim.max_pool2d(
net00, (2, 2), (2, 2))
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net000 = net00
with tf.name_scope('nn.Sequential'):
net000 = slim.batch_norm(
net000)
net000 = slim.nn.relu(net000)
net000 = tf.pad(net000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net000 = slim.conv2d(
net000, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net000 = slim.batch_norm(
net000)
net000 = slim.nn.relu(net000)
net000 = tf.pad(net000, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net000 = slim.conv2d(
net000, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net000 = slim.batch_norm(
net000)
net000 = slim.nn.relu(net000)
net000 = tf.pad(net000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net000 = slim.conv2d(
net000, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net001 = net00
net00 = tf.add_n([net000, net001])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net000 = net00
with tf.name_scope('nn.Sequential'):
net000 = slim.batch_norm(
net000)
net000 = slim.nn.relu(net000)
net000 = tf.pad(net000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net000 = slim.conv2d(
net000, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net000 = slim.batch_norm(
net000)
net000 = slim.nn.relu(net000)
net000 = tf.pad(net000, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net000 = slim.conv2d(
net000, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net000 = slim.batch_norm(
net000)
net000 = slim.nn.relu(net000)
net000 = tf.pad(net000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net000 = slim.conv2d(
net000, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net001 = net00
net00 = tf.add_n([net000, net001])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net000 = net00
with tf.name_scope('nn.Sequential'):
net000 = slim.batch_norm(
net000)
net000 = slim.nn.relu(net000)
net000 = tf.pad(net000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net000 = slim.conv2d(
net000, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net000 = slim.batch_norm(
net000)
net000 = slim.nn.relu(net000)
net000 = tf.pad(net000, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net000 = slim.conv2d(
net000, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net000 = slim.batch_norm(
net000)
net000 = slim.nn.relu(net000)
net000 = tf.pad(net000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net000 = slim.conv2d(
net000, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net001 = net00
net00 = tf.add_n([net000, net001])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net000 = net00
with tf.name_scope('nn.Sequential'):
net000 = tf.pad(net000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net000 = slim.max_pool2d(
net000, (2, 2), (2, 2))
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net0000 = net000
with tf.name_scope('nn.Sequential'):
net0000 = slim.batch_norm(
net0000)
net0000 = slim.nn.relu(
net0000)
net0000 = tf.pad(net0000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0000 = slim.conv2d(
net0000, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0000 = slim.batch_norm(
net0000)
net0000 = slim.nn.relu(
net0000)
net0000 = tf.pad(net0000, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net0000 = slim.conv2d(
net0000, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net0000 = slim.batch_norm(
net0000)
net0000 = slim.nn.relu(
net0000)
net0000 = tf.pad(net0000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0000 = slim.conv2d(
net0000, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0001 = net000
net000 = tf.add_n(
[net0000, net0001])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net0000 = net000
with tf.name_scope('nn.Sequential'):
net0000 = slim.batch_norm(
net0000)
net0000 = slim.nn.relu(
net0000)
net0000 = tf.pad(net0000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0000 = slim.conv2d(
net0000, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0000 = slim.batch_norm(
net0000)
net0000 = slim.nn.relu(
net0000)
net0000 = tf.pad(net0000, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net0000 = slim.conv2d(
net0000, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net0000 = slim.batch_norm(
net0000)
net0000 = slim.nn.relu(
net0000)
net0000 = tf.pad(net0000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0000 = slim.conv2d(
net0000, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0001 = net000
net000 = tf.add_n(
[net0000, net0001])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net0000 = net000
with tf.name_scope('nn.Sequential'):
net0000 = slim.batch_norm(
net0000)
net0000 = slim.nn.relu(
net0000)
net0000 = tf.pad(net0000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0000 = slim.conv2d(
net0000, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0000 = slim.batch_norm(
net0000)
net0000 = slim.nn.relu(
net0000)
net0000 = tf.pad(net0000, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net0000 = slim.conv2d(
net0000, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net0000 = slim.batch_norm(
net0000)
net0000 = slim.nn.relu(
net0000)
net0000 = tf.pad(net0000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0000 = slim.conv2d(
net0000, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0001 = net000
net000 = tf.add_n(
[net0000, net0001])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net0000 = net000
with tf.name_scope('nn.Sequential'):
net0000 = tf.pad(net0000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0000 = slim.max_pool2d(
net0000, (2, 2), (2, 2))
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net00000 = net0000
with tf.name_scope('nn.Sequential'):
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00000 = slim.conv2d(
net00000, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net00000 = slim.conv2d(
net00000, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00000 = slim.conv2d(
net00000, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00001 = net0000
net0000 = tf.add_n(
[net00000, net00001])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net00000 = net0000
with tf.name_scope('nn.Sequential'):
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00000 = slim.conv2d(
net00000, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net00000 = slim.conv2d(
net00000, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00000 = slim.conv2d(
net00000, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00001 = net0000
net0000 = tf.add_n(
[net00000, net00001])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net00000 = net0000
with tf.name_scope('nn.Sequential'):
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00000 = slim.conv2d(
net00000, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net00000 = slim.conv2d(
net00000, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00000 = slim.conv2d(
net00000, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00001 = net0000
net0000 = tf.add_n(
[net00000, net00001])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net00000 = net0000
with tf.name_scope('nn.Sequential'):
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00000 = slim.conv2d(
net00000, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net00000 = slim.conv2d(
net00000, 256, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00000 = slim.conv2d(
net00000, 512, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00001 = net0000
with tf.name_scope('nn.Sequential'):
net00001 = tf.pad(net00001, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00001 = slim.conv2d(
net00001, 512, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0000 = tf.add_n(
[net00000, net00001])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net00000 = net0000
with tf.name_scope('nn.Sequential'):
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00000 = slim.conv2d(
net00000, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net00000 = slim.conv2d(
net00000, 256, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net00000 = slim.batch_norm(
net00000)
net00000 = slim.nn.relu(
net00000)
net00000 = tf.pad(net00000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00000 = slim.conv2d(
net00000, 512, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00001 = net0000
net0000 = tf.add_n(
[net00000, net00001])
net0000 = tf.pad(net0000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0000 = deconv_layer(
net0000, 2, 512, method=deconv)
net0001 = net000
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net00010 = net0001
with tf.name_scope('nn.Sequential'):
net00010 = slim.batch_norm(
net00010)
net00010 = slim.nn.relu(
net00010)
net00010 = tf.pad(net00010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00010 = slim.conv2d(
net00010, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00010 = slim.batch_norm(
net00010)
net00010 = slim.nn.relu(
net00010)
net00010 = tf.pad(net00010, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net00010 = slim.conv2d(
net00010, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net00010 = slim.batch_norm(
net00010)
net00010 = slim.nn.relu(
net00010)
net00010 = tf.pad(net00010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00010 = slim.conv2d(
net00010, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00011 = net0001
net0001 = tf.add_n(
[net00010, net00011])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net00010 = net0001
with tf.name_scope('nn.Sequential'):
net00010 = slim.batch_norm(
net00010)
net00010 = slim.nn.relu(
net00010)
net00010 = tf.pad(net00010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00010 = slim.conv2d(
net00010, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00010 = slim.batch_norm(
net00010)
net00010 = slim.nn.relu(
net00010)
net00010 = tf.pad(net00010, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net00010 = slim.conv2d(
net00010, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net00010 = slim.batch_norm(
net00010)
net00010 = slim.nn.relu(
net00010)
net00010 = tf.pad(net00010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00010 = slim.conv2d(
net00010, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00011 = net0001
net0001 = tf.add_n(
[net00010, net00011])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net00010 = net0001
with tf.name_scope('nn.Sequential'):
net00010 = slim.batch_norm(
net00010)
net00010 = slim.nn.relu(
net00010)
net00010 = tf.pad(net00010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00010 = slim.conv2d(
net00010, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00010 = slim.batch_norm(
net00010)
net00010 = slim.nn.relu(
net00010)
net00010 = tf.pad(net00010, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net00010 = slim.conv2d(
net00010, 256, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net00010 = slim.batch_norm(
net00010)
net00010 = slim.nn.relu(
net00010)
net00010 = tf.pad(net00010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00010 = slim.conv2d(
net00010, 512, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00011 = net0001
with tf.name_scope('nn.Sequential'):
net00011 = tf.pad(net00011, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00011 = slim.conv2d(
net00011, 512, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0001 = tf.add_n(
[net00010, net00011])
net000 = tf.add_n(
[net0000, net0001])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net0000 = net000
with tf.name_scope('nn.Sequential'):
net0000 = slim.batch_norm(
net0000)
net0000 = slim.nn.relu(
net0000)
net0000 = tf.pad(net0000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0000 = slim.conv2d(
net0000, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0000 = slim.batch_norm(
net0000)
net0000 = slim.nn.relu(
net0000)
net0000 = tf.pad(net0000, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net0000 = slim.conv2d(
net0000, 256, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net0000 = slim.batch_norm(
net0000)
net0000 = slim.nn.relu(
net0000)
net0000 = tf.pad(net0000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0000 = slim.conv2d(
net0000, 512, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0001 = net000
net000 = tf.add_n(
[net0000, net0001])
net000 = tf.pad(net000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net000 = deconv_layer(
net000, 2, 512, method=deconv)
net001 = net00
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net0010 = net001
with tf.name_scope('nn.Sequential'):
net0010 = slim.batch_norm(
net0010)
net0010 = slim.nn.relu(
net0010)
net0010 = tf.pad(net0010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0010 = slim.conv2d(
net0010, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0010 = slim.batch_norm(
net0010)
net0010 = slim.nn.relu(
net0010)
net0010 = tf.pad(net0010, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net0010 = slim.conv2d(
net0010, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net0010 = slim.batch_norm(
net0010)
net0010 = slim.nn.relu(
net0010)
net0010 = tf.pad(net0010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0010 = slim.conv2d(
net0010, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0011 = net001
net001 = tf.add_n(
[net0010, net0011])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net0010 = net001
with tf.name_scope('nn.Sequential'):
net0010 = slim.batch_norm(
net0010)
net0010 = slim.nn.relu(
net0010)
net0010 = tf.pad(net0010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0010 = slim.conv2d(
net0010, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0010 = slim.batch_norm(
net0010)
net0010 = slim.nn.relu(
net0010)
net0010 = tf.pad(net0010, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net0010 = slim.conv2d(
net0010, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net0010 = slim.batch_norm(
net0010)
net0010 = slim.nn.relu(
net0010)
net0010 = tf.pad(net0010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0010 = slim.conv2d(
net0010, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0011 = net001
net001 = tf.add_n(
[net0010, net0011])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net0010 = net001
with tf.name_scope('nn.Sequential'):
net0010 = slim.batch_norm(
net0010)
net0010 = slim.nn.relu(
net0010)
net0010 = tf.pad(net0010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0010 = slim.conv2d(
net0010, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0010 = slim.batch_norm(
net0010)
net0010 = slim.nn.relu(
net0010)
net0010 = tf.pad(net0010, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net0010 = slim.conv2d(
net0010, 256, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net0010 = slim.batch_norm(
net0010)
net0010 = slim.nn.relu(
net0010)
net0010 = tf.pad(net0010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0010 = slim.conv2d(
net0010, 512, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net0011 = net001
with tf.name_scope('nn.Sequential'):
net0011 = tf.pad(net0011, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0011 = slim.conv2d(
net0011, 512, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net001 = tf.add_n(
[net0010, net0011])
net00 = tf.add_n([net000, net001])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net000 = net00
with tf.name_scope('nn.Sequential'):
net000 = slim.batch_norm(
net000)
net000 = slim.nn.relu(
net000)
net000 = tf.pad(net000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net000 = slim.conv2d(
net000, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net000 = slim.batch_norm(
net000)
net000 = slim.nn.relu(
net000)
net000 = tf.pad(net000, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net000 = slim.conv2d(
net000, 256, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net000 = slim.batch_norm(
net000)
net000 = slim.nn.relu(
net000)
net000 = tf.pad(net000, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net000 = slim.conv2d(
net000, 512, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net001 = net00
net00 = tf.add_n([net000, net001])
net00 = tf.pad(net00, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00 = deconv_layer(
net00, 2, 512, method=deconv)
net01 = net0
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net010 = net01
with tf.name_scope('nn.Sequential'):
net010 = slim.batch_norm(
net010)
net010 = slim.nn.relu(net010)
net010 = tf.pad(net010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net010 = slim.conv2d(
net010, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net010 = slim.batch_norm(
net010)
net010 = slim.nn.relu(net010)
net010 = tf.pad(net010, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net010 = slim.conv2d(
net010, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net010 = slim.batch_norm(
net010)
net010 = slim.nn.relu(net010)
net010 = tf.pad(net010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net010 = slim.conv2d(
net010, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net011 = net01
net01 = tf.add_n([net010, net011])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net010 = net01
with tf.name_scope('nn.Sequential'):
net010 = slim.batch_norm(
net010)
net010 = slim.nn.relu(net010)
net010 = tf.pad(net010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net010 = slim.conv2d(
net010, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net010 = slim.batch_norm(
net010)
net010 = slim.nn.relu(net010)
net010 = tf.pad(net010, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net010 = slim.conv2d(
net010, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net010 = slim.batch_norm(
net010)
net010 = slim.nn.relu(net010)
net010 = tf.pad(net010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net010 = slim.conv2d(
net010, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net011 = net01
net01 = tf.add_n([net010, net011])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net010 = net01
with tf.name_scope('nn.Sequential'):
net010 = slim.batch_norm(
net010)
net010 = slim.nn.relu(net010)
net010 = tf.pad(net010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net010 = slim.conv2d(
net010, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net010 = slim.batch_norm(
net010)
net010 = slim.nn.relu(net010)
net010 = tf.pad(net010, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net010 = slim.conv2d(
net010, 256, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net010 = slim.batch_norm(
net010)
net010 = slim.nn.relu(net010)
net010 = tf.pad(net010, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net010 = slim.conv2d(
net010, 512, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net011 = net01
with tf.name_scope('nn.Sequential'):
net011 = tf.pad(net011, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net011 = slim.conv2d(
net011, 512, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net01 = tf.add_n([net010, net011])
net0 = tf.add_n([net00, net01])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net00 = net0
with tf.name_scope('nn.Sequential'):
net00 = slim.batch_norm(net00)
net00 = slim.nn.relu(net00)
net00 = tf.pad(net00, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00 = slim.conv2d(
net00, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net00 = slim.batch_norm(net00)
net00 = slim.nn.relu(net00)
net00 = tf.pad(net00, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net00 = slim.conv2d(
net00, 256, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net00 = slim.batch_norm(net00)
net00 = slim.nn.relu(net00)
net00 = tf.pad(net00, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net00 = slim.conv2d(
net00, 512, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net01 = net0
net0 = tf.add_n([net00, net01])
net0 = tf.pad(net0, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net0 = deconv_layer(net0, 2, 512, method=deconv)
net1 = net
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net10 = net1
with tf.name_scope('nn.Sequential'):
net10 = slim.batch_norm(net10)
net10 = slim.nn.relu(net10)
net10 = tf.pad(net10, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net10 = slim.conv2d(
net10, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net10 = slim.batch_norm(net10)
net10 = slim.nn.relu(net10)
net10 = tf.pad(net10, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net10 = slim.conv2d(
net10, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net10 = slim.batch_norm(net10)
net10 = slim.nn.relu(net10)
net10 = tf.pad(net10, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net10 = slim.conv2d(
net10, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net11 = net1
net1 = tf.add_n([net10, net11])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net10 = net1
with tf.name_scope('nn.Sequential'):
net10 = slim.batch_norm(net10)
net10 = slim.nn.relu(net10)
net10 = tf.pad(net10, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net10 = slim.conv2d(
net10, 128, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net10 = slim.batch_norm(net10)
net10 = slim.nn.relu(net10)
net10 = tf.pad(net10, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net10 = slim.conv2d(
net10, 128, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net10 = slim.batch_norm(net10)
net10 = slim.nn.relu(net10)
net10 = tf.pad(net10, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net10 = slim.conv2d(
net10, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net11 = net1
net1 = tf.add_n([net10, net11])
with tf.name_scope('nn.Sequential'):
with tf.name_scope('nn.ConcatTable'):
net10 = net1
with tf.name_scope('nn.Sequential'):
net10 = slim.batch_norm(net10)
net10 = slim.nn.relu(net10)
net10 = tf.pad(net10, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net10 = slim.conv2d(
net10, 256, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net10 = slim.batch_norm(net10)
net10 = slim.nn.relu(net10)
net10 = tf.pad(net10, np.array(
[[0, 0], [1, 1], [1, 1], [0, 0]]))
net10 = slim.conv2d(
net10, 256, (3, 3), (1, 1), activation_fn=None, padding='VALID')
net10 = slim.batch_norm(net10)
net10 = slim.nn.relu(net10)
net10 = tf.pad(net10, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net10 = slim.conv2d(
net10, 512, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net11 = net1
with tf.name_scope('nn.Sequential'):
net11 = tf.pad(net11, np.array(
[[0, 0], [0, 0], [0, 0], [0, 0]]))
net11 = slim.conv2d(
net11, 512, (1, 1), (1, 1), activation_fn=None, padding='VALID')
net1 = tf.add_n([net10, net11])
net = tf.add_n([net0, net1])
net = tf.pad(net, np.array([[0, 0], [0, 0], [0, 0], [0, 0]]))
net = slim.conv2d(net, 512, (1, 1), (1, 1),
activation_fn=None, padding='VALID')
net = slim.batch_norm(net)
net = slim.nn.relu(net)
net = tf.pad(net, np.array([[0, 0], [0, 0], [0, 0], [0, 0]]))
net = slim.conv2d(net, 256, (1, 1), (1, 1),
activation_fn=None, padding='VALID')
net = slim.batch_norm(net)
net = slim.nn.relu(net)
net = tf.pad(net, np.array([[0, 0], [0, 0], [0, 0], [0, 0]]))
net = slim.conv2d(net, out_channels, (1, 1), (1, 1),
activation_fn=None, padding='VALID')
net = tf.pad(net, np.array([[0, 0], [0, 0], [0, 0], [0, 0]]))
net = deconv_layer(net, 4, out_channels, method=deconv)
return net
| [
"tensorflow.image.resize_images",
"tensorflow.shape",
"tensorflow.pad",
"tensorflow.variable_scope",
"tensorflow.concat",
"numpy.array",
"tensorflow.add_n",
"tensorflow.name_scope",
"tensorflow.reduce_mean"
] | [((4444, 4468), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), '(scope)\n', (4461, 4468), True, 'import tensorflow as tf\n'), ((5426, 5492), 'tensorflow.concat', 'tf.concat', ([], {'axis': '(3)', 'values': '[branch_0, branch_1, branch_2, branch_3]'}), '(axis=3, values=[branch_0, branch_1, branch_2, branch_3])\n', (5435, 5492), True, 'import tensorflow as tf\n'), ((5527, 5559), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['net'], {'axis': '[1, 2]'}), '(net, axis=[1, 2])\n', (5541, 5559), True, 'import tensorflow as tf\n'), ((6149, 6173), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), '(scope)\n', (6166, 6173), True, 'import tensorflow as tf\n'), ((7131, 7197), 'tensorflow.concat', 'tf.concat', ([], {'axis': '(3)', 'values': '[branch_0, branch_1, branch_2, branch_3]'}), '(axis=3, values=[branch_0, branch_1, branch_2, branch_3])\n', (7140, 7197), True, 'import tensorflow as tf\n'), ((7464, 7488), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), '(scope)\n', (7481, 7488), True, 'import tensorflow as tf\n'), ((9502, 9518), 'tensorflow.shape', 'tf.shape', (['inputs'], {}), '(inputs)\n', (9510, 9518), True, 'import tensorflow as tf\n'), ((9560, 9608), 'tensorflow.pad', 'tf.pad', (['inputs', '((0, 0), (1, 1), (1, 1), (0, 0))'], {}), '(inputs, ((0, 0), (1, 1), (1, 1), (0, 0)))\n', (9566, 9608), True, 'import tensorflow as tf\n'), ((11173, 11203), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (11186, 11203), True, 'import tensorflow as tf\n'), ((158, 171), 'tensorflow.shape', 'tf.shape', (['net'], {}), '(net)\n', (166, 171), True, 'import tensorflow as tf\n'), ((196, 209), 'tensorflow.shape', 'tf.shape', (['net'], {}), '(net)\n', (204, 209), True, 'import tensorflow as tf\n'), ((4483, 4512), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Branch_0"""'], {}), "('Branch_0')\n", (4500, 4512), True, 'import tensorflow as tf\n'), ((4650, 4679), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Branch_1"""'], {}), "('Branch_1')\n", (4667, 4679), True, 'import tensorflow as tf\n'), ((4928, 4957), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Branch_2"""'], {}), "('Branch_2')\n", (4945, 4957), True, 'import tensorflow as tf\n'), ((5199, 5228), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Branch_3"""'], {}), "('Branch_3')\n", (5216, 5228), True, 'import tensorflow as tf\n'), ((6188, 6217), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Branch_0"""'], {}), "('Branch_0')\n", (6205, 6217), True, 'import tensorflow as tf\n'), ((6355, 6384), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Branch_1"""'], {}), "('Branch_1')\n", (6372, 6384), True, 'import tensorflow as tf\n'), ((6633, 6662), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Branch_2"""'], {}), "('Branch_2')\n", (6650, 6662), True, 'import tensorflow as tf\n'), ((6904, 6933), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Branch_3"""'], {}), "('Branch_3')\n", (6921, 6933), True, 'import tensorflow as tf\n'), ((10274, 10304), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""hourglass"""'], {}), "('hourglass')\n", (10291, 10304), True, 'import tensorflow as tf\n'), ((11218, 11248), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (11231, 11248), True, 'import tensorflow as tf\n'), ((96338, 96380), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (96346, 96380), True, 'import numpy as np\n'), ((11280, 11322), 'numpy.array', 'np.array', (['[[0, 0], [3, 3], [3, 3], [0, 0]]'], {}), '([[0, 0], [3, 3], [3, 3], [0, 0]])\n', (11288, 11322), True, 'import numpy as np\n'), ((11538, 11568), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (11551, 11568), True, 'import tensorflow as tf\n'), ((13141, 13163), 'tensorflow.add_n', 'tf.add_n', (['[net0, net1]'], {}), '([net0, net1])\n', (13149, 13163), True, 'import tensorflow as tf\n'), ((13194, 13236), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (13202, 13236), True, 'import numpy as np\n'), ((13310, 13340), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (13323, 13340), True, 'import tensorflow as tf\n'), ((14603, 14625), 'tensorflow.add_n', 'tf.add_n', (['[net0, net1]'], {}), '([net0, net1])\n', (14611, 14625), True, 'import tensorflow as tf\n'), ((14643, 14673), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (14656, 14673), True, 'import tensorflow as tf\n'), ((15936, 15958), 'tensorflow.add_n', 'tf.add_n', (['[net0, net1]'], {}), '([net0, net1])\n', (15944, 15958), True, 'import tensorflow as tf\n'), ((15976, 16006), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (15989, 16006), True, 'import tensorflow as tf\n'), ((17581, 17603), 'tensorflow.add_n', 'tf.add_n', (['[net0, net1]'], {}), '([net0, net1])\n', (17589, 17603), True, 'import tensorflow as tf\n'), ((17621, 17651), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (17634, 17651), True, 'import tensorflow as tf\n'), ((95539, 95561), 'tensorflow.add_n', 'tf.add_n', (['[net0, net1]'], {}), '([net0, net1])\n', (95547, 95561), True, 'import tensorflow as tf\n'), ((95592, 95634), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (95600, 95634), True, 'import numpy as np\n'), ((95864, 95906), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (95872, 95906), True, 'import numpy as np\n'), ((96136, 96178), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (96144, 96178), True, 'import numpy as np\n'), ((914, 951), 'tensorflow.image.resize_images', 'tf.image.resize_images', (['net', '[nh, nw]'], {}), '(net, [nh, nw])\n', (936, 951), True, 'import tensorflow as tf\n'), ((11591, 11622), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (11604, 11622), True, 'import tensorflow as tf\n'), ((13363, 13394), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (13376, 13394), True, 'import tensorflow as tf\n'), ((14696, 14727), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (14709, 14727), True, 'import tensorflow as tf\n'), ((16029, 16060), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (16042, 16060), True, 'import tensorflow as tf\n'), ((17674, 17705), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (17687, 17705), True, 'import tensorflow as tf\n'), ((11680, 11710), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (11693, 11710), True, 'import tensorflow as tf\n'), ((12834, 12864), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (12847, 12864), True, 'import tensorflow as tf\n'), ((13452, 13482), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (13465, 13482), True, 'import tensorflow as tf\n'), ((14785, 14815), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (14798, 14815), True, 'import tensorflow as tf\n'), ((16118, 16148), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (16131, 16148), True, 'import tensorflow as tf\n'), ((17274, 17304), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (17287, 17304), True, 'import tensorflow as tf\n'), ((17763, 17793), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (17776, 17793), True, 'import tensorflow as tf\n'), ((90149, 90179), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (90162, 90179), True, 'import tensorflow as tf\n'), ((11859, 11901), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (11867, 11901), True, 'import numpy as np\n'), ((12214, 12256), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (12222, 12256), True, 'import numpy as np\n'), ((12569, 12611), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (12577, 12611), True, 'import numpy as np\n'), ((12910, 12952), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (12918, 12952), True, 'import numpy as np\n'), ((13631, 13673), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (13639, 13673), True, 'import numpy as np\n'), ((13986, 14028), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (13994, 14028), True, 'import numpy as np\n'), ((14341, 14383), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (14349, 14383), True, 'import numpy as np\n'), ((14964, 15006), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (14972, 15006), True, 'import numpy as np\n'), ((15319, 15361), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (15327, 15361), True, 'import numpy as np\n'), ((15674, 15716), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (15682, 15716), True, 'import numpy as np\n'), ((16297, 16339), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (16305, 16339), True, 'import numpy as np\n'), ((16653, 16695), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (16661, 16695), True, 'import numpy as np\n'), ((17009, 17051), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (17017, 17051), True, 'import numpy as np\n'), ((17350, 17392), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (17358, 17392), True, 'import numpy as np\n'), ((17839, 17881), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (17847, 17881), True, 'import numpy as np\n'), ((18010, 18040), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (18023, 18040), True, 'import tensorflow as tf\n'), ((19610, 19634), 'tensorflow.add_n', 'tf.add_n', (['[net00, net01]'], {}), '([net00, net01])\n', (19618, 19634), True, 'import tensorflow as tf\n'), ((19664, 19694), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (19677, 19694), True, 'import tensorflow as tf\n'), ((21264, 21288), 'tensorflow.add_n', 'tf.add_n', (['[net00, net01]'], {}), '([net00, net01])\n', (21272, 21288), True, 'import tensorflow as tf\n'), ((21318, 21348), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (21331, 21348), True, 'import tensorflow as tf\n'), ((22918, 22942), 'tensorflow.add_n', 'tf.add_n', (['[net00, net01]'], {}), '([net00, net01])\n', (22926, 22942), True, 'import tensorflow as tf\n'), ((22972, 23002), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (22985, 23002), True, 'import tensorflow as tf\n'), ((88127, 88151), 'tensorflow.add_n', 'tf.add_n', (['[net00, net01]'], {}), '([net00, net01])\n', (88135, 88151), True, 'import tensorflow as tf\n'), ((89946, 89988), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (89954, 89988), True, 'import numpy as np\n'), ((90210, 90240), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (90223, 90240), True, 'import tensorflow as tf\n'), ((91810, 91834), 'tensorflow.add_n', 'tf.add_n', (['[net10, net11]'], {}), '([net10, net11])\n', (91818, 91834), True, 'import tensorflow as tf\n'), ((91864, 91894), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (91877, 91894), True, 'import tensorflow as tf\n'), ((93464, 93488), 'tensorflow.add_n', 'tf.add_n', (['[net10, net11]'], {}), '([net10, net11])\n', (93472, 93488), True, 'import tensorflow as tf\n'), ((93518, 93548), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (93531, 93548), True, 'import tensorflow as tf\n'), ((95492, 95516), 'tensorflow.add_n', 'tf.add_n', (['[net10, net11]'], {}), '([net10, net11])\n', (95500, 95516), True, 'import tensorflow as tf\n'), ((18075, 18106), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (18088, 18106), True, 'import tensorflow as tf\n'), ((19729, 19760), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (19742, 19760), True, 'import tensorflow as tf\n'), ((21383, 21414), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (21396, 21414), True, 'import tensorflow as tf\n'), ((23037, 23068), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (23050, 23068), True, 'import tensorflow as tf\n'), ((88185, 88215), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (88198, 88215), True, 'import tensorflow as tf\n'), ((89877, 89901), 'tensorflow.add_n', 'tf.add_n', (['[net00, net01]'], {}), '([net00, net01])\n', (89885, 89901), True, 'import tensorflow as tf\n'), ((90275, 90306), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (90288, 90306), True, 'import tensorflow as tf\n'), ((91929, 91960), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (91942, 91960), True, 'import tensorflow as tf\n'), ((93583, 93614), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (93596, 93614), True, 'import tensorflow as tf\n'), ((18190, 18220), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (18203, 18220), True, 'import tensorflow as tf\n'), ((19844, 19874), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (19857, 19874), True, 'import tensorflow as tf\n'), ((21498, 21528), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (21511, 21528), True, 'import tensorflow as tf\n'), ((23152, 23182), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (23165, 23182), True, 'import tensorflow as tf\n'), ((81226, 81256), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (81239, 81256), True, 'import tensorflow as tf\n'), ((88254, 88285), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (88267, 88285), True, 'import tensorflow as tf\n'), ((90390, 90420), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (90403, 90420), True, 'import tensorflow as tf\n'), ((92044, 92074), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (92057, 92074), True, 'import tensorflow as tf\n'), ((93698, 93728), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (93711, 93728), True, 'import tensorflow as tf\n'), ((95120, 95150), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (95133, 95150), True, 'import tensorflow as tf\n'), ((18411, 18453), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (18419, 18453), True, 'import numpy as np\n'), ((18847, 18889), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (18855, 18889), True, 'import numpy as np\n'), ((19283, 19325), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (19291, 19325), True, 'import numpy as np\n'), ((20065, 20107), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (20073, 20107), True, 'import numpy as np\n'), ((20501, 20543), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (20509, 20543), True, 'import numpy as np\n'), ((20937, 20979), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (20945, 20979), True, 'import numpy as np\n'), ((21719, 21761), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (21727, 21761), True, 'import numpy as np\n'), ((22155, 22197), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (22163, 22197), True, 'import numpy as np\n'), ((22591, 22633), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (22599, 22633), True, 'import numpy as np\n'), ((23242, 23284), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (23250, 23284), True, 'import numpy as np\n'), ((23492, 23522), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (23505, 23522), True, 'import tensorflow as tf\n'), ((25556, 25582), 'tensorflow.add_n', 'tf.add_n', (['[net000, net001]'], {}), '([net000, net001])\n', (25564, 25582), True, 'import tensorflow as tf\n'), ((25624, 25654), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (25637, 25654), True, 'import tensorflow as tf\n'), ((27688, 27714), 'tensorflow.add_n', 'tf.add_n', (['[net000, net001]'], {}), '([net000, net001])\n', (27696, 27714), True, 'import tensorflow as tf\n'), ((27756, 27786), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (27769, 27786), True, 'import tensorflow as tf\n'), ((29820, 29846), 'tensorflow.add_n', 'tf.add_n', (['[net000, net001]'], {}), '([net000, net001])\n', (29828, 29846), True, 'import tensorflow as tf\n'), ((29888, 29918), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (29901, 29918), True, 'import tensorflow as tf\n'), ((78435, 78461), 'tensorflow.add_n', 'tf.add_n', (['[net000, net001]'], {}), '([net000, net001])\n', (78443, 78461), True, 'import tensorflow as tf\n'), ((80931, 80973), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (80939, 80973), True, 'import numpy as np\n'), ((81299, 81329), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (81312, 81329), True, 'import tensorflow as tf\n'), ((83363, 83389), 'tensorflow.add_n', 'tf.add_n', (['[net010, net011]'], {}), '([net010, net011])\n', (83371, 83389), True, 'import tensorflow as tf\n'), ((83431, 83461), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (83444, 83461), True, 'import tensorflow as tf\n'), ((85495, 85521), 'tensorflow.add_n', 'tf.add_n', (['[net010, net011]'], {}), '([net010, net011])\n', (85503, 85521), True, 'import tensorflow as tf\n'), ((85563, 85593), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (85576, 85593), True, 'import tensorflow as tf\n'), ((88065, 88091), 'tensorflow.add_n', 'tf.add_n', (['[net010, net011]'], {}), '([net010, net011])\n', (88073, 88091), True, 'import tensorflow as tf\n'), ((88377, 88407), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (88390, 88407), True, 'import tensorflow as tf\n'), ((90611, 90653), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (90619, 90653), True, 'import numpy as np\n'), ((91047, 91089), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (91055, 91089), True, 'import numpy as np\n'), ((91483, 91525), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (91491, 91525), True, 'import numpy as np\n'), ((92265, 92307), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (92273, 92307), True, 'import numpy as np\n'), ((92701, 92743), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (92709, 92743), True, 'import numpy as np\n'), ((93137, 93179), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (93145, 93179), True, 'import numpy as np\n'), ((93919, 93961), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (93927, 93961), True, 'import numpy as np\n'), ((94355, 94397), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (94363, 94397), True, 'import numpy as np\n'), ((94791, 94833), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (94799, 94833), True, 'import numpy as np\n'), ((95210, 95252), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (95218, 95252), True, 'import numpy as np\n'), ((23569, 23600), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (23582, 23600), True, 'import tensorflow as tf\n'), ((25701, 25732), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (25714, 25732), True, 'import tensorflow as tf\n'), ((27833, 27864), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (27846, 27864), True, 'import tensorflow as tf\n'), ((29965, 29996), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (29978, 29996), True, 'import tensorflow as tf\n'), ((78507, 78537), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (78520, 78537), True, 'import tensorflow as tf\n'), ((80846, 80872), 'tensorflow.add_n', 'tf.add_n', (['[net000, net001]'], {}), '([net000, net001])\n', (80854, 80872), True, 'import tensorflow as tf\n'), ((81376, 81407), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (81389, 81407), True, 'import tensorflow as tf\n'), ((83508, 83539), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (83521, 83539), True, 'import tensorflow as tf\n'), ((85640, 85671), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (85653, 85671), True, 'import tensorflow as tf\n'), ((88610, 88652), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (88618, 88652), True, 'import numpy as np\n'), ((89070, 89112), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (89078, 89112), True, 'import numpy as np\n'), ((89530, 89572), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (89538, 89572), True, 'import numpy as np\n'), ((23710, 23740), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (23723, 23740), True, 'import tensorflow as tf\n'), ((25842, 25872), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (25855, 25872), True, 'import tensorflow as tf\n'), ((27974, 28004), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (27987, 28004), True, 'import tensorflow as tf\n'), ((30106, 30136), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (30119, 30136), True, 'import tensorflow as tf\n'), ((69636, 69666), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (69649, 69666), True, 'import tensorflow as tf\n'), ((78588, 78619), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (78601, 78619), True, 'import tensorflow as tf\n'), ((81517, 81547), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (81530, 81547), True, 'import tensorflow as tf\n'), ((83649, 83679), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (83662, 83679), True, 'import tensorflow as tf\n'), ((85781, 85811), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (85794, 85811), True, 'import tensorflow as tf\n'), ((87628, 87658), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (87641, 87658), True, 'import tensorflow as tf\n'), ((24026, 24068), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (24034, 24068), True, 'import numpy as np\n'), ((24595, 24637), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (24603, 24637), True, 'import numpy as np\n'), ((25164, 25206), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (25172, 25206), True, 'import numpy as np\n'), ((26158, 26200), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (26166, 26200), True, 'import numpy as np\n'), ((26727, 26769), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (26735, 26769), True, 'import numpy as np\n'), ((27296, 27338), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (27304, 27338), True, 'import numpy as np\n'), ((28290, 28332), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (28298, 28332), True, 'import numpy as np\n'), ((28859, 28901), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (28867, 28901), True, 'import numpy as np\n'), ((29428, 29470), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (29436, 29470), True, 'import numpy as np\n'), ((30210, 30252), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (30218, 30252), True, 'import numpy as np\n'), ((30510, 30540), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (30523, 30540), True, 'import tensorflow as tf\n'), ((33110, 33138), 'tensorflow.add_n', 'tf.add_n', (['[net0000, net0001]'], {}), '([net0000, net0001])\n', (33118, 33138), True, 'import tensorflow as tf\n'), ((33249, 33279), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (33262, 33279), True, 'import tensorflow as tf\n'), ((35849, 35877), 'tensorflow.add_n', 'tf.add_n', (['[net0000, net0001]'], {}), '([net0000, net0001])\n', (35857, 35877), True, 'import tensorflow as tf\n'), ((35988, 36018), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (36001, 36018), True, 'import tensorflow as tf\n'), ((38588, 38616), 'tensorflow.add_n', 'tf.add_n', (['[net0000, net0001]'], {}), '([net0000, net0001])\n', (38596, 38616), True, 'import tensorflow as tf\n'), ((38727, 38757), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (38740, 38757), True, 'import tensorflow as tf\n'), ((66256, 66284), 'tensorflow.add_n', 'tf.add_n', (['[net0000, net0001]'], {}), '([net0000, net0001])\n', (66264, 66284), True, 'import tensorflow as tf\n'), ((69277, 69319), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (69285, 69319), True, 'import numpy as np\n'), ((69721, 69751), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (69734, 69751), True, 'import tensorflow as tf\n'), ((72321, 72349), 'tensorflow.add_n', 'tf.add_n', (['[net0010, net0011]'], {}), '([net0010, net0011])\n', (72329, 72349), True, 'import tensorflow as tf\n'), ((72460, 72490), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (72473, 72490), True, 'import tensorflow as tf\n'), ((75060, 75088), 'tensorflow.add_n', 'tf.add_n', (['[net0010, net0011]'], {}), '([net0010, net0011])\n', (75068, 75088), True, 'import tensorflow as tf\n'), ((75199, 75229), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (75212, 75229), True, 'import tensorflow as tf\n'), ((78301, 78329), 'tensorflow.add_n', 'tf.add_n', (['[net0010, net0011]'], {}), '([net0010, net0011])\n', (78309, 78329), True, 'import tensorflow as tf\n'), ((78737, 78767), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (78750, 78767), True, 'import tensorflow as tf\n'), ((81833, 81875), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (81841, 81875), True, 'import numpy as np\n'), ((82402, 82444), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (82410, 82444), True, 'import numpy as np\n'), ((82971, 83013), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (82979, 83013), True, 'import numpy as np\n'), ((83965, 84007), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (83973, 84007), True, 'import numpy as np\n'), ((84534, 84576), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (84542, 84576), True, 'import numpy as np\n'), ((85103, 85145), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (85111, 85145), True, 'import numpy as np\n'), ((86097, 86139), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (86105, 86139), True, 'import numpy as np\n'), ((86666, 86708), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (86674, 86708), True, 'import numpy as np\n'), ((87235, 87277), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (87243, 87277), True, 'import numpy as np\n'), ((87732, 87774), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (87740, 87774), True, 'import numpy as np\n'), ((30599, 30630), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (30612, 30630), True, 'import tensorflow as tf\n'), ((33338, 33369), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (33351, 33369), True, 'import tensorflow as tf\n'), ((36077, 36108), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (36090, 36108), True, 'import tensorflow as tf\n'), ((38816, 38847), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (38829, 38847), True, 'import tensorflow as tf\n'), ((66399, 66429), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (66412, 66429), True, 'import tensorflow as tf\n'), ((69115, 69143), 'tensorflow.add_n', 'tf.add_n', (['[net0000, net0001]'], {}), '([net0000, net0001])\n', (69123, 69143), True, 'import tensorflow as tf\n'), ((69810, 69841), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (69823, 69841), True, 'import tensorflow as tf\n'), ((72549, 72580), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (72562, 72580), True, 'import tensorflow as tf\n'), ((75288, 75319), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (75301, 75319), True, 'import tensorflow as tf\n'), ((79126, 79168), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (79134, 79168), True, 'import numpy as np\n'), ((79780, 79822), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (79788, 79822), True, 'import numpy as np\n'), ((80434, 80476), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (80442, 80476), True, 'import numpy as np\n'), ((30766, 30796), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (30779, 30796), True, 'import tensorflow as tf\n'), ((33505, 33535), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (33518, 33535), True, 'import tensorflow as tf\n'), ((36244, 36274), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (36257, 36274), True, 'import tensorflow as tf\n'), ((38983, 39013), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (38996, 39013), True, 'import tensorflow as tf\n'), ((56171, 56201), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (56184, 56201), True, 'import tensorflow as tf\n'), ((66492, 66523), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (66505, 66523), True, 'import tensorflow as tf\n'), ((69977, 70007), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (69990, 70007), True, 'import tensorflow as tf\n'), ((72716, 72746), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (72729, 72746), True, 'import tensorflow as tf\n'), ((75455, 75485), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (75468, 75485), True, 'import tensorflow as tf\n'), ((77799, 77829), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (77812, 77829), True, 'import tensorflow as tf\n'), ((31201, 31243), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (31209, 31243), True, 'import numpy as np\n'), ((31927, 31969), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (31935, 31969), True, 'import numpy as np\n'), ((32653, 32695), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (32661, 32695), True, 'import numpy as np\n'), ((33940, 33982), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (33948, 33982), True, 'import numpy as np\n'), ((34666, 34708), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (34674, 34708), True, 'import numpy as np\n'), ((35392, 35434), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (35400, 35434), True, 'import numpy as np\n'), ((36679, 36721), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (36687, 36721), True, 'import numpy as np\n'), ((37405, 37447), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (37413, 37447), True, 'import numpy as np\n'), ((38131, 38173), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (38139, 38173), True, 'import numpy as np\n'), ((39101, 39143), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (39109, 39143), True, 'import numpy as np\n'), ((39451, 39481), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (39464, 39481), True, 'import tensorflow as tf\n'), ((42428, 42458), 'tensorflow.add_n', 'tf.add_n', (['[net00000, net00001]'], {}), '([net00000, net00001])\n', (42436, 42458), True, 'import tensorflow as tf\n'), ((42593, 42623), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (42606, 42623), True, 'import tensorflow as tf\n'), ((45570, 45600), 'tensorflow.add_n', 'tf.add_n', (['[net00000, net00001]'], {}), '([net00000, net00001])\n', (45578, 45600), True, 'import tensorflow as tf\n'), ((45735, 45765), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (45748, 45765), True, 'import tensorflow as tf\n'), ((48712, 48742), 'tensorflow.add_n', 'tf.add_n', (['[net00000, net00001]'], {}), '([net00000, net00001])\n', (48720, 48742), True, 'import tensorflow as tf\n'), ((48877, 48907), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (48890, 48907), True, 'import tensorflow as tf\n'), ((52420, 52450), 'tensorflow.add_n', 'tf.add_n', (['[net00000, net00001]'], {}), '([net00000, net00001])\n', (52428, 52450), True, 'import tensorflow as tf\n'), ((52585, 52615), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (52598, 52615), True, 'import tensorflow as tf\n'), ((55562, 55592), 'tensorflow.add_n', 'tf.add_n', (['[net00000, net00001]'], {}), '([net00000, net00001])\n', (55570, 55592), True, 'import tensorflow as tf\n'), ((55748, 55790), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (55756, 55790), True, 'import numpy as np\n'), ((56268, 56298), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (56281, 56298), True, 'import tensorflow as tf\n'), ((59245, 59275), 'tensorflow.add_n', 'tf.add_n', (['[net00010, net00011]'], {}), '([net00010, net00011])\n', (59253, 59275), True, 'import tensorflow as tf\n'), ((59410, 59440), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (59423, 59440), True, 'import tensorflow as tf\n'), ((62387, 62417), 'tensorflow.add_n', 'tf.add_n', (['[net00010, net00011]'], {}), '([net00010, net00011])\n', (62395, 62417), True, 'import tensorflow as tf\n'), ((62552, 62582), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (62565, 62582), True, 'import tensorflow as tf\n'), ((66095, 66125), 'tensorflow.add_n', 'tf.add_n', (['[net00010, net00011]'], {}), '([net00010, net00011])\n', (66103, 66125), True, 'import tensorflow as tf\n'), ((66667, 66697), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (66680, 66697), True, 'import tensorflow as tf\n'), ((70412, 70454), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (70420, 70454), True, 'import numpy as np\n'), ((71138, 71180), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (71146, 71180), True, 'import numpy as np\n'), ((71864, 71906), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (71872, 71906), True, 'import numpy as np\n'), ((73151, 73193), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (73159, 73193), True, 'import numpy as np\n'), ((73877, 73919), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (73885, 73919), True, 'import numpy as np\n'), ((74603, 74645), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (74611, 74645), True, 'import numpy as np\n'), ((75890, 75932), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (75898, 75932), True, 'import numpy as np\n'), ((76616, 76658), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (76624, 76658), True, 'import numpy as np\n'), ((77342, 77384), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (77350, 77384), True, 'import numpy as np\n'), ((77917, 77959), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (77925, 77959), True, 'import numpy as np\n'), ((39552, 39583), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (39565, 39583), True, 'import tensorflow as tf\n'), ((42694, 42725), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (42707, 42725), True, 'import tensorflow as tf\n'), ((45836, 45867), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (45849, 45867), True, 'import tensorflow as tf\n'), ((48978, 49009), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (48991, 49009), True, 'import tensorflow as tf\n'), ((52686, 52717), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (52699, 52717), True, 'import tensorflow as tf\n'), ((56369, 56400), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (56382, 56400), True, 'import tensorflow as tf\n'), ((59511, 59542), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (59524, 59542), True, 'import tensorflow as tf\n'), ((62653, 62684), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.ConcatTable"""'], {}), "('nn.ConcatTable')\n", (62666, 62684), True, 'import tensorflow as tf\n'), ((67122, 67164), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (67130, 67164), True, 'import numpy as np\n'), ((67880, 67922), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (67888, 67922), True, 'import numpy as np\n'), ((68638, 68680), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (68646, 68680), True, 'import numpy as np\n'), ((39745, 39775), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (39758, 39775), True, 'import tensorflow as tf\n'), ((42887, 42917), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (42900, 42917), True, 'import tensorflow as tf\n'), ((46029, 46059), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (46042, 46059), True, 'import tensorflow as tf\n'), ((49171, 49201), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (49184, 49201), True, 'import tensorflow as tf\n'), ((51853, 51883), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (51866, 51883), True, 'import tensorflow as tf\n'), ((52879, 52909), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (52892, 52909), True, 'import tensorflow as tf\n'), ((56562, 56592), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (56575, 56592), True, 'import tensorflow as tf\n'), ((59704, 59734), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (59717, 59734), True, 'import tensorflow as tf\n'), ((62846, 62876), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (62859, 62876), True, 'import tensorflow as tf\n'), ((65528, 65558), 'tensorflow.name_scope', 'tf.name_scope', (['"""nn.Sequential"""'], {}), "('nn.Sequential')\n", (65541, 65558), True, 'import tensorflow as tf\n'), ((40246, 40288), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (40254, 40288), True, 'import numpy as np\n'), ((41076, 41118), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (41084, 41118), True, 'import numpy as np\n'), ((41906, 41948), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (41914, 41948), True, 'import numpy as np\n'), ((43388, 43430), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (43396, 43430), True, 'import numpy as np\n'), ((44218, 44260), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (44226, 44260), True, 'import numpy as np\n'), ((45048, 45090), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (45056, 45090), True, 'import numpy as np\n'), ((46530, 46572), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (46538, 46572), True, 'import numpy as np\n'), ((47360, 47402), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (47368, 47402), True, 'import numpy as np\n'), ((48190, 48232), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (48198, 48232), True, 'import numpy as np\n'), ((49672, 49714), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (49680, 49714), True, 'import numpy as np\n'), ((50502, 50544), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (50510, 50544), True, 'import numpy as np\n'), ((51332, 51374), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (51340, 51374), True, 'import numpy as np\n'), ((51985, 52027), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (51993, 52027), True, 'import numpy as np\n'), ((53380, 53422), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (53388, 53422), True, 'import numpy as np\n'), ((54210, 54252), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (54218, 54252), True, 'import numpy as np\n'), ((55040, 55082), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (55048, 55082), True, 'import numpy as np\n'), ((57063, 57105), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (57071, 57105), True, 'import numpy as np\n'), ((57893, 57935), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (57901, 57935), True, 'import numpy as np\n'), ((58723, 58765), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (58731, 58765), True, 'import numpy as np\n'), ((60205, 60247), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (60213, 60247), True, 'import numpy as np\n'), ((61035, 61077), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (61043, 61077), True, 'import numpy as np\n'), ((61865, 61907), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (61873, 61907), True, 'import numpy as np\n'), ((63347, 63389), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (63355, 63389), True, 'import numpy as np\n'), ((64177, 64219), 'numpy.array', 'np.array', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), '([[0, 0], [1, 1], [1, 1], [0, 0]])\n', (64185, 64219), True, 'import numpy as np\n'), ((65007, 65049), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (65015, 65049), True, 'import numpy as np\n'), ((65660, 65702), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0], [0, 0], [0, 0]])\n', (65668, 65702), True, 'import numpy as np\n')] |
import os
import argparse
import torch
import torchvision
import numpy as np
from utils import yaml_config_hook
from modules import resnet, network, transform
from evaluation import evaluation
from torch.utils import data
import copy
def inference(loader, model, device):
model.eval()
feature_vector = []
labels_vector = []
extracted_features = []
for step, (x, y) in enumerate(loader):
x = x.to(device)
with torch.no_grad():
c, h = model.forward_cluster(x)
h = h.detach()
c = c.detach()
extracted_features.extend(h.cpu().detach().numpy())
feature_vector.extend(c.cpu().detach().numpy())
labels_vector.extend(y.numpy())
if step % 20 == 0:
print(f"Step [{step}/{len(loader)}]\t Computing features...")
feature_vector = np.array(feature_vector)
labels_vector = np.array(labels_vector)
extracted_features = np.array(extracted_features)
#print("Features shape {}".format(feature_vector.shape))
#print("feature extracted: ", extracted_features.shape)
return feature_vector, labels_vector, extracted_features
if __name__ == "__main__":
parser = argparse.ArgumentParser()
config = yaml_config_hook("config/config_fpi.yaml")
for k, v in config.items():
parser.add_argument(f"--{k}", default=v, type=type(v))
args = parser.parse_args()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if args.dataset == "CIFAR-10":
train_dataset = torchvision.datasets.CIFAR10(
root=args.dataset_dir,
train=True,
download=True,
transform=transform.Transforms(size=args.image_size).test_transform,
)
test_dataset = torchvision.datasets.CIFAR10(
root=args.dataset_dir,
train=False,
download=True,
transform=transform.Transforms(size=args.image_size).test_transform,
)
dataset = data.ConcatDataset([train_dataset, test_dataset])
class_num = 10
elif args.dataset == "CIFAR-100":
train_dataset = torchvision.datasets.CIFAR100(
root=args.dataset_dir,
download=True,
train=True,
transform=transform.Transforms(size=args.image_size).test_transform,
)
test_dataset = torchvision.datasets.CIFAR100(
root=args.dataset_dir,
download=True,
train=False,
transform=transform.Transforms(size=args.image_size).test_transform,
)
dataset = data.ConcatDataset([train_dataset, test_dataset])
class_num = 20
elif args.dataset == "STL-10":
train_dataset = torchvision.datasets.STL10(
root=args.dataset_dir,
split="train",
download=True,
transform=transform.Transforms(size=args.image_size).test_transform,
)
test_dataset = torchvision.datasets.STL10(
root=args.dataset_dir,
split="test",
download=True,
transform=transform.Transforms(size=args.image_size).test_transform,
)
dataset = torch.utils.data.ConcatDataset([train_dataset, test_dataset])
class_num = 10
elif args.dataset == "ImageNet-10":
dataset = torchvision.datasets.ImageFolder(
root='datasets/imagenet-10',
transform=transform.Transforms(size=args.image_size).test_transform,
)
class_num = 10
elif args.dataset == "ImageNet-dogs":
dataset = torchvision.datasets.ImageFolder(
root='datasets/imagenet-dogs',
transform=transform.Transforms(size=args.image_size).test_transform,
)
class_num = 15
elif args.dataset == "tiny-ImageNet":
dataset = torchvision.datasets.ImageFolder(
root='datasets/tiny-imagenet-200/train',
transform=transform.Transforms(size=args.image_size).test_transform,
)
class_num = 200
elif args.dataset == "FASHION-MNIST":
from fmnist import FashionMNIST
train_dataset = FashionMNIST(
root=args.dataset_dir,
train=True,
download=True,
transform=transform.Transforms(size=args.image_size).test_transform,
)
test_dataset = FashionMNIST(
root=args.dataset_dir,
train=False,
download=True,
transform=transform.Transforms(size=args.image_size).test_transform,
)
dataset = data.ConcatDataset([train_dataset, test_dataset])
class_num = 10
elif args.dataset == "FPI":
from fpidataset import Fpidataset
train_dataset = Fpidataset(
train=True,
img_size=args.image_size,
transform=transform.Transforms(width=args.width, height=args.height, s=0.5).test_transform
)
test_dataset = Fpidataset(
train=False,
img_size=args.image_size,
transform=transform.Transforms(width=args.width, height=args.height, s=0.5).test_transform
)
dataset = data.ConcatDataset([train_dataset, test_dataset])
class_num = 10
else:
raise NotImplementedError
data_loader = torch.utils.data.DataLoader(
dataset,
batch_size=500,
shuffle=False,
drop_last=False,
num_workers=args.workers,
)
res = resnet.get_resnet(args.resnet)
model = network.Network(res, args.feature_dim, class_num)
model_fp = os.path.join(args.model_path, "checkpoint_{}.tar".format(args.start_epoch))
model.load_state_dict(torch.load(model_fp, map_location=device.type)['net'])
model.to(device)
print("### Creating features from model ###")
X, Y, extracted_features = inference(data_loader, model, device)
print("extracted Features shape: ",extracted_features.shape)
if args.dataset == "CIFAR-100": # super-class
super_label = [
[72, 4, 95, 30, 55],
[73, 32, 67, 91, 1],
[92, 70, 82, 54, 62],
[16, 61, 9, 10, 28],
[51, 0, 53, 57, 83],
[40, 39, 22, 87, 86],
[20, 25, 94, 84, 5],
[14, 24, 6, 7, 18],
[43, 97, 42, 3, 88],
[37, 17, 76, 12, 68],
[49, 33, 71, 23, 60],
[15, 21, 19, 31, 38],
[75, 63, 66, 64, 34],
[77, 26, 45, 99, 79],
[11, 2, 35, 46, 98],
[29, 93, 27, 78, 44],
[65, 50, 74, 36, 80],
[56, 52, 47, 59, 96],
[8, 58, 90, 13, 48],
[81, 69, 41, 89, 85],
]
Y_copy = copy.copy(Y)
for i in range(20):
for j in super_label[i]:
Y[Y_copy == j] = i
nmi, ari, f, acc, db, s, s_dbw = evaluation.evaluate(Y, X, extracted_features, args.dataset)
print('NMI = {:.4f} ARI = {:.4f} F = {:.4f} ACC = {:.4f} DB = {:.4f} S = {:.4f} S_DBW = {:.4f}'.format(nmi, ari, f, acc, db, s, s_dbw)) | [
"torch.utils.data.ConcatDataset",
"argparse.ArgumentParser",
"modules.resnet.get_resnet",
"torch.load",
"utils.yaml_config_hook",
"numpy.array",
"torch.cuda.is_available",
"evaluation.evaluation.evaluate",
"modules.transform.Transforms",
"torch.utils.data.DataLoader",
"torch.no_grad",
"copy.co... | [((832, 856), 'numpy.array', 'np.array', (['feature_vector'], {}), '(feature_vector)\n', (840, 856), True, 'import numpy as np\n'), ((877, 900), 'numpy.array', 'np.array', (['labels_vector'], {}), '(labels_vector)\n', (885, 900), True, 'import numpy as np\n'), ((926, 954), 'numpy.array', 'np.array', (['extracted_features'], {}), '(extracted_features)\n', (934, 954), True, 'import numpy as np\n'), ((1179, 1204), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1202, 1204), False, 'import argparse\n'), ((1218, 1260), 'utils.yaml_config_hook', 'yaml_config_hook', (['"""config/config_fpi.yaml"""'], {}), "('config/config_fpi.yaml')\n", (1234, 1260), False, 'from utils import yaml_config_hook\n'), ((5255, 5369), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': '(500)', 'shuffle': '(False)', 'drop_last': '(False)', 'num_workers': 'args.workers'}), '(dataset, batch_size=500, shuffle=False,\n drop_last=False, num_workers=args.workers)\n', (5282, 5369), False, 'import torch\n'), ((5424, 5454), 'modules.resnet.get_resnet', 'resnet.get_resnet', (['args.resnet'], {}), '(args.resnet)\n', (5441, 5454), False, 'from modules import resnet, network, transform\n'), ((5467, 5516), 'modules.network.Network', 'network.Network', (['res', 'args.feature_dim', 'class_num'], {}), '(res, args.feature_dim, class_num)\n', (5482, 5516), False, 'from modules import resnet, network, transform\n'), ((6817, 6876), 'evaluation.evaluation.evaluate', 'evaluation.evaluate', (['Y', 'X', 'extracted_features', 'args.dataset'], {}), '(Y, X, extracted_features, args.dataset)\n', (6836, 6876), False, 'from evaluation import evaluation\n'), ((1976, 2025), 'torch.utils.data.ConcatDataset', 'data.ConcatDataset', (['[train_dataset, test_dataset]'], {}), '([train_dataset, test_dataset])\n', (1994, 2025), False, 'from torch.utils import data\n'), ((6667, 6679), 'copy.copy', 'copy.copy', (['Y'], {}), '(Y)\n', (6676, 6679), False, 'import copy\n'), ((447, 462), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (460, 462), False, 'import torch\n'), ((1423, 1448), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1446, 1448), False, 'import torch\n'), ((2569, 2618), 'torch.utils.data.ConcatDataset', 'data.ConcatDataset', (['[train_dataset, test_dataset]'], {}), '([train_dataset, test_dataset])\n', (2587, 2618), False, 'from torch.utils import data\n'), ((5634, 5680), 'torch.load', 'torch.load', (['model_fp'], {'map_location': 'device.type'}), '(model_fp, map_location=device.type)\n', (5644, 5680), False, 'import torch\n'), ((3157, 3218), 'torch.utils.data.ConcatDataset', 'torch.utils.data.ConcatDataset', (['[train_dataset, test_dataset]'], {}), '([train_dataset, test_dataset])\n', (3187, 3218), False, 'import torch\n'), ((1658, 1700), 'modules.transform.Transforms', 'transform.Transforms', ([], {'size': 'args.image_size'}), '(size=args.image_size)\n', (1678, 1700), False, 'from modules import resnet, network, transform\n'), ((1889, 1931), 'modules.transform.Transforms', 'transform.Transforms', ([], {'size': 'args.image_size'}), '(size=args.image_size)\n', (1909, 1931), False, 'from modules import resnet, network, transform\n'), ((2250, 2292), 'modules.transform.Transforms', 'transform.Transforms', ([], {'size': 'args.image_size'}), '(size=args.image_size)\n', (2270, 2292), False, 'from modules import resnet, network, transform\n'), ((2482, 2524), 'modules.transform.Transforms', 'transform.Transforms', ([], {'size': 'args.image_size'}), '(size=args.image_size)\n', (2502, 2524), False, 'from modules import resnet, network, transform\n'), ((2840, 2882), 'modules.transform.Transforms', 'transform.Transforms', ([], {'size': 'args.image_size'}), '(size=args.image_size)\n', (2860, 2882), False, 'from modules import resnet, network, transform\n'), ((3070, 3112), 'modules.transform.Transforms', 'transform.Transforms', ([], {'size': 'args.image_size'}), '(size=args.image_size)\n', (3090, 3112), False, 'from modules import resnet, network, transform\n'), ((3397, 3439), 'modules.transform.Transforms', 'transform.Transforms', ([], {'size': 'args.image_size'}), '(size=args.image_size)\n', (3417, 3439), False, 'from modules import resnet, network, transform\n'), ((4532, 4581), 'torch.utils.data.ConcatDataset', 'data.ConcatDataset', (['[train_dataset, test_dataset]'], {}), '([train_dataset, test_dataset])\n', (4550, 4581), False, 'from torch.utils import data\n'), ((3648, 3690), 'modules.transform.Transforms', 'transform.Transforms', ([], {'size': 'args.image_size'}), '(size=args.image_size)\n', (3668, 3690), False, 'from modules import resnet, network, transform\n'), ((5119, 5168), 'torch.utils.data.ConcatDataset', 'data.ConcatDataset', (['[train_dataset, test_dataset]'], {}), '([train_dataset, test_dataset])\n', (5137, 5168), False, 'from torch.utils import data\n'), ((3909, 3951), 'modules.transform.Transforms', 'transform.Transforms', ([], {'size': 'args.image_size'}), '(size=args.image_size)\n', (3929, 3951), False, 'from modules import resnet, network, transform\n'), ((4230, 4272), 'modules.transform.Transforms', 'transform.Transforms', ([], {'size': 'args.image_size'}), '(size=args.image_size)\n', (4250, 4272), False, 'from modules import resnet, network, transform\n'), ((4445, 4487), 'modules.transform.Transforms', 'transform.Transforms', ([], {'size': 'args.image_size'}), '(size=args.image_size)\n', (4465, 4487), False, 'from modules import resnet, network, transform\n'), ((4799, 4864), 'modules.transform.Transforms', 'transform.Transforms', ([], {'width': 'args.width', 'height': 'args.height', 's': '(0.5)'}), '(width=args.width, height=args.height, s=0.5)\n', (4819, 4864), False, 'from modules import resnet, network, transform\n'), ((5010, 5075), 'modules.transform.Transforms', 'transform.Transforms', ([], {'width': 'args.width', 'height': 'args.height', 's': '(0.5)'}), '(width=args.width, height=args.height, s=0.5)\n', (5030, 5075), False, 'from modules import resnet, network, transform\n')] |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import numpy as np
from pycuda import gpuarray
import pycuda.driver as cuda
from svirl import config as cfg
from svirl.storage import GArray
class Vars(object):
"""This class contains setters and getters for solution variables
order parameter and vector potential"""
def __init__(self, Par, mesh):
self.par = Par
self.mesh = mesh
# Persistent storage: Primary variables that are solved for
self._psi = None
self._vp = None # TODO: this will be renamed to self._a eventually
# Temp storage: Stored on cells, nodes, and edges.
# Used in observables and other classes and fairly general purpose
self._tmp_node_var = None
self._tmp_edge_var = None
self._tmp_cell_var = None
# Temp Storage: Allocated only for reductions
self._tmp_psi_real = None
self._tmp_A_real = None
# copied from variables/parameters.py
self.solveA = np.bool(not np.isposinf(cfg.gl_parameter))
if cfg.order_parameter == 'random':
self.order_parameter = 1.0
self.randomize_order_parameter(level = cfg.random_level, seed = cfg.random_seed)
else:
self.order_parameter = cfg.order_parameter # set order parameter manually
# vector potential is set up here instead of its setter because
# we don't plan on supporting setter for it
shapes = [(cfg.Nxa, cfg.Nya), (cfg.Nxb, cfg.Nyb)]
self._vp = GArray(shape = shapes, dtype = cfg.dtype)
def __del__(self):
pass
@property
def order_parameter(self):
self._psi.sync()
psi = self._psi.get_h().copy()
return psi
@order_parameter.setter
def order_parameter(self, order_parameter):
if isinstance(order_parameter, (np.complexfloating, complex, np.floating, float, np.integer, int)):
order_parameter = cfg.dtype_complex(order_parameter) * np.ones((cfg.Nx, cfg.Ny), cfg.dtype_complex)
assert order_parameter.shape == (cfg.Nx, cfg.Ny)
if self._psi is None:
self._psi = GArray(like = order_parameter)
else:
self._psi.set_h(order_parameter)
self.set_order_parameter_to_zero_outside_material()
self._psi.sync()
def order_parameter_h(self):
return self._psi.get_d_obj()
def set_order_parameter_to_zero_outside_material(self):
if self._psi is None or not self.mesh.have_material_tiling():
return
mt_at_nodes = self.mesh._get_material_tiling_at_nodes()
psi = self._psi.get_h()
psi[~mt_at_nodes] = 0.0
self._psi.need_htod_sync()
self._psi.sync()
def randomize_order_parameter(self, level=1.0, seed=None):
"""Randomizes order parameter:
absolute value *= 1 - level*rand
phase += level*pi*(2.0*rand()-1.0),
where rand is uniformly distributed in [0, 1]
"""
assert 0.0 <= level <= 1.0
self._psi.sync()
if seed is not None:
np.random.seed(seed)
data = (1.0 - level*np.random.rand(cfg.N)) * np.exp(level * 1.0j*np.pi*(2.0*np.random.rand(cfg.N) - 1.0))
self._psi.set_h(data)
self._psi.sync()
@property
def vector_potential(self):
if self._vp is None:
return (np.zeros((cfg.Nxa, cfg.Nya), dtype=cfg.dtype),
np.zeros((cfg.Nxb, cfg.Nyb), dtype=cfg.dtype))
self._vp.sync()
return self._vp.get_vec_h()
@vector_potential.setter
def vector_potential(self, vector_potential):
a, b = vector_potential
self._vp.set_vec_h(a, b)
self._vp.sync()
def vector_potential_h(self):
if self._vp is not None:
return self._vp.get_d_obj()
return np.uintp(0)
#--------------------------
# temporary arrays
#--------------------------
def _tmp_node_var_h(self):
if self._tmp_node_var is None:
self._tmp_node_var = GArray(like = self._psi)
return self._tmp_node_var.get_d_obj()
def _tmp_edge_var_h(self):
if self._tmp_edge_var is None:
shapes = [(cfg.Nxa, cfg.Nya), (cfg.Nxb, cfg.Nyb)]
self._tmp_edge_var = GArray(shape = shapes, dtype = cfg.dtype)
return self._tmp_edge_var.get_d_obj()
def _tmp_cell_var_h(self):
if self._tmp_cell_var is None:
self._tmp_cell_var = GArray(shape = (cfg.Nxc, cfg.Nyc),
dtype = cfg.dtype)
return self._tmp_cell_var.get_d_obj()
def _tmp_psi_real_h(self):
if self._tmp_psi_real is not None:
return self._tmp_psi_real.get_d_obj()
return np.uintp(0)
def _tmp_A_real_h(self):
if self._tmp_A_real is not None:
return self._tmp_A_real.get_d_obj()
return np.uintp(0)
def _alloc_free_temporary_gpu_storage(self, action):
assert action in ['alloc', 'free']
if action == 'alloc':
if self._tmp_psi_real is None:
self._tmp_psi_real = GArray(self.par.grid_size, on =
GArray.on_device, dtype = cfg.dtype)
if self._tmp_A_real is None and self.solveA:
self._tmp_A_real = GArray(self.par.grid_size_A, on =
GArray.on_device, dtype = cfg.dtype)
else:
if self._tmp_psi_real is not None:
self._tmp_psi_real.free()
self._tmp_psi_real = None
if self._tmp_A_real is not None:
self._tmp_A_real.free()
self._tmp_A_real = None
| [
"numpy.ones",
"numpy.random.rand",
"svirl.config.dtype_complex",
"numpy.zeros",
"numpy.random.seed",
"svirl.storage.GArray",
"numpy.uintp",
"numpy.isposinf"
] | [((1560, 1597), 'svirl.storage.GArray', 'GArray', ([], {'shape': 'shapes', 'dtype': 'cfg.dtype'}), '(shape=shapes, dtype=cfg.dtype)\n', (1566, 1597), False, 'from svirl.storage import GArray\n'), ((3903, 3914), 'numpy.uintp', 'np.uintp', (['(0)'], {}), '(0)\n', (3911, 3914), True, 'import numpy as np\n'), ((4827, 4838), 'numpy.uintp', 'np.uintp', (['(0)'], {}), '(0)\n', (4835, 4838), True, 'import numpy as np\n'), ((4975, 4986), 'numpy.uintp', 'np.uintp', (['(0)'], {}), '(0)\n', (4983, 4986), True, 'import numpy as np\n'), ((2180, 2208), 'svirl.storage.GArray', 'GArray', ([], {'like': 'order_parameter'}), '(like=order_parameter)\n', (2186, 2208), False, 'from svirl.storage import GArray\n'), ((3142, 3162), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (3156, 3162), True, 'import numpy as np\n'), ((4107, 4129), 'svirl.storage.GArray', 'GArray', ([], {'like': 'self._psi'}), '(like=self._psi)\n', (4113, 4129), False, 'from svirl.storage import GArray\n'), ((4347, 4384), 'svirl.storage.GArray', 'GArray', ([], {'shape': 'shapes', 'dtype': 'cfg.dtype'}), '(shape=shapes, dtype=cfg.dtype)\n', (4353, 4384), False, 'from svirl.storage import GArray\n'), ((4541, 4590), 'svirl.storage.GArray', 'GArray', ([], {'shape': '(cfg.Nxc, cfg.Nyc)', 'dtype': 'cfg.dtype'}), '(shape=(cfg.Nxc, cfg.Nyc), dtype=cfg.dtype)\n', (4547, 4590), False, 'from svirl.storage import GArray\n'), ((1046, 1075), 'numpy.isposinf', 'np.isposinf', (['cfg.gl_parameter'], {}), '(cfg.gl_parameter)\n', (1057, 1075), True, 'import numpy as np\n'), ((1986, 2020), 'svirl.config.dtype_complex', 'cfg.dtype_complex', (['order_parameter'], {}), '(order_parameter)\n', (2003, 2020), True, 'from svirl import config as cfg\n'), ((2023, 2067), 'numpy.ones', 'np.ones', (['(cfg.Nx, cfg.Ny)', 'cfg.dtype_complex'], {}), '((cfg.Nx, cfg.Ny), cfg.dtype_complex)\n', (2030, 2067), True, 'import numpy as np\n'), ((3431, 3476), 'numpy.zeros', 'np.zeros', (['(cfg.Nxa, cfg.Nya)'], {'dtype': 'cfg.dtype'}), '((cfg.Nxa, cfg.Nya), dtype=cfg.dtype)\n', (3439, 3476), True, 'import numpy as np\n'), ((3498, 3543), 'numpy.zeros', 'np.zeros', (['(cfg.Nxb, cfg.Nyb)'], {'dtype': 'cfg.dtype'}), '((cfg.Nxb, cfg.Nyb), dtype=cfg.dtype)\n', (3506, 3543), True, 'import numpy as np\n'), ((5199, 5263), 'svirl.storage.GArray', 'GArray', (['self.par.grid_size'], {'on': 'GArray.on_device', 'dtype': 'cfg.dtype'}), '(self.par.grid_size, on=GArray.on_device, dtype=cfg.dtype)\n', (5205, 5263), False, 'from svirl.storage import GArray\n'), ((5384, 5450), 'svirl.storage.GArray', 'GArray', (['self.par.grid_size_A'], {'on': 'GArray.on_device', 'dtype': 'cfg.dtype'}), '(self.par.grid_size_A, on=GArray.on_device, dtype=cfg.dtype)\n', (5390, 5450), False, 'from svirl.storage import GArray\n'), ((3192, 3213), 'numpy.random.rand', 'np.random.rand', (['cfg.N'], {}), '(cfg.N)\n', (3206, 3213), True, 'import numpy as np\n'), ((3248, 3269), 'numpy.random.rand', 'np.random.rand', (['cfg.N'], {}), '(cfg.N)\n', (3262, 3269), True, 'import numpy as np\n')] |
"""
"""
import os, sys
import re
import logging
import datetime
from functools import reduce
from collections import namedtuple
from glob import glob
from copy import deepcopy
from typing import Union, Optional, List, Dict, Tuple, Sequence, Iterable, NoReturn, Any
from numbers import Real, Number
import numpy as np
np.set_printoptions(precision=5, suppress=True)
import pandas as pd
from scipy import interpolate
from sklearn.utils import compute_class_weight
from wfdb.io import _header
from wfdb import Record, MultiRecord
from easydict import EasyDict as ED
from ..cfg import DEFAULTS
__all__ = [
"get_record_list_recursive",
"get_record_list_recursive2",
"get_record_list_recursive3",
"dict_to_str",
"str2bool",
"diff_with_step",
"ms2samples",
"samples2ms",
"get_mask",
"class_weight_to_sample_weight",
"plot_single_lead",
"init_logger",
"get_date_str",
"rdheader",
"ensure_lead_fmt", "ensure_siglen",
"ECGWaveForm", "masks_to_waveforms",
"mask_to_intervals",
"list_sum",
"read_log_txt", "read_event_scalars",
"dicts_equal",
"default_class_repr",
"MovingAverage",
]
def get_record_list_recursive(db_dir:str, rec_ext:str) -> List[str]:
""" finished, checked,
get the list of records in `db_dir` recursively,
for example, there are two folders "patient1", "patient2" in `db_dir`,
and there are records "A0001", "A0002", ... in "patient1"; "B0001", "B0002", ... in "patient2",
then the output would be "patient1{sep}A0001", ..., "patient2{sep}B0001", ...,
sep is determined by the system
Parameters
----------
db_dir: str,
the parent (root) path of the whole database
rec_ext: str,
extension of the record files
Returns
-------
res: list of str,
list of records, in lexicographical order
"""
res = []
db_dir = os.path.join(db_dir, "tmp").replace("tmp", "") # make sure `db_dir` ends with a sep
roots = [db_dir]
while len(roots) > 0:
new_roots = []
for r in roots:
tmp = [os.path.join(r, item) for item in os.listdir(r)]
res += [item for item in tmp if os.path.isfile(item)]
new_roots += [item for item in tmp if os.path.isdir(item)]
roots = deepcopy(new_roots)
res = [os.path.splitext(item)[0].replace(db_dir, "") for item in res if item.endswith(rec_ext)]
res = sorted(res)
return res
def get_record_list_recursive2(db_dir:str, rec_pattern:str) -> List[str]:
""" finished, checked,
get the list of records in `db_dir` recursively,
for example, there are two folders "patient1", "patient2" in `db_dir`,
and there are records "A0001", "A0002", ... in "patient1"; "B0001", "B0002", ... in "patient2",
then the output would be "patient1{sep}A0001", ..., "patient2{sep}B0001", ...,
sep is determined by the system
Parameters
----------
db_dir: str,
the parent (root) path of the whole database
rec_pattern: str,
pattern of the record filenames, e.g. "A*.mat"
Returns
-------
res: list of str,
list of records, in lexicographical order
"""
res = []
db_dir = os.path.join(db_dir, "tmp").replace("tmp", "") # make sure `db_dir` ends with a sep
roots = [db_dir]
while len(roots) > 0:
new_roots = []
for r in roots:
tmp = [os.path.join(r, item) for item in os.listdir(r)]
# res += [item for item in tmp if os.path.isfile(item)]
res += glob(os.path.join(r, rec_pattern), recursive=False)
new_roots += [item for item in tmp if os.path.isdir(item)]
roots = deepcopy(new_roots)
res = [os.path.splitext(item)[0].replace(db_dir, "") for item in res]
res = sorted(res)
return res
def get_record_list_recursive3(db_dir:str, rec_patterns:Union[str,Dict[str,str]]) -> Union[List[str], Dict[str, List[str]]]:
""" finished, checked,
get the list of records in `db_dir` recursively,
for example, there are two folders "patient1", "patient2" in `db_dir`,
and there are records "A0001", "A0002", ... in "patient1"; "B0001", "B0002", ... in "patient2",
then the output would be "patient1{sep}A0001", ..., "patient2{sep}B0001", ...,
sep is determined by the system
Parameters
----------
db_dir: str,
the parent (root) path of the whole database
rec_patterns: str or dict,
pattern of the record filenames, e.g. "A(?:\d+).mat",
or patterns of several subsets, e.g. `{"A": "A(?:\d+).mat"}`
Returns
-------
res: list of str,
list of records, in lexicographical order
"""
if isinstance(rec_patterns, str):
res = []
elif isinstance(rec_patterns, dict):
res = {k:[] for k in rec_patterns.keys()}
db_dir = os.path.join(db_dir, "tmp").replace("tmp", "") # make sure `db_dir` ends with a sep
roots = [db_dir]
while len(roots) > 0:
new_roots = []
for r in roots:
tmp = [os.path.join(r, item) for item in os.listdir(r)]
# res += [item for item in tmp if os.path.isfile(item)]
if isinstance(rec_patterns, str):
res += list(filter(re.compile(rec_patterns).search, tmp))
elif isinstance(rec_patterns, dict):
for k in rec_patterns.keys():
res[k] += list(filter(re.compile(rec_patterns[k]).search, tmp))
new_roots += [item for item in tmp if os.path.isdir(item)]
roots = deepcopy(new_roots)
if isinstance(rec_patterns, str):
res = [os.path.splitext(item)[0].replace(db_dir, "") for item in res]
res = sorted(res)
elif isinstance(rec_patterns, dict):
for k in rec_patterns.keys():
res[k] = [os.path.splitext(item)[0].replace(db_dir, "") for item in res[k]]
res[k] = sorted(res[k])
return res
def dict_to_str(d:Union[dict, list, tuple], current_depth:int=1, indent_spaces:int=4) -> str:
""" finished, checked,
convert a (possibly) nested dict into a `str` of json-like formatted form,
this nested dict might also contain lists or tuples of dict (and of str, int, etc.)
Parameters
----------
d: dict, or list, or tuple,
a (possibly) nested `dict`, or a list of `dict`
current_depth: int, default 1,
depth of `d` in the (possible) parent `dict` or `list`
indent_spaces: int, default 4,
the indent spaces of each depth
Returns
-------
s: str,
the formatted string
"""
assert isinstance(d, (dict, list, tuple))
if len(d) == 0:
s = f"{{}}" if isinstance(d, dict) else f"[]"
return s
# flat_types = (Number, bool, str,)
flat_types = (Number, bool,)
flat_sep = ", "
s = "\n"
unit_indent = " "*indent_spaces
prefix = unit_indent*current_depth
if isinstance(d, (list, tuple)):
if all([isinstance(v, flat_types) for v in d]):
len_per_line = 110
current_len = len(prefix) + 1 # + 1 for a comma
val = []
for idx, v in enumerate(d):
add_v = f"\042{v}\042" if isinstance(v, str) else str(v)
add_len = len(add_v) + len(flat_sep)
if current_len + add_len > len_per_line:
val = ", ".join([item for item in val])
s += f"{prefix}{val},\n"
val = [add_v]
current_len = len(prefix) + 1 + len(add_v)
else:
val.append(add_v)
current_len += add_len
if len(val) > 0:
val = ", ".join([item for item in val])
s += f"{prefix}{val}\n"
else:
for idx, v in enumerate(d):
if isinstance(v, (dict, list, tuple)):
s += f"{prefix}{dict_to_str(v, current_depth+1)}"
else:
val = f"\042{v}\042" if isinstance(v, str) else v
s += f"{prefix}{val}"
if idx < len(d) - 1:
s += ",\n"
else:
s += "\n"
elif isinstance(d, dict):
for idx, (k, v) in enumerate(d.items()):
key = f"\042{k}\042" if isinstance(k, str) else k
if isinstance(v, (dict, list, tuple)):
s += f"{prefix}{key}: {dict_to_str(v, current_depth+1)}"
else:
val = f"\042{v}\042" if isinstance(v, str) else v
s += f"{prefix}{key}: {val}"
if idx < len(d) - 1:
s += ",\n"
else:
s += "\n"
s += unit_indent*(current_depth-1)
s = f"{{{s}}}" if isinstance(d, dict) else f"[{s}]"
return s
def str2bool(v:Union[str, bool]) -> bool:
""" finished, checked,
converts a "boolean" value possibly in the format of str to bool
Parameters
----------
v: str or bool,
the "boolean" value
Returns
-------
b: bool,
`v` in the format of bool
References
----------
https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
"""
if isinstance(v, bool):
b = v
elif v.lower() in ("yes", "true", "t", "y", "1"):
b = True
elif v.lower() in ("no", "false", "f", "n", "0"):
b = False
else:
raise ValueError("Boolean value expected.")
return b
def diff_with_step(a:np.ndarray, step:int=1, **kwargs) -> np.ndarray:
""" finished, checked,
compute a[n+step] - a[n] for all valid n
Parameters
----------
a: ndarray,
the input data
step: int, default 1,
the step to compute the difference
kwargs: dict,
Returns
-------
d: ndarray:
the difference array
"""
if step >= len(a):
raise ValueError(f"step ({step}) should be less than the length ({len(a)}) of `a`")
d = a[step:] - a[:-step]
return d
def ms2samples(t:Real, fs:Real) -> int:
""" finished, checked,
convert time `t` with units in ms to number of samples
Parameters
----------
t: real number,
time with units in ms
fs: real number,
sampling frequency of a signal
Returns
-------
n_samples: int,
number of samples corresponding to time `t`
"""
n_samples = t * fs // 1000
return n_samples
def samples2ms(n_samples:int, fs:Real) -> Real:
""" finished, checked,
inverse function of `ms2samples`
Parameters
----------
n_samples: int,
number of sample points
fs: real number,
sampling frequency of a signal
Returns
-------
t: real number,
time duration correponding to `n_samples`
"""
t = n_samples * 1000 / fs
return t
def get_mask(shape:Union[int, Sequence[int]], critical_points:np.ndarray, left_bias:int, right_bias:int, return_fmt:str="mask") -> Union[np.ndarray,list]:
""" finished, checked,
get the mask around the `critical_points`
Parameters
----------
shape: int, or sequence of int,
shape of the mask (and the original data)
critical_points: ndarray,
indices (of the last dimension) of the points around which to be masked (value 1)
left_bias: int, non-negative
bias to the left of the critical points for the mask
right_bias: int, non-negative
bias to the right of the critical points for the mask
return_fmt: str, default "mask",
format of the return values,
"mask" for the usual mask,
can also be "intervals", which consists of a list of intervals
Returns
-------
mask: ndarray or list,
"""
if isinstance(shape, int):
shape = (shape,)
l_itv = [[max(0,cp-left_bias),min(shape[-1],cp+right_bias)] for cp in critical_points]
if return_fmt.lower() == "mask":
mask = np.zeros(shape=shape, dtype=int)
for itv in l_itv:
mask[..., itv[0]:itv[1]] = 1
elif return_fmt.lower() == "intervals":
mask = l_itv
return mask
def class_weight_to_sample_weight(y:np.ndarray, class_weight:Union[str,List[float],np.ndarray,dict]="balanced") -> np.ndarray:
""" finished, checked,
transform class weight to sample weight
Parameters
----------
y: ndarray,
the label (class) of each sample
class_weight: str, or list, or ndarray, or dict, default "balanced",
the weight for each sample class,
if is "balanced", the class weight will automatically be given by
if `y` is of string type, then `class_weight` should be a dict,
if `y` is of numeric type, and `class_weight` is array_like,
then the labels (`y`) should be continuous and start from 0
Returns
-------
sample_weight: ndarray,
the array of sample weight
"""
if not class_weight:
sample_weight = np.ones_like(y, dtype=float)
return sample_weight
try:
sample_weight = y.copy().astype(int)
except:
sample_weight = y.copy()
assert isinstance(class_weight, dict) or class_weight.lower()=="balanced", \
"if `y` are of type str, then class_weight should be \042balanced\042 or a dict"
if isinstance(class_weight, str) and class_weight.lower() == "balanced":
classes = np.unique(y).tolist()
cw = compute_class_weight("balanced", classes=classes, y=y)
trans_func = lambda s: cw[classes.index(s)]
else:
trans_func = lambda s: class_weight[s]
sample_weight = np.vectorize(trans_func)(sample_weight)
sample_weight = sample_weight / np.max(sample_weight)
return sample_weight
def plot_single_lead(t:np.ndarray, sig:np.ndarray, ax:Optional[Any]=None, ticks_granularity:int=0, **kwargs) -> NoReturn:
""" finished, NOT checked,
Parameters
----------
t: ndarray,
the array of time of the signal
sig: ndarray,
the signal itself
ax: Artist, optional,
the `Artist` to plot on
ticks_granularity: int, default 0,
the granularity to plot axis ticks, the higher the more,
0 (no ticks) --> 1 (major ticks) --> 2 (major + minor ticks)
"""
if "plt" not in dir():
import matplotlib.pyplot as plt
palette = {"p_waves": "green", "qrs": "red", "t_waves": "pink",}
plot_alpha = 0.4
y_range = np.max(np.abs(sig)) + 100
if ax is None:
fig_sz_w = int(round(4.8 * (t[-1]-t[0])))
fig_sz_h = 6 * y_range / 1500
fig, ax = plt.subplots(figsize=(fig_sz_w, fig_sz_h))
label = kwargs.get("label", None)
if label:
ax.plot(t, sig, label=kwargs.get("label"))
else:
ax.plot(t, sig)
ax.axhline(y=0, linestyle="-", linewidth="1.0", color="red")
# NOTE that `Locator` has default `MAXTICKS` equal to 1000
if ticks_granularity >= 1:
ax.xaxis.set_major_locator(plt.MultipleLocator(0.2))
ax.yaxis.set_major_locator(plt.MultipleLocator(500))
ax.grid(which="major", linestyle="-", linewidth="0.5", color="red")
if ticks_granularity >= 2:
ax.xaxis.set_minor_locator(plt.MultipleLocator(0.04))
ax.yaxis.set_minor_locator(plt.MultipleLocator(100))
ax.grid(which="minor", linestyle=":", linewidth="0.5", color="black")
waves = kwargs.get("waves", {"p_waves":[], "qrs":[], "t_waves":[]})
for w, l_itv in waves.items():
for itv in l_itv:
ax.axvspan(itv[0], itv[1], color=palette[w], alpha=plot_alpha)
if label:
ax.legend(loc="upper left")
ax.set_xlim(t[0], t[-1])
ax.set_ylim(-y_range, y_range)
ax.set_xlabel("Time [s]")
ax.set_ylabel("Voltage [μV]")
def init_logger(log_dir:str, log_file:Optional[str]=None, log_name:Optional[str]=None, mode:str="a", verbose:int=0) -> logging.Logger:
""" finished, checked,
Parameters
----------
log_dir: str,
directory of the log file
log_file: str, optional,
name of the log file
log_name: str, optional,
name of the logger
mode: str, default "a",
mode of writing the log file, can be one of "a", "w"
verbose: int, default 0,
log verbosity
Returns
-------
logger: Logger
"""
if log_file is None:
log_file = f"log_{get_date_str()}.txt"
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = os.path.join(log_dir, log_file)
print(f"log file path: {log_file}")
logger = logging.getLogger(log_name or DEFAULTS.prefix) # "ECG" to prevent from using the root logger
c_handler = logging.StreamHandler(sys.stdout)
f_handler = logging.FileHandler(log_file)
if verbose >= 2:
print("levels of c_handler and f_handler are set DEBUG")
c_handler.setLevel(logging.DEBUG)
f_handler.setLevel(logging.DEBUG)
logger.setLevel(logging.DEBUG)
elif verbose >= 1:
print("level of c_handler is set INFO, level of f_handler is set DEBUG")
c_handler.setLevel(logging.INFO)
f_handler.setLevel(logging.DEBUG)
logger.setLevel(logging.DEBUG)
else:
print("level of c_handler is set WARNING, level of f_handler is set INFO")
c_handler.setLevel(logging.WARNING)
f_handler.setLevel(logging.INFO)
logger.setLevel(logging.INFO)
c_format = logging.Formatter("%(name)s - %(levelname)s - %(message)s")
f_format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
c_handler.setFormatter(c_format)
f_handler.setFormatter(f_format)
logger.addHandler(c_handler)
logger.addHandler(f_handler)
return logger
def get_date_str(fmt:Optional[str]=None):
""" finished, checked,
Parameters
----------
fmt: str, optional,
format of the string of date
Returns
-------
date_str: str,
current time in the `str` format
"""
now = datetime.datetime.now()
date_str = now.strftime(fmt or "%m-%d_%H-%M")
return date_str
def rdheader(header_data:Union[str, Sequence[str]]) -> Union[Record, MultiRecord]:
""" finished, checked,
modified from `wfdb.rdheader`
Parameters
----------
head_data: str, or sequence of str,
path of the .hea header file, or lines of the .hea header file
"""
if isinstance(header_data, str):
if not header_data.endswith(".hea"):
_header_data = header_data + ".hea"
else:
_header_data = header_data
if not os.path.isfile(_header_data):
raise FileNotFoundError
with open(_header_data, "r") as f:
_header_data = f.read().splitlines()
# Read the header file. Separate comment and non-comment lines
header_lines, comment_lines = [], []
for line in _header_data:
striped_line = line.strip()
# Comment line
if striped_line.startswith("#"):
comment_lines.append(striped_line)
# Non-empty non-comment line = header line.
elif striped_line:
# Look for a comment in the line
ci = striped_line.find("#")
if ci > 0:
header_lines.append(striped_line[:ci])
# comment on same line as header line
comment_lines.append(striped_line[ci:])
else:
header_lines.append(striped_line)
# Get fields from record line
record_fields = _header._parse_record_line(header_lines[0])
# Single segment header - Process signal specification lines
if record_fields["n_seg"] is None:
# Create a single-segment WFDB record object
record = Record()
# There are signals
if len(header_lines)>1:
# Read the fields from the signal lines
signal_fields = _header._parse_signal_lines(header_lines[1:])
# Set the object's signal fields
for field in signal_fields:
setattr(record, field, signal_fields[field])
# Set the object's record line fields
for field in record_fields:
if field == "n_seg":
continue
setattr(record, field, record_fields[field])
# Multi segment header - Process segment specification lines
else:
# Create a multi-segment WFDB record object
record = MultiRecord()
# Read the fields from the segment lines
segment_fields = _header._read_segment_lines(header_lines[1:])
# Set the object's segment fields
for field in segment_fields:
setattr(record, field, segment_fields[field])
# Set the objects' record fields
for field in record_fields:
setattr(record, field, record_fields[field])
# Determine whether the record is fixed or variable
if record.seg_len[0] == 0:
record.layout = "variable"
else:
record.layout = "fixed"
# Set the comments field
record.comments = [line.strip(" \t#") for line in comment_lines]
return record
def ensure_lead_fmt(values:Sequence[Real], n_leads:int=12, fmt:str="lead_first") -> np.ndarray:
""" finished, checked,
ensure the `n_leads`-lead (ECG) signal to be of the format of `fmt`
Parameters
----------
values: sequence,
values of the `n_leads`-lead (ECG) signal
n_leads: int, default 12,
number of leads
fmt: str, default "lead_first", case insensitive,
format of the output values, can be one of
"lead_first" (alias "channel_first"), "lead_last" (alias "channel_last")
Returns
-------
out_values: ndarray,
ECG signal in the format of `fmt`
"""
out_values = np.array(values)
lead_dim = np.where(np.array(out_values.shape) == n_leads)[0]
if not any([[0] == lead_dim or [1] == lead_dim]):
raise ValueError(f"not valid {n_leads}-lead signal")
lead_dim = lead_dim[0]
if (lead_dim == 1 and fmt.lower() in ["lead_first", "channel_first"]) \
or (lead_dim == 0 and fmt.lower() in ["lead_last", "channel_last"]):
out_values = out_values.T
return out_values
return out_values
def ensure_siglen(values:Sequence[Real], siglen:int, fmt:str="lead_first") -> np.ndarray:
""" finished, checked,
ensure the (ECG) signal to be of length `siglen`,
strategy:
if `values` has length greater than `siglen`,
the central `siglen` samples will be adopted;
otherwise, zero padding will be added to both sides
Parameters
----------
values: sequence,
values of the `n_leads`-lead (ECG) signal
siglen: int,
length of the signal supposed to have
fmt: str, default "lead_first", case insensitive,
format of the input and output values, can be one of
"lead_first" (alias "channel_first"), "lead_last" (alias "channel_last")
Returns
-------
out_values: ndarray,
ECG signal in the format of `fmt` and of fixed length `siglen`
"""
if fmt.lower() in ["channel_last", "lead_last"]:
_values = np.array(values).T
else:
_values = np.array(values).copy()
original_siglen = _values.shape[1]
n_leads = _values.shape[0]
if original_siglen >= siglen:
start = (original_siglen - siglen) // 2
end = start + siglen
out_values = _values[..., start:end]
else:
pad_len = siglen - original_siglen
pad_left = pad_len // 2
pad_right = pad_len - pad_left
out_values = np.concatenate([np.zeros((n_leads, pad_left)), _values, np.zeros((n_leads, pad_right))], axis=1)
if fmt.lower() in ["channel_last", "lead_last"]:
out_values = out_values.T
return out_values
ECGWaveForm = namedtuple(
typename="ECGWaveForm",
field_names=["name", "onset", "offset", "peak", "duration"],
)
def masks_to_waveforms(masks:np.ndarray,
class_map:Dict[str, int],
fs:Real,
mask_format:str="channel_first",
leads:Optional[Sequence[str]]=None) -> Dict[str, List[ECGWaveForm]]:
""" finished, checked,
convert masks into lists of waveforms
Parameters
----------
masks: ndarray,
wave delineation in the form of masks,
of shape (n_leads, seq_len), or (seq_len,)
class_map: dict,
class map, mapping names to waves to numbers from 0 to n_classes-1,
the keys should contain "pwave", "qrs", "twave"
fs: real number,
sampling frequency of the signal corresponding to the `masks`,
used to compute the duration of each waveform
mask_format: str, default "channel_first",
format of the mask, used only when `masks.ndim = 2`
"channel_last" (alias "lead_last"), or
"channel_first" (alias "lead_first")
leads: str or list of str, optional,
the names of leads corresponding to the channels of the `masks`
Returns
-------
waves: dict,
each item value is a list containing the `ECGWaveForm`s corr. to the lead;
each item key is from `leads` if `leads` is set,
otherwise would be "lead_1", "lead_2", ..., "lead_n"
"""
if masks.ndim == 1:
_masks = masks[np.newaxis,...]
elif masks.ndim == 2:
if mask_format.lower() not in ["channel_first", "lead_first",]:
_masks = masks.T
else:
_masks = masks.copy()
else:
raise ValueError(f"masks should be of dim 1 or 2, but got a {masks.ndim}d array")
_leads = [f"lead_{idx+1}" for idx in range(_masks.shape[0])] if leads is None else leads
assert len(_leads) == _masks.shape[0]
_class_map = ED(deepcopy(class_map))
waves = ED({lead_name:[] for lead_name in _leads})
for channel_idx, lead_name in enumerate(_leads):
current_mask = _masks[channel_idx,...]
for wave_name, wave_number in _class_map.items():
if wave_name.lower() not in ["pwave", "qrs", "twave",]:
continue
current_wave_inds = np.where(current_mask==wave_number)[0]
if len(current_wave_inds) == 0:
continue
np.where(np.diff(current_wave_inds)>1)
split_inds = np.where(np.diff(current_wave_inds)>1)[0].tolist()
split_inds = sorted(split_inds+[i+1 for i in split_inds])
split_inds = [0] + split_inds + [len(current_wave_inds)-1]
for i in range(len(split_inds)//2):
itv_start = current_wave_inds[split_inds[2*i]]
itv_end = current_wave_inds[split_inds[2*i+1]]+1
w = ECGWaveForm(
name=wave_name.lower(),
onset=itv_start,
offset=itv_end,
peak=np.nan,
duration=1000*(itv_end-itv_start)/fs, # ms
)
waves[lead_name].append(w)
waves[lead_name].sort(key=lambda w: w.onset)
return waves
def mask_to_intervals(mask:np.ndarray,
vals:Optional[Union[int,Sequence[int]]]=None,
right_inclusive:bool=False) -> Union[list, dict]:
""" finished, checked,
Parameters
----------
mask: ndarray,
1d mask
vals: int or sequence of int, optional,
values in `mask` to obtain intervals
right_inclusive: bool, default False,
if True, the intervals will be right inclusive
otherwise, right exclusive
Returns
-------
intervals: dict or list,
the intervals corr. to each value in `vals` if `vals` is `None` or `Sequence`;
or the intervals corr. to `vals` if `vals` is int.
each interval is of the form `[a,b]`
"""
if vals is None:
_vals = list(set(mask))
elif isinstance(vals, int):
_vals = [vals]
else:
_vals = vals
# assert set(_vals) & set(mask) == set(_vals)
bias = 0 if right_inclusive else 1
intervals = {v:[] for v in _vals}
for v in _vals:
valid_inds = np.where(np.array(mask)==v)[0]
if len(valid_inds) == 0:
continue
split_indices = np.where(np.diff(valid_inds)>1)[0]
split_indices = split_indices.tolist() + (split_indices+1).tolist()
split_indices = sorted([0] + split_indices + [len(valid_inds)-1])
for idx in range(len(split_indices)//2):
intervals[v].append(
[valid_inds[split_indices[2*idx]], valid_inds[split_indices[2*idx+1]]+bias]
)
if isinstance(vals, int):
intervals = intervals[vals]
return intervals
def list_sum(l:Sequence[list]) -> list:
""" finished, checked,
Parameters
----------
l: sequence of list,
the sequence of lists to obtain the summation
Returns
-------
l_sum: list,
sum of `l`,
i.e. if l = [list1, list2, ...], then l_sum = list1 + list2 + ...
"""
l_sum = reduce(lambda a,b: a+b, l, [])
return l_sum
def read_log_txt(fp:str,
epoch_startswith:str="Train epoch_",
scalar_startswith:Union[str,Iterable[str]]="train/|test/") -> pd.DataFrame:
""" finished, checked,
read from log txt file, in case tensorboard not working
Parameters
----------
fp: str,
path to the log txt file
epoch_startswith: str,
indicator of the start of the start of an epoch
scalar_startswith: str or iterable of str,
indicators of the scalar recordings,
if is str, should be indicators separated by "|"
Returns
-------
summary: DataFrame,
scalars summary, in the format of a pandas DataFrame
"""
with open(fp, "r") as f:
content = f.read().splitlines()
if isinstance(scalar_startswith, str):
field_pattern = f"^({scalar_startswith})"
else:
field_pattern = f"""^({"|".join(scalar_startswith)})"""
summary = []
new_line = None
for l in content:
if l.startswith(epoch_startswith):
if new_line:
summary.append(new_line)
epoch = re.findall("[\d]+", l)[0]
new_line = {"epoch": epoch}
if re.findall(field_pattern, l):
field, val = l.split(":")
field = field.strip()
val = float(val.strip())
new_line[field] = val
summary.append(new_line)
summary = pd.DataFrame(summary)
return summary
def read_event_scalars(fp:str, keys:Optional[Union[str,Iterable[str]]]=None) -> Union[pd.DataFrame,Dict[str,pd.DataFrame]]:
""" finished, checked,
read scalars from event file, in case tensorboard not working
Parameters
----------
fp: str,
path to the event file
keys: str or iterable of str, optional,
field names of the scalars to read,
if is None, scalars of all fields will be read
Returns
-------
summary: DataFrame or dict of DataFrame
the wall_time, step, value of the scalars
"""
try:
from tensorflow.python.summary.event_accumulator import EventAccumulator
except:
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
event_acc = EventAccumulator(fp)
event_acc.Reload()
if keys:
if isinstance(keys, str):
_keys = [keys]
else:
_keys = keys
else:
_keys = event_acc.scalars.Keys()
summary = {}
for k in _keys:
df = pd.DataFrame([[item.wall_time, item.step, item.value] for item in event_acc.scalars.Items(k)])
df.columns = ["wall_time", "step", "value"]
summary[k] = df
if isinstance(keys, str):
summary = summary[k]
return summary
def dicts_equal(d1:dict, d2:dict) -> bool:
""" finished, checked,
Parameters
----------
d1, d2: dict,
the two dicts to compare equality
Returns
-------
bool, True if `d1` equals `d2`
NOTE
----
the existence of numpy array, torch Tensor, pandas DataFrame and Series would probably
cause errors when directly use the default `__eq__` method of dict,
for example `{"a": np.array([1,2])} == {"a": np.array([1,2])}` would raise the following
```python
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
```
Example
-------
>>> d1 = {"a": pd.DataFrame([{"hehe":1,"haha":2}])[["haha","hehe"]]}
>>> d2 = {"a": pd.DataFrame([{"hehe":1,"haha":2}])[["hehe","haha"]]}
>>> dicts_equal(d1, d2)
... True
"""
import torch
if len(d1) != len(d2):
return False
for k,v in d1.items():
if k not in d2 or not isinstance(d2[k], type(v)):
return False
if isinstance(v, dict):
if not dicts_equal(v, d2[k]):
return False
elif isinstance(v, np.ndarray):
if v.shape != d2[k].shape or not (v==d2[k]).all():
return False
elif isinstance(v, torch.Tensor):
if v.shape != d2[k].shape or not (v==d2[k]).all().item():
return False
elif isinstance(v, pd.DataFrame):
if v.shape != d2[k].shape or set(v.columns) != set(d2[k].columns):
# consider: should one check index be equal?
return False
# for c in v.columns:
# if not (v[c] == d2[k][c]).all():
# return False
if not (v.values == d2[k][v.columns].values).all():
return False
elif isinstance(v, pd.Series):
if v.shape != d2[k].shape or v.name != d2[k].name:
return False
if not (v==d2[k]).all():
return False
# TODO: consider whether there are any other dtypes that should be treated similarly
else: # other dtypes whose equality can be directly checked
if v != d2[k]:
return False
return True
def default_class_repr(c:object, align:str="center", depth:int=1) -> str:
""" finished, checked,
Parameters
----------
c: object,
the object to be represented
align: str, default "center",
the alignment of the class arguments
Returns
-------
str,
the representation of the class
"""
indent = 4*depth*" "
closing_indent = 4*(depth-1)*" "
if not hasattr(c, "extra_repr_keys"):
return repr(c)
elif len(c.extra_repr_keys()) > 0:
max_len = max([len(k) for k in c.extra_repr_keys()])
extra_str = "(\n" + \
",\n".join([
f"""{indent}{k.ljust(max_len, " ") if align.lower() in ["center", "c"] else k} = {default_class_repr(eval(f"c.{k}"),align,depth+1)}""" \
for k in c.__dir__() if k in c.extra_repr_keys()
]) + \
f"{closing_indent}\n)"
else:
extra_str = ""
return f"{c.__class__.__name__}{extra_str}"
class MovingAverage(object):
""" finished, checked, to be improved,
moving average
References
----------
[1] https://en.wikipedia.org/wiki/Moving_average
"""
def __init__(self, data:Optional[Sequence]=None, **kwargs:Any) -> NoReturn:
"""
Parameters
----------
data: array_like,
the series data to compute its moving average
kwargs: auxilliary key word arguments
"""
if data is None:
self.data = np.array([])
else:
self.data = np.array(data)
self.verbose = kwargs.get("verbose", 0)
def __call__(self, data:Optional[Sequence]=None, method:str="ema", **kwargs:Any) -> np.ndarray:
"""
Parameters
----------
method: str,
method for computing moving average, can be one of
- "sma", "simple", "simple moving average"
- "ema", "ewma", "exponential", "exponential weighted", "exponential moving average", "exponential weighted moving average"
- "cma", "cumulative", "cumulative moving average"
- "wma", "weighted", "weighted moving average"
"""
m = method.lower().replace("_", " ")
if m in ["sma", "simple", "simple moving average"]:
func = self._sma
elif m in ["ema", "ewma", "exponential", "exponential weighted", "exponential moving average", "exponential weighted moving average"]:
func = self._ema
elif m in ["cma", "cumulative", "cumulative moving average"]:
func = self._cma
elif m in ["wma", "weighted", "weighted moving average"]:
func = self._wma
else:
raise NotImplementedError
if data is not None:
self.data = np.array(data)
return func(**kwargs)
def _sma(self, window:int=5, center:bool=False, **kwargs:Any) -> np.ndarray:
"""
simple moving average
Parameters
----------
window: int, default 5,
window length of the moving average
center: bool, default False,
if True, when computing the output value at each point, the window will be centered at that point;
otherwise the previous `window` points of the current point will be used
"""
smoothed = []
if center:
hw = window//2
window = hw*2+1
for n in range(window):
smoothed.append(np.mean(self.data[:n+1]))
prev = smoothed[-1]
for n, d in enumerate(self.data[window:]):
s = prev + (d - self.data[n]) / window
prev = s
smoothed.append(s)
smoothed = np.array(smoothed)
if center:
smoothed[hw:-hw] = smoothed[window-1:]
for n in range(hw):
smoothed[n] = np.mean(self.data[:n+hw+1])
smoothed[-n-1] = np.mean(self.data[-n-hw-1:])
return smoothed
def _ema(self, weight:float=0.6, **kwargs:Any) -> np.ndarray:
"""
exponential moving average,
which is also the function used in Tensorboard Scalar panel,
whose parameter `smoothing` is the `weight` here
Parameters
----------
weight: float, default 0.6,
weight of the previous data point
"""
smoothed = []
prev = self.data[0]
for d in self.data:
s = prev * weight + (1 - weight) * d
prev = s
smoothed.append(s)
smoothed = np.array(smoothed)
return smoothed
def _cma(self, **kwargs) -> np.ndarray:
"""
cumulative moving average
"""
smoothed = []
prev = 0
for n, d in enumerate(self.data):
s = prev + (d - prev) / (n+1)
prev = s
smoothed.append(s)
smoothed = np.array(smoothed)
return smoothed
def _wma(self, window:int=5, **kwargs:Any) -> np.ndarray:
"""
weighted moving average
Parameters
----------
window: int, default 5,
window length of the moving average
"""
# smoothed = []
# total = []
# numerator = []
conv = np.arange(1, window+1)[::-1]
deno = np.sum(conv)
smoothed = np.convolve(conv, self.data, mode="same") / deno
return smoothed
| [
"logging.getLogger",
"logging.StreamHandler",
"numpy.convolve",
"re.compile",
"numpy.array",
"wfdb.io._header._parse_signal_lines",
"matplotlib.pyplot.MultipleLocator",
"sklearn.utils.compute_class_weight",
"copy.deepcopy",
"wfdb.io._header._read_segment_lines",
"wfdb.io._header._parse_record_li... | [((318, 365), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(5)', 'suppress': '(True)'}), '(precision=5, suppress=True)\n', (337, 365), True, 'import numpy as np\n'), ((23807, 23906), 'collections.namedtuple', 'namedtuple', ([], {'typename': '"""ECGWaveForm"""', 'field_names': "['name', 'onset', 'offset', 'peak', 'duration']"}), "(typename='ECGWaveForm', field_names=['name', 'onset', 'offset',\n 'peak', 'duration'])\n", (23817, 23906), False, 'from collections import namedtuple\n'), ((16458, 16489), 'os.path.join', 'os.path.join', (['log_dir', 'log_file'], {}), '(log_dir, log_file)\n', (16470, 16489), False, 'import os, sys\n'), ((16544, 16590), 'logging.getLogger', 'logging.getLogger', (['(log_name or DEFAULTS.prefix)'], {}), '(log_name or DEFAULTS.prefix)\n', (16561, 16590), False, 'import logging\n'), ((16655, 16688), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (16676, 16688), False, 'import logging\n'), ((16705, 16734), 'logging.FileHandler', 'logging.FileHandler', (['log_file'], {}), '(log_file)\n', (16724, 16734), False, 'import logging\n'), ((17403, 17462), 'logging.Formatter', 'logging.Formatter', (['"""%(name)s - %(levelname)s - %(message)s"""'], {}), "('%(name)s - %(levelname)s - %(message)s')\n", (17420, 17462), False, 'import logging\n'), ((17478, 17551), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s - %(name)s - %(levelname)s - %(message)s"""'], {}), "('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n", (17495, 17551), False, 'import logging\n'), ((17978, 18001), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (17999, 18001), False, 'import datetime\n'), ((19489, 19532), 'wfdb.io._header._parse_record_line', '_header._parse_record_line', (['header_lines[0]'], {}), '(header_lines[0])\n', (19515, 19532), False, 'from wfdb.io import _header\n'), ((21758, 21774), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (21766, 21774), True, 'import numpy as np\n'), ((25796, 25839), 'easydict.EasyDict', 'ED', (['{lead_name: [] for lead_name in _leads}'], {}), '({lead_name: [] for lead_name in _leads})\n', (25798, 25839), True, 'from easydict import EasyDict as ED\n'), ((29018, 29051), 'functools.reduce', 'reduce', (['(lambda a, b: a + b)', 'l', '[]'], {}), '(lambda a, b: a + b, l, [])\n', (29024, 29051), False, 'from functools import reduce\n'), ((30477, 30498), 'pandas.DataFrame', 'pd.DataFrame', (['summary'], {}), '(summary)\n', (30489, 30498), True, 'import pandas as pd\n'), ((31293, 31313), 'tensorboard.backend.event_processing.event_accumulator.EventAccumulator', 'EventAccumulator', (['fp'], {}), '(fp)\n', (31309, 31313), False, 'from tensorboard.backend.event_processing.event_accumulator import EventAccumulator\n'), ((2298, 2317), 'copy.deepcopy', 'deepcopy', (['new_roots'], {}), '(new_roots)\n', (2306, 2317), False, 'from copy import deepcopy\n'), ((3689, 3708), 'copy.deepcopy', 'deepcopy', (['new_roots'], {}), '(new_roots)\n', (3697, 3708), False, 'from copy import deepcopy\n'), ((5551, 5570), 'copy.deepcopy', 'deepcopy', (['new_roots'], {}), '(new_roots)\n', (5559, 5570), False, 'from copy import deepcopy\n'), ((11946, 11978), 'numpy.zeros', 'np.zeros', ([], {'shape': 'shape', 'dtype': 'int'}), '(shape=shape, dtype=int)\n', (11954, 11978), True, 'import numpy as np\n'), ((12964, 12992), 'numpy.ones_like', 'np.ones_like', (['y'], {'dtype': 'float'}), '(y, dtype=float)\n', (12976, 12992), True, 'import numpy as np\n'), ((13439, 13493), 'sklearn.utils.compute_class_weight', 'compute_class_weight', (['"""balanced"""'], {'classes': 'classes', 'y': 'y'}), "('balanced', classes=classes, y=y)\n", (13459, 13493), False, 'from sklearn.utils import compute_class_weight\n'), ((13623, 13647), 'numpy.vectorize', 'np.vectorize', (['trans_func'], {}), '(trans_func)\n', (13635, 13647), True, 'import numpy as np\n'), ((13699, 13720), 'numpy.max', 'np.max', (['sample_weight'], {}), '(sample_weight)\n', (13705, 13720), True, 'import numpy as np\n'), ((14593, 14635), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(fig_sz_w, fig_sz_h)'}), '(figsize=(fig_sz_w, fig_sz_h))\n', (14605, 14635), True, 'import matplotlib.pyplot as plt\n'), ((16389, 16412), 'os.path.exists', 'os.path.exists', (['log_dir'], {}), '(log_dir)\n', (16403, 16412), False, 'import os, sys\n'), ((16422, 16442), 'os.makedirs', 'os.makedirs', (['log_dir'], {}), '(log_dir)\n', (16433, 16442), False, 'import os, sys\n'), ((19708, 19716), 'wfdb.Record', 'Record', ([], {}), '()\n', (19714, 19716), False, 'from wfdb import Record, MultiRecord\n'), ((20392, 20405), 'wfdb.MultiRecord', 'MultiRecord', ([], {}), '()\n', (20403, 20405), False, 'from wfdb import Record, MultiRecord\n'), ((20480, 20525), 'wfdb.io._header._read_segment_lines', '_header._read_segment_lines', (['header_lines[1:]'], {}), '(header_lines[1:])\n', (20507, 20525), False, 'from wfdb.io import _header\n'), ((25762, 25781), 'copy.deepcopy', 'deepcopy', (['class_map'], {}), '(class_map)\n', (25770, 25781), False, 'from copy import deepcopy\n'), ((30261, 30289), 're.findall', 're.findall', (['field_pattern', 'l'], {}), '(field_pattern, l)\n', (30271, 30289), False, 'import re\n'), ((37746, 37764), 'numpy.array', 'np.array', (['smoothed'], {}), '(smoothed)\n', (37754, 37764), True, 'import numpy as np\n'), ((38583, 38601), 'numpy.array', 'np.array', (['smoothed'], {}), '(smoothed)\n', (38591, 38601), True, 'import numpy as np\n'), ((38923, 38941), 'numpy.array', 'np.array', (['smoothed'], {}), '(smoothed)\n', (38931, 38941), True, 'import numpy as np\n'), ((39333, 39345), 'numpy.sum', 'np.sum', (['conv'], {}), '(conv)\n', (39339, 39345), True, 'import numpy as np\n'), ((1898, 1925), 'os.path.join', 'os.path.join', (['db_dir', '"""tmp"""'], {}), "(db_dir, 'tmp')\n", (1910, 1925), False, 'import os, sys\n'), ((3216, 3243), 'os.path.join', 'os.path.join', (['db_dir', '"""tmp"""'], {}), "(db_dir, 'tmp')\n", (3228, 3243), False, 'import os, sys\n'), ((4850, 4877), 'os.path.join', 'os.path.join', (['db_dir', '"""tmp"""'], {}), "(db_dir, 'tmp')\n", (4862, 4877), False, 'import os, sys\n'), ((14449, 14460), 'numpy.abs', 'np.abs', (['sig'], {}), '(sig)\n', (14455, 14460), True, 'import numpy as np\n'), ((14967, 14991), 'matplotlib.pyplot.MultipleLocator', 'plt.MultipleLocator', (['(0.2)'], {}), '(0.2)\n', (14986, 14991), True, 'import matplotlib.pyplot as plt\n'), ((15028, 15052), 'matplotlib.pyplot.MultipleLocator', 'plt.MultipleLocator', (['(500)'], {}), '(500)\n', (15047, 15052), True, 'import matplotlib.pyplot as plt\n'), ((15196, 15221), 'matplotlib.pyplot.MultipleLocator', 'plt.MultipleLocator', (['(0.04)'], {}), '(0.04)\n', (15215, 15221), True, 'import matplotlib.pyplot as plt\n'), ((15258, 15282), 'matplotlib.pyplot.MultipleLocator', 'plt.MultipleLocator', (['(100)'], {}), '(100)\n', (15277, 15282), True, 'import matplotlib.pyplot as plt\n'), ((18571, 18599), 'os.path.isfile', 'os.path.isfile', (['_header_data'], {}), '(_header_data)\n', (18585, 18599), False, 'import os, sys\n'), ((19858, 19903), 'wfdb.io._header._parse_signal_lines', '_header._parse_signal_lines', (['header_lines[1:]'], {}), '(header_lines[1:])\n', (19885, 19903), False, 'from wfdb.io import _header\n'), ((23136, 23152), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (23144, 23152), True, 'import numpy as np\n'), ((35551, 35563), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (35559, 35563), True, 'import numpy as np\n'), ((35602, 35616), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (35610, 35616), True, 'import numpy as np\n'), ((36830, 36844), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (36838, 36844), True, 'import numpy as np\n'), ((39289, 39313), 'numpy.arange', 'np.arange', (['(1)', '(window + 1)'], {}), '(1, window + 1)\n', (39298, 39313), True, 'import numpy as np\n'), ((39365, 39406), 'numpy.convolve', 'np.convolve', (['conv', 'self.data'], {'mode': '"""same"""'}), "(conv, self.data, mode='same')\n", (39376, 39406), True, 'import numpy as np\n'), ((2096, 2117), 'os.path.join', 'os.path.join', (['r', 'item'], {}), '(r, item)\n', (2108, 2117), False, 'import os, sys\n'), ((3414, 3435), 'os.path.join', 'os.path.join', (['r', 'item'], {}), '(r, item)\n', (3426, 3435), False, 'import os, sys\n'), ((3555, 3583), 'os.path.join', 'os.path.join', (['r', 'rec_pattern'], {}), '(r, rec_pattern)\n', (3567, 3583), False, 'import os, sys\n'), ((5048, 5069), 'os.path.join', 'os.path.join', (['r', 'item'], {}), '(r, item)\n', (5060, 5069), False, 'import os, sys\n'), ((13404, 13416), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (13413, 13416), True, 'import numpy as np\n'), ((21799, 21825), 'numpy.array', 'np.array', (['out_values.shape'], {}), '(out_values.shape)\n', (21807, 21825), True, 'import numpy as np\n'), ((23183, 23199), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (23191, 23199), True, 'import numpy as np\n'), ((23595, 23624), 'numpy.zeros', 'np.zeros', (['(n_leads, pad_left)'], {}), '((n_leads, pad_left))\n', (23603, 23624), True, 'import numpy as np\n'), ((23635, 23665), 'numpy.zeros', 'np.zeros', (['(n_leads, pad_right)'], {}), '((n_leads, pad_right))\n', (23643, 23665), True, 'import numpy as np\n'), ((26122, 26159), 'numpy.where', 'np.where', (['(current_mask == wave_number)'], {}), '(current_mask == wave_number)\n', (26130, 26159), True, 'import numpy as np\n'), ((30184, 30207), 're.findall', 're.findall', (['"""[\\\\d]+"""', 'l'], {}), "('[\\\\d]+', l)\n", (30194, 30207), False, 'import re\n'), ((37519, 37545), 'numpy.mean', 'np.mean', (['self.data[:n + 1]'], {}), '(self.data[:n + 1])\n', (37526, 37545), True, 'import numpy as np\n'), ((37897, 37928), 'numpy.mean', 'np.mean', (['self.data[:n + hw + 1]'], {}), '(self.data[:n + hw + 1])\n', (37904, 37928), True, 'import numpy as np\n'), ((37958, 37990), 'numpy.mean', 'np.mean', (['self.data[-n - hw - 1:]'], {}), '(self.data[-n - hw - 1:])\n', (37965, 37990), True, 'import numpy as np\n'), ((2130, 2143), 'os.listdir', 'os.listdir', (['r'], {}), '(r)\n', (2140, 2143), False, 'import os, sys\n'), ((2189, 2209), 'os.path.isfile', 'os.path.isfile', (['item'], {}), '(item)\n', (2203, 2209), False, 'import os, sys\n'), ((2261, 2280), 'os.path.isdir', 'os.path.isdir', (['item'], {}), '(item)\n', (2274, 2280), False, 'import os, sys\n'), ((2329, 2351), 'os.path.splitext', 'os.path.splitext', (['item'], {}), '(item)\n', (2345, 2351), False, 'import os, sys\n'), ((3448, 3461), 'os.listdir', 'os.listdir', (['r'], {}), '(r)\n', (3458, 3461), False, 'import os, sys\n'), ((3652, 3671), 'os.path.isdir', 'os.path.isdir', (['item'], {}), '(item)\n', (3665, 3671), False, 'import os, sys\n'), ((3720, 3742), 'os.path.splitext', 'os.path.splitext', (['item'], {}), '(item)\n', (3736, 3742), False, 'import os, sys\n'), ((5082, 5095), 'os.listdir', 'os.listdir', (['r'], {}), '(r)\n', (5092, 5095), False, 'import os, sys\n'), ((5514, 5533), 'os.path.isdir', 'os.path.isdir', (['item'], {}), '(item)\n', (5527, 5533), False, 'import os, sys\n'), ((26251, 26277), 'numpy.diff', 'np.diff', (['current_wave_inds'], {}), '(current_wave_inds)\n', (26258, 26277), True, 'import numpy as np\n'), ((28117, 28131), 'numpy.array', 'np.array', (['mask'], {}), '(mask)\n', (28125, 28131), True, 'import numpy as np\n'), ((28226, 28245), 'numpy.diff', 'np.diff', (['valid_inds'], {}), '(valid_inds)\n', (28233, 28245), True, 'import numpy as np\n'), ((5624, 5646), 'os.path.splitext', 'os.path.splitext', (['item'], {}), '(item)\n', (5640, 5646), False, 'import os, sys\n'), ((5246, 5270), 're.compile', 're.compile', (['rec_patterns'], {}), '(rec_patterns)\n', (5256, 5270), False, 'import re\n'), ((5814, 5836), 'os.path.splitext', 'os.path.splitext', (['item'], {}), '(item)\n', (5830, 5836), False, 'import os, sys\n'), ((26315, 26341), 'numpy.diff', 'np.diff', (['current_wave_inds'], {}), '(current_wave_inds)\n', (26322, 26341), True, 'import numpy as np\n'), ((5422, 5449), 're.compile', 're.compile', (['rec_patterns[k]'], {}), '(rec_patterns[k])\n', (5432, 5449), False, 'import re\n')] |
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import normal_init
from mmcv.ops import batched_nms
from mmdet.core import vectorize_labels, bbox_overlaps
from ..builder import HEADS
from .anchor_head import AnchorHead
from .rpn_test_mixin import RPNTestMixin
import numpy as np
import collections
from mmdet.models.losses import ranking_losses
import pdb
@HEADS.register_module()
class RankBasedRPNHead(RPNTestMixin, AnchorHead):
"""RPN head.
Args:
in_channels (int): Number of channels in the input feature map.
""" # noqa: W605
"""RPN head.
Args:
in_channels (int): Number of channels in the input feature map.
""" # noqa: W605
def __init__(self, in_channels, head_weight=0.20, rank_loss_type = 'RankSort', **kwargs):
super(RankBasedRPNHead, self).__init__(1, in_channels, **kwargs)
self.head_weight = head_weight
self.rank_loss_type = rank_loss_type
if self.rank_loss_type == 'RankSort':
self.loss_rank = ranking_losses.RankSort()
elif self.rank_loss_type == 'aLRP':
self.loss_rank = ranking_losses.aLRPLoss()
self.SB_weight = 50
self.period = 7330
self.cls_LRP_hist = collections.deque(maxlen=self.period)
self.reg_LRP_hist = collections.deque(maxlen=self.period)
self.counter = 0
def _init_layers(self):
"""Initialize layers of the head."""
self.rpn_conv = nn.Conv2d(
self.in_channels, self.feat_channels, 3, padding=1)
self.rpn_cls = nn.Conv2d(self.feat_channels,
self.num_anchors * self.cls_out_channels, 1)
self.rpn_reg = nn.Conv2d(self.feat_channels, self.num_anchors * 4, 1)
def init_weights(self):
"""Initialize weights of the head."""
normal_init(self.rpn_conv, std=0.01)
normal_init(self.rpn_cls, std=0.01)
normal_init(self.rpn_reg, std=0.01)
def forward_single(self, x):
"""Forward feature map of a single scale level."""
x = self.rpn_conv(x)
x = F.relu(x, inplace=True)
rpn_cls_score = self.rpn_cls(x)
rpn_bbox_pred = self.rpn_reg(x)
return rpn_cls_score, rpn_bbox_pred
'''
def flatten_labels(self, flat_labels, label_weights):
prediction_number = flat_labels.shape[0]
labels = torch.zeros( [prediction_number], device=flat_labels.device)
labels[flat_labels == 0] = 1.
labels[label_weights == 0] = -1.
return labels.reshape(-1)
'''
def loss(self,
cls_scores,
bbox_preds,
gt_bboxes,
img_metas,
gt_bboxes_ignore=None):
"""Compute losses of the head.
Args:
cls_scores (list[Tensor]): Box scores for each scale level
Has shape (N, num_anchors * num_classes, H, W)
bbox_preds (list[Tensor]): Box energies / deltas for each scale
level with shape (N, num_anchors * 4, H, W)
gt_bboxes (list[Tensor]): Ground truth bboxes for each image with
shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.
img_metas (list[dict]): Meta information of each image, e.g.,
image size, scaling factor, etc.
gt_bboxes_ignore (None | list[Tensor]): specify which bounding
boxes can be ignored when computing the loss.
Returns:
dict[str, Tensor]: A dictionary of loss components.
"""
featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]
assert len(featmap_sizes) == self.anchor_generator.num_levels
device = cls_scores[0].device
anchor_list, valid_flag_list = self.get_anchors(
featmap_sizes, img_metas, device=device)
label_channels = self.cls_out_channels if self.use_sigmoid_cls else 1
cls_reg_targets = self.get_targets(
anchor_list,
valid_flag_list,
gt_bboxes,
img_metas,
gt_bboxes_ignore_list=gt_bboxes_ignore,
gt_labels_list=None,
label_channels=label_channels)
if cls_reg_targets is None:
return None
(labels_list, label_weights_list, bbox_targets_list, bbox_weights_list,
num_total_pos, num_total_neg) = cls_reg_targets
all_labels=[]
all_label_weights=[]
all_cls_scores=[]
all_bbox_targets=[]
all_bbox_weights=[]
all_bbox_preds=[]
for labels, label_weights, cls_score, bbox_targets, bbox_weights, bbox_pred in zip(labels_list, label_weights_list,cls_scores, bbox_targets_list, bbox_weights_list, bbox_preds):
all_labels.append(labels.reshape(-1))
all_label_weights.append(label_weights.reshape(-1))
all_cls_scores.append(cls_score.permute(0, 2, 3, 1).reshape(-1, self.cls_out_channels))
all_bbox_targets.append(bbox_targets.reshape(-1, 4))
all_bbox_weights.append(bbox_weights.reshape(-1, 4))
all_bbox_preds.append(bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4))
cls_labels = torch.cat(all_labels)
all_scores=torch.cat(all_cls_scores)
pos_idx = (cls_labels < self.num_classes)
#flatten_anchors = torch.cat([torch.cat(item, 0) for item in anchor_list])
if pos_idx.sum() > 0:
# regression loss
pos_pred = self.delta2bbox(torch.cat(all_bbox_preds)[pos_idx])
pos_target = self.delta2bbox(torch.cat(all_bbox_targets)[pos_idx])
loss_bbox = self.loss_bbox(pos_pred, pos_target)
# flat_labels = self.flatten_labels(cls_labels, torch.cat(all_label_weights))
flat_labels = vectorize_labels(cls_labels, self.num_classes, torch.cat(all_label_weights))
flat_preds = all_scores.reshape(-1)
if self.rank_loss_type == 'RankSort':
pos_weights = all_scores.detach().sigmoid().max(dim=1)[0][pos_idx]
bbox_avg_factor = torch.sum(pos_weights)
if bbox_avg_factor < 1e-10:
bbox_avg_factor = 1
loss_bbox = torch.sum(pos_weights*loss_bbox)/bbox_avg_factor
IoU_targets = bbox_overlaps(pos_pred.detach(), pos_target, is_aligned=True)
flat_labels[flat_labels==1]=IoU_targets
ranking_loss, sorting_loss = self.loss_rank.apply(flat_preds, flat_labels)
self.SB_weight = (ranking_loss+sorting_loss).detach()/float(loss_bbox.item())
if ranking_loss == 0 and sorting_loss == 0:
print(self.SB_weight)
print(loss_bbox)
self.SB_weight = torch.tensor(0.).cuda()
loss_bbox = torch.tensor(0.).cuda()
print(self.SB_weight)
print(loss_bbox)
else:
loss_bbox *= self.SB_weight
return dict(loss_rpn_rank=self.head_weight*ranking_loss, loss_rpn_sort=self.head_weight*sorting_loss, loss_rpn_bbox=self.head_weight*loss_bbox)
elif self.rank_loss_type == 'aLRP':
e_loc = loss_bbox.detach()/(2*(1-0.7))
losses_cls, rank, order = self.loss_rank.apply(flat_preds, flat_labels, e_loc)
# Order the regression losses considering the scores.
ordered_losses_bbox = loss_bbox[order.detach()].flip(dims=[0])
# aLRP Regression Component
losses_bbox = ((torch.cumsum(ordered_losses_bbox,dim=0)/rank[order.detach()].detach().flip(dims=[0])).mean())
# Self-balancing
self.cls_LRP_hist.append(float(losses_cls.item()))
self.reg_LRP_hist.append(float(losses_bbox.item()))
self.counter+=1
if self.counter == self.period:
self.SB_weight = (np.mean(self.reg_LRP_hist)+np.mean(self.cls_LRP_hist))/np.mean(self.reg_LRP_hist)
self.cls_LRP_hist.clear()
self.reg_LRP_hist.clear()
self.counter=0
losses_bbox *= self.SB_weight
return dict(loss_rpn_cls=self.head_weight*losses_cls, loss_rpn_bbox=self.head_weight*losses_bbox)
else:
losses_bbox=torch.cat(all_bbox_preds).sum()*0+1
if self.rank_loss_type == 'RankSort':
ranking_loss = all_scores.sum()*0+1
sorting_loss = all_scores.sum()*0+1
return dict(loss_rpn_rank=self.head_weight*ranking_loss, loss_rpn_sort=self.head_weight*sorting_loss, loss_rpn_bbox=self.head_weight*losses_bbox)
else:
losses_cls = all_scores.sum()*0+1
return dict(loss_rpn_cls=self.head_weight*losses_cls, loss_rpn_bbox=self.head_weight*losses_bbox)
def delta2bbox(self, deltas, means=[0., 0., 0., 0.], stds=[0.1, 0.1, 0.2, 0.2], max_shape=None, wh_ratio_clip=16/1000):
wx, wy, ww, wh = stds
dx = deltas[:, 0] * wx
dy = deltas[:, 1] * wy
dw = deltas[:, 2] * ww
dh = deltas[:, 3] * wh
max_ratio = np.abs(np.log(wh_ratio_clip))
dw = dw.clamp(min=-max_ratio, max=max_ratio)
dh = dh.clamp(min=-max_ratio, max=max_ratio)
pred_ctr_x = dx
pred_ctr_y = dy
pred_w = torch.exp(dw)
pred_h = torch.exp(dh)
x1 = pred_ctr_x - 0.5 * pred_w
y1 = pred_ctr_y - 0.5 * pred_h
x2 = pred_ctr_x + 0.5 * pred_w
y2 = pred_ctr_y + 0.5 * pred_h
return torch.stack([x1, y1, x2, y2], dim=-1)
def _get_bboxes_single(self,
cls_scores,
bbox_preds,
mlvl_anchors,
img_shape,
scale_factor,
cfg,
rescale=False):
"""Transform outputs for a single batch item into bbox predictions.
Args:
cls_scores (list[Tensor]): Box scores for each scale level
Has shape (num_anchors * num_classes, H, W).
bbox_preds (list[Tensor]): Box energies / deltas for each scale
level with shape (num_anchors * 4, H, W).
mlvl_anchors (list[Tensor]): Box reference for each scale level
with shape (num_total_anchors, 4).
img_shape (tuple[int]): Shape of the input image,
(height, width, 3).
scale_factor (ndarray): Scale factor of the image arange as
(w_scale, h_scale, w_scale, h_scale).
cfg (mmcv.Config): Test / postprocessing configuration,
if None, test_cfg would be used.
rescale (bool): If True, return boxes in original image space.
Returns:
Tensor: Labeled boxes in shape (n, 5), where the first 4 columns
are bounding box positions (tl_x, tl_y, br_x, br_y) and the
5-th column is a score between 0 and 1.
"""
cfg = self.test_cfg if cfg is None else cfg
# bboxes from different level should be independent during NMS,
# level_ids are used as labels for batched NMS to separate them
level_ids = []
mlvl_scores = []
mlvl_bbox_preds = []
mlvl_valid_anchors = []
for idx in range(len(cls_scores)):
rpn_cls_score = cls_scores[idx]
rpn_bbox_pred = bbox_preds[idx]
assert rpn_cls_score.size()[-2:] == rpn_bbox_pred.size()[-2:]
rpn_cls_score = rpn_cls_score.permute(1, 2, 0)
if self.use_sigmoid_cls:
rpn_cls_score = rpn_cls_score.reshape(-1)
scores = rpn_cls_score.sigmoid()
else:
rpn_cls_score = rpn_cls_score.reshape(-1, 2)
# We set FG labels to [0, num_class-1] and BG label to
# num_class in RPN head since mmdet v2.5, which is unified to
# be consistent with other head since mmdet v2.0. In mmdet v2.0
# to v2.4 we keep BG label as 0 and FG label as 1 in rpn head.
scores = rpn_cls_score.softmax(dim=1)[:, 0]
rpn_bbox_pred = rpn_bbox_pred.permute(1, 2, 0).reshape(-1, 4)
anchors = mlvl_anchors[idx]
if cfg.nms_pre > 0 and scores.shape[0] > cfg.nms_pre:
# sort is faster than topk
# _, topk_inds = scores.topk(cfg.nms_pre)
ranked_scores, rank_inds = scores.sort(descending=True)
topk_inds = rank_inds[:cfg.nms_pre]
scores = ranked_scores[:cfg.nms_pre]
rpn_bbox_pred = rpn_bbox_pred[topk_inds, :]
anchors = anchors[topk_inds, :]
mlvl_scores.append(scores)
mlvl_bbox_preds.append(rpn_bbox_pred)
mlvl_valid_anchors.append(anchors)
level_ids.append(
scores.new_full((scores.size(0), ), idx, dtype=torch.long))
scores = torch.cat(mlvl_scores)
anchors = torch.cat(mlvl_valid_anchors)
rpn_bbox_pred = torch.cat(mlvl_bbox_preds)
proposals = self.bbox_coder.decode(
anchors, rpn_bbox_pred, max_shape=img_shape)
ids = torch.cat(level_ids)
if cfg.min_bbox_size > 0:
w = proposals[:, 2] - proposals[:, 0]
h = proposals[:, 3] - proposals[:, 1]
valid_inds = torch.nonzero(
(w >= cfg.min_bbox_size)
& (h >= cfg.min_bbox_size),
as_tuple=False).squeeze()
if valid_inds.sum().item() != len(proposals):
proposals = proposals[valid_inds, :]
scores = scores[valid_inds]
ids = ids[valid_inds]
# TODO: remove the hard coded nms type
nms_cfg = dict(type='nms', iou_threshold=cfg.nms_thr)
dets, keep = batched_nms(proposals, scores, ids, nms_cfg)
return dets[:cfg.nms_post]
| [
"torch.cumsum",
"numpy.mean",
"collections.deque",
"torch.stack",
"numpy.log",
"torch.exp",
"mmcv.cnn.normal_init",
"torch.nn.Conv2d",
"torch.nonzero",
"mmdet.models.losses.ranking_losses.RankSort",
"torch.tensor",
"torch.sum",
"torch.nn.functional.relu",
"mmcv.ops.batched_nms",
"torch.c... | [((1493, 1554), 'torch.nn.Conv2d', 'nn.Conv2d', (['self.in_channels', 'self.feat_channels', '(3)'], {'padding': '(1)'}), '(self.in_channels, self.feat_channels, 3, padding=1)\n', (1502, 1554), True, 'import torch.nn as nn\n'), ((1591, 1665), 'torch.nn.Conv2d', 'nn.Conv2d', (['self.feat_channels', '(self.num_anchors * self.cls_out_channels)', '(1)'], {}), '(self.feat_channels, self.num_anchors * self.cls_out_channels, 1)\n', (1600, 1665), True, 'import torch.nn as nn\n'), ((1722, 1776), 'torch.nn.Conv2d', 'nn.Conv2d', (['self.feat_channels', '(self.num_anchors * 4)', '(1)'], {}), '(self.feat_channels, self.num_anchors * 4, 1)\n', (1731, 1776), True, 'import torch.nn as nn\n'), ((1860, 1896), 'mmcv.cnn.normal_init', 'normal_init', (['self.rpn_conv'], {'std': '(0.01)'}), '(self.rpn_conv, std=0.01)\n', (1871, 1896), False, 'from mmcv.cnn import normal_init\n'), ((1905, 1940), 'mmcv.cnn.normal_init', 'normal_init', (['self.rpn_cls'], {'std': '(0.01)'}), '(self.rpn_cls, std=0.01)\n', (1916, 1940), False, 'from mmcv.cnn import normal_init\n'), ((1949, 1984), 'mmcv.cnn.normal_init', 'normal_init', (['self.rpn_reg'], {'std': '(0.01)'}), '(self.rpn_reg, std=0.01)\n', (1960, 1984), False, 'from mmcv.cnn import normal_init\n'), ((2119, 2142), 'torch.nn.functional.relu', 'F.relu', (['x'], {'inplace': '(True)'}), '(x, inplace=True)\n', (2125, 2142), True, 'import torch.nn.functional as F\n'), ((5207, 5228), 'torch.cat', 'torch.cat', (['all_labels'], {}), '(all_labels)\n', (5216, 5228), False, 'import torch\n'), ((5248, 5273), 'torch.cat', 'torch.cat', (['all_cls_scores'], {}), '(all_cls_scores)\n', (5257, 5273), False, 'import torch\n'), ((9477, 9490), 'torch.exp', 'torch.exp', (['dw'], {}), '(dw)\n', (9486, 9490), False, 'import torch\n'), ((9508, 9521), 'torch.exp', 'torch.exp', (['dh'], {}), '(dh)\n', (9517, 9521), False, 'import torch\n'), ((9703, 9740), 'torch.stack', 'torch.stack', (['[x1, y1, x2, y2]'], {'dim': '(-1)'}), '([x1, y1, x2, y2], dim=-1)\n', (9714, 9740), False, 'import torch\n'), ((13173, 13195), 'torch.cat', 'torch.cat', (['mlvl_scores'], {}), '(mlvl_scores)\n', (13182, 13195), False, 'import torch\n'), ((13214, 13243), 'torch.cat', 'torch.cat', (['mlvl_valid_anchors'], {}), '(mlvl_valid_anchors)\n', (13223, 13243), False, 'import torch\n'), ((13268, 13294), 'torch.cat', 'torch.cat', (['mlvl_bbox_preds'], {}), '(mlvl_bbox_preds)\n', (13277, 13294), False, 'import torch\n'), ((13410, 13430), 'torch.cat', 'torch.cat', (['level_ids'], {}), '(level_ids)\n', (13419, 13430), False, 'import torch\n'), ((14057, 14101), 'mmcv.ops.batched_nms', 'batched_nms', (['proposals', 'scores', 'ids', 'nms_cfg'], {}), '(proposals, scores, ids, nms_cfg)\n', (14068, 14101), False, 'from mmcv.ops import batched_nms\n'), ((1038, 1063), 'mmdet.models.losses.ranking_losses.RankSort', 'ranking_losses.RankSort', ([], {}), '()\n', (1061, 1063), False, 'from mmdet.models.losses import ranking_losses\n'), ((9281, 9302), 'numpy.log', 'np.log', (['wh_ratio_clip'], {}), '(wh_ratio_clip)\n', (9287, 9302), True, 'import numpy as np\n'), ((1137, 1162), 'mmdet.models.losses.ranking_losses.aLRPLoss', 'ranking_losses.aLRPLoss', ([], {}), '()\n', (1160, 1162), False, 'from mmdet.models.losses import ranking_losses\n'), ((1258, 1295), 'collections.deque', 'collections.deque', ([], {'maxlen': 'self.period'}), '(maxlen=self.period)\n', (1275, 1295), False, 'import collections\n'), ((1328, 1365), 'collections.deque', 'collections.deque', ([], {'maxlen': 'self.period'}), '(maxlen=self.period)\n', (1345, 1365), False, 'import collections\n'), ((5846, 5874), 'torch.cat', 'torch.cat', (['all_label_weights'], {}), '(all_label_weights)\n', (5855, 5874), False, 'import torch\n'), ((6092, 6114), 'torch.sum', 'torch.sum', (['pos_weights'], {}), '(pos_weights)\n', (6101, 6114), False, 'import torch\n'), ((5506, 5531), 'torch.cat', 'torch.cat', (['all_bbox_preds'], {}), '(all_bbox_preds)\n', (5515, 5531), False, 'import torch\n'), ((5583, 5610), 'torch.cat', 'torch.cat', (['all_bbox_targets'], {}), '(all_bbox_targets)\n', (5592, 5610), False, 'import torch\n'), ((6228, 6262), 'torch.sum', 'torch.sum', (['(pos_weights * loss_bbox)'], {}), '(pos_weights * loss_bbox)\n', (6237, 6262), False, 'import torch\n'), ((13591, 13678), 'torch.nonzero', 'torch.nonzero', (['((w >= cfg.min_bbox_size) & (h >= cfg.min_bbox_size))'], {'as_tuple': '(False)'}), '((w >= cfg.min_bbox_size) & (h >= cfg.min_bbox_size), as_tuple\n =False)\n', (13604, 13678), False, 'import torch\n'), ((6788, 6805), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (6800, 6805), False, 'import torch\n'), ((6844, 6861), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (6856, 6861), False, 'import torch\n'), ((8078, 8104), 'numpy.mean', 'np.mean', (['self.reg_LRP_hist'], {}), '(self.reg_LRP_hist)\n', (8085, 8104), True, 'import numpy as np\n'), ((8431, 8456), 'torch.cat', 'torch.cat', (['all_bbox_preds'], {}), '(all_bbox_preds)\n', (8440, 8456), False, 'import torch\n'), ((7629, 7669), 'torch.cumsum', 'torch.cumsum', (['ordered_losses_bbox'], {'dim': '(0)'}), '(ordered_losses_bbox, dim=0)\n', (7641, 7669), False, 'import torch\n'), ((8023, 8049), 'numpy.mean', 'np.mean', (['self.reg_LRP_hist'], {}), '(self.reg_LRP_hist)\n', (8030, 8049), True, 'import numpy as np\n'), ((8050, 8076), 'numpy.mean', 'np.mean', (['self.cls_LRP_hist'], {}), '(self.cls_LRP_hist)\n', (8057, 8076), True, 'import numpy as np\n')] |
import sys,os
import pandas as pd
import numpy as np
from sklearn.metrics import confusion_matrix
from networkx import DiGraph
from networkx import relabel_nodes
from sklearn_hierarchical_classification.constants import ROOT
from tqdm import tqdm
import itertools
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 12})
def recursive_predict(graph, classes, class_prob, node):
# If node is leaf, return it
if len(list(graph.successors(node))) == 0:
return node
indices = [classes.index(child_node_id) for child_node_id in graph.successors(node)]
probs = class_prob[indices]
pred_idx = np.argmax(probs)
pred_node = classes[indices[pred_idx]]
pred = recursive_predict(graph, classes, class_prob, pred_node)
return pred
def get_multilabel(pred, graph):
leaf_nodes = [node for node in graph.nodes() if (graph.out_degree(node) == 0)\
and (graph.in_degree(node) == 1)]
nodes = [node for node in graph.nodes() if node != '<ROOT>']
multilabel_pred = np.zeros((pred.shape[0], len(nodes)))
for i in range(pred.shape[0]):
node = pred[i]
while (node != '<ROOT>'):
multilabel_pred[i,node] = 1
predecessors = [idx for idx in graph.predecessors(node)]
node = predecessors[0] # only one parent per node
return multilabel_pred
def get_confusion_matrix(y_true, y_pred, states, plot_states):
y_true_relabel = np.zeros(y_true.shape)
y_pred_relabel = np.zeros(y_pred.shape)
for new_idx,lbl in enumerate(plot_states):
old_idx = states.index(lbl)
y_true_relabel[:,new_idx] = y_true[:,old_idx]
y_pred_relabel[:,new_idx] = y_pred[:,old_idx]
conf_mat = np.dot(y_true_relabel.T, y_pred_relabel)
denom = y_true_relabel.sum(axis=0)
conf_mat = conf_mat.astype(float) / denom.reshape(-1,1)
return conf_mat
def main(argv):
infile = argv[0]
mode = argv[1]
dataset = argv[2]
outdir = argv[3]
# Class hierarchy for sleep stages
class_hierarchy = {
ROOT : {"Wear", "Nonwear"},
"Wear" : {"Wake", "Sleep"},
"Sleep" : {"NREM", "REM"},
"NREM" : {"Light", "NREM 3"},
"Light" : {"NREM 1", "NREM 2"}
}
graph = DiGraph(class_hierarchy)
df = pd.read_csv(infile)
nfolds = len(set(df['Fold']))
sleep_states = [col.split('_')[1] for col in df.columns if col.startswith('true')]
sleep_labels = [idx for idx,state in enumerate(sleep_states)]
true_cols = [col for col in df.columns if col.startswith('true')]
pred_cols = [col for col in df.columns if col.startswith('smooth')]
nclasses = len(true_cols)
node_label_mapping = {
old_label: new_label
for new_label, old_label in enumerate(list(sleep_states))
}
graph = relabel_nodes(graph, node_label_mapping)
plot_states = ['Nonwear', 'Wear', 'Wake', 'Sleep', 'NREM', 'REM',\
'Light', 'NREM 3', 'NREM 1', 'NREM 2']
confusion_mat = np.zeros((len(sleep_states),len(sleep_states)))
for fold in range(nfolds):
true_prob = df[df['Fold'] == fold+1][true_cols].values
pred_prob = df[df['Fold'] == fold+1][pred_cols].values
y_pred = []
for i in tqdm(range(pred_prob.shape[0])):
pred = recursive_predict(graph, list(range(len(sleep_states))), pred_prob[i], '<ROOT>')
y_pred.append(pred)
y_pred = np.array(y_pred)
y_pred = get_multilabel(y_pred, graph).astype(int)
fold_conf_mat = get_confusion_matrix(true_prob, y_pred, sleep_states, plot_states)
confusion_mat = confusion_mat + fold_conf_mat
confusion_mat = confusion_mat*100.0 / nfolds
# Plot confusion matrix
plot_labels = ['Nonwear', 'Wear', 'Wake', 'Sleep', 'NREM', 'REM',\
'N1+N2', 'N3', 'N1', 'N2']
plt.imshow(confusion_mat, interpolation='nearest', cmap=plt.cm.Blues, aspect='auto')
plt.colorbar()
tick_marks = np.arange(len(sleep_states))
plt.xticks(tick_marks, plot_labels, rotation=45)
plt.yticks(tick_marks, plot_labels)
thresh = confusion_mat.max() / 2.0
for i, j in itertools.product(range(confusion_mat.shape[0]), range(confusion_mat.shape[1])):
plt.text(j, i, '{:0.2f}'.format(confusion_mat[i, j]),\
horizontalalignment="center", fontsize=9,\
color="white" if confusion_mat[i, j] > thresh else "black")
plt.ylabel('True label', fontsize=14)
plt.xlabel('Predicted label', fontsize=14)
plt.tight_layout()
plt.savefig(os.path.join(outdir, '-'.join((dataset, mode, 'confmat')) + '.jpg'))
if __name__ == "__main__":
main(sys.argv[1:])
| [
"matplotlib.pyplot.imshow",
"networkx.relabel_nodes",
"pandas.read_csv",
"matplotlib.pyplot.xticks",
"matplotlib.use",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"networkx.DiGraph",
"matplotlib.pyplot.colorbar",
"numpy.argmax",
"matplotlib.pyplot.rcParams.update",
"numpy.zeros",
... | [((282, 303), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (296, 303), False, 'import matplotlib\n'), ((336, 374), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 12}"], {}), "({'font.size': 12})\n", (355, 374), True, 'import matplotlib.pyplot as plt\n'), ((657, 673), 'numpy.argmax', 'np.argmax', (['probs'], {}), '(probs)\n', (666, 673), True, 'import numpy as np\n'), ((1464, 1486), 'numpy.zeros', 'np.zeros', (['y_true.shape'], {}), '(y_true.shape)\n', (1472, 1486), True, 'import numpy as np\n'), ((1506, 1528), 'numpy.zeros', 'np.zeros', (['y_pred.shape'], {}), '(y_pred.shape)\n', (1514, 1528), True, 'import numpy as np\n'), ((1719, 1759), 'numpy.dot', 'np.dot', (['y_true_relabel.T', 'y_pred_relabel'], {}), '(y_true_relabel.T, y_pred_relabel)\n', (1725, 1759), True, 'import numpy as np\n'), ((2207, 2231), 'networkx.DiGraph', 'DiGraph', (['class_hierarchy'], {}), '(class_hierarchy)\n', (2214, 2231), False, 'from networkx import DiGraph\n'), ((2245, 2264), 'pandas.read_csv', 'pd.read_csv', (['infile'], {}), '(infile)\n', (2256, 2264), True, 'import pandas as pd\n'), ((2745, 2785), 'networkx.relabel_nodes', 'relabel_nodes', (['graph', 'node_label_mapping'], {}), '(graph, node_label_mapping)\n', (2758, 2785), False, 'from networkx import relabel_nodes\n'), ((3721, 3809), 'matplotlib.pyplot.imshow', 'plt.imshow', (['confusion_mat'], {'interpolation': '"""nearest"""', 'cmap': 'plt.cm.Blues', 'aspect': '"""auto"""'}), "(confusion_mat, interpolation='nearest', cmap=plt.cm.Blues,\n aspect='auto')\n", (3731, 3809), True, 'import matplotlib.pyplot as plt\n'), ((3808, 3822), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (3820, 3822), True, 'import matplotlib.pyplot as plt\n'), ((3869, 3917), 'matplotlib.pyplot.xticks', 'plt.xticks', (['tick_marks', 'plot_labels'], {'rotation': '(45)'}), '(tick_marks, plot_labels, rotation=45)\n', (3879, 3917), True, 'import matplotlib.pyplot as plt\n'), ((3920, 3955), 'matplotlib.pyplot.yticks', 'plt.yticks', (['tick_marks', 'plot_labels'], {}), '(tick_marks, plot_labels)\n', (3930, 3955), True, 'import matplotlib.pyplot as plt\n'), ((4280, 4317), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""True label"""'], {'fontsize': '(14)'}), "('True label', fontsize=14)\n", (4290, 4317), True, 'import matplotlib.pyplot as plt\n'), ((4320, 4362), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Predicted label"""'], {'fontsize': '(14)'}), "('Predicted label', fontsize=14)\n", (4330, 4362), True, 'import matplotlib.pyplot as plt\n'), ((4365, 4383), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4381, 4383), True, 'import matplotlib.pyplot as plt\n'), ((3323, 3339), 'numpy.array', 'np.array', (['y_pred'], {}), '(y_pred)\n', (3331, 3339), True, 'import numpy as np\n')] |
import numpy as np
import json
from turorials.perlin_noise.obstacle_generation import flood_grid
class EnvironmentRepresentation:
def __init__(self):
self.obstacle_map = None
self.terrain_map = None
self.start_positions = None
self.nb_free_tiles = 0
self.dim = (8, 8)
self.extra_spacing = (0, 0)
def set_dimension(self, n_dim):
self.dim = n_dim
def set_extra_spacing(self, n_spacing):
self.extra_spacing = n_spacing
def get_dimension(self):
return self.dim
def get_obstacle_map(self, extra_spacing=False):
if not extra_spacing:
x_tot, y_tot = self.obstacle_map.shape
return self.obstacle_map[
self.extra_spacing[0]:x_tot-self.extra_spacing[0],
self.extra_spacing[1]:y_tot-self.extra_spacing[1]
]
else:
return self.obstacle_map
def get_terrain_map(self, extra_spacing=False):
if not extra_spacing:
x_tot, y_tot = self.obstacle_map.shape
return self.terrain_map[
self.extra_spacing[0]:x_tot-self.extra_spacing[0],
self.extra_spacing[1]:y_tot-self.extra_spacing[1]
]
else:
return self.terrain_map
def has_terrain_info(self):
return self.terrain_map is not None
def save(self, path, name):
json_to_save = {}
obstacle_path = f"{path}{name}_obstacle_grid.npy"
np.save(obstacle_path, self.obstacle_map)
json_to_save['obstacle_grid'] = obstacle_path
json_to_save['terrain_grid'] = None
if self.terrain_map is not None:
terrain_path = f"{path}{name}_terrain_grid.npy"
np.save(terrain_path, self.terrain_map)
json_to_save['terrain_grid'] = terrain_path
json_to_save['start_positions'] = self.start_positions
json_to_save['nb_free_tiles'] = self.nb_free_tiles
with open(f'{path}{name}.txt', 'w') as output_file:
json.dump(json_to_save, output_file)
def load(self, path, name):
with open(f'{path}{name}.txt') as input_file:
input_data = json.load(input_file)
obstacle_path = input_data['obstacle_grid']
self.obstacle_map = np.load(obstacle_path)
terrain_path = input_data['terrain_grid']
if terrain_path is not None:
self.terrain_map = np.load(terrain_path)
start_positions_array = np.array(input_data['start_positions'])
self.start_positions = [pos for pos in zip(start_positions_array[:, 0], start_positions_array[:, 1])]
self.nb_free_tiles = input_data['nb_free_tiles']
class GeneralEnvironmentRepresentation:
def __init__(self, n_obstacle_map, nb_free_tiles, stat_positions,
n_terrain_map, extra_spacing=0):
assert(n_obstacle_map.shape == n_terrain_map.shape)
self.extra_spacing = extra_spacing
self.obstacle_map = n_obstacle_map
self.nb_free_tiles = nb_free_tiles
self.start_positions = stat_positions
self.terrain_map = n_terrain_map
def get_nb_free_tiles(self):
return self.nb_free_tiles
def get_start_positions(self):
return self.start_positions
def get_obstacle_map(self, extra_spacing=0):
assert(extra_spacing <= self.extra_spacing)
offset = self.extra_spacing - extra_spacing
x_tot, y_tot = self.obstacle_map.shape
return self.obstacle_map[
offset:x_tot - offset,
offset:y_tot - offset
]
def get_terrain_map(self, extra_spacing=0):
assert (extra_spacing <= self.extra_spacing)
offset = self.extra_spacing - extra_spacing
x_tot, y_tot = self.terrain_map.shape
return self.terrain_map[
offset:x_tot-offset,
offset:y_tot-offset
]
def save(self, path, name):
json_to_save = {}
obstacle_path = f"{path}{name}_obstacle_grid.npy"
np.save(obstacle_path, self.obstacle_map)
json_to_save['obstacle_grid'] = obstacle_path
terrain_path = f"{path}{name}_terrain_grid.npy"
np.save(terrain_path, self.terrain_map)
json_to_save['terrain_grid'] = terrain_path
json_to_save['start_positions'] = self.start_positions
json_to_save['nb_free_tiles'] = self.nb_free_tiles
json_to_save['extra_spacing'] = self.extra_spacing
with open(f'{path}{name}.txt', 'w') as output_file:
json.dump(json_to_save, output_file)
def load(self, path, name):
with open(f'{path}{name}.txt') as input_file:
input_data = json.load(input_file)
obstacle_path = input_data['obstacle_grid']
self.obstacle_map = np.load(obstacle_path)
terrain_path = input_data['terrain_grid']
self.terrain_map = np.load(terrain_path)
start_positions_array = np.array(input_data['start_positions'])
self.start_positions = [pos for pos in zip(start_positions_array[:, 0], start_positions_array[:, 1])]
self.nb_free_tiles = input_data['nb_free_tiles']
self.extra_spacing = input_data['extra_spacing']
if __name__ == "__main__":
save_path = "D:/Documenten/Studie/2020-2021/Masterproef/Reinforcement-Learner-For-Coverage-Path-Planning/data/"
name = "test_grid.npy"
obstacle_grid = np.load(save_path + name)
env_repr = EnvironmentRepresentation()
env_repr.obstacle_map = obstacle_grid
regions = flood_grid(obstacle_grid)
if regions[0][0] == 0:
env_repr.start_positions = regions[0][1]
env_repr.nb_free_tiles = len(regions[0][1]) + len(regions[0][2])
print(regions[0][1])
if regions[1][0] == 0:
env_repr.start_positions = regions[1][1]
env_repr.nb_free_tiles = len(regions[1][1]) + len(regions[1][2])
print(regions[1][1])
env_repr.save(save_path, "test_representation")
env_repr2 = EnvironmentRepresentation()
env_repr2.load(save_path, "test_representation")
print(env_repr2.nb_free_tiles)
print(env_repr2.start_positions) | [
"json.dump",
"numpy.array",
"turorials.perlin_noise.obstacle_generation.flood_grid",
"json.load",
"numpy.load",
"numpy.save"
] | [((5488, 5513), 'numpy.load', 'np.load', (['(save_path + name)'], {}), '(save_path + name)\n', (5495, 5513), True, 'import numpy as np\n'), ((5615, 5640), 'turorials.perlin_noise.obstacle_generation.flood_grid', 'flood_grid', (['obstacle_grid'], {}), '(obstacle_grid)\n', (5625, 5640), False, 'from turorials.perlin_noise.obstacle_generation import flood_grid\n'), ((1506, 1547), 'numpy.save', 'np.save', (['obstacle_path', 'self.obstacle_map'], {}), '(obstacle_path, self.obstacle_map)\n', (1513, 1547), True, 'import numpy as np\n'), ((4084, 4125), 'numpy.save', 'np.save', (['obstacle_path', 'self.obstacle_map'], {}), '(obstacle_path, self.obstacle_map)\n', (4091, 4125), True, 'import numpy as np\n'), ((4245, 4284), 'numpy.save', 'np.save', (['terrain_path', 'self.terrain_map'], {}), '(terrain_path, self.terrain_map)\n', (4252, 4284), True, 'import numpy as np\n'), ((1760, 1799), 'numpy.save', 'np.save', (['terrain_path', 'self.terrain_map'], {}), '(terrain_path, self.terrain_map)\n', (1767, 1799), True, 'import numpy as np\n'), ((2052, 2088), 'json.dump', 'json.dump', (['json_to_save', 'output_file'], {}), '(json_to_save, output_file)\n', (2061, 2088), False, 'import json\n'), ((2201, 2222), 'json.load', 'json.load', (['input_file'], {}), '(input_file)\n', (2210, 2222), False, 'import json\n'), ((2311, 2333), 'numpy.load', 'np.load', (['obstacle_path'], {}), '(obstacle_path)\n', (2318, 2333), True, 'import numpy as np\n'), ((2524, 2563), 'numpy.array', 'np.array', (["input_data['start_positions']"], {}), "(input_data['start_positions'])\n", (2532, 2563), True, 'import numpy as np\n'), ((4592, 4628), 'json.dump', 'json.dump', (['json_to_save', 'output_file'], {}), '(json_to_save, output_file)\n', (4601, 4628), False, 'import json\n'), ((4741, 4762), 'json.load', 'json.load', (['input_file'], {}), '(input_file)\n', (4750, 4762), False, 'import json\n'), ((4852, 4874), 'numpy.load', 'np.load', (['obstacle_path'], {}), '(obstacle_path)\n', (4859, 4874), True, 'import numpy as np\n'), ((4961, 4982), 'numpy.load', 'np.load', (['terrain_path'], {}), '(terrain_path)\n', (4968, 4982), True, 'import numpy as np\n'), ((5020, 5059), 'numpy.array', 'np.array', (["input_data['start_positions']"], {}), "(input_data['start_positions'])\n", (5028, 5059), True, 'import numpy as np\n'), ((2465, 2486), 'numpy.load', 'np.load', (['terrain_path'], {}), '(terrain_path)\n', (2472, 2486), True, 'import numpy as np\n')] |
import cv2
import argparse
import numpy as np
from model import Model
from plot_history import plot_model
from tensorflow.keras.optimizers import Adam
from FER2013_data_prep import train_generator, validation_generator
epoch = 50
num_val = 7178
batch_size = 64
num_train = 28709
model = Model()
# Temporarily disable the argparse library for fast debugging
ap = argparse.ArgumentParser("Choose mode")
ap.add_argument("--mode", help="train/display")
mode = ap.parse_args().mode
# mode = input("[Mode]\n>> ")
# print("Mode:", mode)
# Train same model or try other models
if mode == "train":
model.compile(loss="categorical_crossentropy", optimizer=Adam(lr=0.0001, decay=1e-6), metrics=["accuracy"])
model_info = model.fit(
train_generator,
steps_per_epoch=num_train // batch_size,
epochs=epoch,
validation_data=validation_generator,
validation_steps=num_val // batch_size
#callbacks=callback
)
model.save_weights("weight/model.h5")
plot_model(model_info)
# emotions will be displayed on your face from the webcam feed
elif mode == "display":
model.load_weights("weight/model.h5")
cv2.ocl.setUseOpenCL(False)
emotion_dict = {0: "Angry", 1: "Disgusted", 2: "Fearful", 3: "Happy", 4: "Neutral", 5: "Sad", 6: "Surprised"}
cap = cv2.VideoCapture(0)
# cap = cv2.VideoCapture(cv2.CAP_DSHOW)
while True:
ret, frame = cap.read()
frame = cv2.flip(frame, 1)
if not ret:
break
facecasc = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = facecasc.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
for(x, y, w, h) in faces:
cv2.rectangle(frame, (x, y-50), (x+w, y+h+10), (255, 0, 0), 2)
roi_gray = gray[y:y + h, x:x + w]
cropped_img = np.expand_dims(np.expand_dims(cv2.resize(roi_gray, (48, 48)), -1), 0)
prediction = model.predict(cropped_img)
maxindex = int(np.argmax(prediction))
cv2.putText(frame, emotion_dict[maxindex], (x + 20, y - 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255),
2, cv2.LINE_AA)
cv2.imshow('Video', cv2.resize(frame, (1600, 960), interpolation=cv2.INTER_CUBIC))
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows() | [
"cv2.ocl.setUseOpenCL",
"cv2.rectangle",
"model.Model",
"cv2.flip",
"argparse.ArgumentParser",
"numpy.argmax",
"cv2.putText",
"tensorflow.keras.optimizers.Adam",
"plot_history.plot_model",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.cvtColor",
"cv2.CascadeClassifier",
"cv2.resize",
... | [((289, 296), 'model.Model', 'Model', ([], {}), '()\n', (294, 296), False, 'from model import Model\n'), ((365, 403), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""Choose mode"""'], {}), "('Choose mode')\n", (388, 403), False, 'import argparse\n'), ((1005, 1027), 'plot_history.plot_model', 'plot_model', (['model_info'], {}), '(model_info)\n', (1015, 1027), False, 'from plot_history import plot_model\n'), ((1163, 1190), 'cv2.ocl.setUseOpenCL', 'cv2.ocl.setUseOpenCL', (['(False)'], {}), '(False)\n', (1183, 1190), False, 'import cv2\n'), ((1316, 1335), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (1332, 1335), False, 'import cv2\n'), ((2414, 2437), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2435, 2437), False, 'import cv2\n'), ((655, 683), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.0001)', 'decay': '(1e-06)'}), '(lr=0.0001, decay=1e-06)\n', (659, 683), False, 'from tensorflow.keras.optimizers import Adam\n'), ((1446, 1464), 'cv2.flip', 'cv2.flip', (['frame', '(1)'], {}), '(frame, 1)\n', (1454, 1464), False, 'import cv2\n'), ((1524, 1584), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['"""haarcascade_frontalface_default.xml"""'], {}), "('haarcascade_frontalface_default.xml')\n", (1545, 1584), False, 'import cv2\n'), ((1600, 1639), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (1612, 1639), False, 'import cv2\n'), ((1768, 1838), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x, y - 50)', '(x + w, y + h + 10)', '(255, 0, 0)', '(2)'], {}), '(frame, (x, y - 50), (x + w, y + h + 10), (255, 0, 0), 2)\n', (1781, 1838), False, 'import cv2\n'), ((2088, 2215), 'cv2.putText', 'cv2.putText', (['frame', 'emotion_dict[maxindex]', '(x + 20, y - 60)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', '(255, 255, 255)', '(2)', 'cv2.LINE_AA'], {}), '(frame, emotion_dict[maxindex], (x + 20, y - 60), cv2.\n FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)\n', (2099, 2215), False, 'import cv2\n'), ((2264, 2325), 'cv2.resize', 'cv2.resize', (['frame', '(1600, 960)'], {'interpolation': 'cv2.INTER_CUBIC'}), '(frame, (1600, 960), interpolation=cv2.INTER_CUBIC)\n', (2274, 2325), False, 'import cv2\n'), ((2053, 2074), 'numpy.argmax', 'np.argmax', (['prediction'], {}), '(prediction)\n', (2062, 2074), True, 'import numpy as np\n'), ((2338, 2352), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (2349, 2352), False, 'import cv2\n'), ((1934, 1964), 'cv2.resize', 'cv2.resize', (['roi_gray', '(48, 48)'], {}), '(roi_gray, (48, 48))\n', (1944, 1964), False, 'import cv2\n')] |
import os
import unittest
import numpy as np
from PIL import Image
from src.constants.constants import NumericalMetrics
from src.evaluators.habitat_evaluator import HabitatEvaluator
class TestHabitatEvaluatorContinuousCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.evaluator_continuous = HabitatEvaluator(
config_paths="configs/pointnav_rgbd_with_physics.yaml",
input_type="rgbd",
model_path="data/checkpoints/v2/gibson-rgbd-best.pth",
enable_physics=True,
)
def test_evaluate_one_episode_continuous(self):
metrics_list = self.evaluator_continuous.evaluate(
episode_id_last="48",
scene_id_last="data/scene_datasets/habitat-test-scenes/van-gogh-room.glb",
log_dir="logs",
agent_seed=7,
)
avg_metrics = self.evaluator_continuous.compute_avg_metrics(metrics_list)
assert (
np.linalg.norm(avg_metrics[NumericalMetrics.DISTANCE_TO_GOAL] - 0.140662)
< 1e-5
)
assert np.linalg.norm(avg_metrics[NumericalMetrics.SPL] - 0.793321) < 1e-5
if __name__ == "__main__":
unittest.main()
| [
"unittest.main",
"src.evaluators.habitat_evaluator.HabitatEvaluator",
"numpy.linalg.norm"
] | [((1177, 1192), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1190, 1192), False, 'import unittest\n'), ((323, 499), 'src.evaluators.habitat_evaluator.HabitatEvaluator', 'HabitatEvaluator', ([], {'config_paths': '"""configs/pointnav_rgbd_with_physics.yaml"""', 'input_type': '"""rgbd"""', 'model_path': '"""data/checkpoints/v2/gibson-rgbd-best.pth"""', 'enable_physics': '(True)'}), "(config_paths='configs/pointnav_rgbd_with_physics.yaml',\n input_type='rgbd', model_path=\n 'data/checkpoints/v2/gibson-rgbd-best.pth', enable_physics=True)\n", (339, 499), False, 'from src.evaluators.habitat_evaluator import HabitatEvaluator\n'), ((958, 1031), 'numpy.linalg.norm', 'np.linalg.norm', (['(avg_metrics[NumericalMetrics.DISTANCE_TO_GOAL] - 0.140662)'], {}), '(avg_metrics[NumericalMetrics.DISTANCE_TO_GOAL] - 0.140662)\n', (972, 1031), True, 'import numpy as np\n'), ((1076, 1136), 'numpy.linalg.norm', 'np.linalg.norm', (['(avg_metrics[NumericalMetrics.SPL] - 0.793321)'], {}), '(avg_metrics[NumericalMetrics.SPL] - 0.793321)\n', (1090, 1136), True, 'import numpy as np\n')] |
import pymc3 as pm
import numpy as np
from tabulate import tabulate
from scipy.optimize import linprog
import scipy.stats as stats
import matplotlib
from matplotlib import pyplot as plt
import matplotlib.animation as animation
d0 = [20, 28, 24, 20, 23] # observed demand samples
with pm.Model() as m:
d = pm.Gamma('theta', 1, 1) # prior distribution
pm.Poisson('d0', d, observed = d0) # likelihood
samples = pm.sample(10000) # draw samples from the posterior
seaborn.distplot(samples.get_values('theta'), fit=scipy.stats.gamma)
p = np.linspace(10, 16) # price range
d_means = np.exp(s.log_b + s.a * np.log(p).reshape(-1, 1))
plt.plot(p, d_means, c = 'k', alpha = 0.01)
plt.plot(p0, d0, 'o', c = 'r')
plt.show()
| [
"pymc3.Poisson",
"matplotlib.pyplot.plot",
"numpy.log",
"numpy.linspace",
"pymc3.sample",
"pymc3.Model",
"pymc3.Gamma",
"matplotlib.pyplot.show"
] | [((590, 609), 'numpy.linspace', 'np.linspace', (['(10)', '(16)'], {}), '(10, 16)\n', (601, 609), True, 'import numpy as np\n'), ((686, 725), 'matplotlib.pyplot.plot', 'plt.plot', (['p', 'd_means'], {'c': '"""k"""', 'alpha': '(0.01)'}), "(p, d_means, c='k', alpha=0.01)\n", (694, 725), True, 'from matplotlib import pyplot as plt\n'), ((730, 758), 'matplotlib.pyplot.plot', 'plt.plot', (['p0', 'd0', '"""o"""'], {'c': '"""r"""'}), "(p0, d0, 'o', c='r')\n", (738, 758), True, 'from matplotlib import pyplot as plt\n'), ((761, 771), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (769, 771), True, 'from matplotlib import pyplot as plt\n'), ((302, 312), 'pymc3.Model', 'pm.Model', ([], {}), '()\n', (310, 312), True, 'import pymc3 as pm\n'), ((327, 350), 'pymc3.Gamma', 'pm.Gamma', (['"""theta"""', '(1)', '(1)'], {}), "('theta', 1, 1)\n", (335, 350), True, 'import pymc3 as pm\n'), ((385, 417), 'pymc3.Poisson', 'pm.Poisson', (['"""d0"""', 'd'], {'observed': 'd0'}), "('d0', d, observed=d0)\n", (395, 417), True, 'import pymc3 as pm\n'), ((449, 465), 'pymc3.sample', 'pm.sample', (['(10000)'], {}), '(10000)\n', (458, 465), True, 'import pymc3 as pm\n'), ((659, 668), 'numpy.log', 'np.log', (['p'], {}), '(p)\n', (665, 668), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation, cm
from mpl_toolkits.mplot3d import Axes3D
# create a figure
fig = plt.figure()
# initialise 3D Axes
ax = Axes3D(fig)
# remove background grid, fill and axis
ax.grid(False)
ax.xaxis.pane.fill = ax.yaxis.pane.fill = ax.zaxis.pane.fill = False
plt.axis('off')
# tighter fit to window
plt.tight_layout()
# create surface values
x = np.arange(-5, 5, 0.25)
y = np.arange(-5, 5, 0.25)
xx, yy = np.meshgrid(x, y)
r = np.sqrt(xx ** 2 + yy ** 2)
z = np.cos(r)
# create the initialiser with the surface plot
def init():
ax.plot_surface(xx, yy, z, cmap=cm.gnuplot,
linewidth=0, antialiased=False)
return fig,
# create animate function, this will adjust the view one step at a time
def animate(i):
ax.view_init(elev=30.0, azim=i)
return fig,
# create the animated plot
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=360, interval=20, blit=True)
# save as a GIF
anim.save('surface_rotation.gif', fps=30, writer='imagemagick')
| [
"numpy.sqrt",
"matplotlib.animation.FuncAnimation",
"mpl_toolkits.mplot3d.Axes3D",
"matplotlib.pyplot.figure",
"numpy.meshgrid",
"numpy.cos",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.axis",
"numpy.arange"
] | [((159, 171), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (169, 171), True, 'import matplotlib.pyplot as plt\n'), ((200, 211), 'mpl_toolkits.mplot3d.Axes3D', 'Axes3D', (['fig'], {}), '(fig)\n', (206, 211), False, 'from mpl_toolkits.mplot3d import Axes3D\n'), ((340, 355), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (348, 355), True, 'import matplotlib.pyplot as plt\n'), ((382, 400), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (398, 400), True, 'import matplotlib.pyplot as plt\n'), ((433, 455), 'numpy.arange', 'np.arange', (['(-5)', '(5)', '(0.25)'], {}), '(-5, 5, 0.25)\n', (442, 455), True, 'import numpy as np\n'), ((461, 483), 'numpy.arange', 'np.arange', (['(-5)', '(5)', '(0.25)'], {}), '(-5, 5, 0.25)\n', (470, 483), True, 'import numpy as np\n'), ((494, 511), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (505, 511), True, 'import numpy as np\n'), ((517, 543), 'numpy.sqrt', 'np.sqrt', (['(xx ** 2 + yy ** 2)'], {}), '(xx ** 2 + yy ** 2)\n', (524, 543), True, 'import numpy as np\n'), ((549, 558), 'numpy.cos', 'np.cos', (['r'], {}), '(r)\n', (555, 558), True, 'import numpy as np\n'), ((931, 1025), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['fig', 'animate'], {'init_func': 'init', 'frames': '(360)', 'interval': '(20)', 'blit': '(True)'}), '(fig, animate, init_func=init, frames=360, interval=\n 20, blit=True)\n', (954, 1025), False, 'from matplotlib import animation, cm\n')] |
import tensorflow as tf
import numpy as np
from sklearn.metrics import balanced_accuracy_score
import time
import os
def create_graph_placeholders(dataset, use_desc=True, with_tags=True, with_attention=True, use_subgraph=False):
'''
dataset: should be a sequence (list, tuple or array) whose order is [V, A, Labels, masks, graph size, tags, descriptors]
'''
placeholders = []
V_shape = [None] + list(dataset[0].shape[1:])
V = tf.compat.v1.placeholder(tf.as_dtype(dataset[0].dtype), shape=V_shape, name='V_input')
placeholders.append(V)
A_shape = [None] + list(dataset[1].shape[1:])
A = tf.compat.v1.placeholder(tf.as_dtype(dataset[1].dtype), shape=A_shape, name='AdjMat_input')
placeholders.append(A)
labels_shape = [None]
labels = tf.compat.v1.placeholder(tf.as_dtype(dataset[2].dtype), shape=labels_shape, name='labels_input')
placeholders.append(labels)
mask_shape = [None] + list(dataset[3].shape[1:])
masks = tf.compat.v1.placeholder(tf.as_dtype(dataset[3].dtype), shape=mask_shape, name='masks_input')
placeholders.append(masks)
if with_attention:
graph_size_shape = [None]
graph_size = tf.compat.v1.placeholder(tf.as_dtype(dataset[4].dtype), shape=graph_size_shape, name='graph_size_input')
placeholders.append(graph_size)
if with_tags:
tags_shape = [None]
tags = tf.compat.v1.placeholder(tf.as_dtype(dataset[5].dtype), shape=tags_shape, name='tags_input')
placeholders.append(tags)
if use_desc:
global_state_shape = [None] + list(dataset[6].shape[1:])
global_state = tf.compat.v1.placeholder(tf.as_dtype(dataset[6].dtype), shape=global_state_shape, name='global_state_input')
placeholders.append(global_state)
if use_subgraph:
subgraph_size_shape = [None, 2]
subgraph_size = tf.compat.v1.placeholder(tf.as_dtype(dataset[7].dtype), shape=subgraph_size_shape, name='subgraph_size_input')
placeholders.append(subgraph_size)
return placeholders
def create_fc_placeholders(dataset):
embedding_shape = [None] + list(dataset[0].shape[1:])
embedding = tf.compat.v1.placeholder(tf.as_dtype(dataset[0].dtype), shape=embedding_shape, name='Mol_Embedding')
labels_shape = [None]
labels = tf.compat.v1.placeholder(tf.as_dtype(dataset[1].dtype), shape=labels_shape, name='labels_input')
tags_shape = [None]
tags = tf.compat.v1.placeholder(tf.as_dtype(dataset[2].dtype), shape=labels_shape, name='tags_input')
try:
desc_shape = [None] + list(dataset[3].shape[1:])
desc = tf.compat.v1.placeholder(tf.as_dtype(dataset[3].dtype), shape=desc_shape, name='desc_input')
return [embedding, labels, tags, desc]
except:
return [embedding, labels, tags]
def create_input_variable(inputs):
variable_initialization = {}
for i in range(len(inputs)):
placeholder = tf.compat.v1.placeholder(tf.as_dtype(inputs[i].dtype), shape=inputs[i].shape)
var = tf.Variable(placeholder, trainable=False, collections=[tf.GraphKeys.LOCAL_VARIABLES])
variable_initialization[placeholder] = inputs[i]
inputs[i] = var
return inputs, variable_initialization
def verify_dir_exists(dirname):
if os.path.isdir(os.path.dirname(dirname)) == False:
os.makedirs(os.path.dirname(dirname))
def make_feed_dict(placeholders, data_batch):
feed_dict = {}
for i in range(len(placeholders)):
feed_dict.setdefault(placeholders[i], data_batch[i])
return feed_dict
def create_loss_function(V, labels, is_training):
with tf.compat.v1.variable_scope('loss') as scope:
print('Creating loss function and summaries')
cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=V, labels=labels), name='cross_entropy')
correct_prediction = tf.cast(tf.equal(tf.argmax(V, 1), tf.cast(labels, tf.int64)), tf.float32, name='correct_prediction')
accuracy = tf.reduce_mean(correct_prediction, name='accuracy')
max_acc_train = tf.Variable(tf.zeros([]), name="max_acc_train")
max_acc_test = tf.Variable(tf.zeros([]), name="max_acc_test")
max_acc = tf.cond(is_training, lambda: tf.compat.v1.assign(max_acc_train, tf.maximum(max_acc_train, accuracy)), lambda: tf.compat.v1.assign(max_acc_test, tf.maximum(max_acc_test, accuracy)))
tf.compat.v1.add_to_collection('losses', cross_entropy)
tf.compat.v1.summary.scalar('accuracy', accuracy)
tf.compat.v1.summary.scalar('max_accuracy', max_acc)
tf.compat.v1.summary.scalar('cross_entropy', cross_entropy)
reports = {}
reports['accuracy'] = accuracy
reports['max acc.'] = max_acc
reports['cross_entropy'] = cross_entropy
return tf.add_n(tf.compat.v1.get_collection('losses')), reports
def make_train_step(loss, global_step, optimizer='adam', starter_learning_rate=0.1, learning_rate_step=1000, learning_rate_exp=0.1, reports=None):
if reports==None:
reports = {}
print('Preparing training')
if len(tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.REGULARIZATION_LOSSES)) > 0:
loss += tf.add_n(tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.REGULARIZATION_LOSSES))
update_ops = tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
if optimizer == 'adam':
train_step = tf.compat.v1.train.AdamOptimizer().minimize(loss, global_step=global_step, name='train_step')
else:
learning_rate = tf.compat.v1.train.exponential_decay(starter_learning_rate, global_step, learning_rate_step, learning_rate_exp, staircase=True)
train_step = tf.compat.v1.train.MomentumOptimizer(learning_rate, 0.9).minimize(loss, global_step=global_step, name='train_step')
reports['lr'] = learning_rate
tf.compat.v1.summary.scalar('learning_rate', learning_rate)
return train_step, reports
def make_batch(data, epoch, batch_size, with_shuffle=True, name=None):
with tf.compat.v1.variable_scope(name, default_name='input_slice') as scope:
inputs = []
for i in data:
ph = tf.compat.v1.placeholder(tf.as_dtype(i.dtype), shape=i.shape)
inputs.append(ph)
dataset = tf.compat.v1.data.Dataset.from_tensor_slices(tuple(inputs))
if with_shuffle:
dataset = dataset.shuffle(buffer_size=1000).batch(batch_size).repeat(epoch)
else:
dataset = dataset.batch(batch_size).repeat(epoch)
iterator = tf.compat.v1.data.make_initializable_iterator(dataset)
return iterator, inputs
class Model(object):
def __init__(self, model, train_data, valid_data, with_test=False, test_data=None, build_fc=False,
model_name='model', dataset_name='dataset', with_tags=True, use_desc=True, use_subgraph=False,
with_attention=True, snapshot_path='./snapshot/', summary_path='./summary/'):
tf.compat.v1.reset_default_graph()
self.train_data = train_data
self.test_data = valid_data
self.val = with_test
if self.val:
self.val_data = test_data
self.is_training = tf.compat.v1.placeholder(tf.bool, shape=(), name='is_training')
self.global_step = tf.Variable(0,name='global_step',trainable=False)
self.build_fc = build_fc
if build_fc:
self.inputs = create_fc_placeholders(train_data)
else:
self.inputs = create_graph_placeholders(train_data, use_desc=use_desc,
with_tags=with_tags, with_attention=with_attention, use_subgraph=use_subgraph)
self.pred_out, self.labels = model.build_model(self.inputs, self.is_training, self.global_step)
self.snapshot_path = snapshot_path+'/%s/%s/' % (model_name, dataset_name)
self.test_summary_path = summary_path+'/%s/test/%s' %(model_name, dataset_name)
self.train_summary_path = summary_path+'/%s/train/%s' %(model_name, dataset_name)
self.is_finetuning = False
def create_batch(self, num_epoch=100, train_batch_size=256, test_batch_size=None):
self.train_batch_num_per_epoch = int(self.train_data[0].shape[0]/train_batch_size) + 1
self.train_batch_iterator, self.train_batch_placeholders = make_batch(self.train_data, num_epoch, train_batch_size, name='train_batch')
if test_batch_size == None:
self.test_batch_num_per_epoch = 1
self.test_batch_iterator, self.test_batch_placeholders = make_batch(self.test_data, num_epoch, self.test_data[0].shape[0], with_shuffle=0, name='test_batch')
else:
self.test_batch_num_per_epoch = int(self.test_data[0].shape[0]/test_batch_size) + 1
self.test_batch_iterator, self.test_batch_placeholders = make_batch(self.test_data, num_epoch, test_batch_size, with_shuffle=0, name='test_batch')
if self.val:
self.val_batch_iterator, self.val_batch_placeholders = make_batch(self.val_data, num_epoch, self.val_data[0].shape[0], with_shuffle=0, name='val_batch')
def create_loss_function(self):
self.loss, self.reports = create_loss_function(self.pred_out, self.labels, self.is_training)
def make_train_step(self, optimizer='adam'):
self.train_step, self.reports = make_train_step(self.loss, self.global_step, reports=self.reports, optimizer=optimizer)
def fit(self, num_epoch=100,
train_batch_size=256,
test_batch_size=None,
save_info=False,
save_history=True,
save_model=True,
save_att=False,
metric='acc', # one of the ['bacc','acc','loss']
silence=False,
optimizer='adam',
save_summary=True,
early_stop=False,
early_stop_cutoff=20,
max_to_keep=5):
'''
'''
self.create_batch(num_epoch=num_epoch, train_batch_size=train_batch_size, test_batch_size=test_batch_size)
self.create_loss_function()
self.make_train_step(optimizer=optimizer)
gpu_options = tf.compat.v1.GPUOptions(allow_growth=True)
with tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(gpu_options=gpu_options)) as sess:
####################### initialization ########################
sess.run(tf.compat.v1.global_variables_initializer())
sess.run(self.train_batch_iterator.initializer, feed_dict=make_feed_dict(self.train_batch_placeholders, self.train_data))
sess.run(self.test_batch_iterator.initializer, feed_dict=make_feed_dict(self.test_batch_placeholders, self.test_data))
self.train_samples = self.train_batch_iterator.get_next()
self.test_samples = self.test_batch_iterator.get_next()
if self.val:
sess.run(self.val_batch_iterator.initializer, feed_dict=make_feed_dict(self.val_batch_placeholders, self.val_data))
self.val_samples = self.val_batch_iterator.get_next()
sess.run(tf.compat.v1.local_variables_initializer())
if self.is_finetuning:
self.restore_saver.restore(sess, self.restore_file)
###################### Starting summaries #####################
print('Starting summaries')
test_writer = tf.compat.v1.summary.FileWriter(self.test_summary_path, sess.graph)
train_writer = tf.compat.v1.summary.FileWriter(self.train_summary_path, sess.graph)
summary_merged = tf.compat.v1.summary.merge_all()
###################### training record #########################
self.test_max_acc = {}
self.test_max_acc['valid_acc'] = []
self.test_max_acc['valid_cross_entropy'] = []
self.test_max_acc['train_acc'] = []
self.test_max_acc['train_cross_entropy'] = []
if metric == 'bacc':
self.test_max_acc['valid_bacc'] = []
###################### configure model saver #######################
var_list = [var for var in tf.compat.v1.global_variables() if "moving" in var.name]
var_list += [var for var in tf.compat.v1.global_variables() if "Moving" in var.name]
var_list += tf.compat.v1.trainable_variables()
saver = tf.compat.v1.train.Saver(var_list=var_list, max_to_keep=max_to_keep)
if self.build_fc:
ix_of_label_for_saving = 1
ix_of_tag_for_saving = 2
else:
ix_of_label_for_saving = 2
ix_of_tag_for_saving = 5
####################################################################
if save_att:
# Saving the att coefficients of each atom for visualization
graph = tf.compat.v1.get_default_graph()
try:
att_op = graph.get_operation_by_name('Global_Attention/Attentions').outputs[0]
except:
att_op = graph.get_operation_by_name('Multi_Head_Global_Attention/Attentions').outputs[0]
####################################################################
test_metric_cutoff = float('inf') if metric=='loss' else 0.0
early_stop_counter = 0
try:
for epo in range(num_epoch):
####################### train ######################
train_acc = 0.0
train_loss = 0.0
start_time = time.time()
for b in range(self.train_batch_num_per_epoch):
train_batch = sess.run([self.train_samples])[0]
feed_dict = make_feed_dict(self.inputs, train_batch)
feed_dict[self.is_training] = 1
summary, _, train_reports = sess.run([summary_merged, self.train_step, self.reports], feed_dict=feed_dict)
train_acc += train_reports['accuracy']
train_loss += train_reports['cross_entropy']
if save_summary:
train_writer.add_summary(summary, epo)
self.test_max_acc['train_acc'].append(train_acc/self.train_batch_num_per_epoch)
self.test_max_acc['train_cross_entropy'].append(train_loss/self.train_batch_num_per_epoch)
####################### test ######################
test_acc = 0.0
test_loss = 0.0
test_tags = []
test_labels = []
for b in range(self.test_batch_num_per_epoch):
test_batch = sess.run([self.test_samples])[0]
feed_dict = make_feed_dict(self.inputs, test_batch)
feed_dict[self.is_training] = 0
test_tags.append(test_batch[ix_of_tag_for_saving])
test_labels.append(test_batch[ix_of_label_for_saving])
if save_att:
summary, test_reports, out, att = sess.run([summary_merged, self.reports, self.pred_out, att_op],
feed_dict=feed_dict)
else:
summary, test_reports, out = sess.run([summary_merged, self.reports, self.pred_out],
feed_dict=feed_dict)
test_acc += test_reports['accuracy']
test_loss += test_reports['cross_entropy']
if save_summary:
test_writer.add_summary(summary, epo)
self.test_max_acc['valid_acc'].append(test_acc/self.test_batch_num_per_epoch)
self.test_max_acc['valid_cross_entropy'].append(test_loss/self.test_batch_num_per_epoch)
test_tags = np.concatenate(test_tags)
test_labels = np.concatenate(test_labels)
if metric == 'bacc':
out_label = np.array([np.where(j==np.max(j)) for j in out]).reshape(-1)
test_bacc = balanced_accuracy_score(test_labels, out_label)
self.test_max_acc['valid_bacc'].append(test_bacc)
save_metric = test_bacc
is_save = save_metric > test_metric_cutoff
elif metric == 'acc':
save_metric = self.test_max_acc['valid_acc'][-1]
is_save = save_metric > test_metric_cutoff
elif metric == 'loss':
save_metric = self.test_max_acc['valid_cross_entropy'][-1]
is_save = save_metric < test_metric_cutoff
else:
raise ValueError("metric should be the one of ['bacc','acc','loss']")
########################### save model ############################
if is_save:
early_stop_counter = 0
test_metric_cutoff = save_metric
L = str(test_labels.tolist())
out = str(out.tolist())
if save_model:
verify_dir_exists(self.snapshot_path)
saver.save(sess, self.snapshot_path+'TestAcc-{:.2f}'.format(save_metric*100), global_step=epo)
###################### Validation ####################
if self.val:
val_batch = sess.run([self.val_samples])[0]
feed_dict = make_feed_dict(self.inputs, val_batch)
feed_dict[self.is_training] = 0
val_tags = val_batch[ix_of_tag_for_saving]
val_labels = val_batch[ix_of_label_for_saving]
if save_att:
val_reports, val_out, val_att = sess.run([self.reports, self.pred_out, att_op], feed_dict=feed_dict)
else:
val_reports, val_out = sess.run([self.reports, self.pred_out], feed_dict=feed_dict)
val_info = [str(val_reports['accuracy']),
str(val_labels.tolist()),
str(val_out.tolist()),
str(val_tags.tolist())]
if save_att:
val_info.append(str(val_att.tolist()))
self.test_max_acc['test_acc'] = val_reports['accuracy']
######################## save model information ########################
if save_info:
if save_att:
att = str(att.tolist())
model_info = ['step:{}'.format(epo),
'valid_acc:{}'.format(test_reports['accuracy']),
'valid_cross_entropy:{}'.format(test_reports['cross_entropy']),
'train_acc:{}'.format(self.test_max_acc['train_acc'][epo]),
'train_cross_entropy:{}'.format(self.test_max_acc['train_cross_entropy'][epo]),
L, out, str(test_tags.tolist()), att]
else:
model_info = ['step:{}'.format(epo),
'valid_acc:{}'.format(test_reports['accuracy']),
'valid_cross_entropy:{}'.format(test_reports['cross_entropy']),
'train_acc:{}'.format(self.test_max_acc['train_acc'][epo]),
'train_cross_entropy:{}'.format(self.test_max_acc['train_cross_entropy'][epo]),
L, out, str(test_tags.tolist())]
if metric == 'bacc':
model_info.insert(2,'valid_bacc:{}'.format(save_metric))
open(self.snapshot_path+'model-{}_info.txt'.format(epo), 'w').writelines('\n'.join(model_info))
if self.val:
open(self.snapshot_path+'model-val-info.txt', 'w').writelines('\n'.join(val_info))
else:
early_stop_counter += 1
end_time = time.time()
if silence == False:
elapsed_time = end_time - start_time
print_content = '## Epoch {} ==> Train Loss:{:.5f}, Train Acc:{:.2f}, Valid Loss:{:.5f}, Valid Acc:{:.2f}, Elapsed Time:{:.2f} s'
print_content = print_content.format(epo,
self.test_max_acc['train_cross_entropy'][epo],
self.test_max_acc['train_acc'][epo]*100,
self.test_max_acc['valid_cross_entropy'][epo],
self.test_max_acc['valid_acc'][epo]*100,
elapsed_time)
print(print_content)
if early_stop_counter == early_stop_cutoff and early_stop != False:
print('Early stopping ...')
break
except tf.errors.OutOfRangeError:
print("done")
finally:
if save_history:
verify_dir_exists(self.snapshot_path)
open(self.snapshot_path+'history.dir' ,'w').write(str(self.test_max_acc))
sess.close()
return self.test_max_acc
| [
"sklearn.metrics.balanced_accuracy_score",
"tensorflow.compat.v1.train.AdamOptimizer",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.compat.v1.add_to_collection",
"tensorflow.control_dependencies",
"tensorflow.compat.v1.get_collection",
"tensorflow.reduce_mean",
"tensorflow.com... | [((5266, 5328), 'tensorflow.compat.v1.get_collection', 'tf.compat.v1.get_collection', (['tf.compat.v1.GraphKeys.UPDATE_OPS'], {}), '(tf.compat.v1.GraphKeys.UPDATE_OPS)\n', (5293, 5328), True, 'import tensorflow as tf\n'), ((477, 506), 'tensorflow.as_dtype', 'tf.as_dtype', (['dataset[0].dtype'], {}), '(dataset[0].dtype)\n', (488, 506), True, 'import tensorflow as tf\n'), ((649, 678), 'tensorflow.as_dtype', 'tf.as_dtype', (['dataset[1].dtype'], {}), '(dataset[1].dtype)\n', (660, 678), True, 'import tensorflow as tf\n'), ((807, 836), 'tensorflow.as_dtype', 'tf.as_dtype', (['dataset[2].dtype'], {}), '(dataset[2].dtype)\n', (818, 836), True, 'import tensorflow as tf\n'), ((1001, 1030), 'tensorflow.as_dtype', 'tf.as_dtype', (['dataset[3].dtype'], {}), '(dataset[3].dtype)\n', (1012, 1030), True, 'import tensorflow as tf\n'), ((2168, 2197), 'tensorflow.as_dtype', 'tf.as_dtype', (['dataset[0].dtype'], {}), '(dataset[0].dtype)\n', (2179, 2197), True, 'import tensorflow as tf\n'), ((2308, 2337), 'tensorflow.as_dtype', 'tf.as_dtype', (['dataset[1].dtype'], {}), '(dataset[1].dtype)\n', (2319, 2337), True, 'import tensorflow as tf\n'), ((2440, 2469), 'tensorflow.as_dtype', 'tf.as_dtype', (['dataset[2].dtype'], {}), '(dataset[2].dtype)\n', (2451, 2469), True, 'import tensorflow as tf\n'), ((3000, 3090), 'tensorflow.Variable', 'tf.Variable', (['placeholder'], {'trainable': '(False)', 'collections': '[tf.GraphKeys.LOCAL_VARIABLES]'}), '(placeholder, trainable=False, collections=[tf.GraphKeys.\n LOCAL_VARIABLES])\n', (3011, 3090), True, 'import tensorflow as tf\n'), ((3593, 3628), 'tensorflow.compat.v1.variable_scope', 'tf.compat.v1.variable_scope', (['"""loss"""'], {}), "('loss')\n", (3620, 3628), True, 'import tensorflow as tf\n'), ((3976, 4027), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['correct_prediction'], {'name': '"""accuracy"""'}), "(correct_prediction, name='accuracy')\n", (3990, 4027), True, 'import tensorflow as tf\n'), ((4377, 4432), 'tensorflow.compat.v1.add_to_collection', 'tf.compat.v1.add_to_collection', (['"""losses"""', 'cross_entropy'], {}), "('losses', cross_entropy)\n", (4407, 4432), True, 'import tensorflow as tf\n'), ((4441, 4490), 'tensorflow.compat.v1.summary.scalar', 'tf.compat.v1.summary.scalar', (['"""accuracy"""', 'accuracy'], {}), "('accuracy', accuracy)\n", (4468, 4490), True, 'import tensorflow as tf\n'), ((4499, 4551), 'tensorflow.compat.v1.summary.scalar', 'tf.compat.v1.summary.scalar', (['"""max_accuracy"""', 'max_acc'], {}), "('max_accuracy', max_acc)\n", (4526, 4551), True, 'import tensorflow as tf\n'), ((4560, 4619), 'tensorflow.compat.v1.summary.scalar', 'tf.compat.v1.summary.scalar', (['"""cross_entropy"""', 'cross_entropy'], {}), "('cross_entropy', cross_entropy)\n", (4587, 4619), True, 'import tensorflow as tf\n'), ((5344, 5379), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['update_ops'], {}), '(update_ops)\n', (5367, 5379), True, 'import tensorflow as tf\n'), ((6069, 6130), 'tensorflow.compat.v1.variable_scope', 'tf.compat.v1.variable_scope', (['name'], {'default_name': '"""input_slice"""'}), "(name, default_name='input_slice')\n", (6096, 6130), True, 'import tensorflow as tf\n'), ((6579, 6633), 'tensorflow.compat.v1.data.make_initializable_iterator', 'tf.compat.v1.data.make_initializable_iterator', (['dataset'], {}), '(dataset)\n', (6624, 6633), True, 'import tensorflow as tf\n'), ((7004, 7038), 'tensorflow.compat.v1.reset_default_graph', 'tf.compat.v1.reset_default_graph', ([], {}), '()\n', (7036, 7038), True, 'import tensorflow as tf\n'), ((7227, 7290), 'tensorflow.compat.v1.placeholder', 'tf.compat.v1.placeholder', (['tf.bool'], {'shape': '()', 'name': '"""is_training"""'}), "(tf.bool, shape=(), name='is_training')\n", (7251, 7290), True, 'import tensorflow as tf\n'), ((7318, 7369), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'name': '"""global_step"""', 'trainable': '(False)'}), "(0, name='global_step', trainable=False)\n", (7329, 7369), True, 'import tensorflow as tf\n'), ((10281, 10323), 'tensorflow.compat.v1.GPUOptions', 'tf.compat.v1.GPUOptions', ([], {'allow_growth': '(True)'}), '(allow_growth=True)\n', (10304, 10323), True, 'import tensorflow as tf\n'), ((1204, 1233), 'tensorflow.as_dtype', 'tf.as_dtype', (['dataset[4].dtype'], {}), '(dataset[4].dtype)\n', (1215, 1233), True, 'import tensorflow as tf\n'), ((1410, 1439), 'tensorflow.as_dtype', 'tf.as_dtype', (['dataset[5].dtype'], {}), '(dataset[5].dtype)\n', (1421, 1439), True, 'import tensorflow as tf\n'), ((1642, 1671), 'tensorflow.as_dtype', 'tf.as_dtype', (['dataset[6].dtype'], {}), '(dataset[6].dtype)\n', (1653, 1671), True, 'import tensorflow as tf\n'), ((1878, 1907), 'tensorflow.as_dtype', 'tf.as_dtype', (['dataset[7].dtype'], {}), '(dataset[7].dtype)\n', (1889, 1907), True, 'import tensorflow as tf\n'), ((2616, 2645), 'tensorflow.as_dtype', 'tf.as_dtype', (['dataset[3].dtype'], {}), '(dataset[3].dtype)\n', (2627, 2645), True, 'import tensorflow as tf\n'), ((2933, 2961), 'tensorflow.as_dtype', 'tf.as_dtype', (['inputs[i].dtype'], {}), '(inputs[i].dtype)\n', (2944, 2961), True, 'import tensorflow as tf\n'), ((3264, 3288), 'os.path.dirname', 'os.path.dirname', (['dirname'], {}), '(dirname)\n', (3279, 3288), False, 'import os\n'), ((3320, 3344), 'os.path.dirname', 'os.path.dirname', (['dirname'], {}), '(dirname)\n', (3335, 3344), False, 'import os\n'), ((3732, 3803), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'V', 'labels': 'labels'}), '(logits=V, labels=labels)\n', (3778, 3803), True, 'import tensorflow as tf\n'), ((4064, 4076), 'tensorflow.zeros', 'tf.zeros', (['[]'], {}), '([])\n', (4072, 4076), True, 'import tensorflow as tf\n'), ((4135, 4147), 'tensorflow.zeros', 'tf.zeros', (['[]'], {}), '([])\n', (4143, 4147), True, 'import tensorflow as tf\n'), ((4787, 4824), 'tensorflow.compat.v1.get_collection', 'tf.compat.v1.get_collection', (['"""losses"""'], {}), "('losses')\n", (4814, 4824), True, 'import tensorflow as tf\n'), ((5069, 5142), 'tensorflow.compat.v1.get_collection', 'tf.compat.v1.get_collection', (['tf.compat.v1.GraphKeys.REGULARIZATION_LOSSES'], {}), '(tf.compat.v1.GraphKeys.REGULARIZATION_LOSSES)\n', (5096, 5142), True, 'import tensorflow as tf\n'), ((5174, 5247), 'tensorflow.compat.v1.get_collection', 'tf.compat.v1.get_collection', (['tf.compat.v1.GraphKeys.REGULARIZATION_LOSSES'], {}), '(tf.compat.v1.GraphKeys.REGULARIZATION_LOSSES)\n', (5201, 5247), True, 'import tensorflow as tf\n'), ((5574, 5705), 'tensorflow.compat.v1.train.exponential_decay', 'tf.compat.v1.train.exponential_decay', (['starter_learning_rate', 'global_step', 'learning_rate_step', 'learning_rate_exp'], {'staircase': '(True)'}), '(starter_learning_rate, global_step,\n learning_rate_step, learning_rate_exp, staircase=True)\n', (5610, 5705), True, 'import tensorflow as tf\n'), ((5897, 5956), 'tensorflow.compat.v1.summary.scalar', 'tf.compat.v1.summary.scalar', (['"""learning_rate"""', 'learning_rate'], {}), "('learning_rate', learning_rate)\n", (5924, 5956), True, 'import tensorflow as tf\n'), ((11507, 11574), 'tensorflow.compat.v1.summary.FileWriter', 'tf.compat.v1.summary.FileWriter', (['self.test_summary_path', 'sess.graph'], {}), '(self.test_summary_path, sess.graph)\n', (11538, 11574), True, 'import tensorflow as tf\n'), ((11602, 11670), 'tensorflow.compat.v1.summary.FileWriter', 'tf.compat.v1.summary.FileWriter', (['self.train_summary_path', 'sess.graph'], {}), '(self.train_summary_path, sess.graph)\n', (11633, 11670), True, 'import tensorflow as tf\n'), ((11700, 11732), 'tensorflow.compat.v1.summary.merge_all', 'tf.compat.v1.summary.merge_all', ([], {}), '()\n', (11730, 11732), True, 'import tensorflow as tf\n'), ((12444, 12478), 'tensorflow.compat.v1.trainable_variables', 'tf.compat.v1.trainable_variables', ([], {}), '()\n', (12476, 12478), True, 'import tensorflow as tf\n'), ((12499, 12567), 'tensorflow.compat.v1.train.Saver', 'tf.compat.v1.train.Saver', ([], {'var_list': 'var_list', 'max_to_keep': 'max_to_keep'}), '(var_list=var_list, max_to_keep=max_to_keep)\n', (12523, 12567), True, 'import tensorflow as tf\n'), ((3873, 3888), 'tensorflow.argmax', 'tf.argmax', (['V', '(1)'], {}), '(V, 1)\n', (3882, 3888), True, 'import tensorflow as tf\n'), ((3890, 3915), 'tensorflow.cast', 'tf.cast', (['labels', 'tf.int64'], {}), '(labels, tf.int64)\n', (3897, 3915), True, 'import tensorflow as tf\n'), ((6226, 6246), 'tensorflow.as_dtype', 'tf.as_dtype', (['i.dtype'], {}), '(i.dtype)\n', (6237, 6246), True, 'import tensorflow as tf\n'), ((10522, 10565), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (10563, 10565), True, 'import tensorflow as tf\n'), ((11218, 11260), 'tensorflow.compat.v1.local_variables_initializer', 'tf.compat.v1.local_variables_initializer', ([], {}), '()\n', (11258, 11260), True, 'import tensorflow as tf\n'), ((12991, 13023), 'tensorflow.compat.v1.get_default_graph', 'tf.compat.v1.get_default_graph', ([], {}), '()\n', (13021, 13023), True, 'import tensorflow as tf\n'), ((4252, 4287), 'tensorflow.maximum', 'tf.maximum', (['max_acc_train', 'accuracy'], {}), '(max_acc_train, accuracy)\n', (4262, 4287), True, 'import tensorflow as tf\n'), ((4332, 4366), 'tensorflow.maximum', 'tf.maximum', (['max_acc_test', 'accuracy'], {}), '(max_acc_test, accuracy)\n', (4342, 4366), True, 'import tensorflow as tf\n'), ((5438, 5472), 'tensorflow.compat.v1.train.AdamOptimizer', 'tf.compat.v1.train.AdamOptimizer', ([], {}), '()\n', (5470, 5472), True, 'import tensorflow as tf\n'), ((5727, 5783), 'tensorflow.compat.v1.train.MomentumOptimizer', 'tf.compat.v1.train.MomentumOptimizer', (['learning_rate', '(0.9)'], {}), '(learning_rate, 0.9)\n', (5763, 5783), True, 'import tensorflow as tf\n'), ((10365, 10414), 'tensorflow.compat.v1.ConfigProto', 'tf.compat.v1.ConfigProto', ([], {'gpu_options': 'gpu_options'}), '(gpu_options=gpu_options)\n', (10389, 10414), True, 'import tensorflow as tf\n'), ((12264, 12295), 'tensorflow.compat.v1.global_variables', 'tf.compat.v1.global_variables', ([], {}), '()\n', (12293, 12295), True, 'import tensorflow as tf\n'), ((12362, 12393), 'tensorflow.compat.v1.global_variables', 'tf.compat.v1.global_variables', ([], {}), '()\n', (12391, 12393), True, 'import tensorflow as tf\n'), ((13708, 13719), 'time.time', 'time.time', ([], {}), '()\n', (13717, 13719), False, 'import time\n'), ((16160, 16185), 'numpy.concatenate', 'np.concatenate', (['test_tags'], {}), '(test_tags)\n', (16174, 16185), True, 'import numpy as np\n'), ((16220, 16247), 'numpy.concatenate', 'np.concatenate', (['test_labels'], {}), '(test_labels)\n', (16234, 16247), True, 'import numpy as np\n'), ((20930, 20941), 'time.time', 'time.time', ([], {}), '()\n', (20939, 20941), False, 'import time\n'), ((16421, 16468), 'sklearn.metrics.balanced_accuracy_score', 'balanced_accuracy_score', (['test_labels', 'out_label'], {}), '(test_labels, out_label)\n', (16444, 16468), False, 'from sklearn.metrics import balanced_accuracy_score\n'), ((16347, 16356), 'numpy.max', 'np.max', (['j'], {}), '(j)\n', (16353, 16356), True, 'import numpy as np\n')] |
import collections
import functools
import os
import pickle
from typing import (Callable, Dict, Hashable, List, NamedTuple, Optional,
Sequence, Union)
import numpy as np
from stable_baselines.common.base_class import BaseRLModel
from stable_baselines.common.policies import BasePolicy
from stable_baselines.common.vec_env import VecEnv
import tensorflow as tf
from imitation.policies.base import get_action_policy
from imitation.util.reward_wrapper import RewardFn
class Trajectory(NamedTuple):
"""A trajectory, e.g. a one episode rollout from an expert policy.
Attributes:
acts: Actions, shape (trajectory_len, ) + action_shape.
obs: Observations, shape (trajectory_len+1, ) + observation_shape.
rews: Reward, shape (trajectory_len, ).
infos: A list of info dicts, length (trajectory_len, ).
"""
acts: np.ndarray
obs: np.ndarray
rews: np.ndarray
infos: Optional[List[dict]]
def unwrap_traj(traj: Trajectory) -> Trajectory:
"""Uses `MonitorPlus`-captured `obs` and `rews` to replace fields.
This can be useful for bypassing other wrappers to retrieve the original
`obs` and `rews`.
Fails if `infos` is None or if the Trajectory was generated from an
environment without imitation.util.MonitorPlus.
Args:
traj: A Trajectory generated from `MonitorPlus`-wrapped Environments.
Returns:
A copy of `traj` with replaced `obs` and `rews` fields.
"""
ep_info = traj.infos[-1]["episode"]
res = traj._replace(obs=ep_info["obs"], rews=ep_info["rews"])
assert len(res.obs) == len(res.acts) + 1
assert len(res.rews) == len(res.acts)
return res
def recalc_rewards_traj(traj: Trajectory, reward_fn: RewardFn) -> np.ndarray:
"""Returns the rewards of the trajectory calculated under a diff reward fn."""
steps = np.arange(len(traj.rews))
return reward_fn(traj.obs[:-1], traj.acts, traj.obs[1:], steps)
class Transitions(NamedTuple):
"""A batch of obs-act-obs-rew-done transitions.
Usually generated by combining and processing several Trajectories via
`flatten_trajectories()`.
Attributes:
obs: Previous observations. Shape: (batch_size, ) + observation_shape.
The i'th observation `obs[i]` in this array is the observation seen
by the agent when choosing action `act[i]`.
act: Actions. Shape: (batch_size, ) + action_shape.
next_obs: New observation. Shape: (batch_size, ) + observation_shape.
The i'th observation `next_obs[i]` in this array is the observation
after the agent has taken action `act[i]`.
rew: Reward. Shape: (batch_size, ).
The reward `rew[i]` at the i'th timestep is received after the agent has
taken action `act[i]`.
done: Boolean array indicating episode termination. Shape: (batch_size, ).
`done[i]` is true iff `next_obs[i]` the last observation of an episode.
"""
obs: np.ndarray
acts: np.ndarray
next_obs: np.ndarray
rews: np.ndarray
dones: np.ndarray
class TrajectoryAccumulator:
"""Accumulates trajectories step-by-step.
Useful for collecting completed trajectories while ignoring
partially-completed trajectories (e.g. when rolling out a VecEnv to collect a
set number of transitions). Each in-progress trajectory is identified by a
'key', which enables several independent trajectories to be collected at
once. They key can also be left at its default value of `None` if you only
wish to collect one trajectory."""
def __init__(self):
"""Initialise the trajectory accumulator."""
self.partial_trajectories = collections.defaultdict(list)
def add_step(self, step_dict: Dict[str, np.ndarray], key: Hashable = None):
"""Add a single step to the partial trajectory identified by `key`.
Generally a single step could correspond to, e.g., one environment managed
by a VecEnv.
Args:
step_dict: dictionary containing information for the current step. Its
keys could include any (or all) attributes of a `Trajectory` (e.g.
"obs", "acts", etc.).
key: key to uniquely identify the trajectory to append to, if working
with multiple partial trajectories."""
self.partial_trajectories[key].append(step_dict)
def finish_trajectory(self, key: Hashable = None) -> Trajectory:
"""Complete the trajectory labelled with `key`.
Args:
key: key uniquely identifying which in-progress trajectory to remove.
Returns:
traj: list of completed trajectories popped from
`self.partial_trajectories`."""
part_dicts = self.partial_trajectories[key]
del self.partial_trajectories[key]
out_dict_unstacked = collections.defaultdict(list)
for part_dict in part_dicts:
for key, array in part_dict.items():
out_dict_unstacked[key].append(array)
out_dict_stacked = {
key: np.stack(arr_list, axis=0)
for key, arr_list in out_dict_unstacked.items()
}
traj = Trajectory(**out_dict_stacked)
assert traj.rews.shape[0] == traj.acts.shape[0] == traj.obs.shape[0] - 1
return traj
def add_steps_and_auto_finish(self,
acts: np.ndarray,
obs: np.ndarray,
rews: np.ndarray,
dones: np.ndarray,
infos: List[dict]) -> List[Trajectory]:
"""Calls `add_step` repeatedly using acts and the returns from `venv.step`.
Also automatically calls `finish_trajectory()` for each `done == True`.
Before calling this method, each environment index key needs to be
initialized with the initial observation (usually from `venv.reset()`).
See the body of `util.rollout.generate_trajectory` for an example.
Args:
acts: Actions passed into `VecEnv.step()`.
obs: Return value from `VecEnv.step(acts)`.
rews: Return value from `VecEnv.step(acts)`.
dones: Return value from `VecEnv.step(acts)`.
infos: Return value from `VecEnv.step(acts)`.
Returns:
A list of completed trajectories. There should be one Trajectory for
each `True` in the `dones` argument.
"""
trajs = []
for env_idx in range(len(obs)):
assert env_idx in self.partial_trajectories
assert list(self.partial_trajectories[env_idx][0].keys()) == ["obs"], (
"Need to first initialize partial trajectory using "
"self._traj_accum.add_step({'obs': ob}, key=env_idx)")
zip_iter = enumerate(zip(acts, obs, rews, dones, infos))
for env_idx, (act, ob, rew, done, info) in zip_iter:
if done:
# actual obs is inaccurate, so we use the one inserted into step info
# by stable baselines wrapper
real_ob = info['terminal_observation']
else:
real_ob = ob
self.add_step(
dict(
acts=act,
rews=rew,
# this is not the obs corresponding to `act`, but rather the obs
# *after* `act` (see above)
obs=real_ob,
infos=info),
env_idx)
if done:
# finish env_idx-th trajectory
new_traj = self.finish_trajectory(env_idx)
trajs.append(new_traj)
self.add_step(dict(obs=ob), env_idx)
return trajs
GenTrajTerminationFn = Callable[[Sequence[Trajectory]], bool]
def min_episodes(n: int) -> GenTrajTerminationFn:
"""Terminate after collecting n episodes of data.
Argument:
n: Minimum number of episodes of data to collect.
May overshoot if two episodes complete simultaneously (unlikely).
Returns:
A function implementing this termination condition.
"""
assert n >= 1
return lambda trajectories: len(trajectories) >= n
def min_timesteps(n: int) -> GenTrajTerminationFn:
"""Terminate at the first episode after collecting n timesteps of data.
Arguments:
n: Minimum number of timesteps of data to collect.
May overshoot to nearest episode boundary.
Returns:
A function implementing this termination condition.
"""
assert n >= 1
def f(trajectories: Sequence[Trajectory]):
timesteps = sum(len(t.obs) - 1 for t in trajectories)
return timesteps >= n
return f
def make_sample_until(n_timesteps: Optional[int],
n_episodes: Optional[int],
) -> GenTrajTerminationFn:
"""Returns a termination condition sampling until n_timesteps or n_episodes.
Arguments:
n_timesteps: Minimum number of timesteps to sample.
n_episodes: Number of episodes to sample.
Returns:
A termination condition.
Raises:
ValueError if both or neither of n_timesteps and n_episodes are set,
or if either are non-positive.
"""
if n_timesteps is not None and n_episodes is not None:
raise ValueError("n_timesteps and n_episodes were both set")
elif n_timesteps is not None:
assert n_timesteps > 0
return min_timesteps(n_timesteps)
elif n_episodes is not None:
assert n_episodes > 0
return min_episodes(n_episodes)
else:
raise ValueError("Set at least one of n_timesteps and n_episodes")
def generate_trajectories(policy,
venv: VecEnv,
sample_until: GenTrajTerminationFn,
*,
deterministic_policy: bool = False,
) -> Sequence[Trajectory]:
"""Generate trajectory dictionaries from a policy and an environment.
Args:
policy (BasePolicy or BaseRLModel): A stable_baselines policy or RLModel,
trained on the gym environment.
venv: The vectorized environments to interact with.
sample_until: A function determining the termination condition.
It takes a sequence of trajectories, and returns a bool.
Most users will want to use one of `min_episodes` or `min_timesteps`.
deterministic_policy: If True, asks policy to deterministically return
action. Note the trajectories might still be non-deterministic if the
environment has non-determinism!
Returns:
Sequence of `Trajectory` named tuples.
"""
if isinstance(policy, BaseRLModel):
get_action = policy.predict
policy.set_env(venv)
else:
get_action = functools.partial(get_action_policy, policy)
# Collect rollout tuples.
trajectories = []
# accumulator for incomplete trajectories
trajectories_accum = TrajectoryAccumulator()
obs = venv.reset()
for env_idx, ob in enumerate(obs):
# Seed with first obs only. Inside loop, we'll only add second obs from
# each (s,a,r,s') tuple, under the same "obs" key again. That way we still
# get all observations, but they're not duplicated into "next obs" and
# "previous obs" (this matters for, e.g., Atari, where observations are
# really big).
trajectories_accum.add_step(dict(obs=ob), env_idx)
while not sample_until(trajectories):
acts, _ = get_action(obs, deterministic=deterministic_policy)
obs, rews, dones, infos = venv.step(acts)
new_trajs = trajectories_accum.add_steps_and_auto_finish(
acts, obs, rews, dones, infos)
trajectories.extend(new_trajs)
# Note that we just drop partial trajectories. This is not ideal for some
# algos; e.g. BC can probably benefit from partial trajectories, too.
# Sanity checks.
for trajectory in trajectories:
n_steps = len(trajectory.acts)
# extra 1 for the end
exp_obs = (n_steps + 1, ) + venv.observation_space.shape
real_obs = trajectory.obs.shape
assert real_obs == exp_obs, f"expected shape {exp_obs}, got {real_obs}"
exp_act = (n_steps, ) + venv.action_space.shape
real_act = trajectory.acts.shape
assert real_act == exp_act, f"expected shape {exp_act}, got {real_act}"
exp_rew = (n_steps,)
real_rew = trajectory.rews.shape
assert real_rew == exp_rew, f"expected shape {exp_rew}, got {real_rew}"
return trajectories
def rollout_stats(trajectories: Sequence[Trajectory]) -> dict:
"""Calculates various stats for a sequence of trajectories.
Args:
trajectories: Sequence of `Trajectory`.
Returns:
Dictionary containing `n_traj` collected (int), along with episode return
statistics (keys: `{monitor_,}return_{min,mean,std,max}`, float values)
and trajectory length statistics (keys: `len_{min,mean,std,max}`, float
values).
`return_*` values are calculated from environment rewards.
`monitor_*` values are calculated from Monitor-captured rewards, and
are only included if the `trajectories` contain Monitor infos.
"""
assert len(trajectories) > 0
out_stats = {"n_traj": len(trajectories)}
traj_descriptors = {
"return": np.asarray([sum(t.rews) for t in trajectories]),
"len": np.asarray([len(t.rews) for t in trajectories]),
}
infos_peek = trajectories[0].infos
if infos_peek is not None and "episode" in infos_peek[-1]:
monitor_ep_returns = [t.infos[-1]["episode"]["r"] for t in trajectories]
traj_descriptors["monitor_return"] = np.asarray(monitor_ep_returns)
stat_names = ["min", "mean", "std", "max"]
for desc_name, desc_vals in traj_descriptors.items():
for stat_name in stat_names:
stat_value = getattr(np, stat_name)(desc_vals)
out_stats[f"{desc_name}_{stat_name}"] = stat_value
return out_stats
def mean_return(*args, **kwargs) -> float:
"""Find the mean return of a policy.
Shortcut to call `generate_trajectories` and fetch the `rollout_stats` value
for `'return_mean'`; see documentation for `generate_trajectories` and
`rollout_stats`.
"""
trajectories = generate_trajectories(*args, **kwargs)
return rollout_stats(trajectories)["return_mean"]
def flatten_trajectories(trajectories: Sequence[Trajectory]) -> Transitions:
"""Flatten a series of trajectory dictionaries into arrays.
Returns observations, actions, next observations, rewards.
Args:
trajectories: list of trajectories.
Returns:
The trajectories flattened into a single batch of Transitions.
"""
keys = ["obs", "next_obs", "acts", "rews", "dones"]
parts = {key: [] for key in keys}
for traj in trajectories:
parts["acts"].append(traj.acts)
parts["rews"].append(traj.rews)
obs = traj.obs
parts["obs"].append(obs[:-1])
parts["next_obs"].append(obs[1:])
dones = np.zeros_like(traj.rews, dtype=np.bool)
dones[-1] = True
parts["dones"].append(dones)
cat_parts = {
key: np.concatenate(part_list, axis=0)
for key, part_list in parts.items()
}
lengths = set(map(len, cat_parts.values()))
assert len(lengths) == 1, f"expected one length, got {lengths}"
return Transitions(**cat_parts)
def generate_transitions(policy,
venv,
n_timesteps: int,
*,
truncate: bool = True,
**kwargs) -> Transitions:
"""Generate obs-action-next_obs-reward tuples.
Args:
policy (BasePolicy or BaseRLModel): A stable_baselines policy or RLModel,
trained on the gym environment.
venv: The vectorized environments to interact with.
n_timesteps: The minimum number of timesteps to sample.
truncate: If True, then drop any additional samples to ensure that exactly
`n_timesteps` samples are returned.
**kwargs: Passed-through to generate_trajectories.
Returns:
A batch of Transitions. The length of the constituent arrays is guaranteed
to be at least `n_timesteps` (if specified), but may be greater unless
`truncate` is provided as we collect data until the end of each episode.
"""
traj = generate_trajectories(policy, venv,
sample_until=min_timesteps(n_timesteps),
**kwargs)
transitions = flatten_trajectories(traj)
if truncate and n_timesteps is not None:
transitions = Transitions(*(arr[:n_timesteps] for arr in transitions))
return transitions
def save(path: str,
policy: Union[BaseRLModel, BasePolicy],
venv: VecEnv,
sample_until: GenTrajTerminationFn,
*,
unwrap: bool = True,
exclude_infos: bool = True,
**kwargs,
) -> None:
"""Generate policy rollouts and save them to a pickled Sequence[Trajectory].
The `.infos` field of each Trajectory is set to `None` to save space.
Args:
path: Rollouts are saved to this path.
venv: The vectorized environments.
sample_until: End condition for rollout sampling.
unwrap: If True, then save original observations and rewards (instead of
potentially wrapped observations and rewards) by calling
`unwrap_traj()`.
exclude_infos: If True, then exclude `infos` from pickle by setting
this field to None. Excluding `infos` can save a lot of space during
pickles.
deterministic_policy: Argument from `generate_trajectories`.
"""
os.makedirs(os.path.dirname(path), exist_ok=True)
trajs = generate_trajectories(policy, venv, sample_until, **kwargs)
if unwrap:
trajs = [unwrap_traj(traj) for traj in trajs]
if exclude_infos:
trajs = [traj._replace(infos=None) for traj in trajs]
with open(path, "wb") as f:
pickle.dump(trajs, f)
tf.logging.info("Dumped demonstrations to {}.".format(path))
| [
"pickle.dump",
"numpy.asarray",
"os.path.dirname",
"numpy.stack",
"functools.partial",
"collections.defaultdict",
"numpy.concatenate",
"numpy.zeros_like"
] | [((3555, 3584), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (3578, 3584), False, 'import collections\n'), ((4654, 4683), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (4677, 4683), False, 'import collections\n'), ((10203, 10247), 'functools.partial', 'functools.partial', (['get_action_policy', 'policy'], {}), '(get_action_policy, policy)\n', (10220, 10247), False, 'import functools\n'), ((12980, 13010), 'numpy.asarray', 'np.asarray', (['monitor_ep_returns'], {}), '(monitor_ep_returns)\n', (12990, 13010), True, 'import numpy as np\n'), ((14277, 14316), 'numpy.zeros_like', 'np.zeros_like', (['traj.rews'], {'dtype': 'np.bool'}), '(traj.rews, dtype=np.bool)\n', (14290, 14316), True, 'import numpy as np\n'), ((14396, 14429), 'numpy.concatenate', 'np.concatenate', (['part_list'], {'axis': '(0)'}), '(part_list, axis=0)\n', (14410, 14429), True, 'import numpy as np\n'), ((16909, 16930), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (16924, 16930), False, 'import os\n'), ((17207, 17228), 'pickle.dump', 'pickle.dump', (['trajs', 'f'], {}), '(trajs, f)\n', (17218, 17228), False, 'import pickle\n'), ((4842, 4868), 'numpy.stack', 'np.stack', (['arr_list'], {'axis': '(0)'}), '(arr_list, axis=0)\n', (4850, 4868), True, 'import numpy as np\n')] |
import os
import sqlite3 as sql
import numpy as np
def mhc_datasets(table='mhc_data', path='./iedb/', remove_c=False,
remove_u=False, remove_modes=False):
"""
Parameters: 'table' is the table that the data is retrieved
- must be 'mhc_data', 'mhc_test1', 'mhc_test2', or 'mhc_train'
'path' is where the database is stored
remove every sequence with a 'c'
remove every sequence with a 'u'
remove the unusual modes of the dataset
if the table name is 'mhc_data' then will return the entire remaining dataset, otherwise,
returns (in order): the amino acid sequences, the -log10 of binding affinities, and the alleles
"""
if table != 'mhc_data' and table != 'mhc_train' and table != 'mhc_test1' and table != 'mhc_test2':
raise Exception('table name ' + table + ' does not exist')
selection = '*'
if table != 'mhc_data':
selection = 'sequence, meas, mhc'
conn = sql.connect(os.path.join(path, 'mhc.db'))
c = conn.cursor()
c.execute(_create_query(selection, table, remove_c, remove_u, remove_modes))
dataset = np.array(c.fetchall())
conn.close()
if table == 'mhc_data':
return dataset
if table == 'mhc_train':
# Temporary solution to remove benchmark overlaps from train set:
off_limits = np.loadtxt(os.path.join(path, 'benchmark_ic50_sequences.csv'),
delimiter=',', dtype=str)
idx = ~np.array([(seq in off_limits) for seq in dataset[:, 0]]).astype(bool)
dataset = dataset[idx, :]
return dataset.T[0], -np.log10(dataset.T[1].astype(float)), dataset.T[2]
def _create_query(selection, table, remove_c, remove_u, remove_modes):
query = 'SELECT ' + selection + ' FROM ' + table + ' '
if remove_c or remove_u or remove_modes:
query = query + 'WHERE '
if remove_c:
query = query + 'sequence NOT LIKE \'%C%\' AND '
if remove_u:
query = query + 'sequence NOT LIKE \'%U%\' AND '
if remove_modes:
query = query + 'inequality != \'>\''
if query.endswith('AND '):
query = query[:-4]
return query
def mhc_benchmark(path='./data/iedb'):
import pandas as pd
file_path = os.path.join(path, 'IEDB Benchmark Data.txt')
cols = ['Allele', 'Measurement type', 'Peptide seq', 'Measurement value']
df = pd.read_csv(file_path, sep="\t", header=0, na_values='-', usecols=cols)
df = df[df['Measurement type'] == 'ic50']
sequences = df['Peptide seq'].values.astype(str)
ic50s = df['Measurement value'].values
alleles = df['Allele'].values.astype(str)
return sequences, -np.log10(ic50s), alleles | [
"numpy.array",
"numpy.log10",
"os.path.join",
"pandas.read_csv"
] | [((2282, 2327), 'os.path.join', 'os.path.join', (['path', '"""IEDB Benchmark Data.txt"""'], {}), "(path, 'IEDB Benchmark Data.txt')\n", (2294, 2327), False, 'import os\n'), ((2416, 2487), 'pandas.read_csv', 'pd.read_csv', (['file_path'], {'sep': '"""\t"""', 'header': '(0)', 'na_values': '"""-"""', 'usecols': 'cols'}), "(file_path, sep='\\t', header=0, na_values='-', usecols=cols)\n", (2427, 2487), True, 'import pandas as pd\n'), ((1020, 1048), 'os.path.join', 'os.path.join', (['path', '"""mhc.db"""'], {}), "(path, 'mhc.db')\n", (1032, 1048), False, 'import os\n'), ((1393, 1443), 'os.path.join', 'os.path.join', (['path', '"""benchmark_ic50_sequences.csv"""'], {}), "(path, 'benchmark_ic50_sequences.csv')\n", (1405, 1443), False, 'import os\n'), ((2705, 2720), 'numpy.log10', 'np.log10', (['ic50s'], {}), '(ic50s)\n', (2713, 2720), True, 'import numpy as np\n'), ((1518, 1574), 'numpy.array', 'np.array', (['[(seq in off_limits) for seq in dataset[:, 0]]'], {}), '([(seq in off_limits) for seq in dataset[:, 0]])\n', (1526, 1574), True, 'import numpy as np\n')] |
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# ??/??/?? xxxxxxxx Initial Creation.
# 05/28/13 2023 dgilling Implement __str__().
# 01/22/14 2667 bclement preserved milliseconds in string representation
# 03/03/14 2673 bsteffen allow construction using a Date for refTime
# 06/24/14 3096 mnash implement __cmp__
# 06/24/15 4480 dgilling implement __hash__ and __eq__,
# replace __cmp__ with rich comparison
# operators.
# 05/26/16 2416 rjpeter Added str based constructor.
# 08/02/16 2416 tgurney Forecast time regex bug fix,
# plus misc cleanup
#
import calendar
import datetime
import re
import time
import numpy
from six.moves import cStringIO as StringIO
from dynamicserialize.dstypes.java.util import Date
from dynamicserialize.dstypes.java.util import EnumSet
from .TimeRange import TimeRange
_DATE = r'(\d{4}-\d{2}-\d{2})'
_TIME = r'(\d{2}:\d{2}:\d{2})'
_MILLIS = '(?:\.(\d{1,3})(?:\d{1,4})?)?' # might have microsecond but that is thrown out
REFTIME_PATTERN_STR = _DATE + '[ _]' + _TIME + _MILLIS
FORECAST_PATTERN_STR = r'(?:[ _]\((\d+)(?::(\d{1,2}))?\))?'
VALID_PERIOD_PATTERN_STR = r'(?:\[' + REFTIME_PATTERN_STR + '--' + REFTIME_PATTERN_STR + r'\])?'
STR_PATTERN = re.compile(REFTIME_PATTERN_STR + FORECAST_PATTERN_STR + VALID_PERIOD_PATTERN_STR)
class DataTime(object):
def __init__(self, refTime=None, fcstTime=None, validPeriod=None):
"""
Construct a new DataTime.
May also be called as DataTime(str) to parse a string and create a
DataTime from it. Some examples of valid DataTime strings:
'2016-08-02 01:23:45.0'
'2016-08-02 01:23:45.123'
'2016-08-02 01:23:45.0 (17)',
'2016-08-02 01:23:45.0 (17:34)'
'2016-08-02 01:23:45.0[2016-08-02_02:34:45.0--2016-08-02_03:45:56.0]'
'2016-08-02 01:23:45.456_(17:34)[2016-08-02_02:34:45.0--2016-08-02_03:45:56.0]'
"""
if fcstTime is not None:
self.fcstTime = int(fcstTime)
else:
self.fcstTime = 0
self.refTime = refTime
if validPeriod is not None and not isinstance(validPeriod, TimeRange):
raise ValueError("Invalid validPeriod object specified for DataTime.")
self.validPeriod = validPeriod
self.utilityFlags = EnumSet('com.raytheon.uf.common.time.DataTime$FLAG')
self.levelValue = numpy.float64(-1.0)
if self.refTime is not None:
if isinstance(self.refTime, datetime.datetime):
self.refTime = int(calendar.timegm(self.refTime.utctimetuple()) * 1000)
elif isinstance(self.refTime, time.struct_time):
self.refTime = int(calendar.timegm(self.refTime) * 1000)
elif hasattr(self.refTime, 'getTime'):
# getTime should be returning ms, there is no way to check this
# This is expected for java Date
self.refTime = int(self.refTime.getTime())
else:
try:
self.refTime = int(self.refTime)
except ValueError:
# Assume first arg is a string. Attempt to parse.
match = STR_PATTERN.match(self.refTime)
if match is None:
raise ValueError('Could not parse DataTime info from '
+ str(refTime))
groups = match.groups()
rMillis = groups[2] or 0
fcstTimeHr = groups[3]
fcstTimeMin = groups[4]
periodStart = groups[5], groups[6], (groups[7] or 0)
periodEnd = groups[8], groups[9], (groups[10] or 0)
self.refTime = self._getTimeAsEpochMillis(groups[0], groups[1], rMillis)
if fcstTimeHr is not None:
self.fcstTime = int(fcstTimeHr) * 3600
if fcstTimeMin is not None:
self.fcstTime += int(fcstTimeMin) * 60
if periodStart[0] is not None:
self.validPeriod = TimeRange()
periodStartTime = self._getTimeAsEpochMillis(*periodStart)
self.validPeriod.setStart(periodStartTime / 1000)
periodEndTime = self._getTimeAsEpochMillis(*periodEnd)
self.validPeriod.setEnd(periodEndTime / 1000)
self.refTime = Date(self.refTime)
if self.validPeriod is None:
validTimeMillis = self.refTime.getTime() + int(self.fcstTime * 1000)
self.validPeriod = TimeRange()
self.validPeriod.setStart(validTimeMillis / 1000)
self.validPeriod.setEnd(validTimeMillis / 1000)
# figure out utility flags
if self.fcstTime:
self.utilityFlags.add("FCST_USED")
if self.validPeriod and self.validPeriod.isValid():
self.utilityFlags.add("PERIOD_USED")
def getRefTime(self):
return self.refTime
def setRefTime(self, refTime):
self.refTime = refTime
def getFcstTime(self):
return self.fcstTime
def setFcstTime(self, fcstTime):
self.fcstTime = fcstTime
def getValidPeriod(self):
return self.validPeriod
def setValidPeriod(self, validPeriod):
self.validPeriod = validPeriod
def getUtilityFlags(self):
return self.utilityFlags
def setUtilityFlags(self, utilityFlags):
self.utilityFlags = utilityFlags
def getLevelValue(self):
return self.levelValue
def setLevelValue(self, levelValue):
self.levelValue = numpy.float64(levelValue)
def __str__(self):
sbuffer = StringIO()
if self.refTime is not None:
refTimeInSecs = self.refTime.getTime() / 1000
micros = (self.refTime.getTime() % 1000) * 1000
dtObj = datetime.datetime.utcfromtimestamp(refTimeInSecs)
dtObj = dtObj.replace(microsecond=micros)
# This won't be compatible with java or string from java since its to microsecond
sbuffer.write(dtObj.isoformat(' '))
if "FCST_USED" in self.utilityFlags:
hrs = int(self.fcstTime / 3600)
mins = int((self.fcstTime - (hrs * 3600)) / 60)
sbuffer.write(" (" + str(hrs))
if mins != 0:
sbuffer.write(":" + str(mins))
sbuffer.write(")")
if "PERIOD_USED" in self.utilityFlags:
sbuffer.write("[")
sbuffer.write(self.validPeriod.start.isoformat(' '))
sbuffer.write("--")
sbuffer.write(self.validPeriod.end.isoformat(' '))
sbuffer.write("]")
strVal = sbuffer.getvalue()
sbuffer.close()
return strVal
def __repr__(self):
return "<DataTime instance: " + str(self) + " >"
def __hash__(self):
hashCode = hash(self.refTime) ^ hash(self.fcstTime)
if self.validPeriod is not None and self.validPeriod.isValid():
hashCode ^= hash(self.validPeriod.getStart())
hashCode ^= hash(self.validPeriod.getEnd())
hashCode ^= hash(self.levelValue)
return hashCode
def __eq__(self, other):
if not isinstance(self, type(other)):
return False
if other.getRefTime() is None:
return self.fcstTime == other.fcstTime
dataTime1 = (self.refTime, self.fcstTime, self.validPeriod, self.levelValue)
dataTime2 = (other.refTime, other.fcstTime, other.validPeriod, other.levelValue)
return dataTime1 == dataTime2
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
if not isinstance(self, type(other)):
return NotImplemented
myValidTime = self.getRefTime().getTime() + self.getFcstTime()
otherValidTime = other.getRefTime().getTime() + other.getFcstTime()
if myValidTime < otherValidTime:
return True
if self.fcstTime < other.fcstTime:
return True
if self.levelValue < other.levelValue:
return True
myValidPeriod = self.validPeriod
otherValidPeriod = other.validPeriod
if myValidPeriod != otherValidPeriod:
if myValidPeriod.duration() < otherValidPeriod.duration():
return True
return myValidPeriod.getStartInMillis() < otherValidPeriod.getStartInMillis()
return False
def __le__(self, other):
if not isinstance(self, type(other)):
return NotImplemented
return self.__lt__(other) or self.__eq__(other)
def __gt__(self, other):
if not isinstance(self, type(other)):
return NotImplemented
myValidTime = self.getRefTime().getTime() + self.getFcstTime()
otherValidTime = other.getRefTime().getTime() + other.getFcstTime()
if myValidTime > otherValidTime:
return True
if self.fcstTime > other.fcstTime:
return True
if self.levelValue > other.levelValue:
return True
myValidPeriod = self.validPeriod
otherValidPeriod = other.validPeriod
if myValidPeriod != otherValidPeriod:
if myValidPeriod.duration() > otherValidPeriod.duration():
return True
return myValidPeriod.getStartInMillis() > otherValidPeriod.getStartInMillis()
return False
def __ge__(self, other):
if not isinstance(self, type(other)):
return NotImplemented
return self.__gt__(other) or self.__eq__(other)
def _getTimeAsEpochMillis(self, dateStr, timeStr, millis):
t = time.strptime(dateStr + ' ' + timeStr, '%Y-%m-%d %H:%M:%S')
epochSeconds = calendar.timegm(t)
return int(epochSeconds * 1000) + int(millis)
| [
"datetime.datetime.utcfromtimestamp",
"time.strptime",
"re.compile",
"dynamicserialize.dstypes.java.util.EnumSet",
"numpy.float64",
"calendar.timegm",
"dynamicserialize.dstypes.java.util.Date",
"six.moves.cStringIO"
] | [((1655, 1740), 're.compile', 're.compile', (['(REFTIME_PATTERN_STR + FORECAST_PATTERN_STR + VALID_PERIOD_PATTERN_STR)'], {}), '(REFTIME_PATTERN_STR + FORECAST_PATTERN_STR +\n VALID_PERIOD_PATTERN_STR)\n', (1665, 1740), False, 'import re\n'), ((2755, 2807), 'dynamicserialize.dstypes.java.util.EnumSet', 'EnumSet', (['"""com.raytheon.uf.common.time.DataTime$FLAG"""'], {}), "('com.raytheon.uf.common.time.DataTime$FLAG')\n", (2762, 2807), False, 'from dynamicserialize.dstypes.java.util import EnumSet\n'), ((2834, 2853), 'numpy.float64', 'numpy.float64', (['(-1.0)'], {}), '(-1.0)\n', (2847, 2853), False, 'import numpy\n'), ((6148, 6173), 'numpy.float64', 'numpy.float64', (['levelValue'], {}), '(levelValue)\n', (6161, 6173), False, 'import numpy\n'), ((6216, 6226), 'six.moves.cStringIO', 'StringIO', ([], {}), '()\n', (6224, 6226), True, 'from six.moves import cStringIO as StringIO\n'), ((10213, 10272), 'time.strptime', 'time.strptime', (["(dateStr + ' ' + timeStr)", '"""%Y-%m-%d %H:%M:%S"""'], {}), "(dateStr + ' ' + timeStr, '%Y-%m-%d %H:%M:%S')\n", (10226, 10272), False, 'import time\n'), ((10296, 10314), 'calendar.timegm', 'calendar.timegm', (['t'], {}), '(t)\n', (10311, 10314), False, 'import calendar\n'), ((4930, 4948), 'dynamicserialize.dstypes.java.util.Date', 'Date', (['self.refTime'], {}), '(self.refTime)\n', (4934, 4948), False, 'from dynamicserialize.dstypes.java.util import Date\n'), ((6403, 6452), 'datetime.datetime.utcfromtimestamp', 'datetime.datetime.utcfromtimestamp', (['refTimeInSecs'], {}), '(refTimeInSecs)\n', (6437, 6452), False, 'import datetime\n'), ((3136, 3165), 'calendar.timegm', 'calendar.timegm', (['self.refTime'], {}), '(self.refTime)\n', (3151, 3165), False, 'import calendar\n')] |
"""
Authors: The Vollab Developers 2004-2021
License: BSD 3 clause
Calculate the local volatility surface for given characteristic function in three steps:
1. For a given characteristic function use Fast Fourier Transform to get call price surface.
2. Uses the Lets Be Rational function for fast calculation of implied volatility.
3. Construct local volatility using Dupire's formula and cubic spline interpolation.
"""
import numpy as np
from scipy.interpolate import CubicSpline
from .ImpliedVolatilitySurface import *
from .SplineSurface import SplineSurface
from .FFTEuropeanCallPrice import compute_call_prices_matrix
def change_variables(market_params, maturity_time, strikes, smile):
"""
Change variables to log-strike and variance.
Args:
market_params: The market parameters.
maturity_time: The maturity times.
strikes: The strikes of the smile.
smile: The implied volatility at the strikes.
Returns:
A pair of numpy arrays of equal size, log-strikes, variance.
"""
forward = market_params.forward(maturity_time)
rel_log_strikes = np.array(strikes)
rel_log_strikes /= forward
rel_log_strikes = np.log(rel_log_strikes)
variance = np.square(smile)
variance *= maturity_time
return rel_log_strikes, variance
def compute_derivatives(log_strikes, variances):
"""
Args:
log_strikes: An array of log strikes.
variances: An array of variances.
Returns:
A tuple, a cubic spline through the data,
array of the first derivatives,
array of the second derivatives.
"""
spline = CubicSpline(log_strikes, variances)
deriv_1 = spline(variances, 1)
deriv_2 = spline(variances, 2)
return deriv_1, deriv_2
def compute_denominator(log_strike, variance, deriv_1, deriv_2):
"""
Compute denominator in local vol equation.
Args:
log_strike: The log-strike.
variance: The variance.
deriv_1: The first derivative of variance wrt log strike.
deriv_2: The second derivative of variance wrt log strike.
Returns:
The denominator in local vol equation.
"""
return 1.0 - (log_strike * deriv_1 / variance) \
+ 0.25 * (-0.25 - (1.0 / variance)
+ (log_strike * log_strike / variance * variance)) \
* (deriv_1 * deriv_1) \
+ 0.5 * deriv_2
def compute_denominator_row(market_params, strikes, maturity_time, smile):
"""
Compute the denominator in local vol equation for a given maturity time.
Args:
market_params:The market parameters.
strikes: The strikes.
maturity_time: The tenor.
smile: The smile.
Returns:
"""
row = []
log_strikes, variances = change_variables(market_params, maturity_time, strikes, smile)
derivs_1, derivs_2 = compute_derivatives(log_strikes, variances)
for log_strike, variance, deriv_1, deriv_2 in zip(log_strikes, variances, derivs_1, derivs_2):
row.append(compute_denominator(log_strike, variance, deriv_1, deriv_2))
return row
def compute_denominator_matrix(market_params, strikes, maturity_times, implied_vol_surface):
"""
Args:
market_params: The market params.
strikes: The strikes.
maturity_times: The maturity times.
implied_vol_surface: The implied vol surface matrix.
Returns:
"""
matrix = []
for tenor, smile in zip(maturity_times, implied_vol_surface):
matrix.append(compute_denominator_row(market_params, strikes, tenor, smile))
return matrix
def compute_dvariance_dmaturity(market_params, strikes, tenors, implied_vol_surface):
"""
Calculate the matrix of derivatives in variance by maturity.
Args:
characteristic_function: The characteristic function.
market_params:The market parameters.
strike_selector: Predicate function for selecting strikes.
tenors: The maturity times of interest.
Returns:
A matrix of local volatility for the given strikes and tenors.
"""
smile_splines = []
for tenor, smile in zip(tenors, implied_vol_surface):
dummy, variances = change_variables(market_params, tenor, strikes, smile)
smile_splines.append(CubicSpline(strikes, variances))
tenor_splines = []
for strike in strikes:
variances = []
for spline in smile_splines:
variances.append(spline(strike))
tenor_splines.append(CubicSpline(tenors, variances))
dvariance_dmaturity = []
for tenor in tenors:
row = []
for idx_strike, strike in enumerate(strikes):
row.append(tenor_splines[idx_strike](tenor, 1))
dvariance_dmaturity.append(row)
return dvariance_dmaturity
def compute_local_vol_matrix(characteristic_function,
market_params,
strike_selector,
maturity_times):
"""
Calculate a matrix of local volatility at the given strikes and maturity_times.
Args:
characteristic_function: The characteristic function.
market_params:The market parameters.
strike_selector: Predicate function for selecting strikes.
maturity_times: The maturity_times of interest.
Returns:
A matrix of local volatility at the given strikes and maturity_times.
"""
strikes, maturity_times, implied_vol_surface = \
compute_implied_vol_surface(characteristic_function,
market_params,
strike_selector,
maturity_times)
denom_matrix = compute_denominator_matrix(market_params,
strikes,
maturity_times,
implied_vol_surface)
dvariance_dtenor_matrix = compute_dvariance_dmaturity(market_params,
strikes,
maturity_times,
implied_vol_surface)
local_vol_surface = np.empty([len(maturity_times), len(strikes)])
for idx_tenor in range(len(maturity_times)):
for idx_strike in range(len(strikes)):
dvariance_dtenor = dvariance_dtenor_matrix[idx_tenor][idx_strike]
denom = denom_matrix[idx_tenor][idx_strike]
local_vol_surface[idx_tenor][idx_strike] = np.sqrt(dvariance_dtenor / denom)
return strikes, maturity_times, local_vol_surface
def compute_local_vol_spline_surface(characteristic_function,
market_params,
strike_selector,
maturity_times,
maturity_time_floor=0.25):
"""
Compute the local volatility surface.
Args:
characteristic_function: The characteristic function.
market_params:The market parameters.
strike_selector: Predicate function for selecting strikes.
maturity_times: The maturity times of the surface.
maturity_time_floor: Times smaller than this will be extrapolated flat.
Returns: A tuple of: strikes, maturities, call prices, local vol as a spline surface
"""
# calculate call prices
selected_strikes, maturity_times, call_prices_by_fft = \
compute_call_prices_matrix(characteristic_function,
market_params,
strike_selector,
maturity_times)
# calculate the local vol surface
floored_maturity_times = np.array([t for t in maturity_times if t > maturity_time_floor])
local_vol_matrix_results = compute_local_vol_matrix(characteristic_function,
market_params,
strike_selector,
floored_maturity_times)
# make the spline surface
local_vol_spline_surface = SplineSurface(selected_strikes,
floored_maturity_times,
local_vol_matrix_results[2],
maturity_times)
return selected_strikes, maturity_times, call_prices_by_fft, local_vol_spline_surface
| [
"numpy.sqrt",
"scipy.interpolate.CubicSpline",
"numpy.log",
"numpy.square",
"numpy.array"
] | [((1160, 1177), 'numpy.array', 'np.array', (['strikes'], {}), '(strikes)\n', (1168, 1177), True, 'import numpy as np\n'), ((1231, 1254), 'numpy.log', 'np.log', (['rel_log_strikes'], {}), '(rel_log_strikes)\n', (1237, 1254), True, 'import numpy as np\n'), ((1271, 1287), 'numpy.square', 'np.square', (['smile'], {}), '(smile)\n', (1280, 1287), True, 'import numpy as np\n'), ((1682, 1717), 'scipy.interpolate.CubicSpline', 'CubicSpline', (['log_strikes', 'variances'], {}), '(log_strikes, variances)\n', (1693, 1717), False, 'from scipy.interpolate import CubicSpline\n'), ((7852, 7916), 'numpy.array', 'np.array', (['[t for t in maturity_times if t > maturity_time_floor]'], {}), '([t for t in maturity_times if t > maturity_time_floor])\n', (7860, 7916), True, 'import numpy as np\n'), ((4334, 4365), 'scipy.interpolate.CubicSpline', 'CubicSpline', (['strikes', 'variances'], {}), '(strikes, variances)\n', (4345, 4365), False, 'from scipy.interpolate import CubicSpline\n'), ((4552, 4582), 'scipy.interpolate.CubicSpline', 'CubicSpline', (['tenors', 'variances'], {}), '(tenors, variances)\n', (4563, 4582), False, 'from scipy.interpolate import CubicSpline\n'), ((6634, 6667), 'numpy.sqrt', 'np.sqrt', (['(dvariance_dtenor / denom)'], {}), '(dvariance_dtenor / denom)\n', (6641, 6667), True, 'import numpy as np\n')] |
from __future__ import print_function
import os
import sys
import torch
import os.path
import numpy as np
from utils import *
from PIL import Image
import torch.utils.data as data
import torchvision.transforms as transforms
utils_path = '/home/parker/code/AtlasNet/utils/'
open3d_path = '/home/parker/packages/Open3D/build/lib/'
sys.path.append(utils_path)
sys.path.append(open3d_path)
from cloud import ScanData
from py3d import *
class TangConvShapeNet(data.Dataset):
def __init__(self, root="/home/parker/datasets/TangConvRand", class_choice="couch",
train = True, npoints=2500, normal=False, balanced=False,
gen_view=False, SVR=False, idx=0, num_scales=3, max_points=2500,
input_channels=3):
self.balanced = balanced
self.normal = normal
self.train = train
self.root = root
self.npoints = npoints
self.datapath = []
self.catfile = os.path.join('../data/synsetoffset2category.txt')
self.cat = {}
self.meta = {}
self.SVR = SVR
self.gen_view = gen_view
self.idx=idx
self.num_scales = num_scales
self.training_data = []
self.max_points = max_points
self.input_channels = input_channels
# From catfile, get chosen categories we want to use
with open(self.catfile, 'r') as f:
for line in f:
ls = line.strip().split()
self.cat[ls[0]] = ls[1]
if not class_choice is None:
self.cat = {k:v for k,v in self.cat.items() if k in class_choice}
print(self.cat)
for item in self.cat:
# Get directories of objects of a specific class in ShapeNetRendering folder
dir_cat = os.path.join(self.root, self.cat[item])
fns = sorted(os.listdir(dir_cat))
print('category: ', self.cat[item], 'files: ' + str(len(fns)))
# First 20% of data for testing, last 80% for training
if train:
fns = fns[:int(len(fns) * 0.8)]
else:
fns = fns[int(len(fns) * 0.8):]
# self.meta[item][0] = TangConv precompute directory
# [1] = ShapeNet point cloud file (.ply)
# [2] = name of the category of the item
# [3] = item name
#
# [x] = path to the normalized_model dir in ShapeNetCorev2
# For each non-matched item, remove it form self.cat
if len(fns) != 0:
self.meta[item] = []
for fn in fns:
self.meta[item].append((os.path.join(dir_cat, fn),
os.path.join(dir_cat, fn, fn + '.points.ply'),
item, fn))
self.idx2cat = {}
self.size = {}
# Stores self.meta[item] info into self.datapath[i]
i = 0
for item in self.cat:
self.idx2cat[i] = item
self.size[i] = len(self.meta[item])
i = i + 1
for fn in self.meta[item]:
self.datapath.append(fn)
self.perCatValueMeter = {}
for item in self.cat:
self.perCatValueMeter[item] = AverageValueMeter()
def __getitem__(self, index):
fn = self.datapath[index]
# Reads each scale_x.npz file and extracts s.points, s.conv_ind, s.pool_ind,
# s.depth, and s.normals. Each scale represents a different layer size in the
# TangConv encoder.
s = ScanData()
s.load(fn[0], self.num_scales)
s.remap_depth()
s.remap_normals()
### ISSUE TO FIX ###
if np.asarray(s.clouds[0].normals).shape[0] < self.max_points:
s.resize(self.max_points)
else:
s.load(self.datapath[-2][0], self.num_scales)
s.remap_depth()
s.remap_normals()
masks = []
masks.append([np.asarray(s.clouds[0].points), s.conv_ind[0], s.pool_ind[0].astype(int), s.depth[0], s.pool_mask[0]])
masks.append([np.asarray(s.clouds[1].points), s.conv_ind[1], s.pool_ind[1].astype(int), s.depth[1], s.pool_mask[1]])
masks.append([np.asarray(s.clouds[2].points), s.conv_ind[2], s.pool_ind[2].astype(int), s.depth[2], s.pool_mask[2]])
normals = torch.from_numpy(np.asarray(s.clouds[0].normals))
# return[0] : masks and other params for all scales
# [1] : Normals of object
# [2] : category name
# [3] : item name
#
# [x] : path to the normalized_model drir in ShapeNetCorev2
return masks, normals.contiguous(), fn[2], fn[3]
def __len__(self):
return len(self.datapath)
if __name__ == '__main__':
d = TangConvShapeNet(class_choice = None, balanced= False, train=True, npoints=2500)
masks, normals, cat, item = d.__getitem__(50)
a = masks[2][2]
b = np.where(a > 625, 1, 0)
print(np.count_nonzero(b))
print(a)
print(masks[0][2].shape)
print(cat)
print(item)
# print(type(masks[0][0]))
# print(type(masks[0][1]))
# print(type(masks[0][2]))
# print(type(masks[0][3]))
# print(type(masks[0][4]))
# print(normals.shape)
### FOR CHECKING POOL MASK SIZE ###
# faulty_samples = {}
# for i in range(0, len(d)):
# masks, normals, cat, item = d.__getitem__(100)
# a = masks[2][2]
# b = np.where(a > 1250, 1, 0)
# if np.count_nonzero(b) > 0:
# faulty_samples.append([cat, item])
# print(np.count_nonzero(b))
# print('Found at index {}'.format(i))
# with open('faulty.txt', 'w') as f:
# for item in faulty_samples:
# f.write("%s\n" % item)
### FOR CHECKING INDEXING MASK SIZE ###
# faulty_samples = {}
# for i in range(0, len(d)):
# masks, normals, cat, item = d.__getitem__(100)
# a = masks[2][1]
# b = np.where(a > 625, 1, 0)
# if np.count_nonzero(b) > 0:
# faulty_samples.append([cat, item])
# print(np.count_nonzero(b))
# print('Found at index {}'.format(i))
# with open('faulty.txt', 'w') as f:
# for item in faulty_samples:
# f.write("%s\n" % item)
| [
"os.listdir",
"numpy.where",
"os.path.join",
"numpy.asarray",
"numpy.count_nonzero",
"sys.path.append",
"cloud.ScanData"
] | [((330, 357), 'sys.path.append', 'sys.path.append', (['utils_path'], {}), '(utils_path)\n', (345, 357), False, 'import sys\n'), ((358, 386), 'sys.path.append', 'sys.path.append', (['open3d_path'], {}), '(open3d_path)\n', (373, 386), False, 'import sys\n'), ((5024, 5047), 'numpy.where', 'np.where', (['(a > 625)', '(1)', '(0)'], {}), '(a > 625, 1, 0)\n', (5032, 5047), True, 'import numpy as np\n'), ((948, 997), 'os.path.join', 'os.path.join', (['"""../data/synsetoffset2category.txt"""'], {}), "('../data/synsetoffset2category.txt')\n", (960, 997), False, 'import os\n'), ((3620, 3630), 'cloud.ScanData', 'ScanData', ([], {}), '()\n', (3628, 3630), False, 'from cloud import ScanData\n'), ((5058, 5077), 'numpy.count_nonzero', 'np.count_nonzero', (['b'], {}), '(b)\n', (5074, 5077), True, 'import numpy as np\n'), ((1770, 1809), 'os.path.join', 'os.path.join', (['self.root', 'self.cat[item]'], {}), '(self.root, self.cat[item])\n', (1782, 1809), False, 'import os\n'), ((4420, 4451), 'numpy.asarray', 'np.asarray', (['s.clouds[0].normals'], {}), '(s.clouds[0].normals)\n', (4430, 4451), True, 'import numpy as np\n'), ((1835, 1854), 'os.listdir', 'os.listdir', (['dir_cat'], {}), '(dir_cat)\n', (1845, 1854), False, 'import os\n'), ((4031, 4061), 'numpy.asarray', 'np.asarray', (['s.clouds[0].points'], {}), '(s.clouds[0].points)\n', (4041, 4061), True, 'import numpy as np\n'), ((4156, 4186), 'numpy.asarray', 'np.asarray', (['s.clouds[1].points'], {}), '(s.clouds[1].points)\n', (4166, 4186), True, 'import numpy as np\n'), ((4281, 4311), 'numpy.asarray', 'np.asarray', (['s.clouds[2].points'], {}), '(s.clouds[2].points)\n', (4291, 4311), True, 'import numpy as np\n'), ((3761, 3792), 'numpy.asarray', 'np.asarray', (['s.clouds[0].normals'], {}), '(s.clouds[0].normals)\n', (3771, 3792), True, 'import numpy as np\n'), ((2692, 2717), 'os.path.join', 'os.path.join', (['dir_cat', 'fn'], {}), '(dir_cat, fn)\n', (2704, 2717), False, 'import os\n'), ((2763, 2808), 'os.path.join', 'os.path.join', (['dir_cat', 'fn', "(fn + '.points.ply')"], {}), "(dir_cat, fn, fn + '.points.ply')\n", (2775, 2808), False, 'import os\n')] |
import sys,os,urllib,subprocess
import numpy as np
import requests
from tqdm import tqdm
from shapely.geometry import Point,LineString,Polygon,MultiPoint,MultiLineString,MultiPolygon,GeometryCollection
from shapely.ops import transform,cascaded_union,unary_union
from functools import partial
import pyproj
from pyproj import Proj
import mshapely
from mshapely import DF
from mshapely.misc import add_method
from .file import File
class OSM(object):
"""
OSM object prepares the osm coastline using spatial manipulation for gmsh, such as
downloading,extracting,simplifying and resampling for gmsh.
It also creates the mesh using gmsh.
Parameters
----------
obj:obj
name:str,
format:str,
localFolder:path
minDensity:float
maxDensity:float
shorelineGrowth:float
limitFineDensity:float
simplification:object
a:
defaultDomain:object
a:
b:
input:object
a:
b:
output:object
a:
pproj:str
pgeo:str
Note
----
Any spatial manipulation is performed on the projected coordinate system.
Results are converted back to geographic coordinates.
Attributes
----------
osm:zip, OSM fine resolution coastline
sosm:zip, Simplified OSM resolution coastline
domain: Polygon
Model domain
density:MultiPoint
MultiPoint of the density
"""
def __init__(self,obj):
self.name = obj.get( 'name', "default")
self.format = obj.get( 'format', "slf")
self.localFolder = obj.get( 'localFolder', "")
self.minDensity = obj.get( 'minDensity', 10)
self.limitFineDensity= obj.get( 'limitFineDensity', 1000)
self.limitCoarseDensity= obj.get( 'limitCoarseDensity', 2000)
self.maxDensity = obj.get( 'maxDensity', 10000)
self.shorelineGrowth = obj.get( 'shorelineGrowth', 1.2)
self.simplification = obj.get( 'simplification', {})
self.defaultDomain = obj.get( 'defaultDomain', {})
self.input=input= obj.get( 'input', {})
self.output = obj.get( 'output', {})
self.pproj = pproj = obj.get( 'proj', "EPSG:3573")
self.pgeo = pgeo = obj.get( 'proj', "EPSG:4326")
self.printCommands = obj.get( 'printCommands', False)
self.version=None
# "+proj=laea +lat_0=90 +lon_0=-100 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m"
self.togeo = partial(pyproj.transform,Proj(init=pproj),Proj(init=pgeo))
self.toproj = partial(pyproj.transform,Proj(init=pgeo),Proj(init=pproj))
#
# Check input or get/create input if required
#
self._checkInput(input,'domain')
self._checkInput(input,'density')
self._checkInput(input,'osm')
self._checkInput(input,'sosm')
if not 'domain' in input:input['domain']=self._getDefaultDomain()
if not 'density' in input:input['density']=self._getDefaultDensity()
if not 'osm' in input:input['osm']=OSM.downloadOSM(self.localFolder,"osm")
if not 'sosm' in input:input['sosm']=OSM.downloadOSM(self.localFolder,"sosm")
#
# Input and temporay output are saved into a "File"
#
# Input
self.osm=File('osm',parent=self,geoPath=input['osm'])
self.sosm=File('sosm',parent=self,geoPath=input['sosm'])
self.domain=File('domain',parent=self,geoPath=input['domain'])
self.density=File('density',parent=self,geoPath=input['density'])
# Temporary output
self.densityFineZone=File('densityFineZone',parent=self,fproj=self._getdensityFineZone)
self.densityCoarseZone=File('densityCoarseZone',parent=self,fproj=self._getdensityCoarseZone)
self.osmFine=File('osmFine',parent=self,fproj=self._getOSMFine)
self.osmCoarse=File('osmCoarse',parent=self,fproj=self._getOSMCoarse)
self.osmCoarseZone=File('osmCoarseZone',parent=self,fproj=self._getOSMCoarseZone)
self.osmCoarseS=File('osmCoarseS',versioned=True,parent=self,fproj=self._getOSMCoarseS)
self.osmDomain=File('osmDomain',versioned=True,parent=self,fproj=self._getosmDomain)
self.osmSimplify=File('osmSimplify',versioned=True,parent=self,fproj=self._getosmSimplify)
self.osmResample=File('osmResample',versioned=True,parent=self,fproj=self._getosmResample)
self.osmMesh=File('osmMesh',parent=self,versioned=True,ext=".msh",fproj=self._getosmMesh)
self.osmMeshBoundaries=File('osmMeshBoundaries',versioned=True,parent=self,fgeo=self._getosmMeshBoundaries)
self.osmMeshEdges=File('osmMeshEdges',versioned=True,parent=self,fgeo=self._getosmMeshEdges)
self.meshmbtiles=File('mesh',parent=self,versioned=True,ext=".mbtiles",fgeo=self._getmbtiles)
#
# Get list of File(s) within the OSM class
#
self.listFiles=[p for p in dir(self) if isinstance(getattr(self,p),File)]
#
# Documentation
#
self.densityFineZone.__doc__=self._getdensityFineZone.__doc__
self.densityCoarseZone.__doc__=self._getdensityCoarseZone.__doc__
self.osmFine.__doc__=self._getOSMFine.__doc__
self.osmCoarse.__doc__=self._getOSMCoarse.__doc__
self.osmCoarseZone.__doc__=self._getOSMCoarseZone.__doc__
self.osmCoarseS.__doc__=self._getOSMCoarseS.__doc__
self.osmDomain.__doc__=self._getosmDomain.__doc__
self.osmSimplify.__doc__=self._getosmSimplify.__doc__
self.osmResample.__doc__=self._getosmResample.__doc__
self.osmMesh.__doc__=self._getosmMesh.__doc__
self.osmMeshBoundaries.__doc__=self._getosmMeshBoundaries.__doc__
self.osmMeshEdges.__doc__=self._getosmMeshEdges.__doc__
self.meshmbtiles.__doc__=self._getmbtiles.__doc__
def compute(self):
# print(os.path.exists(self.osmMesh.geoPath))
for name in self.listFiles:
file=getattr(self,name)
if file.versioned==True:
file._geo=None
file._proj=None
for name in self.listFiles:
file=getattr(self,name)
file.geo()
def setSimplificaton(self,obj,version=None):
self.simplification=obj
self.version=version
self.compute()
# for name in self.listFiles:
# file=getattr(self,name)
# if file.dependencies is not None and "simplification" in file.dependencies:
# file.delete()
def _checkInput(self,input,name):
""" Check if input exist
"""
def pathExist(path):
localFolder = self.localFolder
return (os.path.exists(path) or os.path.exists(os.path.join(localFolder,path)))
if name in input and not pathExist(input[name]):raise Exception("{} does not exist".format(input[name]))
def _getDefaultDomain(self):
""" Create default domain geojson
"""
obj = self.defaultDomain
toproj =self.toproj
togeo =self.togeo
output = os.path.join(self.localFolder,"domain.geojson")
if os.path.exists(output):return output
center = obj.get( 'center', [-63.553987,44.627934])
radius = obj.get( 'radius', 10)
geo=Point(center).proj(toproj).buffer(radius*1000)
geo.proj(togeo).write(output)
return output
def _getDefaultDensity(self):
""" Create default density geojson
"""
obj = self.defaultDomain
minDensity = self.minDensity
maxDensity = self.maxDensity
shorelineGrowth = self.shorelineGrowth
output=os.path.join(self.localFolder,"density.geojson")
if os.path.exists(output):return output
density = np.array(obj.get( 'density', [[-63.553987,44.627934,1.0,1.2]]))
df=DF(density,minDensity=np.min(density[:,2]),maxDensity=maxDensity,minGrowth=np.min(density[:,3]))
df.write(output)
return output
def _getdensityFineZone(self,projectedPath=None,dependencies = ['density','minDensity','limitFineDensity']):
"""
Create density zones/area based on density object.
This zone is used to extract fined osm coastline.
"""
return self.__getdensityZone(projectedPath,self.limitFineDensity)
def _getdensityCoarseZone(self,projectedPath=None,dependencies = ['density','minDensity','limitCoarseDensity']):
"""
Create density zones/area based on density object.
This zone is used to extract fined osm coastline.
"""
return self.__getdensityZone(projectedPath,self.limitCoarseDensity)
def __getdensityZone(self,projectedPath,_maxDensity):
"""
Create density zones/area based on density object.
This zone is used to extract fined osm coastline.
"""
minDensity=self.minDensity
density=DF.read(self.density.projPath)
buffers=[]
for d in density.dp:
maxDistance = DF.getl_D(d[2],d[3],_maxDensity)
buffers.append(Point(d[:2]).buffer(maxDistance))
buffers=cascaded_union(buffers)
buffers.write(projectedPath)
return buffers
def _name(self,path):
""" Extract basename without extention
"""
return os.path.splitext(os.path.basename(path))[0]
def _getOSMFine(self,projectedPath=None,dependencies = ['densityFineZone']):
""" Extract fine osm coastline within the densityZone.
"""
densityFineZone=self.densityFineZone
epsg=self.pproj.split(":")[1]
osmPath = self.input['osm']
zipname = 'water-polygons-split-4326/water_polygons.shp'
zipPath = "\"/vsizip/" + osmPath + "/" + zipname + "\""
zoneName = os.path.splitext(os.path.basename(densityFineZone.projPath))[0]
zone = densityFineZone.projPath
# pg_sql = "\"With osm AS(SELECT ST_Transform(water_polygons.geometry,{2}) as geo FROM water_polygons,'{0}'.'{1}' zone WHERE ST_Intersects(ST_Transform(water_polygons.geometry,{2}), ST_Envelope(zone.geometry))),osm2 AS(SELECT ST_Simplify(ST_Buffer(ST_Simplify(osm.geo,10),0),10) as geo FROM osm) SELECT osm2.geo FROM osm2,'{0}'.'{1}' zone WHERE osm2.geo is NOT NULL;\"".format(zone,zoneName,epsg)
pg_sql = "\"With osm AS(SELECT ST_Transform(water_polygons.geometry,{2}) as geo FROM water_polygons),osm2 AS(SELECT ST_Simplify(ST_Buffer(ST_Simplify(osm.geo,10),0),10) as geo FROM osm,'{0}'.'{1}' zone WHERE ST_Intersects(osm.geo, zone.geometry)) SELECT ST_Intersection(osm2.geo,zone.geometry) FROM osm2,'{0}'.'{1}' zone WHERE osm2.geo is NOT NULL;\"".format(zone,zoneName,epsg)
command = "ogr2ogr -skipfailures -f \"GeoJSON\" {0} -nln \"{3}\" -nlt POLYGON -dialect \"SQLITE\" -sql {2} {1}".format(projectedPath,zipPath,pg_sql,self._name(projectedPath))
if self.printCommands: print(command)
t=tqdm(total=1)
subprocess.call(command, shell=True)
t.update(1);t.close()
def _getOSMCoarse(self,projectedPath=None,dependencies = ['domain']):
"""
Extract osm coastline from zip file.
This avoids unpacking the zip file.
"""
domain=self.domain
osmPath=self.sosm.geoPath
epsgp=self.pproj.split(":")[1]
epsgg=self.pgeo.split(":")[1]
domain=domain.geoPath
zipname = 'simplified-water-polygons-split-3857/simplified_water_polygons.shp'
zipPath = "\"/vsizip/" + osmPath + "/" + zipname + "\""
name = os.path.basename(domain)
name = os.path.splitext(name)[0]
pg_sql = "\"With one AS(SELECT ST_Buffer(ST_Transform(A.geometry,{2}),0) as geometry FROM simplified_water_polygons A,'{0}'.'{1}' B WHERE ST_Intersects(ST_Transform(A.geometry,{2}), ST_Transform(SetSRID(B.geometry,{3}),{2}))) SELECT ST_Union(one.geometry) from one WHERE one.geometry is not null;\"".format(domain,name,epsgp,epsgg)
command = "ogr2ogr -skipfailures -f \"GeoJSON\" {0} -nln \"{3}\" -dialect \"SQLITE\" -sql {1} {2}".format(projectedPath,pg_sql,zipPath,self._name(projectedPath))
if self.printCommands: print(command)
t=tqdm(total=1)
subprocess.call(command, shell=True)
t.update(1);t.close()
def _getOSMCoarseZone(self,projectedPath=None,dependencies = ['osmCoarse','densityCoarseZone']):
"""
Extract osm coastline from zip file and simplify based on extent.
This avoids unpacking the zip file.
"""
osmCoarse=self.osmCoarse
densityCoarseZone=self.densityCoarseZone
pg_sql = "\"SELECT ST_Intersection(A.geometry,B.geometry) as geometry FROM '{0}'.'{1}' A,'{2}'.'{3}' B;\"".format(osmCoarse.projPath,self._name(osmCoarse.projPath),densityCoarseZone.projPath,self._name(densityCoarseZone.projPath))
command = "ogr2ogr -skipfailures -f \"GeoJSON\" {0} -nln \"{3}\" -dialect \"SQLITE\" -sql {1} {2}".format(projectedPath,pg_sql,osmCoarse.projPath,self._name(projectedPath))
if self.printCommands: print(command)
t=tqdm(total=1)
subprocess.call(command, shell=True)
t.update(1);t.close()
def _getOSMCoarseS(self,projectedPath=None,dependencies=['osmCoarse','simplification']):
"""
Extract osm coastline from zip file and simplify based on extent.
This avoids unpacking the zip file.
Warning: needs RAM
"""
osmCoarse=self.osmCoarse
simplification = self.simplification
osmPath=osmCoarse.projPath
isimplify=simplification['isimplify']
buffering=simplification['buffer']
fsimplify=simplification['fsimplify']
# ogrinfo
# Needs at least 2.6GB without simplify
# buffer1000,s50=15minutes
# Simplify 500,buffer1000,s50=10minutes
# Simplify 1000,buffer10000,s50=30sec
# Simplify 500,buffer5000,s50=4msec
pg_sql = "\"With one AS(SELECT ST_Simplify(ST_Buffer(ST_Buffer(ST_Simplify(A.geometry,{2}),-{3}),{3}),{4}) as geometry FROM '{0}'.'{1}' A) SELECT one.geometry from one WHERE one.geometry is not null;\"".format(osmPath,self._name(osmPath),isimplify,buffering,fsimplify)
command = "ogr2ogr -skipfailures -f \"GeoJSON\" {0} -nln \"{3}\" -dialect \"SQLITE\" -sql {1} {2}".format(projectedPath,pg_sql,osmPath,self._name(projectedPath))
if self.printCommands: print(command)
t=tqdm(total=1)
subprocess.call(command, shell=True)
t.update(1);t.close()
def _getosmDomain(self,projectedPath=None,dependencies = ['domain','osmCoarseS']):
"""
Extract osm coastline using the domain.
It will only keep the largest Polygon.
"""
domain = self.domain
osmCoarseS = self.osmCoarseS
geo = osmCoarseS.proj().geometry
domain=domain.proj().geometry
t=tqdm(total=1)
geo=geo.largest().removeHoles(np.pi*np.power(5000,2))
geo=geo.intersection(domain)
geo.write(projectedPath).plot().savePlot(os.path.splitext(projectedPath)[0]+".png")
t.update(1);t.close()
return geo
def _getosmSimplify(self,projectedPath=None,dependencies = ['density','osmDomain','osmFine']):
"""
Simplify osm shoreline based on density field
"""
df = DF.read(self.density.projPath)
osmDomain = self.osmDomain
osmFine = self.osmFine
osmCoarseZone = self.osmCoarseZone
geo=osmDomain.proj().geometry
geo=geo.dsimplify(df,limitFineDensity=self.limitFineDensity,limitCoarseDensity=self.limitCoarseDensity,fine=osmFine.proj().geometry,coarse=osmCoarseZone.proj().geometry,progress=True)
geo=geo.largest()
geo.write(projectedPath).plot().savePlot(os.path.splitext(projectedPath)[0]+".png")
return geo
def _getosmResample(self,projectedPath=None,dependencies = ['density','osmSimplify','minDensity','maxDensity','shorelineGrowth']):
"""
Resample osm shoreline using interior nearest points and density growth field.
"""
# df = DF.read(self.density.projPath)
osmSimplify = self.osmSimplify
minDensity = self.minDensity
maxDensity = self.maxDensity
shorelineGrowth = self.shorelineGrowth
geo=osmSimplify.proj().geometry
df=DF(minDensity=minDensity,maxDensity=maxDensity,minGrowth=shorelineGrowth,maxDensitySimplify=10000,progress=True)
df=df.inearest(geo,progress=True,minDistance=100)
geo=geo.dresample(df,progress=True)
geo.write(projectedPath).plot().savePlot(os.path.splitext(projectedPath)[0]+".png")
return geo
def _getosmMesh(self,projectedPath=None,dependencies = ['density','osmResample','minDensity','maxDensity','shorelineGrowth']):
"""
Resample osm shoreline using interior nearest points and density growth field.
"""
# df = DF.read(self.density.projPath)
osmResample = self.osmResample
minDensity = self.minDensity
maxDensity = self.maxDensity
shorelineGrowth = self.shorelineGrowth
geo=osmResample.proj().geometry
df=DF(minDensity=minDensity,maxDensity=maxDensity,minGrowth=shorelineGrowth,maxDensitySimplify=10000,progress=True)
df=df.inearest(geo,progress=True,minDistance=10,minLength=True)
geo.msh(projectedPath,df).plot().savePlot(os.path.splitext(projectedPath)[0]+".png")
def _getosmMeshBoundaries(self,geographicPath=None,dependencies=['osmMesh']):
"""
"""
mesh=self.osmMesh.geo()
mesh.boundaries.write(geographicPath)
def _getosmMeshEdges(self,geographicPath=None,dependencies=['osmMesh']):
"""
"""
mesh=self.osmMesh.geo()
mesh.geoedges.write(geographicPath)
def _getmbtiles(self,geographicPath,dependencies=['osmMeshBoundaries','osmMeshEdges']):
edgembitle=os.path.join(os.path.dirname(geographicPath),"edges.mbtiles")
boundarymbtile=os.path.join(os.path.dirname(geographicPath),"boundaries.mbtiles")
if os.path.exists(edgembitle):os.remove(edgembitle)
if os.path.exists(boundarymbtile):os.remove(boundarymbtile)
command = "tippecanoe -z11 -o {0} -an -l edges {1};tippecanoe -z11 -o {2} -an -l boundaries {3};tile-join {0} {2} -o {4}".format(edgembitle,self.osmMeshEdges.geoPath,boundarymbtile,self.osmMeshBoundaries.geoPath,geographicPath)
if self.printCommands: print(command)
subprocess.call(command, shell=True)
@staticmethod
def transform_geo(project,geo):
"""
project:proj4
geo:Shapely object
"""
return transform(project,geo)
@staticmethod
def ogr2ogrT(inputPath,output,s_srs,t_srs,zipLayer=""):
"""
zipLayer:To determine the layer within a zipfile:
>>> vim {path}.zip
"""
if os.path.splitext(inputPath)[1]==".zip":
basename = os.path.splitext(os.path.basename(inputPath))[0]
zipname = '{}/{}.shp'.format(basename,zipLayer)
inputPath = "\"/vsizip/" + inputPath + "/" + zipname + "\""
command = "ogr2ogr -skipfailures -f \"GeoJSON\" {0} -s_srs \"{1}\" -t_srs \"{2}\" {3}".format(output,s_srs,t_srs,inputPath)
# print(command)
subprocess.call(command, shell=True)
@staticmethod
def downloadOSM(folder,option,overwrite=False):
"""
Download OSM coastline file (600MB).
This geometry is splitted into partions (simarlar to a kdtree).
option=[osm,sosm,...]
"""
if option=="osm":
http = 'https://osmdata.openstreetmap.de/download/water-polygons-split-4326.zip'
elif option=="sosm":
http="https://osmdata.openstreetmap.de/download/simplified-water-polygons-split-3857.zip"
else:
raise Exception("Not a choice")
name = os.path.basename(http)
osmPath =os.path.join(folder,name)
if not os.path.exists(osmPath) or overwrite:
response = requests.get(http, stream=True)
total_length = int(response.headers.get('content-length', 0))
t=tqdm(total=total_length, unit='iB', unit_scale=True)
with open(osmPath, "wb") as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
t.update(len(chunk))
f.write(chunk)
t.close()
return osmPath | [
"mshapely.DF",
"os.path.exists",
"shapely.ops.transform",
"numpy.power",
"tqdm.tqdm",
"os.path.join",
"os.path.splitext",
"requests.get",
"numpy.min",
"shapely.geometry.Point",
"os.path.dirname",
"mshapely.DF.read",
"subprocess.call",
"os.path.basename",
"pyproj.Proj",
"mshapely.DF.get... | [((6611, 6659), 'os.path.join', 'os.path.join', (['self.localFolder', '"""domain.geojson"""'], {}), "(self.localFolder, 'domain.geojson')\n", (6623, 6659), False, 'import sys, os, urllib, subprocess\n'), ((6666, 6688), 'os.path.exists', 'os.path.exists', (['output'], {}), '(output)\n', (6680, 6688), False, 'import sys, os, urllib, subprocess\n'), ((7156, 7205), 'os.path.join', 'os.path.join', (['self.localFolder', '"""density.geojson"""'], {}), "(self.localFolder, 'density.geojson')\n", (7168, 7205), False, 'import sys, os, urllib, subprocess\n'), ((7212, 7234), 'os.path.exists', 'os.path.exists', (['output'], {}), '(output)\n', (7226, 7234), False, 'import sys, os, urllib, subprocess\n'), ((8338, 8368), 'mshapely.DF.read', 'DF.read', (['self.density.projPath'], {}), '(self.density.projPath)\n', (8345, 8368), False, 'from mshapely import DF\n'), ((8535, 8558), 'shapely.ops.cascaded_union', 'cascaded_union', (['buffers'], {}), '(buffers)\n', (8549, 8558), False, 'from shapely.ops import transform, cascaded_union, unary_union\n'), ((10253, 10266), 'tqdm.tqdm', 'tqdm', ([], {'total': '(1)'}), '(total=1)\n', (10257, 10266), False, 'from tqdm import tqdm\n'), ((10271, 10307), 'subprocess.call', 'subprocess.call', (['command'], {'shell': '(True)'}), '(command, shell=True)\n', (10286, 10307), False, 'import sys, os, urllib, subprocess\n'), ((10811, 10835), 'os.path.basename', 'os.path.basename', (['domain'], {}), '(domain)\n', (10827, 10835), False, 'import sys, os, urllib, subprocess\n'), ((11444, 11457), 'tqdm.tqdm', 'tqdm', ([], {'total': '(1)'}), '(total=1)\n', (11448, 11457), False, 'from tqdm import tqdm\n'), ((11462, 11498), 'subprocess.call', 'subprocess.call', (['command'], {'shell': '(True)'}), '(command, shell=True)\n', (11477, 11498), False, 'import sys, os, urllib, subprocess\n'), ((12290, 12303), 'tqdm.tqdm', 'tqdm', ([], {'total': '(1)'}), '(total=1)\n', (12294, 12303), False, 'from tqdm import tqdm\n'), ((12308, 12344), 'subprocess.call', 'subprocess.call', (['command'], {'shell': '(True)'}), '(command, shell=True)\n', (12323, 12344), False, 'import sys, os, urllib, subprocess\n'), ((13593, 13606), 'tqdm.tqdm', 'tqdm', ([], {'total': '(1)'}), '(total=1)\n', (13597, 13606), False, 'from tqdm import tqdm\n'), ((13611, 13647), 'subprocess.call', 'subprocess.call', (['command'], {'shell': '(True)'}), '(command, shell=True)\n', (13626, 13647), False, 'import sys, os, urllib, subprocess\n'), ((14022, 14035), 'tqdm.tqdm', 'tqdm', ([], {'total': '(1)'}), '(total=1)\n', (14026, 14035), False, 'from tqdm import tqdm\n'), ((14440, 14470), 'mshapely.DF.read', 'DF.read', (['self.density.projPath'], {}), '(self.density.projPath)\n', (14447, 14470), False, 'from mshapely import DF\n'), ((15401, 15521), 'mshapely.DF', 'DF', ([], {'minDensity': 'minDensity', 'maxDensity': 'maxDensity', 'minGrowth': 'shorelineGrowth', 'maxDensitySimplify': '(10000)', 'progress': '(True)'}), '(minDensity=minDensity, maxDensity=maxDensity, minGrowth=shorelineGrowth,\n maxDensitySimplify=10000, progress=True)\n', (15403, 15521), False, 'from mshapely import DF\n'), ((16186, 16306), 'mshapely.DF', 'DF', ([], {'minDensity': 'minDensity', 'maxDensity': 'maxDensity', 'minGrowth': 'shorelineGrowth', 'maxDensitySimplify': '(10000)', 'progress': '(True)'}), '(minDensity=minDensity, maxDensity=maxDensity, minGrowth=shorelineGrowth,\n maxDensitySimplify=10000, progress=True)\n', (16188, 16306), False, 'from mshapely import DF\n'), ((17060, 17086), 'os.path.exists', 'os.path.exists', (['edgembitle'], {}), '(edgembitle)\n', (17074, 17086), False, 'import sys, os, urllib, subprocess\n'), ((17116, 17146), 'os.path.exists', 'os.path.exists', (['boundarymbtile'], {}), '(boundarymbtile)\n', (17130, 17146), False, 'import sys, os, urllib, subprocess\n'), ((17452, 17488), 'subprocess.call', 'subprocess.call', (['command'], {'shell': '(True)'}), '(command, shell=True)\n', (17467, 17488), False, 'import sys, os, urllib, subprocess\n'), ((17613, 17636), 'shapely.ops.transform', 'transform', (['project', 'geo'], {}), '(project, geo)\n', (17622, 17636), False, 'from shapely.ops import transform, cascaded_union, unary_union\n'), ((18202, 18238), 'subprocess.call', 'subprocess.call', (['command'], {'shell': '(True)'}), '(command, shell=True)\n', (18217, 18238), False, 'import sys, os, urllib, subprocess\n'), ((18761, 18783), 'os.path.basename', 'os.path.basename', (['http'], {}), '(http)\n', (18777, 18783), False, 'import sys, os, urllib, subprocess\n'), ((18797, 18823), 'os.path.join', 'os.path.join', (['folder', 'name'], {}), '(folder, name)\n', (18809, 18823), False, 'import sys, os, urllib, subprocess\n'), ((2337, 2353), 'pyproj.Proj', 'Proj', ([], {'init': 'pproj'}), '(init=pproj)\n', (2341, 2353), False, 'from pyproj import Proj\n'), ((2354, 2369), 'pyproj.Proj', 'Proj', ([], {'init': 'pgeo'}), '(init=pgeo)\n', (2358, 2369), False, 'from pyproj import Proj\n'), ((2414, 2429), 'pyproj.Proj', 'Proj', ([], {'init': 'pgeo'}), '(init=pgeo)\n', (2418, 2429), False, 'from pyproj import Proj\n'), ((2430, 2446), 'pyproj.Proj', 'Proj', ([], {'init': 'pproj'}), '(init=pproj)\n', (2434, 2446), False, 'from pyproj import Proj\n'), ((8434, 8468), 'mshapely.DF.getl_D', 'DF.getl_D', (['d[2]', 'd[3]', '_maxDensity'], {}), '(d[2], d[3], _maxDensity)\n', (8443, 8468), False, 'from mshapely import DF\n'), ((10847, 10869), 'os.path.splitext', 'os.path.splitext', (['name'], {}), '(name)\n', (10863, 10869), False, 'import sys, os, urllib, subprocess\n'), ((16918, 16949), 'os.path.dirname', 'os.path.dirname', (['geographicPath'], {}), '(geographicPath)\n', (16933, 16949), False, 'import sys, os, urllib, subprocess\n'), ((16999, 17030), 'os.path.dirname', 'os.path.dirname', (['geographicPath'], {}), '(geographicPath)\n', (17014, 17030), False, 'import sys, os, urllib, subprocess\n'), ((17087, 17108), 'os.remove', 'os.remove', (['edgembitle'], {}), '(edgembitle)\n', (17096, 17108), False, 'import sys, os, urllib, subprocess\n'), ((17147, 17172), 'os.remove', 'os.remove', (['boundarymbtile'], {}), '(boundarymbtile)\n', (17156, 17172), False, 'import sys, os, urllib, subprocess\n'), ((18894, 18925), 'requests.get', 'requests.get', (['http'], {'stream': '(True)'}), '(http, stream=True)\n', (18906, 18925), False, 'import requests\n'), ((19002, 19054), 'tqdm.tqdm', 'tqdm', ([], {'total': 'total_length', 'unit': '"""iB"""', 'unit_scale': '(True)'}), "(total=total_length, unit='iB', unit_scale=True)\n", (19006, 19054), False, 'from tqdm import tqdm\n'), ((6251, 6271), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (6265, 6271), False, 'import sys, os, urllib, subprocess\n'), ((7361, 7382), 'numpy.min', 'np.min', (['density[:, 2]'], {}), '(density[:, 2])\n', (7367, 7382), True, 'import numpy as np\n'), ((7414, 7435), 'numpy.min', 'np.min', (['density[:, 3]'], {}), '(density[:, 3])\n', (7420, 7435), True, 'import numpy as np\n'), ((8715, 8737), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (8731, 8737), False, 'import sys, os, urllib, subprocess\n'), ((9159, 9201), 'os.path.basename', 'os.path.basename', (['densityFineZone.projPath'], {}), '(densityFineZone.projPath)\n', (9175, 9201), False, 'import sys, os, urllib, subprocess\n'), ((14076, 14093), 'numpy.power', 'np.power', (['(5000)', '(2)'], {}), '(5000, 2)\n', (14084, 14093), True, 'import numpy as np\n'), ((17818, 17845), 'os.path.splitext', 'os.path.splitext', (['inputPath'], {}), '(inputPath)\n', (17834, 17845), False, 'import sys, os, urllib, subprocess\n'), ((18839, 18862), 'os.path.exists', 'os.path.exists', (['osmPath'], {}), '(osmPath)\n', (18853, 18862), False, 'import sys, os, urllib, subprocess\n'), ((6290, 6321), 'os.path.join', 'os.path.join', (['localFolder', 'path'], {}), '(localFolder, path)\n', (6302, 6321), False, 'import sys, os, urllib, subprocess\n'), ((14172, 14203), 'os.path.splitext', 'os.path.splitext', (['projectedPath'], {}), '(projectedPath)\n', (14188, 14203), False, 'import sys, os, urllib, subprocess\n'), ((14867, 14898), 'os.path.splitext', 'os.path.splitext', (['projectedPath'], {}), '(projectedPath)\n', (14883, 14898), False, 'import sys, os, urllib, subprocess\n'), ((15663, 15694), 'os.path.splitext', 'os.path.splitext', (['projectedPath'], {}), '(projectedPath)\n', (15679, 15694), False, 'import sys, os, urllib, subprocess\n'), ((16418, 16449), 'os.path.splitext', 'os.path.splitext', (['projectedPath'], {}), '(projectedPath)\n', (16434, 16449), False, 'import sys, os, urllib, subprocess\n'), ((17892, 17919), 'os.path.basename', 'os.path.basename', (['inputPath'], {}), '(inputPath)\n', (17908, 17919), False, 'import sys, os, urllib, subprocess\n'), ((6813, 6826), 'shapely.geometry.Point', 'Point', (['center'], {}), '(center)\n', (6818, 6826), False, 'from shapely.geometry import Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, GeometryCollection\n'), ((8488, 8500), 'shapely.geometry.Point', 'Point', (['d[:2]'], {}), '(d[:2])\n', (8493, 8500), False, 'from shapely.geometry import Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, GeometryCollection\n')] |
#!/usr/bin/env python
#==========================================================================
import numpy as np
from gryffin import Gryffin
# choose the synthetic function from
# ... Dejong:
# ...
from benchmark_functions import Dejong as Benchmark
from category_writer import CategoryWriter
#==========================================================================
# `global` variables
BUDGET = 24
CONFIG_FILE = 'config.json'
NUM_DIMS = 2
NUM_OPTS = 21
#==========================================================================
# write categories
category_writer = CategoryWriter(num_opts = NUM_OPTS, num_dims = NUM_DIMS)
category_writer.write_categories(home_dir = './', num_descs = 2, with_descriptors = False)
# create benchmark function
benchmark = Benchmark(num_dims = NUM_DIMS, num_opts = NUM_OPTS)
# initialize gryffin
gryffin = Gryffin(CONFIG_FILE)
#==========================================================================
# plotting instructions (optional)
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('paper', font_scale = 1.5)
colors = sns.color_palette('RdYlBu', 8)
colors = [colors[-1], colors[0]]
fig = plt.figure(figsize = (6, 6))
ax0 = plt.subplot2grid((2, 2), (0, 0))
ax1 = plt.subplot2grid((2, 2), (1, 0))
ax2 = plt.subplot2grid((2, 2), (1, 1))
axs = [ax0, ax1, ax2]
plt.ion()
#==========================================================================
observations = []
for _ in range(BUDGET):
# get a new sample
samples = gryffin.recommend(observations = observations)
# get measurements for samples
new_observations = []
for sample in samples:
param = np.array([sample['param_0'][0], sample['param_1'][0]])
measurement = benchmark(param)
sample['obj'] = measurement
new_observations.append(sample)
# optional instructions just for plotting
for ax in axs:
ax.cla()
# plotting ground truth
x_domain = np.linspace(0., 1., NUM_OPTS)
y_domain = np.linspace(0., 1., NUM_OPTS)
X, Y = np.meshgrid(x_domain, y_domain)
Z = np.zeros((len(x_domain), len(y_domain)))
for x_index, x_element in enumerate(x_domain):
for y_index, y_element in enumerate(y_domain):
loss_value = benchmark(['x_{}'.format(x_index), 'x_{}'.format(y_index)])
Z[y_index, x_index] = loss_value
levels = np.linspace(np.amin(Z), np.amax(Z), 256)
ax0.imshow(Z, plt.cm.bone_r, origin = 'lower', aspect = 'auto')
# plotting surrogates
kernel = gryffin.bayesian_network.kernel_contribution
sampling_parameters = gryffin.bayesian_network.sampling_param_values
x_domain = np.linspace(0., NUM_OPTS - 1, NUM_OPTS)
y_domain = np.linspace(0., NUM_OPTS - 1, NUM_OPTS)
Z = np.zeros((len(x_domain), len(y_domain)))
for x_index, x_element in enumerate(x_domain):
for y_index, y_element in enumerate(y_domain):
param = np.array([x_element, y_element]) #, dtype = np.float32)
num, den = kernel(param)
loss_value = (num + sampling_parameters[0]) * den
Z[y_index, x_index] = loss_value
levels = np.linspace(np.amin(Z), np.amax(Z), 256)
# ax1.contourf(X, Y, Z, cmap = plt.cm.bone_r, levels = levels)
ax1.imshow(Z, plt.cm.bone_r, origin = 'lower', aspect = 'auto')
# plotting surrogates
Z = np.zeros((len(x_domain), len(y_domain)))
for x_index, x_element in enumerate(x_domain):
for y_index, y_element in enumerate(y_domain):
param = np.array([x_element, y_element]) #, dtype = np.float32)
num, den = kernel(param)
loss_value = (num + sampling_parameters[1]) * den
Z[y_index, x_index] = loss_value
levels = np.linspace(np.amin(Z), np.amax(Z), 256)
ax2.imshow(Z, plt.cm.bone_r, origin = 'lower', aspect = 'auto')
for obs_index, obs in enumerate(observations):
ax0.plot(int(obs['param_0'][0][2:]), int(obs['param_1'][0][2:]), marker = 'o', color = colors[obs_index % len(colors)], markersize = 5)
ax1.plot(int(obs['param_0'][0][2:]), int(obs['param_1'][0][2:]), marker = 'o', color = colors[obs_index % len(colors)], markersize = 5)
ax2.plot(int(obs['param_0'][0][2:]), int(obs['param_1'][0][2:]), marker = 'o', color = colors[obs_index % len(colors)], markersize = 5)
for obs_index, obs in enumerate(new_observations):
ax0.plot(int(obs['param_0'][0][2:]), int(obs['param_1'][0][2:]), marker = 'D', color = colors[obs_index % len(colors)], markersize = 8)
ax1.plot(int(obs['param_0'][0][2:]), int(obs['param_1'][0][2:]), marker = 'D', color = colors[obs_index % len(colors)], markersize = 8)
ax2.plot(int(obs['param_0'][0][2:]), int(obs['param_1'][0][2:]), marker = 'D', color = colors[obs_index % len(colors)], markersize = 8)
plt.pause(0.05)
# add measurements to cache
observations.extend(new_observations)
| [
"numpy.amax",
"numpy.amin",
"seaborn.color_palette",
"benchmark_functions.Dejong",
"seaborn.set_context",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.linspace",
"gryffin.Gryffin",
"matplotlib.pyplot.ion",
"numpy.meshgrid",
"matplotlib.pyplot.pause",
"category_writer.CategoryWriter",
... | [((598, 650), 'category_writer.CategoryWriter', 'CategoryWriter', ([], {'num_opts': 'NUM_OPTS', 'num_dims': 'NUM_DIMS'}), '(num_opts=NUM_OPTS, num_dims=NUM_DIMS)\n', (612, 650), False, 'from category_writer import CategoryWriter\n'), ((792, 839), 'benchmark_functions.Dejong', 'Benchmark', ([], {'num_dims': 'NUM_DIMS', 'num_opts': 'NUM_OPTS'}), '(num_dims=NUM_DIMS, num_opts=NUM_OPTS)\n', (801, 839), True, 'from benchmark_functions import Dejong as Benchmark\n'), ((876, 896), 'gryffin.Gryffin', 'Gryffin', (['CONFIG_FILE'], {}), '(CONFIG_FILE)\n', (883, 896), False, 'from gryffin import Gryffin\n'), ((1064, 1104), 'seaborn.set_context', 'sns.set_context', (['"""paper"""'], {'font_scale': '(1.5)'}), "('paper', font_scale=1.5)\n", (1079, 1104), True, 'import seaborn as sns\n'), ((1117, 1147), 'seaborn.color_palette', 'sns.color_palette', (['"""RdYlBu"""', '(8)'], {}), "('RdYlBu', 8)\n", (1134, 1147), True, 'import seaborn as sns\n'), ((1188, 1214), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 6)'}), '(figsize=(6, 6))\n', (1198, 1214), True, 'import matplotlib.pyplot as plt\n'), ((1223, 1255), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(2, 2)', '(0, 0)'], {}), '((2, 2), (0, 0))\n', (1239, 1255), True, 'import matplotlib.pyplot as plt\n'), ((1262, 1294), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(2, 2)', '(1, 0)'], {}), '((2, 2), (1, 0))\n', (1278, 1294), True, 'import matplotlib.pyplot as plt\n'), ((1301, 1333), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(2, 2)', '(1, 1)'], {}), '((2, 2), (1, 1))\n', (1317, 1333), True, 'import matplotlib.pyplot as plt\n'), ((1356, 1365), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (1363, 1365), True, 'import matplotlib.pyplot as plt\n'), ((1985, 2016), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', 'NUM_OPTS'], {}), '(0.0, 1.0, NUM_OPTS)\n', (1996, 2016), True, 'import numpy as np\n'), ((2030, 2061), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', 'NUM_OPTS'], {}), '(0.0, 1.0, NUM_OPTS)\n', (2041, 2061), True, 'import numpy as np\n'), ((2071, 2102), 'numpy.meshgrid', 'np.meshgrid', (['x_domain', 'y_domain'], {}), '(x_domain, y_domain)\n', (2082, 2102), True, 'import numpy as np\n'), ((2701, 2741), 'numpy.linspace', 'np.linspace', (['(0.0)', '(NUM_OPTS - 1)', 'NUM_OPTS'], {}), '(0.0, NUM_OPTS - 1, NUM_OPTS)\n', (2712, 2741), True, 'import numpy as np\n'), ((2756, 2796), 'numpy.linspace', 'np.linspace', (['(0.0)', '(NUM_OPTS - 1)', 'NUM_OPTS'], {}), '(0.0, NUM_OPTS - 1, NUM_OPTS)\n', (2767, 2796), True, 'import numpy as np\n'), ((4875, 4890), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.05)'], {}), '(0.05)\n', (4884, 4890), True, 'import matplotlib.pyplot as plt\n'), ((1686, 1740), 'numpy.array', 'np.array', (["[sample['param_0'][0], sample['param_1'][0]]"], {}), "([sample['param_0'][0], sample['param_1'][0]])\n", (1694, 1740), True, 'import numpy as np\n'), ((2417, 2427), 'numpy.amin', 'np.amin', (['Z'], {}), '(Z)\n', (2424, 2427), True, 'import numpy as np\n'), ((2429, 2439), 'numpy.amax', 'np.amax', (['Z'], {}), '(Z)\n', (2436, 2439), True, 'import numpy as np\n'), ((3202, 3212), 'numpy.amin', 'np.amin', (['Z'], {}), '(Z)\n', (3209, 3212), True, 'import numpy as np\n'), ((3214, 3224), 'numpy.amax', 'np.amax', (['Z'], {}), '(Z)\n', (3221, 3224), True, 'import numpy as np\n'), ((3801, 3811), 'numpy.amin', 'np.amin', (['Z'], {}), '(Z)\n', (3808, 3811), True, 'import numpy as np\n'), ((3813, 3823), 'numpy.amax', 'np.amax', (['Z'], {}), '(Z)\n', (3820, 3823), True, 'import numpy as np\n'), ((2974, 3006), 'numpy.array', 'np.array', (['[x_element, y_element]'], {}), '([x_element, y_element])\n', (2982, 3006), True, 'import numpy as np\n'), ((3573, 3605), 'numpy.array', 'np.array', (['[x_element, y_element]'], {}), '([x_element, y_element])\n', (3581, 3605), True, 'import numpy as np\n')] |
try:
from .model import NNModel
from PIL import Image
from scipy.misc import imsave, imresize
# Importing the required Keras modules containing models, layers, optimizers, losses, etc
from keras.models import Model
from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation
from keras.layers.normalization import BatchNormalization
from keras.layers.core import Reshape, Permute
from keras.preprocessing.image import img_to_array, load_img, array_to_img
from keras.optimizers import Adam, RMSprop
from keras.losses import categorical_crossentropy, sparse_categorical_crossentropy, binary_crossentropy
from keras.metrics import categorical_accuracy, sparse_categorical_accuracy, binary_accuracy
from os import listdir
from os.path import isfile, exists, join, realpath, splitext, basename
from os.path import split as pathsplit
from random import randint
import tensorflow as tf
import glob
import matplotlib.pyplot as plt
import numpy as np
from utils import transfromXY
except ImportError as err:
exit(err)
class AerialBuildingsModel(NNModel):
"""
Neural network model for buildings segmentation in aerial images.
Sources:
- buildings dataset -> https://project.inria.fr/aerialimagelabeling/
"""
def __init__(self):
"""
Initialization of the model.
"""
super().__init__("model", "aerial_buildings", model_name=self.__class__.__name__.lower())
# Number of classes to segment
# 0 -> not a building
# 1 -> a building
self.__nClasses = 1
# Input data shape
self.input_shape = (256, 256, 3)
# File extensions for data to predict
self.FILE_EXTENSIONS = [
"tif",
"tiff",
"png",
"jpg",
"jpeg"
]
def create_layers(self):
"""
Creates each layer of the model.
"""
base_dir = join(realpath(__file__).split("src")[0], "datas/aerial_buildings")
train_dir = join(base_dir, "training")
val_dir = join(base_dir, "validation")
assert exists(train_dir) is True
assert exists(val_dir) is True
def create_generator(folder, batch_size=2):
x_dir = join(folder, "x")
y_dir = join(folder, "y")
assert exists(x_dir) is True
assert exists(y_dir) is True
# FIX: glob.glob is waaaaay faster than [f for f in listdir() if isfile(f)]
x_files = glob.glob(join(x_dir, "*.tif")) + glob.glob(join(x_dir, "*.tiff"))
y_files = glob.glob(join(y_dir, "*.tif")) + glob.glob(join(y_dir, "*.tiff"))
assert len(x_files) == len(y_files)
# Number of files
nbr_files = len(x_files)
# Let's begin the training/validation with the first file
index = 0
while True:
x, y = list(), list()
for i in range(batch_size):
# Get a new index
index = (index + 1) % nbr_files
# MUST be true (files must have the same name)
assert pathsplit(x_files[index])[-1] == pathsplit(y_files[index])[-1]
x_img = img_to_array(load_img(x_files[index]))
y_img = img_to_array(load_img(y_files[index]))
# Resize each image
x_img, y_img = imresize(x_img, self.input_shape[:2]), imresize(y_img, self.input_shape[:2])
# Apply a transformation on these images
# x_img, y_img = transfromXY(x_img, y_img)
# Change y shape : (m, n, 3) -> (m, n, 2) (2 is the class number)
temp_y_img = np.zeros(self.input_shape[:2] + (1,))
temp_y_img[y_img[:, :, 0] == 0] = 0
temp_y_img[y_img[:, :, 0] == 255] = 1
y_img = temp_y_img
# Convert to float
x_img = x_img.astype('float32')
y_img = y_img.astype('float32')
# Divide by the maximum value of each pixel
x_img /= 255
# Append images to the lists
x.append(x_img)
y.append(y_img)
yield np.array(x), np.array(y)
# Create a generator for each step
train_generator = create_generator(train_dir, 6) # 12600 images
val_generator = create_generator(val_dir, 6) # 5400 images
# Datas
self.datas = {"train_generator": train_generator, "val_generator": val_generator}
# Inputs
inputs = Input(self.input_shape)
# ----- First Convolution - Max Pooling -----
# 3x3 Convolution
conv1 = Conv2D(16, (3, 3), padding='same', data_format='channels_last', name='conv1_1')(inputs)
print("conv1:", conv1.shape)
acti1 = Activation(tf.nn.relu, name='acti1_1')(conv1)
# Dropout of 0.2
drop1 = Dropout(0.2, name='drop1_1')(acti1)
# 3x3 Convolution
conv1 = Conv2D(16, (3, 3), padding='same', data_format='channels_last', name='conv1_2')(drop1)
print("conv1:", conv1.shape)
acti1 = Activation(tf.nn.relu, name='acti1_2')(conv1)
# 2x2 Max Pooling
pool1 = MaxPooling2D(pool_size=(2, 2), name='pool1_1')(acti1)
# ----- Second Convolution - Max Pooling -----
# 3x3 Convolution
conv2 = Conv2D(32, (3, 3), padding='same', data_format='channels_last', name='conv2_1')(pool1)
print("conv2:", conv2.shape)
acti2 = Activation(tf.nn.relu, name='acti2_1')(conv2)
# Dropout of 0.2
drop2 = Dropout(0.2, name='drop2_1')(acti2)
# 3x3 Convolution
conv2 = Conv2D(32, (3, 3), padding='same', data_format='channels_last', name='conv2_2')(drop2)
print("conv2:", conv2.shape)
acti2 = Activation(tf.nn.relu, name='acti2_2')(conv2)
# 2x2 Max Pooling
pool2 = MaxPooling2D(pool_size=(2, 2), name='pool2_1')(acti2)
# ----- Third Convolution - Max Pooling -----
# 3x3 Convolution
conv3 = Conv2D(64, (3, 3), padding='same', data_format='channels_last', name='conv3_1')(pool2)
print("conv3:", conv3.shape)
acti3 = Activation(tf.nn.relu, name='acti3_1')(conv3)
# Dropout of 0.2
drop3 = Dropout(0.2, name='drop3_2')(acti3)
# 3x3 Convolution
conv3 = Conv2D(64, (3, 3), padding='same', data_format='channels_last', name='conv3_2')(drop3)
print("conv3:", conv3.shape)
acti3 = Activation(tf.nn.relu, name='acti3_2')(conv3)
# 2x2 Max Pooling
pool3 = MaxPooling2D(pool_size=(2, 2), name='pool3_1')(acti3)
# ----- Fourth Convolution - Max Pooling -----
# 3x3 Convolution
conv4 = Conv2D(128, (3, 3), padding='same', data_format='channels_last', name='conv4_1')(pool3)
print("conv4:", conv4.shape)
acti4 = Activation(tf.nn.relu, name='acti4_1')(conv4)
# Dropout of 0.2
drop4 = Dropout(0.2, name='drop4_2')(acti4)
# 3x3 Convolution
conv4 = Conv2D(128, (3, 3), padding='same', data_format='channels_last', name='conv4_2')(drop4)
print("conv4:", conv4.shape)
acti4 = Activation(tf.nn.relu, name='acti4_2')(conv4)
# 2x2 Max Pooling
pool4 = MaxPooling2D(pool_size=(2, 2), name='pool4_1')(acti4)
# ----- Fifth Convolution -----
# 3x3 Convolution - No dilation
conv5_d1 = Conv2D(256, (3, 3), dilation_rate=1, padding='same', data_format='channels_last', name='conv5_d1')(
pool4)
print("conv5_d1:", conv5_d1.shape)
bnor5_d1 = BatchNormalization(name='bnor5_d1', momentum=0.825)(conv5_d1)
acti5_d1 = Activation(tf.nn.relu, name='acti5_d1')(bnor5_d1)
# Dropout of 0.25
drop5_d1 = Dropout(0.25, name='drop5_d1')(acti5_d1)
# 3x3 Convolution - 2x2 dilation
conv5_d2 = Conv2D(256, (3, 3), dilation_rate=2, padding='same', data_format='channels_last', name='conv5_d2')(
pool4)
print("conv5_d2:", conv5_d2.shape)
bnor5_d2 = BatchNormalization(name='bnor5_d2', momentum=0.825)(conv5_d2)
acti5_d2 = Activation(tf.nn.relu, name='acti5_d2')(bnor5_d2)
# Dropout of 0.25
drop5_d2 = Dropout(0.25, name='drop5_d2')(acti5_d2)
# 3x3 Convolution - 4x4 dilation
conv5_d4 = Conv2D(256, (3, 3), dilation_rate=4, padding='same', data_format='channels_last', name='conv5_d4')(
pool4)
print("conv5_d4:", conv5_d4.shape)
bnor5_d4 = BatchNormalization(name='bnor5_d4', momentum=0.825)(conv5_d4)
acti5_d4 = Activation(tf.nn.relu, name='acti5_d4')(bnor5_d4)
# Dropout of 0.25
drop5_d4 = Dropout(0.25, name='drop5_d4')(acti5_d4)
# 3x3 Convolution - 8x8 dilation
conv5_d8 = Conv2D(256, (3, 3), dilation_rate=8, padding='same', data_format='channels_last', name='conv5_d8')(
pool4)
print("conv5_d8:", conv5_d8.shape)
bnor5_d8 = BatchNormalization(name='bnor5_d8', momentum=0.825)(conv5_d8)
acti5_d8 = Activation(tf.nn.relu, name='acti5_d8')(bnor5_d8)
# Dropout of 0.25
drop5_d8 = Dropout(0.25, name='drop5_d8')(acti5_d8)
# Concatenate all of the dilated convolutions
conc5_d = Concatenate(axis=3, name='conc5_d')([drop5_d1, drop5_d2, drop5_d4, drop5_d8])
# 3x3 Convolution
conv5 = Conv2D(256, (3, 3), padding='same', data_format='channels_last', name='conv5_1')(conc5_d)
print("conv5:", conv5.shape)
bnor5 = BatchNormalization(name='bnor5_1', momentum=0.825)(conv5)
acti5 = Activation(tf.nn.relu, name='acti5_1')(bnor5)
# ----- Sixth Convolution -----
# 2x2 Up Sampling
upsp6 = UpSampling2D(size=(2, 2), name='upsp6_1')(acti5)
# Concatenation
conc6 = Concatenate(axis=3, name='conc6_1')([upsp6, acti4])
# 3x3 Convolution
conv6 = Conv2D(128, (3, 3), padding='same', data_format='channels_last', name='conv6_1')(conc6)
print("conv6:", conv6.shape)
acti6 = Activation(tf.nn.relu, name='acti6_1')(conv6)
# Dropout of 0.2
drop6 = Dropout(0.2, name='drop6_2')(acti6)
# 3x3 Convolution
conv6 = Conv2D(128, (3, 3), padding='same', data_format='channels_last', name='conv6_2')(drop6)
print("conv6:", conv6.shape)
acti6 = Activation(tf.nn.relu, name='acti6_2')(conv6)
# ----- Seventh Convolution - Up Sampling -----
# 2x2 Up Sampling
upsp7 = UpSampling2D(size=(2, 2), name='upsp7_1')(acti6)
# Concatenation
conc7 = Concatenate(axis=3, name='conc7_1')([upsp7, acti3])
# 3x3 Convolution
conv7 = Conv2D(64, (3, 3), padding='same', data_format='channels_last', name='conv7_1')(conc7)
print("conv7:", conv7.shape)
acti7 = Activation(tf.nn.relu, name='acti7_1')(conv7)
# Dropout of 0.2
drop7 = Dropout(0.2, name='drop7_2')(acti7)
# 3x3 Convolution
conv7 = Conv2D(64, (3, 3), padding='same', data_format='channels_last', name='conv7_2')(drop7)
print("conv7:", conv7.shape)
acti7 = Activation(tf.nn.relu, name='acti7_2')(conv7)
# ----- Eighth Convolution - Up Sampling -----
# 2x2 Up Sampling
upsp8 = UpSampling2D(size=(2, 2), name='upsp8_1')(acti7)
# Concatenation
conc8 = Concatenate(axis=3, name='conc8_1')([upsp8, acti2])
# 3x3 Convolution
conv8 = Conv2D(32, (3, 3), padding='same', data_format='channels_last', name='conv8_1')(conc8)
print("conv8:", conv8.shape)
acti8 = Activation(tf.nn.relu, name='acti8_1')(conv8)
# Dropout of 0.2
drop8 = Dropout(0.2, name='drop8_1')(acti8)
# 3x3 Convolution
conv8 = Conv2D(32, (3, 3), padding='same', data_format='channels_last', name='conv8_2')(drop8)
print("conv8:", conv8.shape)
acti8 = Activation(tf.nn.relu, name='acti8_2')(conv8)
# ----- Ninth Convolution - Up Sampling -----
# 2x2 Up Sampling
upsp9 = UpSampling2D(size=(2, 2), name='upsp9_1')(acti8)
# Concatenation
conc9 = Concatenate(axis=3, name='conc9_1')([upsp9, acti1])
# 3x3 Convolution
conv9 = Conv2D(16, (3, 3), padding='same', data_format='channels_last', name='conv9_1')(conc9)
print("conv9:", conv9.shape)
acti9 = Activation(tf.nn.relu, name='acti9_1')(conv9)
# Dropout of 0.2
drop9 = Dropout(0.2, name='drop9_1')(acti9)
# 3x3 Convolution
conv9 = Conv2D(16, (3, 3), padding='same', data_format='channels_last', name='conv9_2')(drop9)
print("conv9:", conv9.shape)
acti9 = Activation(tf.nn.relu, name='acti9_2')(conv9)
# ----- Tenth Convolution (outputs) -----
# 3x3 Convolution
conv10 = Conv2D(2, (3, 3), padding='same', data_format='channels_last', name='conv10_1')(acti9)
print("conv10:", conv10.shape)
acti10 = Activation(tf.nn.sigmoid, name='acti10_1')(conv10)
# 1x1 Convolution
conv10 = Conv2D(self.__nClasses, (1, 1), padding='same', data_format='channels_last', name='conv10_2')(acti10)
print("conv10:", conv10.shape)
acti10 = Activation(tf.nn.sigmoid, name='acti10_2')(conv10)
# Set a new model with the inputs and the outputs (tenth convolution)
self.set_model(Model(inputs=inputs, outputs=acti10))
# Get a summary of the previously create model
self.get_model().summary()
def learn(self):
"""
Compiles and fits a model, evaluation is optional.
"""
# Starting the training
self._training = True
# Number of epochs
epochs = 10
# Learning rate
learning_rate = 1e-4
# Compiling the model with an optimizer and a loss function
self._model.compile(optimizer=Adam(lr=learning_rate, decay=learning_rate / epochs),
loss=binary_crossentropy,
metrics=[binary_accuracy])
# Fitting the model by using our train and validation data
# It returns the history that can be plot in the future
if "train_generator" in self.datas and "val_generator" in self.datas:
# Fit including validation datas
self._history = self._model.fit_generator(
self.datas["train_generator"],
steps_per_epoch=5000,
epochs=epochs,
validation_data=self.datas["val_generator"],
validation_steps=1500)
elif "train_generator" in self.datas:
# Fit without validation datas
self._history = self._model.fit_generator(
self.datas["train_generator"],
steps_per_epoch=5000,
epochs=epochs)
else:
raise NotImplementedError("Unknown data")
if "test_generator" in self.datas:
# Evaluation of the model
test_loss, acc_test = self._model.evaluate_generator(self.datas["test_generator"], steps=250, verbose=1)
print("Loss / test: " + str(test_loss) + " and accuracy: " + str(acc_test))
# Training is over
self._training = False
def predict_output(self):
"""
Predicts an output for a given list of files/data.
"""
for filename in self.filenames:
print(filename)
# Open the desired picture
im = Image.open(filename)
# Get the image array
img_to_predict = np.array(im)
# Be careful -> each pixel value must be a float
img_to_predict = img_to_predict.astype('float32')
# Close the file pointer (if possible)
im.close()
# Store the real shape for later
real_shape = img_to_predict.shape
# At this time we can only use images of shape (m*500, n*500, 3)
assert real_shape[0] % 500 == 0
assert real_shape[1] % 500 == 0
# Predict the segmentation for this picture (its array is stored in data)
pred = np.zeros(real_shape[:2] + (1,))
for i in range(int(real_shape[0] / 500)):
for j in range(int(real_shape[1] / 500)):
print(i, j)
# Get a sub-array of the main array
sub_array = img_to_predict[i * 500:(i + 1) * 500:, j * 500:(j + 1) * 500:, :]
sub_img = array_to_img(sub_array).resize(self.input_shape[:2])
# Because array_to_img is modifying array values to [0,255] we have
# to divide each value by 255
sub_array = np.array(sub_img) / 255.
# Predict the segmentation for this sub-array
pred_array = self._model.predict(sub_array.reshape((1,) + sub_array.shape))
pred_img = array_to_img(pred_array.reshape(pred_array.shape[1:])).resize((500, 500))
pred_array = np.array(pred_img).reshape(500, 500, 1)
# Add this sub-array to the main array
pred[i * 500:(i + 1) * 500:, j * 500:(j + 1) * 500:, :] = pred_array / 255.
# Reshape the image array to (m, n, 3)
reshaped_img_array = np.array(Image.fromarray(img_to_predict).resize(real_shape[:2][::-1]))
# If the result for the second value is more than 0.9 -> store a
# "green" array for this index
reshaped_img_array[pred[:, :, 0] > 0.9] = [0, 240, 0]
# Now, for each element in the picture, replace it or not
img_to_predict[reshaped_img_array[:, :, 1] == 240] = [0, 240, 0]
# Create a new Image instance with the new_img_array array
new_img = Image.fromarray(img_to_predict.astype('uint8'))
# Finally, save this image
new_img.save(basename(splitext(self.__filename)[0]) + "_segmented_img.jpg")
# Save the unsegmented image
imsave(basename(splitext(self.__filename)[0]) + "_unsegmented_img.jpg",
np.array(Image.open(self.__filename)))
# Hold on, close the pointers before leaving
new_img.close()
print("Done")
| [
"keras.layers.Conv2D",
"numpy.array",
"keras.layers.Activation",
"scipy.misc.imresize",
"keras.preprocessing.image.array_to_img",
"os.path.exists",
"os.path.split",
"keras.models.Model",
"keras.optimizers.Adam",
"keras.layers.MaxPooling2D",
"keras.layers.normalization.BatchNormalization",
"ker... | [((2124, 2150), 'os.path.join', 'join', (['base_dir', '"""training"""'], {}), "(base_dir, 'training')\n", (2128, 2150), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n'), ((2169, 2197), 'os.path.join', 'join', (['base_dir', '"""validation"""'], {}), "(base_dir, 'validation')\n", (2173, 2197), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n'), ((4780, 4803), 'keras.layers.Input', 'Input', (['self.input_shape'], {}), '(self.input_shape)\n', (4785, 4803), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((2214, 2231), 'os.path.exists', 'exists', (['train_dir'], {}), '(train_dir)\n', (2220, 2231), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n'), ((2255, 2270), 'os.path.exists', 'exists', (['val_dir'], {}), '(val_dir)\n', (2261, 2270), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n'), ((2352, 2369), 'os.path.join', 'join', (['folder', '"""x"""'], {}), "(folder, 'x')\n", (2356, 2369), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n'), ((2390, 2407), 'os.path.join', 'join', (['folder', '"""y"""'], {}), "(folder, 'y')\n", (2394, 2407), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n'), ((4900, 4979), 'keras.layers.Conv2D', 'Conv2D', (['(16)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv1_1"""'}), "(16, (3, 3), padding='same', data_format='channels_last', name='conv1_1')\n", (4906, 4979), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((5041, 5079), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti1_1"""'}), "(tf.nn.relu, name='acti1_1')\n", (5051, 5079), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((5128, 5156), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {'name': '"""drop1_1"""'}), "(0.2, name='drop1_1')\n", (5135, 5156), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((5206, 5285), 'keras.layers.Conv2D', 'Conv2D', (['(16)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv1_2"""'}), "(16, (3, 3), padding='same', data_format='channels_last', name='conv1_2')\n", (5212, 5285), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((5346, 5384), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti1_2"""'}), "(tf.nn.relu, name='acti1_2')\n", (5356, 5384), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((5434, 5480), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)', 'name': '"""pool1_1"""'}), "(pool_size=(2, 2), name='pool1_1')\n", (5446, 5480), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((5586, 5665), 'keras.layers.Conv2D', 'Conv2D', (['(32)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv2_1"""'}), "(32, (3, 3), padding='same', data_format='channels_last', name='conv2_1')\n", (5592, 5665), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((5726, 5764), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti2_1"""'}), "(tf.nn.relu, name='acti2_1')\n", (5736, 5764), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((5813, 5841), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {'name': '"""drop2_1"""'}), "(0.2, name='drop2_1')\n", (5820, 5841), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((5891, 5970), 'keras.layers.Conv2D', 'Conv2D', (['(32)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv2_2"""'}), "(32, (3, 3), padding='same', data_format='channels_last', name='conv2_2')\n", (5897, 5970), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((6031, 6069), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti2_2"""'}), "(tf.nn.relu, name='acti2_2')\n", (6041, 6069), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((6119, 6165), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)', 'name': '"""pool2_1"""'}), "(pool_size=(2, 2), name='pool2_1')\n", (6131, 6165), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((6270, 6349), 'keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv3_1"""'}), "(64, (3, 3), padding='same', data_format='channels_last', name='conv3_1')\n", (6276, 6349), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((6410, 6448), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti3_1"""'}), "(tf.nn.relu, name='acti3_1')\n", (6420, 6448), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((6497, 6525), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {'name': '"""drop3_2"""'}), "(0.2, name='drop3_2')\n", (6504, 6525), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((6575, 6654), 'keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv3_2"""'}), "(64, (3, 3), padding='same', data_format='channels_last', name='conv3_2')\n", (6581, 6654), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((6715, 6753), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti3_2"""'}), "(tf.nn.relu, name='acti3_2')\n", (6725, 6753), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((6803, 6849), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)', 'name': '"""pool3_1"""'}), "(pool_size=(2, 2), name='pool3_1')\n", (6815, 6849), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((6955, 7040), 'keras.layers.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv4_1"""'}), "(128, (3, 3), padding='same', data_format='channels_last', name='conv4_1'\n )\n", (6961, 7040), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((7096, 7134), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti4_1"""'}), "(tf.nn.relu, name='acti4_1')\n", (7106, 7134), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((7183, 7211), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {'name': '"""drop4_2"""'}), "(0.2, name='drop4_2')\n", (7190, 7211), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((7261, 7346), 'keras.layers.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv4_2"""'}), "(128, (3, 3), padding='same', data_format='channels_last', name='conv4_2'\n )\n", (7267, 7346), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((7402, 7440), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti4_2"""'}), "(tf.nn.relu, name='acti4_2')\n", (7412, 7440), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((7490, 7536), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)', 'name': '"""pool4_1"""'}), "(pool_size=(2, 2), name='pool4_1')\n", (7502, 7536), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((7644, 7747), 'keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'dilation_rate': '(1)', 'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv5_d1"""'}), "(256, (3, 3), dilation_rate=1, padding='same', data_format=\n 'channels_last', name='conv5_d1')\n", (7650, 7747), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((7825, 7876), 'keras.layers.normalization.BatchNormalization', 'BatchNormalization', ([], {'name': '"""bnor5_d1"""', 'momentum': '(0.825)'}), "(name='bnor5_d1', momentum=0.825)\n", (7843, 7876), False, 'from keras.layers.normalization import BatchNormalization\n'), ((7906, 7945), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti5_d1"""'}), "(tf.nn.relu, name='acti5_d1')\n", (7916, 7945), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((8001, 8031), 'keras.layers.Dropout', 'Dropout', (['(0.25)'], {'name': '"""drop5_d1"""'}), "(0.25, name='drop5_d1')\n", (8008, 8031), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((8102, 8205), 'keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'dilation_rate': '(2)', 'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv5_d2"""'}), "(256, (3, 3), dilation_rate=2, padding='same', data_format=\n 'channels_last', name='conv5_d2')\n", (8108, 8205), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((8283, 8334), 'keras.layers.normalization.BatchNormalization', 'BatchNormalization', ([], {'name': '"""bnor5_d2"""', 'momentum': '(0.825)'}), "(name='bnor5_d2', momentum=0.825)\n", (8301, 8334), False, 'from keras.layers.normalization import BatchNormalization\n'), ((8364, 8403), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti5_d2"""'}), "(tf.nn.relu, name='acti5_d2')\n", (8374, 8403), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((8459, 8489), 'keras.layers.Dropout', 'Dropout', (['(0.25)'], {'name': '"""drop5_d2"""'}), "(0.25, name='drop5_d2')\n", (8466, 8489), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((8560, 8663), 'keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'dilation_rate': '(4)', 'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv5_d4"""'}), "(256, (3, 3), dilation_rate=4, padding='same', data_format=\n 'channels_last', name='conv5_d4')\n", (8566, 8663), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((8741, 8792), 'keras.layers.normalization.BatchNormalization', 'BatchNormalization', ([], {'name': '"""bnor5_d4"""', 'momentum': '(0.825)'}), "(name='bnor5_d4', momentum=0.825)\n", (8759, 8792), False, 'from keras.layers.normalization import BatchNormalization\n'), ((8822, 8861), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti5_d4"""'}), "(tf.nn.relu, name='acti5_d4')\n", (8832, 8861), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((8917, 8947), 'keras.layers.Dropout', 'Dropout', (['(0.25)'], {'name': '"""drop5_d4"""'}), "(0.25, name='drop5_d4')\n", (8924, 8947), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((9018, 9121), 'keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'dilation_rate': '(8)', 'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv5_d8"""'}), "(256, (3, 3), dilation_rate=8, padding='same', data_format=\n 'channels_last', name='conv5_d8')\n", (9024, 9121), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((9199, 9250), 'keras.layers.normalization.BatchNormalization', 'BatchNormalization', ([], {'name': '"""bnor5_d8"""', 'momentum': '(0.825)'}), "(name='bnor5_d8', momentum=0.825)\n", (9217, 9250), False, 'from keras.layers.normalization import BatchNormalization\n'), ((9280, 9319), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti5_d8"""'}), "(tf.nn.relu, name='acti5_d8')\n", (9290, 9319), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((9375, 9405), 'keras.layers.Dropout', 'Dropout', (['(0.25)'], {'name': '"""drop5_d8"""'}), "(0.25, name='drop5_d8')\n", (9382, 9405), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((9488, 9523), 'keras.layers.Concatenate', 'Concatenate', ([], {'axis': '(3)', 'name': '"""conc5_d"""'}), "(axis=3, name='conc5_d')\n", (9499, 9523), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((9608, 9693), 'keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv5_1"""'}), "(256, (3, 3), padding='same', data_format='channels_last', name='conv5_1'\n )\n", (9614, 9693), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((9751, 9801), 'keras.layers.normalization.BatchNormalization', 'BatchNormalization', ([], {'name': '"""bnor5_1"""', 'momentum': '(0.825)'}), "(name='bnor5_1', momentum=0.825)\n", (9769, 9801), False, 'from keras.layers.normalization import BatchNormalization\n'), ((9825, 9863), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti5_1"""'}), "(tf.nn.relu, name='acti5_1')\n", (9835, 9863), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((9954, 9995), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)', 'name': '"""upsp6_1"""'}), "(size=(2, 2), name='upsp6_1')\n", (9966, 9995), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((10043, 10078), 'keras.layers.Concatenate', 'Concatenate', ([], {'axis': '(3)', 'name': '"""conc6_1"""'}), "(axis=3, name='conc6_1')\n", (10054, 10078), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((10137, 10222), 'keras.layers.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv6_1"""'}), "(128, (3, 3), padding='same', data_format='channels_last', name='conv6_1'\n )\n", (10143, 10222), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((10278, 10316), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti6_1"""'}), "(tf.nn.relu, name='acti6_1')\n", (10288, 10316), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((10365, 10393), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {'name': '"""drop6_2"""'}), "(0.2, name='drop6_2')\n", (10372, 10393), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((10443, 10528), 'keras.layers.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv6_2"""'}), "(128, (3, 3), padding='same', data_format='channels_last', name='conv6_2'\n )\n", (10449, 10528), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((10584, 10622), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti6_2"""'}), "(tf.nn.relu, name='acti6_2')\n", (10594, 10622), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((10729, 10770), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)', 'name': '"""upsp7_1"""'}), "(size=(2, 2), name='upsp7_1')\n", (10741, 10770), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((10818, 10853), 'keras.layers.Concatenate', 'Concatenate', ([], {'axis': '(3)', 'name': '"""conc7_1"""'}), "(axis=3, name='conc7_1')\n", (10829, 10853), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((10912, 10991), 'keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv7_1"""'}), "(64, (3, 3), padding='same', data_format='channels_last', name='conv7_1')\n", (10918, 10991), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((11052, 11090), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti7_1"""'}), "(tf.nn.relu, name='acti7_1')\n", (11062, 11090), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((11139, 11167), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {'name': '"""drop7_2"""'}), "(0.2, name='drop7_2')\n", (11146, 11167), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((11217, 11296), 'keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv7_2"""'}), "(64, (3, 3), padding='same', data_format='channels_last', name='conv7_2')\n", (11223, 11296), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((11357, 11395), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti7_2"""'}), "(tf.nn.relu, name='acti7_2')\n", (11367, 11395), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((11501, 11542), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)', 'name': '"""upsp8_1"""'}), "(size=(2, 2), name='upsp8_1')\n", (11513, 11542), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((11590, 11625), 'keras.layers.Concatenate', 'Concatenate', ([], {'axis': '(3)', 'name': '"""conc8_1"""'}), "(axis=3, name='conc8_1')\n", (11601, 11625), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((11684, 11763), 'keras.layers.Conv2D', 'Conv2D', (['(32)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv8_1"""'}), "(32, (3, 3), padding='same', data_format='channels_last', name='conv8_1')\n", (11690, 11763), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((11824, 11862), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti8_1"""'}), "(tf.nn.relu, name='acti8_1')\n", (11834, 11862), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((11911, 11939), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {'name': '"""drop8_1"""'}), "(0.2, name='drop8_1')\n", (11918, 11939), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((11989, 12068), 'keras.layers.Conv2D', 'Conv2D', (['(32)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv8_2"""'}), "(32, (3, 3), padding='same', data_format='channels_last', name='conv8_2')\n", (11995, 12068), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((12129, 12167), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti8_2"""'}), "(tf.nn.relu, name='acti8_2')\n", (12139, 12167), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((12272, 12313), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)', 'name': '"""upsp9_1"""'}), "(size=(2, 2), name='upsp9_1')\n", (12284, 12313), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((12361, 12396), 'keras.layers.Concatenate', 'Concatenate', ([], {'axis': '(3)', 'name': '"""conc9_1"""'}), "(axis=3, name='conc9_1')\n", (12372, 12396), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((12455, 12534), 'keras.layers.Conv2D', 'Conv2D', (['(16)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv9_1"""'}), "(16, (3, 3), padding='same', data_format='channels_last', name='conv9_1')\n", (12461, 12534), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((12595, 12633), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti9_1"""'}), "(tf.nn.relu, name='acti9_1')\n", (12605, 12633), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((12682, 12710), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {'name': '"""drop9_1"""'}), "(0.2, name='drop9_1')\n", (12689, 12710), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((12760, 12839), 'keras.layers.Conv2D', 'Conv2D', (['(16)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv9_2"""'}), "(16, (3, 3), padding='same', data_format='channels_last', name='conv9_2')\n", (12766, 12839), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((12900, 12938), 'keras.layers.Activation', 'Activation', (['tf.nn.relu'], {'name': '"""acti9_2"""'}), "(tf.nn.relu, name='acti9_2')\n", (12910, 12938), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((13040, 13119), 'keras.layers.Conv2D', 'Conv2D', (['(2)', '(3, 3)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv10_1"""'}), "(2, (3, 3), padding='same', data_format='channels_last', name='conv10_1')\n", (13046, 13119), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((13183, 13225), 'keras.layers.Activation', 'Activation', (['tf.nn.sigmoid'], {'name': '"""acti10_1"""'}), "(tf.nn.sigmoid, name='acti10_1')\n", (13193, 13225), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((13277, 13374), 'keras.layers.Conv2D', 'Conv2D', (['self.__nClasses', '(1, 1)'], {'padding': '"""same"""', 'data_format': '"""channels_last"""', 'name': '"""conv10_2"""'}), "(self.__nClasses, (1, 1), padding='same', data_format='channels_last',\n name='conv10_2')\n", (13283, 13374), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((13435, 13477), 'keras.layers.Activation', 'Activation', (['tf.nn.sigmoid'], {'name': '"""acti10_2"""'}), "(tf.nn.sigmoid, name='acti10_2')\n", (13445, 13477), False, 'from keras.layers import Input, Conv2D, Dropout, MaxPooling2D, UpSampling2D, Concatenate, Activation\n'), ((13588, 13624), 'keras.models.Model', 'Model', ([], {'inputs': 'inputs', 'outputs': 'acti10'}), '(inputs=inputs, outputs=acti10)\n', (13593, 13624), False, 'from keras.models import Model\n'), ((15692, 15712), 'PIL.Image.open', 'Image.open', (['filename'], {}), '(filename)\n', (15702, 15712), False, 'from PIL import Image\n'), ((15776, 15788), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (15784, 15788), True, 'import numpy as np\n'), ((16349, 16380), 'numpy.zeros', 'np.zeros', (['(real_shape[:2] + (1,))'], {}), '(real_shape[:2] + (1,))\n', (16357, 16380), True, 'import numpy as np\n'), ((2428, 2441), 'os.path.exists', 'exists', (['x_dir'], {}), '(x_dir)\n', (2434, 2441), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n'), ((2469, 2482), 'os.path.exists', 'exists', (['y_dir'], {}), '(y_dir)\n', (2475, 2482), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n'), ((14091, 14143), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'learning_rate', 'decay': '(learning_rate / epochs)'}), '(lr=learning_rate, decay=learning_rate / epochs)\n', (14095, 14143), False, 'from keras.optimizers import Adam, RMSprop\n'), ((2612, 2632), 'os.path.join', 'join', (['x_dir', '"""*.tif"""'], {}), "(x_dir, '*.tif')\n", (2616, 2632), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n'), ((2646, 2667), 'os.path.join', 'join', (['x_dir', '"""*.tiff"""'], {}), "(x_dir, '*.tiff')\n", (2650, 2667), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n'), ((2701, 2721), 'os.path.join', 'join', (['y_dir', '"""*.tif"""'], {}), "(y_dir, '*.tif')\n", (2705, 2721), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n'), ((2735, 2756), 'os.path.join', 'join', (['y_dir', '"""*.tiff"""'], {}), "(y_dir, '*.tiff')\n", (2739, 2756), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n'), ((3853, 3890), 'numpy.zeros', 'np.zeros', (['(self.input_shape[:2] + (1,))'], {}), '(self.input_shape[:2] + (1,))\n', (3861, 3890), True, 'import numpy as np\n'), ((18366, 18393), 'PIL.Image.open', 'Image.open', (['self.__filename'], {}), '(self.__filename)\n', (18376, 18393), False, 'from PIL import Image\n'), ((2042, 2060), 'os.path.realpath', 'realpath', (['__file__'], {}), '(__file__)\n', (2050, 2060), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n'), ((3363, 3387), 'keras.preprocessing.image.load_img', 'load_img', (['x_files[index]'], {}), '(x_files[index])\n', (3371, 3387), False, 'from keras.preprocessing.image import img_to_array, load_img, array_to_img\n'), ((3430, 3454), 'keras.preprocessing.image.load_img', 'load_img', (['y_files[index]'], {}), '(y_files[index])\n', (3438, 3454), False, 'from keras.preprocessing.image import img_to_array, load_img, array_to_img\n'), ((3532, 3569), 'scipy.misc.imresize', 'imresize', (['x_img', 'self.input_shape[:2]'], {}), '(x_img, self.input_shape[:2])\n', (3540, 3569), False, 'from scipy.misc import imsave, imresize\n'), ((3571, 3608), 'scipy.misc.imresize', 'imresize', (['y_img', 'self.input_shape[:2]'], {}), '(y_img, self.input_shape[:2])\n', (3579, 3608), False, 'from scipy.misc import imsave, imresize\n'), ((4428, 4439), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (4436, 4439), True, 'import numpy as np\n'), ((4441, 4452), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (4449, 4452), True, 'import numpy as np\n'), ((16933, 16950), 'numpy.array', 'np.array', (['sub_img'], {}), '(sub_img)\n', (16941, 16950), True, 'import numpy as np\n'), ((17548, 17579), 'PIL.Image.fromarray', 'Image.fromarray', (['img_to_predict'], {}), '(img_to_predict)\n', (17563, 17579), False, 'from PIL import Image\n'), ((3258, 3283), 'os.path.split', 'pathsplit', (['x_files[index]'], {}), '(x_files[index])\n', (3267, 3283), True, 'from os.path import split as pathsplit\n'), ((3291, 3316), 'os.path.split', 'pathsplit', (['y_files[index]'], {}), '(y_files[index])\n', (3300, 3316), True, 'from os.path import split as pathsplit\n'), ((16709, 16732), 'keras.preprocessing.image.array_to_img', 'array_to_img', (['sub_array'], {}), '(sub_array)\n', (16721, 16732), False, 'from keras.preprocessing.image import img_to_array, load_img, array_to_img\n'), ((17259, 17277), 'numpy.array', 'np.array', (['pred_img'], {}), '(pred_img)\n', (17267, 17277), True, 'import numpy as np\n'), ((18159, 18184), 'os.path.splitext', 'splitext', (['self.__filename'], {}), '(self.__filename)\n', (18167, 18184), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n'), ((18282, 18307), 'os.path.splitext', 'splitext', (['self.__filename'], {}), '(self.__filename)\n', (18290, 18307), False, 'from os.path import isfile, exists, join, realpath, splitext, basename\n')] |
# train a simple MLP on the synthetic sklearn data
import numpy as np
import pandas as pd
import os
from pathlib import Path
from tqdm import tqdm
import torch
from torch import nn, optim, tensor, FloatTensor
from torch.utils.data import Dataset, TensorDataset, DataLoader
from data.skl_synthetic import load_skl_data
from models.linear import LinearMLP, LinearAE, LinearFEA
from plotting import plot_losses, plot_predicted_vs_actual
import matplotlib.pyplot as plt
def main(*args, **kwargs):
torch.manual_seed(123)
# load data, set model paramaters
# ---------------------------------
home = Path.home()
path_for_data = home/"teas-data/sklearn/"
if not os.path.exists(path_for_data):
raise ValueError("No data. By default, this script uses synthetic data that you can generate by running skl_synthetic.py. Otherwise please modify this script")
if os.path.exists(path_for_data):
X_train, X_valid, X_test, Y_train, Y_valid, Y_test = map(FloatTensor, load_skl_data(path_for_data))
batch_size = 128
train_ds = TensorDataset(X_train, Y_train)
valid_ds = TensorDataset(X_valid, Y_valid)
test_ds = TensorDataset(X_test, Y_test)
train_dl = DataLoader(train_ds, batch_size)
valid_dl = DataLoader(valid_ds, batch_size)
test_dl = DataLoader(test_ds, batch_size)
# these give us some shape values for later
X, Y = next(iter(train_ds))
input_dim = X.shape[0]
hidden_dim = 512
output_dim = Y.shape[0]
# first, train and benchmark a simple Linear MLP
lmlp_model = LinearMLP([input_dim, 512, output_dim])
# train the linear MLP
epochs = 10
lr = 1e-2
opt = optim.Adam(lmlp_model.parameters(), lr)
mse = nn.MSELoss()
train_loss, valid_loss = [], []
print("Training a linear MLP")
for e in tqdm(range(epochs)):
this_train_loss = np.mean([lmlp_model.update_batch(X, Y, opt, mse) for X, Y in train_dl])
this_valid_loss = np.mean([lmlp_model.update_batch(X, Y, opt, mse, train=False) for X, Y in valid_dl])
train_loss.append(this_train_loss)
valid_loss.append(this_valid_loss)
plot_losses(epochs, train_loss, valid_loss)
# visualise predicted vs. actual
# pull out a random row
idx = np.random.randint(0, X_valid.shape[1])
X, Y = valid_ds[idx]
Y_hat = lmlp_model(X)
# Y_hat vs. Y
plot_predicted_vs_actual(Y, Y_hat, idx)
# test losses
test_pred = []
pred_error = []
mse = nn.MSELoss()
for X, Y in test_ds:
Y_hat = lmlp_model(X)
test_pred.append(Y_hat.detach().numpy())
pred_error.append(mse(Y_hat, Y).detach().numpy())
print("Final test MSE loss on prediction task (linear MLP): {}".format(np.mean(pred_error)))
if __name__ == "__main__":
main() | [
"torch.manual_seed",
"os.path.exists",
"models.linear.LinearMLP",
"plotting.plot_predicted_vs_actual",
"numpy.mean",
"pathlib.Path.home",
"data.skl_synthetic.load_skl_data",
"torch.utils.data.TensorDataset",
"plotting.plot_losses",
"torch.nn.MSELoss",
"numpy.random.randint",
"torch.utils.data.... | [((502, 524), 'torch.manual_seed', 'torch.manual_seed', (['(123)'], {}), '(123)\n', (519, 524), False, 'import torch\n'), ((617, 628), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (626, 628), False, 'from pathlib import Path\n'), ((892, 921), 'os.path.exists', 'os.path.exists', (['path_for_data'], {}), '(path_for_data)\n', (906, 921), False, 'import os\n'), ((1068, 1099), 'torch.utils.data.TensorDataset', 'TensorDataset', (['X_train', 'Y_train'], {}), '(X_train, Y_train)\n', (1081, 1099), False, 'from torch.utils.data import Dataset, TensorDataset, DataLoader\n'), ((1115, 1146), 'torch.utils.data.TensorDataset', 'TensorDataset', (['X_valid', 'Y_valid'], {}), '(X_valid, Y_valid)\n', (1128, 1146), False, 'from torch.utils.data import Dataset, TensorDataset, DataLoader\n'), ((1161, 1190), 'torch.utils.data.TensorDataset', 'TensorDataset', (['X_test', 'Y_test'], {}), '(X_test, Y_test)\n', (1174, 1190), False, 'from torch.utils.data import Dataset, TensorDataset, DataLoader\n'), ((1206, 1238), 'torch.utils.data.DataLoader', 'DataLoader', (['train_ds', 'batch_size'], {}), '(train_ds, batch_size)\n', (1216, 1238), False, 'from torch.utils.data import Dataset, TensorDataset, DataLoader\n'), ((1254, 1286), 'torch.utils.data.DataLoader', 'DataLoader', (['valid_ds', 'batch_size'], {}), '(valid_ds, batch_size)\n', (1264, 1286), False, 'from torch.utils.data import Dataset, TensorDataset, DataLoader\n'), ((1301, 1332), 'torch.utils.data.DataLoader', 'DataLoader', (['test_ds', 'batch_size'], {}), '(test_ds, batch_size)\n', (1311, 1332), False, 'from torch.utils.data import Dataset, TensorDataset, DataLoader\n'), ((1562, 1601), 'models.linear.LinearMLP', 'LinearMLP', (['[input_dim, 512, output_dim]'], {}), '([input_dim, 512, output_dim])\n', (1571, 1601), False, 'from models.linear import LinearMLP, LinearAE, LinearFEA\n'), ((1720, 1732), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (1730, 1732), False, 'from torch import nn, optim, tensor, FloatTensor\n'), ((2139, 2182), 'plotting.plot_losses', 'plot_losses', (['epochs', 'train_loss', 'valid_loss'], {}), '(epochs, train_loss, valid_loss)\n', (2150, 2182), False, 'from plotting import plot_losses, plot_predicted_vs_actual\n'), ((2259, 2297), 'numpy.random.randint', 'np.random.randint', (['(0)', 'X_valid.shape[1]'], {}), '(0, X_valid.shape[1])\n', (2276, 2297), True, 'import numpy as np\n'), ((2371, 2410), 'plotting.plot_predicted_vs_actual', 'plot_predicted_vs_actual', (['Y', 'Y_hat', 'idx'], {}), '(Y, Y_hat, idx)\n', (2395, 2410), False, 'from plotting import plot_losses, plot_predicted_vs_actual\n'), ((2479, 2491), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (2489, 2491), False, 'from torch import nn, optim, tensor, FloatTensor\n'), ((686, 715), 'os.path.exists', 'os.path.exists', (['path_for_data'], {}), '(path_for_data)\n', (700, 715), False, 'import os\n'), ((1001, 1029), 'data.skl_synthetic.load_skl_data', 'load_skl_data', (['path_for_data'], {}), '(path_for_data)\n', (1014, 1029), False, 'from data.skl_synthetic import load_skl_data\n'), ((2729, 2748), 'numpy.mean', 'np.mean', (['pred_error'], {}), '(pred_error)\n', (2736, 2748), True, 'import numpy as np\n')] |
import numpy as np
from src.data.DataBase import DataBase
from src.vectoring.VectorBuilderBase import VectorBuilderBase
class ImageVectorBuilder(VectorBuilderBase):
def __init__(self, extracted_data: DataBase):
extracted_data.assert_is_extracted()
self.__data__ = extracted_data
self.__labels_c__ = len(self.__data__.labels)
def build_img_vector(self, img_id):
vec = np.zeros(self.__labels_c__)
index = self.__data__.rows_img_id.index(img_id)
row_labels = self.__data__.rows_labels[index]
row_scores = self.__data__.rows_scores[index]
for label_i, label in enumerate(row_labels):
score = row_scores[label_i]
label_vec_ind = self.__data__.labels.index(label)
old_score = vec[label_vec_ind]
vec[label_vec_ind] = max(old_score, score)
return np.array(vec)
def build_vector(self, segment):
resulting_vector = np.zeros(self.__labels_c__)
for img_id in segment:
vec = self.build_img_vector(img_id)
resulting_vector = np.array([max(vec[i], resulting_vector[i]) for i in range(self.__labels_c__)])
return resulting_vector
| [
"numpy.array",
"numpy.zeros"
] | [((414, 441), 'numpy.zeros', 'np.zeros', (['self.__labels_c__'], {}), '(self.__labels_c__)\n', (422, 441), True, 'import numpy as np\n'), ((876, 889), 'numpy.array', 'np.array', (['vec'], {}), '(vec)\n', (884, 889), True, 'import numpy as np\n'), ((955, 982), 'numpy.zeros', 'np.zeros', (['self.__labels_c__'], {}), '(self.__labels_c__)\n', (963, 982), True, 'import numpy as np\n')] |
"""Numeric features transformers."""
from typing import Union
import numpy as np
from ..dataset.base import LAMLDataset
from ..dataset.np_pd_dataset import NumpyDataset
from ..dataset.np_pd_dataset import PandasDataset
from ..dataset.roles import CategoryRole
from ..dataset.roles import NumericRole
from .base import LAMLTransformer
# type - something that can be converted to pandas dataset
NumpyTransformable = Union[NumpyDataset, PandasDataset]
def numeric_check(dataset: LAMLDataset):
"""Check if all passed vars are categories.
Args:
dataset: Dataset to check.
Raises:
AssertionError: If there is non number role.
"""
roles = dataset.roles
features = dataset.features
for f in features:
assert roles[f].name == "Numeric", "Only numbers accepted in this transformer"
class NaNFlags(LAMLTransformer):
"""Create NaN flags.
Args:
nan_rate: Nan rate cutoff.
"""
_fit_checks = (numeric_check,)
_transform_checks = ()
_fname_prefix = "nanflg"
def __init__(self, nan_rate: float = 0.005):
self.nan_rate = nan_rate
def fit(self, dataset: NumpyTransformable):
"""Extract nan flags.
Args:
dataset: Pandas or Numpy dataset of categorical features.
Returns:
self.
"""
# set transformer names and add checks
for check_func in self._fit_checks:
check_func(dataset)
# set transformer features
# convert to accepted dtype and get attributes
dataset = dataset.to_numpy()
data = dataset.data
# fit ...
ds_nan_rate = np.isnan(data).mean(axis=0)
self.nan_cols = [name for (name, nan_rate) in zip(dataset.features, ds_nan_rate) if nan_rate > self.nan_rate]
self._features = list(self.nan_cols)
return self
def transform(self, dataset: NumpyTransformable) -> NumpyDataset:
"""Transform - extract null flags.
Args:
dataset: Pandas or Numpy dataset of categorical features.
Returns:
Numpy dataset with encoded labels.
"""
# checks here
super().transform(dataset)
# convert to accepted dtype and get attributes
dataset = dataset.to_numpy()
nans = dataset[:, self.nan_cols].data
# transform
new_arr = np.isnan(nans).astype(np.float32)
# create resulted
output = dataset.empty().to_numpy()
output.set_data(new_arr, self.features, NumericRole(np.float32))
return output
class FillnaMedian(LAMLTransformer):
"""Fillna with median."""
_fit_checks = (numeric_check,)
_transform_checks = ()
_fname_prefix = "fillnamed"
def fit(self, dataset: NumpyTransformable):
"""Estimate medians.
Args:
dataset: Pandas or Numpy dataset of categorical features.
Returns:
self.
"""
# set transformer names and add checks
super().fit(dataset)
# set transformer features
# convert to accepted dtype and get attributes
dataset = dataset.to_numpy()
data = dataset.data
self.meds = np.nanmedian(data, axis=0)
self.meds[np.isnan(self.meds)] = 0
return self
def transform(self, dataset: NumpyTransformable) -> NumpyDataset:
"""Transform - fillna with medians.
Args:
dataset: Pandas or Numpy dataset of categorical features.
Returns:
Numpy dataset with encoded labels.
"""
# checks here
super().transform(dataset)
# convert to accepted dtype and get attributes
dataset = dataset.to_numpy()
data = dataset.data
# transform
data = np.where(np.isnan(data), self.meds, data)
# create resulted
output = dataset.empty().to_numpy()
output.set_data(data, self.features, NumericRole(np.float32))
return output
class FillInf(LAMLTransformer):
"""Fill inf with nan to handle as nan value."""
_fit_checks = (numeric_check,)
_transform_checks = ()
_fname_prefix = "fillinf"
def transform(self, dataset: NumpyTransformable) -> NumpyDataset:
"""Replace inf to nan.
Args:
dataset: Pandas or Numpy dataset of categorical features.
Returns:
Numpy dataset with encoded labels.
"""
# checks here
super().transform(dataset)
# convert to accepted dtype and get attributes
dataset = dataset.to_numpy()
data = dataset.data
# transform
data = np.where(np.isinf(data), np.nan, data)
# create resulted
output = dataset.empty().to_numpy()
output.set_data(data, self.features, NumericRole(np.float32))
return output
class LogOdds(LAMLTransformer):
"""Convert probs to logodds."""
_fit_checks = (numeric_check,)
_transform_checks = ()
_fname_prefix = "logodds"
def transform(self, dataset: NumpyTransformable) -> NumpyDataset:
"""Transform - convert num values to logodds.
Args:
dataset: Pandas or Numpy dataset of categorical features.
Returns:
Numpy dataset with encoded labels.
"""
# checks here
super().transform(dataset)
# convert to accepted dtype and get attributes
dataset = dataset.to_numpy()
data = dataset.data
# transform
# TODO: maybe np.exp and then cliping and logodds?
data = np.clip(data, 1e-7, 1 - 1e-7)
data = np.log(data / (1 - data))
# create resulted
output = dataset.empty().to_numpy()
output.set_data(data, self.features, NumericRole(np.float32))
return output
class StandardScaler(LAMLTransformer):
"""Classic StandardScaler."""
_fit_checks = (numeric_check,)
_transform_checks = ()
_fname_prefix = "scaler"
def fit(self, dataset: NumpyTransformable):
"""Estimate means and stds.
Args:
dataset: Pandas or Numpy dataset of categorical features.
Returns:
self.
"""
# set transformer names and add checks
super().fit(dataset)
# set transformer features
# convert to accepted dtype and get attributes
dataset = dataset.to_numpy()
data = dataset.data
self.means = np.nanmean(data, axis=0)
self.stds = np.nanstd(data, axis=0)
# Fix zero stds to 1
self.stds[(self.stds == 0) | np.isnan(self.stds)] = 1
return self
def transform(self, dataset: NumpyTransformable) -> NumpyDataset:
"""Scale test data.
Args:
dataset: Pandas or Numpy dataset of numeric features.
Returns:
Numpy dataset with encoded labels.
"""
# checks here
super().transform(dataset)
# convert to accepted dtype and get attributes
dataset = dataset.to_numpy()
data = dataset.data
# transform
data = (data - self.means) / self.stds
# create resulted
output = dataset.empty().to_numpy()
output.set_data(data, self.features, NumericRole(np.float32))
return output
class QuantileBinning(LAMLTransformer):
"""Discretization of numeric features by quantiles.
Args:
nbins: maximum number of bins.
"""
_fit_checks = (numeric_check,)
_transform_checks = ()
_fname_prefix = "qntl"
def __init__(self, nbins: int = 10):
self.nbins = nbins
def fit(self, dataset: NumpyTransformable):
"""Estimate bins borders.
Args:
dataset: Pandas or Numpy dataset of numeric features.
Returns:
self.
"""
# set transformer names and add checks
super().fit(dataset)
# set transformer features
# convert to accepted dtype and get attributes
dataset = dataset.to_numpy()
data = dataset.data
sl = np.isnan(data)
grid = np.linspace(0, 1, self.nbins + 1)[1:-1]
self.bins = []
for n in range(data.shape[1]):
q = np.quantile(data[:, n][~sl[:, n]], q=grid)
q = np.unique(q)
self.bins.append(q)
return self
def transform(self, dataset: NumpyTransformable) -> NumpyDataset:
"""Apply bin borders.
Args:
dataset: Pandas or Numpy dataset of numeric features.
Returns:
Numpy dataset with encoded labels.
"""
# checks here
super().transform(dataset)
# convert to accepted dtype and get attributes
dataset = dataset.to_numpy()
data = dataset.data
# transform
sl = np.isnan(data)
new_data = np.zeros(data.shape, dtype=np.int32)
for n, b in enumerate(self.bins):
new_data[:, n] = np.searchsorted(b, np.where(sl[:, n], np.inf, data[:, n])) + 1
new_data = np.where(sl, 0, new_data)
# create resulted
output = dataset.empty().to_numpy()
output.set_data(new_data, self.features, CategoryRole(np.int32, label_encoded=True))
return output
| [
"numpy.clip",
"numpy.nanstd",
"numpy.unique",
"numpy.nanmedian",
"numpy.where",
"numpy.log",
"numpy.nanmean",
"numpy.zeros",
"numpy.linspace",
"numpy.isnan",
"numpy.quantile",
"numpy.isinf"
] | [((3209, 3235), 'numpy.nanmedian', 'np.nanmedian', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (3221, 3235), True, 'import numpy as np\n'), ((5578, 5609), 'numpy.clip', 'np.clip', (['data', '(1e-07)', '(1 - 1e-07)'], {}), '(data, 1e-07, 1 - 1e-07)\n', (5585, 5609), True, 'import numpy as np\n'), ((5623, 5648), 'numpy.log', 'np.log', (['(data / (1 - data))'], {}), '(data / (1 - data))\n', (5629, 5648), True, 'import numpy as np\n'), ((6453, 6477), 'numpy.nanmean', 'np.nanmean', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (6463, 6477), True, 'import numpy as np\n'), ((6498, 6521), 'numpy.nanstd', 'np.nanstd', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (6507, 6521), True, 'import numpy as np\n'), ((8076, 8090), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (8084, 8090), True, 'import numpy as np\n'), ((8822, 8836), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (8830, 8836), True, 'import numpy as np\n'), ((8857, 8893), 'numpy.zeros', 'np.zeros', (['data.shape'], {'dtype': 'np.int32'}), '(data.shape, dtype=np.int32)\n', (8865, 8893), True, 'import numpy as np\n'), ((9049, 9074), 'numpy.where', 'np.where', (['sl', '(0)', 'new_data'], {}), '(sl, 0, new_data)\n', (9057, 9074), True, 'import numpy as np\n'), ((3254, 3273), 'numpy.isnan', 'np.isnan', (['self.meds'], {}), '(self.meds)\n', (3262, 3273), True, 'import numpy as np\n'), ((3799, 3813), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (3807, 3813), True, 'import numpy as np\n'), ((4662, 4676), 'numpy.isinf', 'np.isinf', (['data'], {}), '(data)\n', (4670, 4676), True, 'import numpy as np\n'), ((8106, 8139), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(self.nbins + 1)'], {}), '(0, 1, self.nbins + 1)\n', (8117, 8139), True, 'import numpy as np\n'), ((8226, 8268), 'numpy.quantile', 'np.quantile', (['data[:, n][~sl[:, n]]'], {'q': 'grid'}), '(data[:, n][~sl[:, n]], q=grid)\n', (8237, 8268), True, 'import numpy as np\n'), ((8285, 8297), 'numpy.unique', 'np.unique', (['q'], {}), '(q)\n', (8294, 8297), True, 'import numpy as np\n'), ((1656, 1670), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (1664, 1670), True, 'import numpy as np\n'), ((2379, 2393), 'numpy.isnan', 'np.isnan', (['nans'], {}), '(nans)\n', (2387, 2393), True, 'import numpy as np\n'), ((6588, 6607), 'numpy.isnan', 'np.isnan', (['self.stds'], {}), '(self.stds)\n', (6596, 6607), True, 'import numpy as np\n'), ((8985, 9023), 'numpy.where', 'np.where', (['sl[:, n]', 'np.inf', 'data[:, n]'], {}), '(sl[:, n], np.inf, data[:, n])\n', (8993, 9023), True, 'import numpy as np\n')] |
#%%
import os
cwd = os.getcwd()
dir_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(dir_path)
import argparse
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import torchvision.utils
import numpy as np
import os.path
from scipy.io import loadmat
from vae_models import *
from utils import *
from args_python import *
from matplotlib import pyplot as plt
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import Dataset
import torchvision.transforms as transforms
from sklearn.model_selection import train_test_split
import hdf5storage
EulerN=3
QuaternionN=4
ScaleSpaceAndGainN=2
class CustomDataset(Dataset):
"""TensorDataset with support of transforms.
"""
def __init__(self, tensors, transform=None):
assert all(tensors[0].size(0) == tensor.size(0) for tensor in tensors)
self.tensors = tensors
self.transform = transform
def __getitem__(self, index):
x = self.tensors[0][index]
if self.transform:
x = self.transform(x)
y = self.tensors[1][index]
return x, y
def __len__(self):
return self.tensors[0].size(0)
#%%
def train(args, model, device, train_loader, optimizer, epoch, writer, Rbeta, zipped_vals, scheduler, kl_weight=None, anneal_rate=None):
model.train()
run_angle_loss = 0.0
run_recon_loss = 0.0
run_kl_loss = 0.0
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
mu, logvar, angle_gain_scale, in_data, output = model(data)
if args.UseQuaternionNotEuler:
R_est = quaternion2R(angle_gain_scale[:,0:QuaternionN])
R_target = quaternion2R(target[:,0:QuaternionN])
gt, pred, rot_loss = getlossrotation(True, R_est, R_target)
gain_scale_loss = getlossspacescale(angle_gain_scale[:,QuaternionN],target[:,QuaternionN]) + getlossgain(angle_gain_scale[:,QuaternionN+1],target[:,QuaternionN+1])
angle_loss = rot_loss + gain_scale_loss
else:
R_est = euler2R(angle_gain_scale[:,0:EulerN])
R_target = euler2R(target[:,0:EulerN])
gt, pred, rot_loss = getlossrotation(True, R_est, R_target)
gain_scale_loss = getlossspacescale(angle_gain_scale[:,EulerN],target[:,EulerN]) + getlossgain(angle_gain_scale[:,EulerN+1],target[:,EulerN+1])
angle_loss = rot_loss + gain_scale_loss
recon_loss = nn.MSELoss()(torch.flatten(output,1), torch.flatten(in_data,1))
kl_loss = (-0.5 * torch.sum(1 + logvar - mu.pow(2) - torch.exp(logvar)))/data.shape[0]
if args.test:
print("Ground truth : {} \n Predicted values : {}".format(torch.transpose(gt,1,2), pred))
# also need to show reconstructed images
break
run_angle_loss += angle_loss.item()
run_recon_loss += recon_loss.item()
run_kl_loss += kl_loss.item()
kl_weight = min(1.0, kl_weight + anneal_rate)
tot_loss = args.coeff_angle_loss*angle_loss + args.coeff_recon_loss*recon_loss + kl_weight*kl_loss
tot_loss.backward()
optimizer.step()
scheduler.step()
if (batch_idx+1) % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tAngle Loss: {:.8f}, Recon loss: {:.8f}, KL Loss: {:.8f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx * len(data) / len(train_loader.dataset), run_angle_loss/args.log_interval, run_recon_loss/args.log_interval, run_kl_loss/args.log_interval))
writer.add_scalar('Training/Angle_loss', run_angle_loss/args.log_interval, epoch*len(train_loader)+batch_idx)
writer.add_scalar('Training/Reconstruction_loss', run_recon_loss/args.log_interval, epoch*len(train_loader)+batch_idx)
writer.add_scalar('Training/KL_loss', run_kl_loss/args.log_interval, epoch*len(train_loader)+batch_idx)
writer.add_graph(model, data)
for tag, value in model.named_parameters():
tag = tag.replace('.', '/')
writer.add_histogram(tag, value.detach().cpu().numpy(), batch_idx+1)
writer.add_histogram(tag+'/grad', value.grad.detach().cpu().numpy(), batch_idx+1)
run_angle_loss = 0.0
run_recon_loss = 0.0
run_kl_loss = 0.0
return kl_weight
def validate(args, model, device, val_loader, Rbeta, zipped_vals):
model.eval()
val_angle_loss = 0.0
val_recon_loss = 0.0
val_kl_loss = 0.0
with torch.no_grad():
for data, target in val_loader:
data, target = data.to(device), target.to(device)
mu, logvar, angle_gain_scale, in_data, output = model(data)
if args.UseQuaternionNotEuler:
R_est = quaternion2R(angle_gain_scale[:,0:QuaternionN])
R_target = quaternion2R(target[:,0:QuaternionN])
gt, pred, rot_loss = getlossrotation(True, R_est, R_target)
gain_scale_loss = getlossspacescale(angle_gain_scale[:,QuaternionN],target[:,QuaternionN]) + getlossgain(angle_gain_scale[:,QuaternionN+1],target[:,QuaternionN+1])
loss_value = rot_loss + gain_scale_loss
else:
R_est = euler2R(angle_gain_scale[:,0:EulerN])
R_target = euler2R(target[:,0:EulerN])
gt, pred, rot_loss = getlossrotation(True, R_est, R_target)
gain_scale_loss = getlossspacescale(angle_gain_scale[:,EulerN],target[:,EulerN]) + getlossgain(angle_gain_scale[:,EulerN+1],target[:,EulerN+1])
loss_value = rot_loss + gain_scale_loss
val_angle_loss += loss_value
val_recon_loss += nn.MSELoss()(torch.flatten(output,1), torch.flatten(in_data,1))
val_kl_loss += -0.5 * torch.sum(1 + logvar - mu.pow(2) - torch.exp(logvar))
val_angle_loss /= len(val_loader)
val_recon_loss /= len(val_loader)
val_kl_loss /= len(val_loader)
print('\nValidation set: Angle loss: {:.8f}, Recon loss: {:.8f}, KL loss: {:.8f}\n'.format(val_angle_loss.item(), val_recon_loss.item(), val_kl_loss.item()))
if args.test:
print("Ground truth : {} \n\n Predicted values : {} \n".format(torch.transpose(gt,1,2), pred))
return val_angle_loss, val_recon_loss, val_kl_loss
def test(args, model, device, test_loader, Rbeta, zipped_vals, data_stat):
if args.get_pred_only:
model.eval()
test_out_list = []
with torch.no_grad():
for data in test_loader:
data = data.to(device)
_, _, output, _, _ = model(data)
test_out_list.append(output.detach().numpy())
save_mat = np.concatenate(test_out_list)
hdf5storage.savemat(args.pred_folder+'/pred_labels.mat', {'labeldata':save_mat})
else:
model.eval()
test_angle_loss = 0.0
test_recon_loss = 0.0
test_kl_loss = 0.0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
mu, logvar, angle_gain_scale, in_data, output = model(data)
if args.UseQuaternionNotEuler:
R_est = quaternion2R(angle_gain_scale[:,0:QuaternionN])
R_target = quaternion2R(target[:,0:QuaternionN])
gt, pred, rot_loss = getlossrotation(True, R_est, R_target)
gain_scale_loss = getlossspacescale(angle_gain_scale[:,QuaternionN],target[:,QuaternionN]) + getlossgain(angle_gain_scale[:,QuaternionN+1],target[:,QuaternionN+1])
loss_value = rot_loss + gain_scale_loss
else:
R_est = euler2R(angle_gain_scale[:,0:EulerN])
R_target = euler2R(target[:,0:EulerN])
gt, pred, rot_loss = getlossrotation(True, R_est, R_target)
gain_scale_loss = getlossspacescale(angle_gain_scale[:,EulerN],target[:,EulerN]) + getlossgain(angle_gain_scale[:,EulerN+1],target[:,EulerN+1])
loss_value = rot_loss + gain_scale_loss
test_angle_loss += loss_value
test_recon_loss += nn.MSELoss()(torch.flatten(output,1), torch.flatten(in_data,1))
test_kl_loss += -0.5 * torch.sum(1 + logvar - mu.pow(2) - torch.exp(logvar))
test_angle_loss /= len(test_loader)
test_recon_loss /= len(test_loader)
test_kl_loss /= len(test_loader)
print('\nTest set: Angle loss: {:.8f}, Recon loss: {:.8f}, KL loss: {:.8f}\n'.format(test_angle_loss.item(), test_recon_loss.item(), test_kl_loss.item()))
if args.test:
print("Ground truth : {} \n\n Predicted values : {} \n".format(torch.transpose(gt,1,2), pred))
for data, target in test_loader:
data, target = data.to(device), target.to(device)
_, _, _, in_data, output_net = model(data)
output = torch.reshape(output_net[0:64,:], (64, data.shape[1], data.shape[2], data.shape[3]))
data_unnorm = torch.zeros_like(data)
data_unnorm[0:64,:,:,:] = data[0:64,:,:,:]*data_stat[1] + data_stat[0]
output[0:64,:,:,:] = output[0:64,:,:,:]*data_stat[1] + data_stat[0]
grid = torchvision.utils.make_grid(data_unnorm[0:64,:,:,:].detach())
matplotlib_imshow(grid, name="org_image.png", one_channel=True)
grid = torchvision.utils.make_grid(output[0:64,:,:,:].detach())
matplotlib_imshow(grid, name="vae_recon.png", one_channel=True)
# latent space interpolation between 2 images from test-dataset
start = [0,2,4,6,8,10]
dest = [30,32,34,36,38,40]
alpha = np.linspace(0,1,11)
dec_out = torch.zeros((len(alpha)*len(start), data.shape[1], data.shape[2], data.shape[3]))
for ii in range(len(start)):
data_interp1 = torch.unsqueeze(data[start[ii],:,:,:],dim=0)
data_interp2 = torch.unsqueeze(data[dest[ii],:,:,:],dim=0)
z_mu1, z_logvar1, z_euler1, _, dec_out1 = model(data_interp1)
z_mu2, z_logvar2, z_euler2, _, dec_out2 = model(data_interp2)
std1 = torch.exp(0.5*z_logvar1)
eps1 = torch.randn_like(std1)
rep1 = z_mu1 + eps1*std1
std2 = torch.exp(0.5*z_logvar2)
eps2 = torch.randn_like(std2)
rep2 = z_mu2 + eps2*std2
for a in range(len(alpha)):
z_euler_interp = (1-alpha[a])*z_euler1 + alpha[a]*z_euler2
feat_vec_interp = torch.cat([z_euler_interp, rep2],dim=1)
lin_out_interp = model.dec_in(feat_vec_interp)
lin_out_interp = torch.reshape(lin_out_interp, (-1,model.ch_factor_6out6,7,7))
d_out = model.decoder(lin_out_interp)
dec_out[(len(alpha)*ii)+a,:,:,:] = torch.squeeze(d_out)
# random sampling of latent space by fixing euler angle fed to it.
dec_sample = torch.zeros_like(data[0:len(alpha),:,:,:])
for idx in range(len(alpha)):
rep_sample = torch.randn_like(std1)
z_euler1 = torch.tensor([[0.39644146, 0.75766391, 0.77631556, 1.00424026, 1.0780347]], device=rep_sample.device)
feat_vec_interp = torch.cat([z_euler1, rep_sample],dim=1)
lin_out_interp = model.dec_in(feat_vec_interp)
lin_out_interp = torch.reshape(lin_out_interp, (-1,model.ch_factor_6out6,7,7))
d_out = model.decoder(lin_out_interp)
dec_sample[idx,:,:,:] = torch.squeeze(d_out)
grid = torchvision.utils.make_grid(dec_out.detach(),nrow=len(alpha))
matplotlib_imshow(grid, name="interpolations.png", one_channel=True)
grid = torchvision.utils.make_grid(dec_sample.detach(),len(alpha))
matplotlib_imshow(grid, name="sample_from_gaussian.png", one_channel=True)
break
def main():
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=100, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=600, metavar='N',
help='number of epochs to train (default: 600)')
parser.add_argument('--no-cuda', action='store_false', default=False,
help='disables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=100, metavar='N',
help='how many batches to wait before logging training status')
parser.add_argument('--arch', default='EulerGainConvVAE',help='the architecture to use. options are VGG, MLP for now. Can add more')
parser.add_argument('--UseQuaternionNotEuler', action='store_true', default=False, help='give this flag in order to use the Quaternion representation, otherwise the Euler angles representation will be used')
parser.add_argument('--ScaleSpaceMin', type=float, default=0.8, help='minimum value of the space scaling')
parser.add_argument('--ScaleSpaceMax', type=float, default=1.2, help='maximum value of the space scaling')
parser.add_argument('--GainMin', type=float, default=0.8, help='minimum value of the gain')
parser.add_argument('--GainMax', type=float, default=1.2, help='maximum value of the gain')
parser.add_argument('--RootDirectory4Data', default='./', help='the name of the root director for the data')
parser.add_argument('--carve_val', action='store_false', default=True, help='Whether validation set has to be carved out from the training set. Default is true')
parser.add_argument('--test', action='store_true', default=False, help='Whether train or test mode. Default is train mode.')
parser.add_argument('--coeff_angle_loss', type=float, default=1, help='Lagrangian multiplier for the angle loss term')
parser.add_argument('--coeff_recon_loss', type=float, default=2, help='Lagrangian multiplier for the reconstruction loss term')
parser.add_argument('--coeff_kl_loss', type=float, default=1, help='Lagrangian multiplier for the KL divergence loss term')
parser.add_argument('--get_pred_only', action='store_true', default=False, help='Get only predictions from images')
parser.add_argument('--pred_folder', default='./', help='Directory of file with test images.')
args = parser.parse_args()
# args=Args()
#
use_cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
device = torch.device("cuda" if use_cuda else "cpu")
trainingdirectory = args.RootDirectory4Data+"/"+"training"
trainingimagefile="imagefile.mat"
traininglabelfile="labelfile.mat"
train_images = hdf5storage.loadmat(os.path.join(trainingdirectory, trainingimagefile))['imagedata']
train_labels = hdf5storage.loadmat(os.path.join(trainingdirectory, traininglabelfile))['labeldata']
if args.carve_val:
print("Carving out validation set from training set")
train_images, val_images, train_labels, val_labels = train_test_split(train_images, train_labels, test_size=0.1, random_state=42)
else:
print("Loading validation set")
validationdirectory = args.RootDirectory4Data+"/"+"validation"
validationimagefile="imagefile.mat"
validationlabelfile="labelfile.mat"
val_images = hdf5storage.loadmat(os.path.join(validationdirectory, validationimagefile))['imagedata']
val_labels = hdf5storage.loadmat(os.path.join(validationdirectory, validationlabelfile))['labeldata']
train_images = np.expand_dims(train_images,1)
val_images = np.expand_dims(val_images,1)
mean = np.mean(train_images)
std = np.std(train_images)
data_stat = [mean, std]
print("Dataset mean is {}".format(mean))
print("Dataset std is {}".format(std))
norm_train_images = (train_images - mean)/std
norm_val_images = (val_images - mean)/std
kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
train_dataset = torch.utils.data.TensorDataset(torch.Tensor(norm_train_images), torch.Tensor(train_labels))
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, **kwargs)
val_dataset = torch.utils.data.TensorDataset(torch.Tensor(norm_val_images), torch.Tensor(val_labels))
val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=args.test_batch_size, shuffle=True, **kwargs)
# torch.autograd.set_detect_anomaly(True)
if args.arch == "EulerGainConvVAE":
model = EulerGainConvVAE(args).to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=5e-4, amsgrad=True)
scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=1e-5, cycle_momentum=False, steps_per_epoch=len(train_loader), epochs=100)
'''
STILL IN DEVELOPMENT
if args.arch == "EulerGainVAE":
model = EulerGainVAE(args).to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=5e-4, amsgrad=True)
scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=1e-5, cycle_momentum=False, steps_per_epoch=len(train_loader), epochs=args.epochs)
if args.arch == "EulerGainConvVAE2":
model = EulerGainConvVAE2(args).to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=5e-4, amsgrad=True)
scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=1e-5, cycle_momentum=False, steps_per_epoch=len(train_loader), epochs=100)
'''
if args.UseQuaternionNotEuler:
ckpts_dir_name = f"checkpoints{args.RootDirectory4Data[7:]}/Quaternion_{args.epochs}/{args.arch}"
log_dir = f"runs{args.RootDirectory4Data[7:]}/Quaternion_{args.epochs}/{args.arch}"
else:
ckpts_dir_name = f"checkpoints{args.RootDirectory4Data[7:]}/Euler_{args.epochs}/{args.arch}"
log_dir = f"runs{args.RootDirectory4Data[7:]}/Euler_{args.epochs}/{args.arch}"
# load data
if args.get_pred_only:
testingdirectory = args.pred_folder
testingimagefile="imagefile.mat"
test_images = hdf5storage.loadmat(os.path.join(testingdirectory, testingimagefile))['imagedata']
test_images = np.expand_dims(test_images,1)
norm_test_images = (test_images - mean)/std
test_dataset = torch.utils.data.TensorDataset(torch.Tensor(norm_test_images))
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=args.test_batch_size, shuffle=False, **kwargs)
model.load_state_dict(torch.load(f"{ckpts_dir_name}/angle_regress_{args.epochs}.pt")) # make sure to load from latest checkpoint
print("Test set predictions\n")
zipped_vals = None
Rbeta = None
test(args, model, device, test_loader, Rbeta, zipped_vals, data_stat)
else:
testingdirectory = args.RootDirectory4Data+"/"+"testing"
testingimagefile="imagefile.mat"
testinglabelfile="labelfile.mat"
test_images = hdf5storage.loadmat(os.path.join(testingdirectory, testingimagefile))['imagedata']
test_labels = hdf5storage.loadmat(os.path.join(testingdirectory, testinglabelfile))['labeldata']
test_images = np.expand_dims(test_images,1)
norm_test_images = (test_images - mean)/std
test_dataset = torch.utils.data.TensorDataset(torch.Tensor(norm_test_images), torch.Tensor(test_labels))
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=args.test_batch_size, shuffle=True, **kwargs)
# model.load_state_dict(torch.load(f"{ckpts_dir_name}/angle_regress_300.pt")) # make sure to load from latest checkpoint
os.makedirs(ckpts_dir_name, exist_ok=True)
writer = SummaryWriter(log_dir=log_dir,flush_secs=10)
Rbeta=None
zipped_vals=None
if not args.test:
kl_weight = 0.1
anneal_rate = (1.0 - 0.1) / (10 * len(train_loader))
for epoch in range(1, args.epochs + 1):
if (epoch-1)%100==0:
kl_weight=0.1
scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=1e-5, cycle_momentum=False, steps_per_epoch=len(train_loader), epochs=100)
kl_weight = train(args, model, device, train_loader, optimizer, epoch, writer, Rbeta, zipped_vals, scheduler, kl_weight, anneal_rate)
val_angle_loss, val_recon_loss, val_kl_loss = validate(args, model, device, val_loader, Rbeta, zipped_vals)
writer.add_scalar('Validation/Angle_loss', val_angle_loss, epoch)
writer.add_scalar('Validation/Reconstruction_loss', val_recon_loss, epoch)
writer.add_scalar('Validation/KL_loss', val_kl_loss, epoch)
if epoch%(args.epochs/10)==0:
torch.save(model.state_dict(),f"{ckpts_dir_name}/angle_regress_{epoch}.pt")
writer.close()
else:
model.load_state_dict(torch.load(f"{ckpts_dir_name}/angle_regress_{args.epochs}.pt")) # make sure to load from latest checkpoint
print("Test set predictions\n")
test(args, model, device, test_loader, Rbeta, zipped_vals, data_stat)
if __name__ == '__main__':
main()
#%%
#####################################
# visualize few samples of the data
#####################################
# trainingdirectory="./data_big_Haar0.2/training"
# testingdirectory="./data_big_Haar0.2/testing"
# trainingimagefile="imagefile.mat"
# testingimagefile="imagefile.mat"
# traininglabelfile="labelfile.mat"
# testinglabelfile="labelfile.mat"
# #read the Matlab .mat files
# train_images = hdf5storage.loadmat(os.path.join(trainingdirectory, trainingimagefile))['imagedata']
# train_labels = hdf5storage.loadmat(os.path.join(trainingdirectory, traininglabelfile))['labeldata']
# test_images = hdf5storage.loadmat(os.path.join(testingdirectory, testingimagefile))['imagedata']
# test_labels = hdf5storage.loadmat(os.path.join(testingdirectory, testinglabelfile))['labeldata']
# train_images = np.expand_dims(train_images,1)
# test_images = np.expand_dims(test_images,1)
# use_cuda = False
# kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
# train_dataset = CustomDataset(tensors=(torch.Tensor(train_images), torch.Tensor(train_labels)))
# train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=24, shuffle=True, **kwargs, drop_last=False)
# for batch_idx, (data, target) in enumerate(train_loader):
# # print(data.shape)
# grid = torchvision.utils.make_grid(data)
# matplotlib_imshow(grid, one_channel=True)
# # print(target.numpy())
# break
# %%
###########################
# train test split of data
###########################
# import numpy as np
# import hdf5storage
# from sklearn.model_selection import train_test_split
# images = hdf5storage.loadmat("imagefile1.mat")["imagedata"]
# labels = hdf5storage.loadmat("labelfile.mat")["labeldata"]
# train_images, test_images, train_labels, test_labels = train_test_split(images, labels, test_size=0.1, random_state=42)
# print(train_images.shape)
# print(test_images.shape)
# print(train_labels.shape)
# print(test_labels.shape)
# hdf5storage.savemat('./training/imagefile.mat',{"imagedata":train_images})
# hdf5storage.savemat('./training/labelfile.mat',{"labeldata":train_labels})
# hdf5storage.savemat('./testing/imagefile.mat',{"imagedata":test_images})
# hdf5storage.savemat('./testing/labelfile.mat',{"labeldata":test_labels})
# test_images, val_images, test_labels, val_labels = train_test_split(val_images, val_labels, test_size=0.5, random_state=42)
# hdf5storage.savemat('./validation/imagefile.mat',{"imagedata":val_images})
# hdf5storage.savemat('./validation/labelfile.mat',{"labeldata":val_labels})
# %%
###########################
# read from tf events file
###########################
# import numpy as np
# from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
# import matplotlib as mpl
# import matplotlib.pyplot as plt
# import hdf5storage
# tf_size_guidance = {'scalars':10000}
# event_acc = EventAccumulator('./events.out.tfevents.1582062336.superman.11982.0', tf_size_guidance)
# event_acc.Reload()
# training_accuracies = event_acc.Scalars('training_loss')
# validation_accuracies = event_acc.Scalars('validation_loss')
# steps_train = len(training_accuracies)
# y_train = np.zeros([steps_train, 1])
# steps_val = len(validation_accuracies)
# y_val = np.zeros([steps_val, 1])
# for i in range(steps_train):
# y_train[i, 0] = training_accuracies[i][2] # value
# for i in range(steps_val):
# y_val[i, 0] = validation_accuracies[i][2] # value
# hdf5storage.savemat('./training_curve.mat',{'values':y_train})
# hdf5storage.savemat('./validation_curve.mat',{'values':y_val})
#%%
######################################################
# plot train val curves with x, y labels and title
######################################################
# import numpy as np
# from matplotlib import pyplot as plt
# train_file_name = 'Training_recon_loss.csv'
# val_file_name = 'Val_recon_loss.csv'
# train_data = np.genfromtxt(train_file_name, delimiter=',')
# train_data = train_data[1:,:]
# val_data = np.genfromtxt(val_file_name, delimiter=',')
# val_data = val_data[1:,:]
# plt.figure()
# plt.plot(train_data[:,1], train_data[:,2])
# plt.ylim(0.01,0.1)
# plt.title('Training Reconstruction loss curve')
# plt.xlabel("Iterations")
# plt.ylabel("Loss")
# plt.savefig('train_recon_loss.png')
# plt.figure()
# plt.plot(val_data[:,1], val_data[:,2])
# plt.ylim(0.01,0.1)
# plt.title('Validation Reconstruction loss curve')
# plt.xlabel("Epochs")
# plt.ylabel("Loss")
# plt.savefig('val_recon_loss.png')
# %%
# visualize real samples
#import torch, torchvision, hdf5storage
#from matplotlib import pyplot as plt
#images = hdf5storage.loadmat('imagefile.mat')['imagedata']
#img_tensor = torch.Tensor(images[0:64,:])
#img_tensor = torch.unsqueeze(img_tensor, 1)
#grid = torchvision.utils.make_grid(img_tensor, nrow=8)
#grid = grid.mean(dim=0)
#npimg = grid.cpu().numpy()
#str_name = "real_images.png"
#plt.imsave(str_name, npimg, cmap="Greys") | [
"torch.exp",
"torch.nn.MSELoss",
"torch.cuda.is_available",
"torch.squeeze",
"numpy.mean",
"torch.utils.tensorboard.SummaryWriter",
"argparse.ArgumentParser",
"torch.unsqueeze",
"numpy.linspace",
"numpy.concatenate",
"torch.zeros_like",
"sklearn.model_selection.train_test_split",
"torch.Tens... | [((20, 31), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (29, 31), False, 'import os\n'), ((88, 106), 'os.chdir', 'os.chdir', (['dir_path'], {}), '(dir_path)\n', (96, 106), False, 'import os\n'), ((60, 86), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (76, 86), False, 'import os\n'), ((12495, 12555), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""PyTorch MNIST Example"""'}), "(description='PyTorch MNIST Example')\n", (12518, 12555), False, 'import argparse\n'), ((15337, 15365), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (15354, 15365), False, 'import torch\n'), ((15380, 15423), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (15392, 15423), False, 'import torch\n'), ((16456, 16487), 'numpy.expand_dims', 'np.expand_dims', (['train_images', '(1)'], {}), '(train_images, 1)\n', (16470, 16487), True, 'import numpy as np\n'), ((16504, 16533), 'numpy.expand_dims', 'np.expand_dims', (['val_images', '(1)'], {}), '(val_images, 1)\n', (16518, 16533), True, 'import numpy as np\n'), ((16549, 16570), 'numpy.mean', 'np.mean', (['train_images'], {}), '(train_images)\n', (16556, 16570), True, 'import numpy as np\n'), ((16581, 16601), 'numpy.std', 'np.std', (['train_images'], {}), '(train_images)\n', (16587, 16601), True, 'import numpy as np\n'), ((17020, 17118), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(True)'}), '(train_dataset, batch_size=args.batch_size,\n shuffle=True, **kwargs)\n', (17047, 17118), False, 'import torch\n'), ((17238, 17339), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['val_dataset'], {'batch_size': 'args.test_batch_size', 'shuffle': '(True)'}), '(val_dataset, batch_size=args.test_batch_size,\n shuffle=True, **kwargs)\n', (17265, 17339), False, 'import torch\n'), ((4752, 4767), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4765, 4767), False, 'import torch\n'), ((6947, 6976), 'numpy.concatenate', 'np.concatenate', (['test_out_list'], {}), '(test_out_list)\n', (6961, 6976), True, 'import numpy as np\n'), ((6986, 7073), 'hdf5storage.savemat', 'hdf5storage.savemat', (["(args.pred_folder + '/pred_labels.mat')", "{'labeldata': save_mat}"], {}), "(args.pred_folder + '/pred_labels.mat', {'labeldata':\n save_mat})\n", (7005, 7073), False, 'import hdf5storage\n'), ((15307, 15332), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (15330, 15332), False, 'import torch\n'), ((15928, 16004), 'sklearn.model_selection.train_test_split', 'train_test_split', (['train_images', 'train_labels'], {'test_size': '(0.1)', 'random_state': '(42)'}), '(train_images, train_labels, test_size=0.1, random_state=42)\n', (15944, 16004), False, 'from sklearn.model_selection import train_test_split\n'), ((16940, 16971), 'torch.Tensor', 'torch.Tensor', (['norm_train_images'], {}), '(norm_train_images)\n', (16952, 16971), False, 'import torch\n'), ((16973, 16999), 'torch.Tensor', 'torch.Tensor', (['train_labels'], {}), '(train_labels)\n', (16985, 16999), False, 'import torch\n'), ((17164, 17193), 'torch.Tensor', 'torch.Tensor', (['norm_val_images'], {}), '(norm_val_images)\n', (17176, 17193), False, 'import torch\n'), ((17195, 17219), 'torch.Tensor', 'torch.Tensor', (['val_labels'], {}), '(val_labels)\n', (17207, 17219), False, 'import torch\n'), ((19146, 19176), 'numpy.expand_dims', 'np.expand_dims', (['test_images', '(1)'], {}), '(test_images, 1)\n', (19160, 19176), True, 'import numpy as np\n'), ((19337, 19440), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['test_dataset'], {'batch_size': 'args.test_batch_size', 'shuffle': '(False)'}), '(test_dataset, batch_size=args.test_batch_size,\n shuffle=False, **kwargs)\n', (19364, 19440), False, 'import torch\n'), ((20142, 20172), 'numpy.expand_dims', 'np.expand_dims', (['test_images', '(1)'], {}), '(test_images, 1)\n', (20156, 20172), True, 'import numpy as np\n'), ((20360, 20462), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['test_dataset'], {'batch_size': 'args.test_batch_size', 'shuffle': '(True)'}), '(test_dataset, batch_size=args.test_batch_size,\n shuffle=True, **kwargs)\n', (20387, 20462), False, 'import torch\n'), ((20614, 20656), 'os.makedirs', 'os.makedirs', (['ckpts_dir_name'], {'exist_ok': '(True)'}), '(ckpts_dir_name, exist_ok=True)\n', (20625, 20656), False, 'import os\n'), ((20674, 20719), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', ([], {'log_dir': 'log_dir', 'flush_secs': '(10)'}), '(log_dir=log_dir, flush_secs=10)\n', (20687, 20719), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((2607, 2619), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (2617, 2619), True, 'import torch.nn as nn\n'), ((2620, 2644), 'torch.flatten', 'torch.flatten', (['output', '(1)'], {}), '(output, 1)\n', (2633, 2644), False, 'import torch\n'), ((2645, 2670), 'torch.flatten', 'torch.flatten', (['in_data', '(1)'], {}), '(in_data, 1)\n', (2658, 2670), False, 'import torch\n'), ((6723, 6738), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6736, 6738), False, 'import torch\n'), ((7206, 7221), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7219, 7221), False, 'import torch\n'), ((9268, 9358), 'torch.reshape', 'torch.reshape', (['output_net[0:64, :]', '(64, data.shape[1], data.shape[2], data.shape[3])'], {}), '(output_net[0:64, :], (64, data.shape[1], data.shape[2], data.\n shape[3]))\n', (9281, 9358), False, 'import torch\n'), ((9379, 9401), 'torch.zeros_like', 'torch.zeros_like', (['data'], {}), '(data)\n', (9395, 9401), False, 'import torch\n'), ((10059, 10080), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(11)'], {}), '(0, 1, 11)\n', (10070, 10080), True, 'import numpy as np\n'), ((15603, 15653), 'os.path.join', 'os.path.join', (['trainingdirectory', 'trainingimagefile'], {}), '(trainingdirectory, trainingimagefile)\n', (15615, 15653), False, 'import os\n'), ((15707, 15757), 'os.path.join', 'os.path.join', (['trainingdirectory', 'traininglabelfile'], {}), '(trainingdirectory, traininglabelfile)\n', (15719, 15757), False, 'import os\n'), ((19283, 19313), 'torch.Tensor', 'torch.Tensor', (['norm_test_images'], {}), '(norm_test_images)\n', (19295, 19313), False, 'import torch\n'), ((19468, 19530), 'torch.load', 'torch.load', (['f"""{ckpts_dir_name}/angle_regress_{args.epochs}.pt"""'], {}), "(f'{ckpts_dir_name}/angle_regress_{args.epochs}.pt')\n", (19478, 19530), False, 'import torch\n'), ((20279, 20309), 'torch.Tensor', 'torch.Tensor', (['norm_test_images'], {}), '(norm_test_images)\n', (20291, 20309), False, 'import torch\n'), ((20311, 20336), 'torch.Tensor', 'torch.Tensor', (['test_labels'], {}), '(test_labels)\n', (20323, 20336), False, 'import torch\n'), ((5938, 5950), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (5948, 5950), True, 'import torch.nn as nn\n'), ((5951, 5975), 'torch.flatten', 'torch.flatten', (['output', '(1)'], {}), '(output, 1)\n', (5964, 5975), False, 'import torch\n'), ((5976, 6001), 'torch.flatten', 'torch.flatten', (['in_data', '(1)'], {}), '(in_data, 1)\n', (5989, 6001), False, 'import torch\n'), ((6461, 6486), 'torch.transpose', 'torch.transpose', (['gt', '(1)', '(2)'], {}), '(gt, 1, 2)\n', (6476, 6486), False, 'import torch\n'), ((10273, 10321), 'torch.unsqueeze', 'torch.unsqueeze', (['data[start[ii], :, :, :]'], {'dim': '(0)'}), '(data[start[ii], :, :, :], dim=0)\n', (10288, 10321), False, 'import torch\n'), ((10349, 10396), 'torch.unsqueeze', 'torch.unsqueeze', (['data[dest[ii], :, :, :]'], {'dim': '(0)'}), '(data[dest[ii], :, :, :], dim=0)\n', (10364, 10396), False, 'import torch\n'), ((10574, 10600), 'torch.exp', 'torch.exp', (['(0.5 * z_logvar1)'], {}), '(0.5 * z_logvar1)\n', (10583, 10600), False, 'import torch\n'), ((10622, 10644), 'torch.randn_like', 'torch.randn_like', (['std1'], {}), '(std1)\n', (10638, 10644), False, 'import torch\n'), ((10711, 10737), 'torch.exp', 'torch.exp', (['(0.5 * z_logvar2)'], {}), '(0.5 * z_logvar2)\n', (10720, 10737), False, 'import torch\n'), ((10759, 10781), 'torch.randn_like', 'torch.randn_like', (['std2'], {}), '(std2)\n', (10775, 10781), False, 'import torch\n'), ((11582, 11604), 'torch.randn_like', 'torch.randn_like', (['std1'], {}), '(std1)\n', (11598, 11604), False, 'import torch\n'), ((11632, 11737), 'torch.tensor', 'torch.tensor', (['[[0.39644146, 0.75766391, 0.77631556, 1.00424026, 1.0780347]]'], {'device': 'rep_sample.device'}), '([[0.39644146, 0.75766391, 0.77631556, 1.00424026, 1.0780347]],\n device=rep_sample.device)\n', (11644, 11737), False, 'import torch\n'), ((11768, 11808), 'torch.cat', 'torch.cat', (['[z_euler1, rep_sample]'], {'dim': '(1)'}), '([z_euler1, rep_sample], dim=1)\n', (11777, 11808), False, 'import torch\n'), ((11905, 11969), 'torch.reshape', 'torch.reshape', (['lin_out_interp', '(-1, model.ch_factor_6out6, 7, 7)'], {}), '(lin_out_interp, (-1, model.ch_factor_6out6, 7, 7))\n', (11918, 11969), False, 'import torch\n'), ((12062, 12082), 'torch.squeeze', 'torch.squeeze', (['d_out'], {}), '(d_out)\n', (12075, 12082), False, 'import torch\n'), ((16257, 16311), 'os.path.join', 'os.path.join', (['validationdirectory', 'validationimagefile'], {}), '(validationdirectory, validationimagefile)\n', (16269, 16311), False, 'import os\n'), ((16367, 16421), 'os.path.join', 'os.path.join', (['validationdirectory', 'validationlabelfile'], {}), '(validationdirectory, validationlabelfile)\n', (16379, 16421), False, 'import os\n'), ((19061, 19109), 'os.path.join', 'os.path.join', (['testingdirectory', 'testingimagefile'], {}), '(testingdirectory, testingimagefile)\n', (19073, 19109), False, 'import os\n'), ((19947, 19995), 'os.path.join', 'os.path.join', (['testingdirectory', 'testingimagefile'], {}), '(testingdirectory, testingimagefile)\n', (19959, 19995), False, 'import os\n'), ((20052, 20100), 'os.path.join', 'os.path.join', (['testingdirectory', 'testinglabelfile'], {}), '(testingdirectory, testinglabelfile)\n', (20064, 20100), False, 'import os\n'), ((21921, 21983), 'torch.load', 'torch.load', (['f"""{ckpts_dir_name}/angle_regress_{args.epochs}.pt"""'], {}), "(f'{ckpts_dir_name}/angle_regress_{args.epochs}.pt')\n", (21931, 21983), False, 'import torch\n'), ((2861, 2886), 'torch.transpose', 'torch.transpose', (['gt', '(1)', '(2)'], {}), '(gt, 1, 2)\n', (2876, 2886), False, 'import torch\n'), ((8479, 8491), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (8489, 8491), True, 'import torch.nn as nn\n'), ((8492, 8516), 'torch.flatten', 'torch.flatten', (['output', '(1)'], {}), '(output, 1)\n', (8505, 8516), False, 'import torch\n'), ((8517, 8542), 'torch.flatten', 'torch.flatten', (['in_data', '(1)'], {}), '(in_data, 1)\n', (8530, 8542), False, 'import torch\n'), ((9034, 9059), 'torch.transpose', 'torch.transpose', (['gt', '(1)', '(2)'], {}), '(gt, 1, 2)\n', (9049, 9059), False, 'import torch\n'), ((11006, 11046), 'torch.cat', 'torch.cat', (['[z_euler_interp, rep2]'], {'dim': '(1)'}), '([z_euler_interp, rep2], dim=1)\n', (11015, 11046), False, 'import torch\n'), ((11152, 11216), 'torch.reshape', 'torch.reshape', (['lin_out_interp', '(-1, model.ch_factor_6out6, 7, 7)'], {}), '(lin_out_interp, (-1, model.ch_factor_6out6, 7, 7))\n', (11165, 11216), False, 'import torch\n'), ((11327, 11347), 'torch.squeeze', 'torch.squeeze', (['d_out'], {}), '(d_out)\n', (11340, 11347), False, 'import torch\n'), ((2732, 2749), 'torch.exp', 'torch.exp', (['logvar'], {}), '(logvar)\n', (2741, 2749), False, 'import torch\n'), ((6071, 6088), 'torch.exp', 'torch.exp', (['logvar'], {}), '(logvar)\n', (6080, 6088), False, 'import torch\n'), ((8617, 8634), 'torch.exp', 'torch.exp', (['logvar'], {}), '(logvar)\n', (8626, 8634), False, 'import torch\n')] |
import ctypes as ct
import numpy as np
import scipy.interpolate as interpolate
import sharpy.utils.controller_interface as controller_interface
import sharpy.utils.settings as settings
import sharpy.utils.control_utils as control_utils
import sharpy.utils.cout_utils as cout
import sharpy.structure.utils.lagrangeconstraints as lc
@controller_interface.controller
class TakeOffTrajectoryController(controller_interface.BaseController):
r"""
"""
controller_id = 'TakeOffTrajectoryController'
settings_types = dict()
settings_default = dict()
settings_description = dict()
settings_types['trajectory_input_file'] = 'str'
settings_default['trajectory_input_file'] = None
settings_description['trajectory_input_file'] = 'Route and file name of the trajectory file given as a csv with columns: time, x, y, z'
settings_types['dt'] = 'float'
settings_default['dt'] = None
settings_description['dt'] = 'Time step of the simulation'
settings_types['trajectory_method'] = 'str'
settings_default['trajectory_method'] = 'lagrange'
settings_description['trajectory_method'] = (
'Trajectory controller method. For now, "lagrange" is the supported option')
settings_types['controlled_constraint'] = 'str'
settings_default['controlled_constraint'] = None
settings_description['controlled_constraint'] = ('Name of the controlled constraint in the multibody context' +
' Usually, it is something like `constraint_00`.')
settings_types['controller_log_route'] = 'str'
settings_default['controller_log_route'] = './output/'
settings_description['controller_log_route'] = (
'Directory where the log will be stored')
settings_types['write_controller_log'] = 'bool'
settings_default['write_controller_log'] = True
settings_description['write_controller_log'] = (
'Controls if the log from the controller is written or not.')
settings_types['free_trajectory_structural_solver'] = 'str'
settings_default['free_trajectory_structural_solver'] = ''
settings_description['free_trajectory_structural_solver'] = (
'If different than and empty string, the structural solver' +
' will be changed after the end of the trajectory has been reached')
settings_types['free_trajectory_structural_substeps'] = 'int'
settings_default['free_trajectory_structural_substeps'] = 0
settings_description['free_trajectory_structural_substeps'] = (
'Controls the structural solver' +
' structural substeps once the end of the trajectory has been reached')
settings_types['initial_ramp_length_structural_substeps'] = 'int'
settings_default['initial_ramp_length_structural_substeps'] = 10
settings_description['initial_ramp_length_structural_substeps'] = (
'Controls the number of timesteps that are used to increase the' +
' structural substeps from 0')
settings_table = settings.SettingsTable()
__doc__ += settings_table.generate(settings_types,
settings_default,
settings_description)
def __init__(self):
self.in_dict = None
self.data = None
self.settings = None
self.input_history = None
self.trajectory_interp = None
self.trajectory_vel_interp = None
self.t_limits = np.zeros((2,))
self.controlled_body = None
self.controlled_node = None
self.log = None
def initialise(self, in_dict, controller_id=None):
self.in_dict = in_dict
settings.to_custom_types(self.in_dict,
self.settings_types,
self.settings_default)
self.settings = self.in_dict
self.controller_id = controller_id
if self.settings['write_controller_log']:
# TODO substitute for table writer in cout_utils.
self.log = open(self.settings['controller_log_route'] +
'/' + self.controller_id + '.log.csv', 'w+')
self.log.write(('#'+ 1*'{:>2},' + 6*'{:>12},' + '{:>12}\n').
format('tstep', 'time', 'Ref. state', 'state', 'Pcontrol', 'Icontrol', 'Dcontrol', 'control'))
self.log.flush()
# save input time history
try:
self.input_history = (
np.loadtxt(
self.settings['trajectory_input_file'], delimiter=','))
except OSError:
raise OSError('File {} not found in {}'.format(
self.settings['time_history_input_file'], self.controller_id))
self.process_trajectory()
def control(self, data, controlled_state):
r"""
Main routine of the controller.
Input is `data` (the self.data in the solver), and
`currrent_state` which is a dictionary with ['structural', 'aero']
time steps for the current iteration.
:param data: problem data containing all the information.
:param controlled_state: `dict` with two vars: `structural` and `aero`
containing the `timestep_info` that will be returned with the
control variables.
:returns: A `dict` with `structural` and `aero` time steps and control
input included.
"""
# get current state input
# note: with or without the -1?
time = (data.ts - 1)*self.settings['dt'].value
i_current = data.ts
try:
constraint = controlled_state['structural'].\
mb_dict[self.settings['controlled_constraint']]
except KeyError:
return controlled_state
except TypeError:
import pdb
pdb.set_trace()
if self.controlled_body is None or self.controlled_node is None:
self.controlled_body = constraint['body_number']
self.controlled_node = constraint['node_number']
# reset info to include only fresh info
controlled_state['info'] = dict()
# apply it where needed.
traj_command, end_of_traj = self.controller_wrapper(time)
if end_of_traj:
lc.remove_constraint(controlled_state['structural'].mb_dict,
self.settings['controlled_constraint'])
if not self.settings['free_trajectory_structural_solver'] == '':
controlled_state['info']['structural_solver'] = (
self.settings['free_trajectory_structural_solver'])
controlled_state['info']['structural_substeps'] = (
self.settings['free_trajectory_structural_substeps'])
return controlled_state
constraint['velocity'][:] = traj_command
if self.settings['write_controller_log']:
self.log.write(('{:>6d},'
+ 3*'{:>12.6f},'
+ '{:>12.6f}\n').format(i_current,
time,
traj_command[0],
traj_command[1],
traj_command[2]))
if self.settings['initial_ramp_length_structural_substeps'].value >= 0:
if (i_current <
self.settings['initial_ramp_length_structural_substeps'].value):
controlled_state['info']['structural_substeps'] = \
ct.c_int(i_current - 1)
elif (i_current ==
self.settings['initial_ramp_length_structural_substeps'].value):
controlled_state['info']['structural_substeps'] = None
return controlled_state
def process_trajectory(self, dxdt=True):
"""
See https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.interpolate.UnivariateSpline.html
"""
self.trajectory_interp = []
# Make sure s = 0.5 is ok.
self.t_limits[:] = (np.min(self.input_history[:, 0]),
np.max(self.input_history[:, 0]))
for i_dim in range(3):
self.trajectory_interp.append(
interpolate.UnivariateSpline(self.input_history[:, 0],
self.input_history[:, i_dim + 1],
k=1,
s=0.,
ext='raise'))
if dxdt:
self.trajectory_vel_interp = []
for i_dim in range(3):
self.trajectory_vel_interp.append(
self.trajectory_interp[i_dim].derivative())
def controller_wrapper(self, t):
output_traj = np.zeros((3,))
end_of_traj = False
if self.settings['trajectory_method'] == 'lagrange':
# check that t is in input limits
if self.t_limits[0] <= t <= self.t_limits[1]:
# return velocities
for i_dim in range(3):
output_traj[i_dim] = self.trajectory_vel_interp[i_dim](t)
else:
for i_dim in range(3):
output_traj[i_dim] = np.nan
end_of_traj = True
else:
raise NotImplementedError('The trajectory_method ' +
self.settings['trajectory_method'] +
' is not yet implemented.')
return output_traj, end_of_traj
def __exit__(self, *args):
self.log.close()
| [
"scipy.interpolate.UnivariateSpline",
"sharpy.utils.settings.SettingsTable",
"numpy.max",
"numpy.zeros",
"sharpy.structure.utils.lagrangeconstraints.remove_constraint",
"pdb.set_trace",
"numpy.min",
"ctypes.c_int",
"numpy.loadtxt",
"sharpy.utils.settings.to_custom_types"
] | [((2957, 2981), 'sharpy.utils.settings.SettingsTable', 'settings.SettingsTable', ([], {}), '()\n', (2979, 2981), True, 'import sharpy.utils.settings as settings\n'), ((3401, 3415), 'numpy.zeros', 'np.zeros', (['(2,)'], {}), '((2,))\n', (3409, 3415), True, 'import numpy as np\n'), ((3609, 3696), 'sharpy.utils.settings.to_custom_types', 'settings.to_custom_types', (['self.in_dict', 'self.settings_types', 'self.settings_default'], {}), '(self.in_dict, self.settings_types, self.\n settings_default)\n', (3633, 3696), True, 'import sharpy.utils.settings as settings\n'), ((8800, 8814), 'numpy.zeros', 'np.zeros', (['(3,)'], {}), '((3,))\n', (8808, 8814), True, 'import numpy as np\n'), ((4409, 4474), 'numpy.loadtxt', 'np.loadtxt', (["self.settings['trajectory_input_file']"], {'delimiter': '""","""'}), "(self.settings['trajectory_input_file'], delimiter=',')\n", (4419, 4474), True, 'import numpy as np\n'), ((6205, 6310), 'sharpy.structure.utils.lagrangeconstraints.remove_constraint', 'lc.remove_constraint', (["controlled_state['structural'].mb_dict", "self.settings['controlled_constraint']"], {}), "(controlled_state['structural'].mb_dict, self.settings[\n 'controlled_constraint'])\n", (6225, 6310), True, 'import sharpy.structure.utils.lagrangeconstraints as lc\n'), ((8049, 8081), 'numpy.min', 'np.min', (['self.input_history[:, 0]'], {}), '(self.input_history[:, 0])\n', (8055, 8081), True, 'import numpy as np\n'), ((8111, 8143), 'numpy.max', 'np.max', (['self.input_history[:, 0]'], {}), '(self.input_history[:, 0])\n', (8117, 8143), True, 'import numpy as np\n'), ((5766, 5781), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (5779, 5781), False, 'import pdb\n'), ((7526, 7549), 'ctypes.c_int', 'ct.c_int', (['(i_current - 1)'], {}), '(i_current - 1)\n', (7534, 7549), True, 'import ctypes as ct\n'), ((8235, 8352), 'scipy.interpolate.UnivariateSpline', 'interpolate.UnivariateSpline', (['self.input_history[:, 0]', 'self.input_history[:, i_dim + 1]'], {'k': '(1)', 's': '(0.0)', 'ext': '"""raise"""'}), "(self.input_history[:, 0], self.input_history[:,\n i_dim + 1], k=1, s=0.0, ext='raise')\n", (8263, 8352), True, 'import scipy.interpolate as interpolate\n')] |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
'''
Bert evaluation assessment method script.
'''
import math
import numpy as np
from .CRF import postprocess
class Accuracy():
'''
calculate accuracy
'''
def __init__(self):
self.acc_num = 0
self.total_num = 0
def update(self, logits, labels):
labels = labels.asnumpy()
labels = np.reshape(labels, -1)
logits = logits.asnumpy()
logit_id = np.argmax(logits, axis=-1)
self.acc_num += np.sum(labels == logit_id)
self.total_num += len(labels)
class F1():
'''
calculate F1 score
'''
def __init__(self, use_crf=False, num_labels=2):
self.TP = 0
self.FP = 0
self.FN = 0
self.use_crf = use_crf
self.num_labels = num_labels
def update(self, logits, labels):
'''
update F1 score
'''
labels = labels.asnumpy()
labels = np.reshape(labels, -1)
if self.use_crf:
backpointers, best_tag_id = logits
best_path = postprocess(backpointers, best_tag_id)
logit_id = []
for ele in best_path:
logit_id.extend(ele)
else:
logits = logits.asnumpy()
logit_id = np.argmax(logits, axis=-1)
logit_id = np.reshape(logit_id, -1)
pos_eva = np.isin(logit_id, [i for i in range(1, self.num_labels)])
pos_label = np.isin(labels, [i for i in range(1, self.num_labels)])
self.TP += np.sum(pos_eva&pos_label)
self.FP += np.sum(pos_eva&(~pos_label))
self.FN += np.sum((~pos_eva)&pos_label)
class SpanF1():
'''
calculate F1、precision and recall score in span manner for NER
'''
def __init__(self, use_crf=False, label2id=None):
self.TP = 0
self.FP = 0
self.FN = 0
self.use_crf = use_crf
self.label2id = label2id
if label2id is None:
raise ValueError("label2id info should not be empty")
self.id2label = {}
for key, value in label2id.items():
self.id2label[value] = key
def tag2span(self, ids):
'''
conbert ids list to span mode
'''
labels = np.array([self.id2label[id] for id in ids])
spans = []
prev_label = None
for idx, tag in enumerate(labels):
tag = tag.lower()
cur_label, label = tag[:1], tag[2:]
if cur_label in ('b', 's'):
spans.append((label, [idx, idx]))
elif cur_label in ('m', 'e') and prev_label in ('b', 'm') and label == spans[-1][0]:
spans[-1][1][1] = idx
elif cur_label == 'o':
pass
else:
spans.append((label, [idx, idx]))
prev_label = cur_label
return [(span[0], (span[1][0], span[1][1] + 1)) for span in spans]
def update(self, logits, labels):
'''
update span F1 score
'''
labels = labels.asnumpy()
labels = np.reshape(labels, -1)
if self.use_crf:
backpointers, best_tag_id = logits
best_path = postprocess(backpointers, best_tag_id)
logit_id = []
for ele in best_path:
logit_id.extend(ele)
else:
logits = logits.asnumpy()
logit_id = np.argmax(logits, axis=-1)
logit_id = np.reshape(logit_id, -1)
label_spans = self.tag2span(labels)
pred_spans = self.tag2span(logit_id)
for span in pred_spans:
if span in label_spans:
self.TP += 1
label_spans.remove(span)
else:
self.FP += 1
for span in label_spans:
self.FN += 1
class MCC():
'''
Calculate Matthews Correlation Coefficient
'''
def __init__(self):
self.TP = 0
self.FP = 0
self.FN = 0
self.TN = 0
def update(self, logits, labels):
'''
MCC update
'''
labels = labels.asnumpy()
labels = np.reshape(labels, -1)
labels = labels.astype(np.bool)
logits = logits.asnumpy()
logit_id = np.argmax(logits, axis=-1)
logit_id = np.reshape(logit_id, -1)
logit_id = logit_id.astype(np.bool)
ornot = logit_id ^ labels
self.TP += (~ornot & labels).sum()
self.FP += (ornot & ~labels).sum()
self.FN += (ornot & labels).sum()
self.TN += (~ornot & ~labels).sum()
def cal(self):
mcc = (self.TP*self.TN - self.FP*self.FN)/math.sqrt((self.TP+self.FP)*(self.TP+self.FN) *
(self.TN+self.FP)*(self.TN+self.FN))
return mcc
class Spearman_Correlation():
'''
Calculate Spearman Correlation Coefficient
'''
def __init__(self):
self.label = []
self.logit = []
def update(self, logits, labels):
labels = labels.asnumpy()
labels = np.reshape(labels, -1)
logits = logits.asnumpy()
logits = np.reshape(logits, -1)
self.label.append(labels)
self.logit.append(logits)
def cal(self):
'''
Calculate Spearman Correlation
'''
label = np.concatenate(self.label)
logit = np.concatenate(self.logit)
sort_label = label.argsort()[::-1]
sort_logit = logit.argsort()[::-1]
n = len(label)
d_acc = 0
for i in range(n):
d = np.where(sort_label == i)[0] - np.where(sort_logit == i)[0]
d_acc += d**2
ps = 1 - 6*d_acc/n/(n**2-1)
return ps
| [
"numpy.reshape",
"numpy.where",
"math.sqrt",
"numpy.argmax",
"numpy.sum",
"numpy.array",
"numpy.concatenate"
] | [((1001, 1023), 'numpy.reshape', 'np.reshape', (['labels', '(-1)'], {}), '(labels, -1)\n', (1011, 1023), True, 'import numpy as np\n'), ((1077, 1103), 'numpy.argmax', 'np.argmax', (['logits'], {'axis': '(-1)'}), '(logits, axis=-1)\n', (1086, 1103), True, 'import numpy as np\n'), ((1128, 1154), 'numpy.sum', 'np.sum', (['(labels == logit_id)'], {}), '(labels == logit_id)\n', (1134, 1154), True, 'import numpy as np\n'), ((1564, 1586), 'numpy.reshape', 'np.reshape', (['labels', '(-1)'], {}), '(labels, -1)\n', (1574, 1586), True, 'import numpy as np\n'), ((2140, 2167), 'numpy.sum', 'np.sum', (['(pos_eva & pos_label)'], {}), '(pos_eva & pos_label)\n', (2146, 2167), True, 'import numpy as np\n'), ((2185, 2213), 'numpy.sum', 'np.sum', (['(pos_eva & ~pos_label)'], {}), '(pos_eva & ~pos_label)\n', (2191, 2213), True, 'import numpy as np\n'), ((2233, 2261), 'numpy.sum', 'np.sum', (['(~pos_eva & pos_label)'], {}), '(~pos_eva & pos_label)\n', (2239, 2261), True, 'import numpy as np\n'), ((2855, 2898), 'numpy.array', 'np.array', (['[self.id2label[id] for id in ids]'], {}), '([self.id2label[id] for id in ids])\n', (2863, 2898), True, 'import numpy as np\n'), ((3668, 3690), 'numpy.reshape', 'np.reshape', (['labels', '(-1)'], {}), '(labels, -1)\n', (3678, 3690), True, 'import numpy as np\n'), ((4720, 4742), 'numpy.reshape', 'np.reshape', (['labels', '(-1)'], {}), '(labels, -1)\n', (4730, 4742), True, 'import numpy as np\n'), ((4836, 4862), 'numpy.argmax', 'np.argmax', (['logits'], {'axis': '(-1)'}), '(logits, axis=-1)\n', (4845, 4862), True, 'import numpy as np\n'), ((4882, 4906), 'numpy.reshape', 'np.reshape', (['logit_id', '(-1)'], {}), '(logit_id, -1)\n', (4892, 4906), True, 'import numpy as np\n'), ((5648, 5670), 'numpy.reshape', 'np.reshape', (['labels', '(-1)'], {}), '(labels, -1)\n', (5658, 5670), True, 'import numpy as np\n'), ((5722, 5744), 'numpy.reshape', 'np.reshape', (['logits', '(-1)'], {}), '(logits, -1)\n', (5732, 5744), True, 'import numpy as np\n'), ((5912, 5938), 'numpy.concatenate', 'np.concatenate', (['self.label'], {}), '(self.label)\n', (5926, 5938), True, 'import numpy as np\n'), ((5955, 5981), 'numpy.concatenate', 'np.concatenate', (['self.logit'], {}), '(self.logit)\n', (5969, 5981), True, 'import numpy as np\n'), ((1894, 1920), 'numpy.argmax', 'np.argmax', (['logits'], {'axis': '(-1)'}), '(logits, axis=-1)\n', (1903, 1920), True, 'import numpy as np\n'), ((1944, 1968), 'numpy.reshape', 'np.reshape', (['logit_id', '(-1)'], {}), '(logit_id, -1)\n', (1954, 1968), True, 'import numpy as np\n'), ((3998, 4024), 'numpy.argmax', 'np.argmax', (['logits'], {'axis': '(-1)'}), '(logits, axis=-1)\n', (4007, 4024), True, 'import numpy as np\n'), ((4048, 4072), 'numpy.reshape', 'np.reshape', (['logit_id', '(-1)'], {}), '(logit_id, -1)\n', (4058, 4072), True, 'import numpy as np\n'), ((5228, 5328), 'math.sqrt', 'math.sqrt', (['((self.TP + self.FP) * (self.TP + self.FN) * (self.TN + self.FP) * (self.TN +\n self.FN))'], {}), '((self.TP + self.FP) * (self.TP + self.FN) * (self.TN + self.FP) *\n (self.TN + self.FN))\n', (5237, 5328), False, 'import math\n'), ((6152, 6177), 'numpy.where', 'np.where', (['(sort_label == i)'], {}), '(sort_label == i)\n', (6160, 6177), True, 'import numpy as np\n'), ((6183, 6208), 'numpy.where', 'np.where', (['(sort_logit == i)'], {}), '(sort_logit == i)\n', (6191, 6208), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import os
import json
import pandas as pd
import re
import ir_thermography.thermometry as irt
import matplotlib.ticker as ticker
from scipy import interpolate
from scipy.signal import savgol_filter
from scipy import interpolate
import platform
base_path = r'C:\Users\erick\OneDrive\Documents\ucsd\Postdoc\research\data\firing_tests\heat_flux_calibration\IR Thermography Calibration'
# data_file = 'LT_GR008G_4mTorr-contact-shield_080PCT_60GAIN 2022-05-06_1'
data_file = 'LT_GR008G_6mTorr-contact-shield_100PCT_50GAIN 2022-05-04_1'
time_constant_1, time_constant_2 = 2.1148, 2.1148
emissivity = 1.0 - (36.9 / 100)
tc_min = 0.0
def correct_thermocouple_response(measured_temperature, measured_time, time_constant, debug=False):
n = len(measured_time)
k = int(n / 10)
k = k + 1 if k % 2 == 0 else k
T = savgol_filter(measured_temperature, k, 2)
dTdt = np.gradient(T, measured_time, edge_order=2)
if debug:
for ti, Ti, Ts, dti in zip(measured_time, measured_temperature, T, dTdt):
print(f'{ti:6.3f} s, T = {Ti:6.2f} °C, T_smooth: {Ts:6.3f} dT/dt = {dti:>5.3E}')
# dTdt = savgol_filter(dTdt, k, 3)
r = T + time_constant * dTdt
r = savgol_filter(r, k - 4, 3)
return r
def get_experiment_params(relative_path: str, filename: str):
# Read the experiment parameters
results_csv = os.path.join(relative_path, f'{filename}.csv')
count = 0
params = {}
with open(results_csv) as f:
for line in f:
if line.startswith('#'):
if count > 1:
l = line.strip()
print(l)
if l == '#Data:':
break
pattern1 = re.compile("\s+(.*?):\s(.*?)\s(.*?)$")
pattern2 = re.compile("\s+(.*?):\s(.*?)$")
matches1 = pattern1.findall(l)
matches2 = pattern2.findall(l)
if len(matches1) > 0:
params[matches1[0][0]] = {
'value': matches1[0][1],
'units': matches1[0][2]
}
elif len(matches2) > 0:
params[matches2[0][0]] = {
'value': matches2[0][1],
'units': ''
}
count += 1
return params
if __name__ == '__main__':
if platform.system() == 'Windows':
base_path = r'\\?\\' + base_path
results_path = os.path.join(base_path, 'temperature_data')
data_filetag = data_file
print('results_path: ', results_path)
main_csv = os.path.join(base_path, data_filetag + '.csv')
if not os.path.exists(results_path):
os.makedirs(results_path)
measurements_df = pd.read_csv(main_csv, comment='#').apply(pd.to_numeric)
experiment_params = get_experiment_params(relative_path=base_path, filename=data_file)
photodiode_gain = experiment_params['Photodiode Gain']['value']
laser_power_setting = experiment_params['Laser Power Setpoint']['value']
sample_name = experiment_params['Sample Name']['value']
output_path = os.path.join(results_path, f'{sample_name.upper()}_{laser_power_setting}')
if not os.path.exists(output_path):
os.makedirs(output_path)
with open('plot_style.json', 'r') as file:
json_file = json.load(file)
plot_style = json_file['defaultPlotStyle']
mpl.rcParams.update(plot_style)
thermometry = irt.PDThermometer()
# print(measurements_df)
measurement_time = measurements_df['Measurement Time (s)'].values
trigger_voltage = measurements_df['Trigger (V)'].values
photodiode_voltage = measurements_df['Photodiode Voltage (V)'].values
# for i, p in enumerate(photodiode_voltage):
# if np.isnan(p):
# print(i, measurement_time[i], p)
tc_csv = os.path.join(base_path, data_filetag + '_tcdata.csv')
tc_df = pd.read_csv(tc_csv, comment='#').apply(pd.to_numeric)
tc_time = tc_df['Time (s)'].values
temperature_a = tc_df['TC1 (C)'].values
# temperature_b = tc_df['TC2 (C)'].values
ta_corrected = correct_thermocouple_response(
measured_temperature=temperature_a, measured_time=tc_time, time_constant=time_constant_1
)
t_max_idx = measurement_time <= 3.0
tc_max_idx = tc_time <= np.inf
measurement_time = measurement_time[t_max_idx]
trigger_voltage = trigger_voltage[t_max_idx]
photodiode_voltage = photodiode_voltage[t_max_idx]
tc_time = tc_time[tc_max_idx]
temperature_a = temperature_a[tc_max_idx]
ta_corrected = ta_corrected[tc_max_idx]
trigger_voltage = savgol_filter(trigger_voltage, 5, 4)
irradiation_time_idx = trigger_voltage > 1.5
irradiation_time = measurement_time[irradiation_time_idx]
reflection_signal = np.zeros_like(photodiode_voltage)
sg_window = 9
photodiode_voltage[irradiation_time_idx] = savgol_filter(photodiode_voltage[irradiation_time_idx], sg_window, 2)
t_pulse_max = irradiation_time.max() + 0.2
noise_level = np.abs(photodiode_voltage[measurement_time > t_pulse_max]).max()
print(f"Noise Level: {noise_level:.4f} V")
t0 = irradiation_time.min()
# t0_idx = (np.abs(measurement_time - t0)).argmin() - 1
# t0 = measurement_time[t0_idx]
irradiation_time -= t0
measurement_time -= t0
n = 3
reflective_signal_zero_idx = (np.abs(measurement_time)).argmin() + n
reflection_signal_max_idx = (np.abs(measurement_time - 0.5)).argmin()
reflection_signal[irradiation_time_idx] = photodiode_voltage[reflective_signal_zero_idx]
reflection_signal[reflective_signal_zero_idx - n] = 0.0
reflection_signal[reflection_signal_max_idx:reflection_signal_max_idx] = photodiode_voltage[reflection_signal_max_idx:reflection_signal_max_idx]
print(f"Baseline signal: {photodiode_voltage[reflective_signal_zero_idx]:.3f} V")
thermometry.gain = int(photodiode_gain)
print(f"Calibration Factor: {thermometry.calibration_factor}")
thermometry.emissivity = emissivity
photodiode_corrected = photodiode_voltage - reflection_signal
pd_corrected_min = photodiode_corrected[irradiation_time_idx].min()
photodiode_corrected[irradiation_time_idx] -= pd_corrected_min + 0.5 * noise_level
time_pd_idx = (photodiode_corrected > 0.0) & (measurement_time > noise_level)
measurement_time_pd = measurement_time[time_pd_idx]
photodiode_voltage_positive = photodiode_corrected[time_pd_idx]
measurement_time_pd = measurement_time_pd[n:-2]
photodiode_voltage_positive = photodiode_voltage_positive[n:-2]
temperature_pd = thermometry.get_temperature(voltage=photodiode_voltage_positive) - 273.15
temperature_pd = savgol_filter(temperature_pd, 15, 2)
print(f't0 = {t0:.3f} s')
fig_pd, ax_pd = plt.subplots()
fig_pd.set_size_inches(5.0, 3.5)
color_pd = 'C0'
color_tr = 'C5'
ax_pd.plot(measurement_time, photodiode_voltage, color=color_pd, lw=1.75, label='Photodiode Raw')
ax_pd.set_xlim(measurement_time.min(), measurement_time.max())
ax_tr = ax_pd.twinx()
ax_pd.set_zorder(1)
ax_tr.set_zorder(0)
ax_pd.patch.set_visible(False)
ax_tr.plot(measurement_time, trigger_voltage, color=color_tr, lw=1.75)
ax_pd.set_xlabel('Time (s)')
ax_pd.set_ylabel(f'Voltage (V)', color=color_pd)
ax_pd.tick_params(axis='y', labelcolor=color_pd)
ax_tr.set_ylabel(f'Trigger Signal (V)', color=color_tr)
ax_tr.tick_params(axis='y', labelcolor=color_tr)
ax_pd.plot(measurement_time, reflection_signal, color='k', lw=1.25, ls='--', label='Reflection Baseline')
ax_pd.plot(measurement_time, photodiode_corrected, color='C1', lw=1.25, label='Corrected')
ax_pd.ticklabel_format(useMathText=True)
ax_pd.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax_pd.yaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax_pd.ticklabel_format(useMathText=True)
ax_tr.yaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax_pd.set_title(f"Photodiode Signal at {photodiode_gain} dB Gain,\n{laser_power_setting}% Laser Power")
ax_pd.legend(
loc='upper right', frameon=False
)
tr_ylim = ax_tr.get_ylim()
ax_pd.set_ylim(bottom=tr_ylim[0], top=max(1.25 * photodiode_corrected.max(), 1.0))
ax_tr.set_ylim(bottom=tr_ylim[0], top=1.1 * trigger_voltage.max())
fig_pd.tight_layout()
fig_t, ax_t = plt.subplots()
fig_t.set_size_inches(4.5, 3.0)
tol = 0.25
tc_0 = temperature_a[0]
print(f'TC[t=0]: {tc_0:4.2f} °C')
msk_onset = (ta_corrected - tc_0) > tol
time_onset = tc_time[msk_onset]
time_onset = time_onset[0]
idx_onset = (np.abs(tc_time - time_onset)).argmin() - 5
# print(idx_onset)
tc_time = tc_time[idx_onset::]
tc_time -= tc_time.min()
temperature_a = temperature_a[idx_onset::]
ta_corrected = ta_corrected[idx_onset::]
tc_time_positive_idx = tc_time > 0
tc_time = tc_time[tc_time_positive_idx]
temperature_a = temperature_a[tc_time_positive_idx]
ta_corrected = ta_corrected[tc_time_positive_idx]
ax_t.plot(
measurement_time_pd, temperature_pd, lw=1.5, label=f'Photodiode $\\epsilon = {thermometry.emissivity}$',
color='C2'
)
ax_t.plot(tc_time, temperature_a, lw=1.5, label='TC(x = 1.0 cm)', color='C3')
ax_t.plot(tc_time, ta_corrected, lw=1.5, label='TC(x = 1.0 cm) corrected ', color='C3', ls='--')
ax_t.set_xlim(measurement_time.min(), measurement_time.max())
ax_t.set_xlabel(f'Time (s)')
ax_t.set_ylabel(f'Temperature (°C)')
ax_t.set_title("Graphite type GR001CC")
# ax_t.legend(loc='upper right', frameon=False)
leg = ax_t.legend(frameon=False, loc='best', fontsize=10)
colors = ['C2', 'C3', 'C3']
for color, text in zip(colors, leg.get_texts()):
text.set_color(color)
fig_t.tight_layout()
surface_temp_df = pd.DataFrame(data={
'Time (s)':measurement_time_pd,
'Surface Temperature (°C)': temperature_pd
})
surface_temp_df.to_csv(os.path.join(output_path, f'{data_filetag}_surface_temp.csv'), index=False)
fig_pd.savefig(os.path.join(output_path, f'{data_filetag}_photodiode_voltage.png'), dpi=600)
fig_t.savefig(os.path.join(output_path, f'{data_filetag}_measured_temperatures.png'), dpi=600)
fig_t2, ax_tm = plt.subplots()
fig_t2.set_size_inches(5.0, 3.5)
ax_tm.plot(tc_time, temperature_a, lw=1.75, label='TCA @ x = 1.0 cm', color='C3')
ax_tm.plot(tc_time, ta_corrected, lw=1.75, label='TCA @ x = 1.0 cm Corrected', color='C3', ls=":")
ax_tm.set_xlabel(f'Time (s)')
ax_tm.set_ylabel(f'Temperature (°C)')
ax_tm.set_title("Graphite type GR008G")
leg = ax_tm.legend(frameon=True, loc='best', fontsize=9)
fig_t2.tight_layout()
tc_smoothed_df = pd.DataFrame(
data={
'Time (s)': tc_time,
'Temperature A (C)': temperature_a,
'Corrected Temperature A (C)': ta_corrected
}
)
smoothed_csv = os.path.join(output_path, f'{data_filetag}_corrected_temperature_data.csv')
print('Destiantion of smoothed: ', smoothed_csv)
tc_smoothed_df.to_csv(smoothed_csv, index=False)
fig_t2.savefig(os.path.join(output_path, f'{data_filetag}_corrected_temperature.png'), dpi=600)
plt.show()
| [
"os.path.exists",
"numpy.abs",
"matplotlib.rcParams.update",
"matplotlib.pyplot.show",
"os.makedirs",
"matplotlib.ticker.MultipleLocator",
"pandas.read_csv",
"re.compile",
"os.path.join",
"scipy.signal.savgol_filter",
"json.load",
"platform.system",
"pandas.DataFrame",
"numpy.gradient",
... | [((898, 939), 'scipy.signal.savgol_filter', 'savgol_filter', (['measured_temperature', 'k', '(2)'], {}), '(measured_temperature, k, 2)\n', (911, 939), False, 'from scipy.signal import savgol_filter\n'), ((951, 994), 'numpy.gradient', 'np.gradient', (['T', 'measured_time'], {'edge_order': '(2)'}), '(T, measured_time, edge_order=2)\n', (962, 994), True, 'import numpy as np\n'), ((1264, 1290), 'scipy.signal.savgol_filter', 'savgol_filter', (['r', '(k - 4)', '(3)'], {}), '(r, k - 4, 3)\n', (1277, 1290), False, 'from scipy.signal import savgol_filter\n'), ((1423, 1469), 'os.path.join', 'os.path.join', (['relative_path', 'f"""{filename}.csv"""'], {}), "(relative_path, f'{filename}.csv')\n", (1435, 1469), False, 'import os\n'), ((2603, 2646), 'os.path.join', 'os.path.join', (['base_path', '"""temperature_data"""'], {}), "(base_path, 'temperature_data')\n", (2615, 2646), False, 'import os\n'), ((2733, 2779), 'os.path.join', 'os.path.join', (['base_path', "(data_filetag + '.csv')"], {}), "(base_path, data_filetag + '.csv')\n", (2745, 2779), False, 'import os\n'), ((3535, 3566), 'matplotlib.rcParams.update', 'mpl.rcParams.update', (['plot_style'], {}), '(plot_style)\n', (3554, 3566), True, 'import matplotlib as mpl\n'), ((3586, 3605), 'ir_thermography.thermometry.PDThermometer', 'irt.PDThermometer', ([], {}), '()\n', (3603, 3605), True, 'import ir_thermography.thermometry as irt\n'), ((3978, 4031), 'os.path.join', 'os.path.join', (['base_path', "(data_filetag + '_tcdata.csv')"], {}), "(base_path, data_filetag + '_tcdata.csv')\n", (3990, 4031), False, 'import os\n'), ((4761, 4797), 'scipy.signal.savgol_filter', 'savgol_filter', (['trigger_voltage', '(5)', '(4)'], {}), '(trigger_voltage, 5, 4)\n', (4774, 4797), False, 'from scipy.signal import savgol_filter\n'), ((4934, 4967), 'numpy.zeros_like', 'np.zeros_like', (['photodiode_voltage'], {}), '(photodiode_voltage)\n', (4947, 4967), True, 'import numpy as np\n'), ((5034, 5103), 'scipy.signal.savgol_filter', 'savgol_filter', (['photodiode_voltage[irradiation_time_idx]', 'sg_window', '(2)'], {}), '(photodiode_voltage[irradiation_time_idx], sg_window, 2)\n', (5047, 5103), False, 'from scipy.signal import savgol_filter\n'), ((6832, 6868), 'scipy.signal.savgol_filter', 'savgol_filter', (['temperature_pd', '(15)', '(2)'], {}), '(temperature_pd, 15, 2)\n', (6845, 6868), False, 'from scipy.signal import savgol_filter\n'), ((6921, 6935), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (6933, 6935), True, 'import matplotlib.pyplot as plt\n'), ((8521, 8535), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (8533, 8535), True, 'import matplotlib.pyplot as plt\n'), ((9997, 10097), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': "{'Time (s)': measurement_time_pd, 'Surface Temperature (°C)': temperature_pd}"}), "(data={'Time (s)': measurement_time_pd,\n 'Surface Temperature (°C)': temperature_pd})\n", (10009, 10097), True, 'import pandas as pd\n'), ((10439, 10453), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (10451, 10453), True, 'import matplotlib.pyplot as plt\n'), ((10912, 11037), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': "{'Time (s)': tc_time, 'Temperature A (C)': temperature_a,\n 'Corrected Temperature A (C)': ta_corrected}"}), "(data={'Time (s)': tc_time, 'Temperature A (C)': temperature_a,\n 'Corrected Temperature A (C)': ta_corrected})\n", (10924, 11037), True, 'import pandas as pd\n'), ((11113, 11188), 'os.path.join', 'os.path.join', (['output_path', 'f"""{data_filetag}_corrected_temperature_data.csv"""'], {}), "(output_path, f'{data_filetag}_corrected_temperature_data.csv')\n", (11125, 11188), False, 'import os\n'), ((11401, 11411), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11409, 11411), True, 'import matplotlib.pyplot as plt\n'), ((2511, 2528), 'platform.system', 'platform.system', ([], {}), '()\n', (2526, 2528), False, 'import platform\n'), ((2791, 2819), 'os.path.exists', 'os.path.exists', (['results_path'], {}), '(results_path)\n', (2805, 2819), False, 'import os\n'), ((2829, 2854), 'os.makedirs', 'os.makedirs', (['results_path'], {}), '(results_path)\n', (2840, 2854), False, 'import os\n'), ((3334, 3361), 'os.path.exists', 'os.path.exists', (['output_path'], {}), '(output_path)\n', (3348, 3361), False, 'import os\n'), ((3371, 3395), 'os.makedirs', 'os.makedirs', (['output_path'], {}), '(output_path)\n', (3382, 3395), False, 'import os\n'), ((3464, 3479), 'json.load', 'json.load', (['file'], {}), '(file)\n', (3473, 3479), False, 'import json\n'), ((7905, 7933), 'matplotlib.ticker.MultipleLocator', 'ticker.MultipleLocator', (['(0.25)'], {}), '(0.25)\n', (7927, 7933), True, 'import matplotlib.ticker as ticker\n'), ((7969, 7997), 'matplotlib.ticker.MultipleLocator', 'ticker.MultipleLocator', (['(0.25)'], {}), '(0.25)\n', (7991, 7997), True, 'import matplotlib.ticker as ticker\n'), ((8079, 8107), 'matplotlib.ticker.MultipleLocator', 'ticker.MultipleLocator', (['(0.25)'], {}), '(0.25)\n', (8101, 8107), True, 'import matplotlib.ticker as ticker\n'), ((10143, 10204), 'os.path.join', 'os.path.join', (['output_path', 'f"""{data_filetag}_surface_temp.csv"""'], {}), "(output_path, f'{data_filetag}_surface_temp.csv')\n", (10155, 10204), False, 'import os\n'), ((10239, 10306), 'os.path.join', 'os.path.join', (['output_path', 'f"""{data_filetag}_photodiode_voltage.png"""'], {}), "(output_path, f'{data_filetag}_photodiode_voltage.png')\n", (10251, 10306), False, 'import os\n'), ((10335, 10405), 'os.path.join', 'os.path.join', (['output_path', 'f"""{data_filetag}_measured_temperatures.png"""'], {}), "(output_path, f'{data_filetag}_measured_temperatures.png')\n", (10347, 10405), False, 'import os\n'), ((11315, 11385), 'os.path.join', 'os.path.join', (['output_path', 'f"""{data_filetag}_corrected_temperature.png"""'], {}), "(output_path, f'{data_filetag}_corrected_temperature.png')\n", (11327, 11385), False, 'import os\n'), ((2878, 2912), 'pandas.read_csv', 'pd.read_csv', (['main_csv'], {'comment': '"""#"""'}), "(main_csv, comment='#')\n", (2889, 2912), True, 'import pandas as pd\n'), ((4044, 4076), 'pandas.read_csv', 'pd.read_csv', (['tc_csv'], {'comment': '"""#"""'}), "(tc_csv, comment='#')\n", (4055, 4076), True, 'import pandas as pd\n'), ((5171, 5229), 'numpy.abs', 'np.abs', (['photodiode_voltage[measurement_time > t_pulse_max]'], {}), '(photodiode_voltage[measurement_time > t_pulse_max])\n', (5177, 5229), True, 'import numpy as np\n'), ((5583, 5613), 'numpy.abs', 'np.abs', (['(measurement_time - 0.5)'], {}), '(measurement_time - 0.5)\n', (5589, 5613), True, 'import numpy as np\n'), ((5511, 5535), 'numpy.abs', 'np.abs', (['measurement_time'], {}), '(measurement_time)\n', (5517, 5535), True, 'import numpy as np\n'), ((8782, 8810), 'numpy.abs', 'np.abs', (['(tc_time - time_onset)'], {}), '(tc_time - time_onset)\n', (8788, 8810), True, 'import numpy as np\n'), ((1788, 1829), 're.compile', 're.compile', (['"""\\\\s+(.*?):\\\\s(.*?)\\\\s(.*?)$"""'], {}), "('\\\\s+(.*?):\\\\s(.*?)\\\\s(.*?)$')\n", (1798, 1829), False, 'import re\n'), ((1858, 1891), 're.compile', 're.compile', (['"""\\\\s+(.*?):\\\\s(.*?)$"""'], {}), "('\\\\s+(.*?):\\\\s(.*?)$')\n", (1868, 1891), False, 'import re\n')] |
import os
import sys
root_path = os.path.abspath("../../")
if root_path not in sys.path:
sys.path.append(root_path)
import numpy as np
from math import pi
from Util.Timing import Timing
from Util.Bases import ClassifierBase
sqrt_pi = (2 * pi) ** 0.5
class NBFunctions:
@staticmethod
def gaussian(x, mu, sigma):
return np.exp(-(x - mu) ** 2 / (2 * sigma ** 2)) / (sqrt_pi * sigma)
@staticmethod
def gaussian_maximum_likelihood(labelled_x, n_category, dim):
mu = [np.sum(
labelled_x[c][dim]) / len(labelled_x[c][dim]) for c in range(n_category)]
sigma = [np.sum(
(labelled_x[c][dim] - mu[c]) ** 2) / len(labelled_x[c][dim]) for c in range(n_category)]
def func(_c):
def sub(x):
return NBFunctions.gaussian(x, mu[_c], sigma[_c])
return sub
return [func(_c=c) for c in range(n_category)]
class NaiveBayes(ClassifierBase):
NaiveBayesTiming = Timing()
def __init__(self, **kwargs):
super(NaiveBayes, self).__init__(**kwargs)
self._x = self._y = self._data = None
self._n_possibilities = self._p_category = None
self._labelled_x = self._label_zip = None
self._cat_counter = self._con_counter = None
self.label_dict = self._feat_dicts = None
self._params["lb"] = kwargs.get("lb", 1)
def feed_data(self, x, y, sample_weight=None):
pass
def feed_sample_weight(self, sample_weight=None):
pass
@NaiveBayesTiming.timeit(level=2, prefix="[API] ")
def get_prior_probability(self, lb=1):
return [(c_num + lb) / (len(self._y) + lb * len(self._cat_counter))
for c_num in self._cat_counter]
@NaiveBayesTiming.timeit(level=2, prefix="[API] ")
def fit(self, x=None, y=None, sample_weight=None, lb=None):
if sample_weight is None:
sample_weight = self._params["sample_weight"]
if lb is None:
lb = self._params["lb"]
if x is not None and y is not None:
self.feed_data(x, y, sample_weight)
self._fit(lb)
def _fit(self, lb):
pass
def _func(self, x, i):
pass
@NaiveBayesTiming.timeit(level=1, prefix="[API] ")
def predict(self, x, get_raw_result=False, **kwargs):
if isinstance(x, np.ndarray):
x = x.tolist()
else:
x = [xx[:] for xx in x]
x = self._transfer_x(x)
m_arg, m_probability = np.zeros(len(x), dtype=np.int8), np.zeros(len(x))
for i in range(len(self._cat_counter)):
p = self._func(x, i)
mask = p > m_probability
m_arg[mask], m_probability[mask] = i, p[mask]
if not get_raw_result:
return np.array([self.label_dict[arg] for arg in m_arg])
return m_probability
def _transfer_x(self, x):
return x
| [
"Util.Timing.Timing",
"numpy.exp",
"numpy.array",
"numpy.sum",
"os.path.abspath",
"sys.path.append"
] | [((33, 58), 'os.path.abspath', 'os.path.abspath', (['"""../../"""'], {}), "('../../')\n", (48, 58), False, 'import os\n'), ((93, 119), 'sys.path.append', 'sys.path.append', (['root_path'], {}), '(root_path)\n', (108, 119), False, 'import sys\n'), ((976, 984), 'Util.Timing.Timing', 'Timing', ([], {}), '()\n', (982, 984), False, 'from Util.Timing import Timing\n'), ((343, 384), 'numpy.exp', 'np.exp', (['(-(x - mu) ** 2 / (2 * sigma ** 2))'], {}), '(-(x - mu) ** 2 / (2 * sigma ** 2))\n', (349, 384), True, 'import numpy as np\n'), ((2764, 2813), 'numpy.array', 'np.array', (['[self.label_dict[arg] for arg in m_arg]'], {}), '([self.label_dict[arg] for arg in m_arg])\n', (2772, 2813), True, 'import numpy as np\n'), ((505, 531), 'numpy.sum', 'np.sum', (['labelled_x[c][dim]'], {}), '(labelled_x[c][dim])\n', (511, 531), True, 'import numpy as np\n'), ((616, 657), 'numpy.sum', 'np.sum', (['((labelled_x[c][dim] - mu[c]) ** 2)'], {}), '((labelled_x[c][dim] - mu[c]) ** 2)\n', (622, 657), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
import torch
def plot_weight_graph(epochs, loss_lists, labels, name=''):
epochs_array = np.arange(epochs)
ax = plt.axes(xlabel='epoch', ylabel='weight', xticks=np.arange(0, epochs, 10),
yticks=np.arange(0, 10.0, 0.1))
ax.set_title(name)
y_min = float('inf')
for loss_list, label in zip(loss_lists, labels):
plt.plot(epochs_array, loss_list, label=label)
min_loss = min(loss_list).cpu() if torch.is_tensor(min(loss_list)) else min(loss_list)
y_min = min(y_min, min_loss)
ax.legend()
plt.grid(True, axis='y')
plt.ylim(bottom=y_min-0.1, top=1.)
plt.savefig('./images/%s.png'%name)
plt.clf()
def plot_accuracy_graph(epochs, loss_lists, labels, name=''):
epochs_array = np.arange(epochs)
ax = plt.axes(xlabel='epoch', ylabel='accuracy', xticks=np.arange(0, epochs, 10),
yticks=np.arange(0, 10.0, 0.1))
ax.set_title(name)
y_min = float('inf')
for loss_list, label in zip(loss_lists, labels):
plt.plot(epochs_array, loss_list, label=label)
y_min = min(y_min, min(loss_list))
ax.legend()
plt.grid(True, axis='y')
plt.ylim(bottom=y_min-0.1, top=1.0)
plt.savefig('./images/%s.png'%name)
plt.clf()
def plot_loss_graph(epochs, loss_lists, labels, name=''):
epochs_array = np.arange(epochs)
ax = plt.axes(xlabel='epoch', ylabel='loss', xticks=np.arange(0, epochs, 10),
yticks=np.arange(0, 10.0, 0.1))
ax.set_title(name)
y_min = float('inf')
for loss_list, label in zip(loss_lists, labels):
plt.plot(epochs_array, loss_list, label=label)
y_min = min(y_min, min(loss_list))
ax.legend()
plt.grid(True, axis='y')
plt.ylim(bottom=y_min-0.1, top=4.0)
plt.savefig('./images/%s.png'%name)
plt.clf() | [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"numpy.arange"
] | [((145, 162), 'numpy.arange', 'np.arange', (['epochs'], {}), '(epochs)\n', (154, 162), True, 'import numpy as np\n'), ((605, 629), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {'axis': '"""y"""'}), "(True, axis='y')\n", (613, 629), True, 'import matplotlib.pyplot as plt\n'), ((634, 671), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {'bottom': '(y_min - 0.1)', 'top': '(1.0)'}), '(bottom=y_min - 0.1, top=1.0)\n', (642, 671), True, 'import matplotlib.pyplot as plt\n'), ((673, 710), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('./images/%s.png' % name)"], {}), "('./images/%s.png' % name)\n", (684, 710), True, 'import matplotlib.pyplot as plt\n'), ((713, 722), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (720, 722), True, 'import matplotlib.pyplot as plt\n'), ((806, 823), 'numpy.arange', 'np.arange', (['epochs'], {}), '(epochs)\n', (815, 823), True, 'import numpy as np\n'), ((1179, 1203), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {'axis': '"""y"""'}), "(True, axis='y')\n", (1187, 1203), True, 'import matplotlib.pyplot as plt\n'), ((1208, 1245), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {'bottom': '(y_min - 0.1)', 'top': '(1.0)'}), '(bottom=y_min - 0.1, top=1.0)\n', (1216, 1245), True, 'import matplotlib.pyplot as plt\n'), ((1248, 1285), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('./images/%s.png' % name)"], {}), "('./images/%s.png' % name)\n", (1259, 1285), True, 'import matplotlib.pyplot as plt\n'), ((1288, 1297), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1295, 1297), True, 'import matplotlib.pyplot as plt\n'), ((1377, 1394), 'numpy.arange', 'np.arange', (['epochs'], {}), '(epochs)\n', (1386, 1394), True, 'import numpy as np\n'), ((1746, 1770), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {'axis': '"""y"""'}), "(True, axis='y')\n", (1754, 1770), True, 'import matplotlib.pyplot as plt\n'), ((1775, 1812), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {'bottom': '(y_min - 0.1)', 'top': '(4.0)'}), '(bottom=y_min - 0.1, top=4.0)\n', (1783, 1812), True, 'import matplotlib.pyplot as plt\n'), ((1815, 1852), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('./images/%s.png' % name)"], {}), "('./images/%s.png' % name)\n", (1826, 1852), True, 'import matplotlib.pyplot as plt\n'), ((1855, 1864), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1862, 1864), True, 'import matplotlib.pyplot as plt\n'), ((406, 452), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs_array', 'loss_list'], {'label': 'label'}), '(epochs_array, loss_list, label=label)\n', (414, 452), True, 'import matplotlib.pyplot as plt\n'), ((1069, 1115), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs_array', 'loss_list'], {'label': 'label'}), '(epochs_array, loss_list, label=label)\n', (1077, 1115), True, 'import matplotlib.pyplot as plt\n'), ((1636, 1682), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs_array', 'loss_list'], {'label': 'label'}), '(epochs_array, loss_list, label=label)\n', (1644, 1682), True, 'import matplotlib.pyplot as plt\n'), ((221, 245), 'numpy.arange', 'np.arange', (['(0)', 'epochs', '(10)'], {}), '(0, epochs, 10)\n', (230, 245), True, 'import numpy as np\n'), ((272, 295), 'numpy.arange', 'np.arange', (['(0)', '(10.0)', '(0.1)'], {}), '(0, 10.0, 0.1)\n', (281, 295), True, 'import numpy as np\n'), ((884, 908), 'numpy.arange', 'np.arange', (['(0)', 'epochs', '(10)'], {}), '(0, epochs, 10)\n', (893, 908), True, 'import numpy as np\n'), ((935, 958), 'numpy.arange', 'np.arange', (['(0)', '(10.0)', '(0.1)'], {}), '(0, 10.0, 0.1)\n', (944, 958), True, 'import numpy as np\n'), ((1451, 1475), 'numpy.arange', 'np.arange', (['(0)', 'epochs', '(10)'], {}), '(0, epochs, 10)\n', (1460, 1475), True, 'import numpy as np\n'), ((1502, 1525), 'numpy.arange', 'np.arange', (['(0)', '(10.0)', '(0.1)'], {}), '(0, 10.0, 0.1)\n', (1511, 1525), True, 'import numpy as np\n')] |
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from scipy.ndimage import gaussian_filter1d
import tensorflow as tf
import os
from scipy import signal
import scipy
from skued import baseline_dt
def make_prediction(X, model, crystal_system):
# Use this function for final prediction to ensure correct symmetry for lattice parameters
y_pred = model.predict(X)
if ((crystal_system == "hexagonal") or (crystal_system == "cubic") or (crystal_system == "tetragonal") or (crystal_system == "trigonal")):
enforce_symmetry(y_pred,crystal_system)
return y_pred
def enforce_symmetry(prediction_array, crystal_system):
# This function correctly enforces a a c for trigonal, tetragonal, hexagonal and cubic crystals;
# No return is needed since arrays are passed in by reference in python; i.e. prediction_array is overwritten
if ((crystal_system == "hexagonal") or (crystal_system == "tetragonal") or (crystal_system == "trigonal")):
for prediction in prediction_array:
if abs(prediction[0]-prediction[1]) < abs(prediction[0]-prediction[2]):
prediction[0] = (prediction[0]+prediction[1])/2
prediction[1] = prediction[0]
else:
prediction[1] = (prediction[1] + prediction[2]) / 2
prediction[2] = prediction[1]
if (crystal_system == "cubic"):
for prediction in prediction_array:
prediction[0] = np.mean(prediction)
prediction[1] = prediction[0]
prediction[2] = prediction[0]
def normalize01(X):
# Normalize data to 0 1 range
Xnew = []
for i in range(len(X)):
norm = ((X[i] - np.min(X[i]))/((np.max(X[i]) - np.min(X[i])) + 0.000001))
Xnew.append(norm)
Xnew = np.array(Xnew)
return Xnew
# Augmentations
def augment(X, X_random, shift_offset=True, intensity_shift=True, linear_comb=True, gaussian_noise=True,gaussian_broaden=True, shift=15, percent_scale=0.30, num_examples=4, impurity_scale=0.10,noise_level=0.005, probability=1.0, sigma=1.0):
if len(X.shape) == 3: # Need to reduce dimensions in order for other calculations to work
X = np.reshape(X, (X.shape[0], X.shape[1]))
if shift_offset:
X = shift_spectra(X, shift)
if intensity_shift:
X = intensity_modulation(X, percent_scale)
if linear_comb:
X = linear_combination(X, X_random, num_examples, impurity_scale)
if gaussian_noise:
X = gaussian_noise_baseline(X, noise_level, probability)
if gaussian_broaden:
X = gaussian_broaden_data(X)
X = np.reshape(X, (X.shape[0], X.shape[1],1))
return X
def shift_spectra(X, shift=10):
# Random shift between -shift and shift; Based on code for shifting numpy arrays: https://stackoverflow.com/questions/30399534/shift-elements-in-a-numpy-array
shift = np.random.randint(shift) - int(shift/2)
augmented = np.empty_like(X)
if shift > 0:
augmented[:, :shift] = 0
augmented[:, shift:] = X[:, :-shift]
elif shift < 0:
augmented[:, shift:] = 0
augmented[:, :shift] = X[:, -shift:]
else:
augmented[:, :] = X
return augmented
def intensity_modulation(X, percent_scale=0.20):
# Random intensity modulation
X += X*np.repeat(np.random.uniform(-percent_scale, percent_scale, size=(X.shape[0], 100)), X.shape[1]/100, axis=1)
return normalize01(X)
def linear_combination(X, X_random, num_examples=3, impurity_scale=0.10):
# Random number between 1 and num_examples for linear combination adding
if num_examples != 0:
num_combinations = np.random.randint(num_examples) + 1
else:
num_combinations = 1
batch_size = X.shape[0]
X_random = X_random[0:batch_size]
for i in range(num_combinations):
X += np.random.uniform(0.05, impurity_scale, size=(batch_size, 1)) * (np.random.permutation(X_random)[0:batch_size])
X = normalize01(X)
return X
def gaussian_noise_baseline(X, noise_level=0.02, probability=1.0):
# Add gaussian noise to the baseline
if np.random.rand() < probability:
X += np.random.uniform(0,noise_level, size=(X.shape[0], 1))*np.random.normal(noise_level, 1, size=(X.shape[0],X.shape[1]))
#X += abs(np.random.normal(0, noise_level/3, size=(X.shape[0],X.shape[1]))) # for changing baseline noise experiments
return abs(X)
def gaussian_broaden_data(X):
# Add gaussian broaden to the data
sigma = np.random.uniform(1, 5)
return normalize01(gaussian_filter1d(X, sigma, axis=1))
def mean_absolute_percentage_error(y_true, y_pred):
# Calculate MPE
y_true, y_pred = np.array(y_true), np.array(y_pred)
return np.mean(np.abs((y_true - y_pred) / (y_true + 0.0000001))) * 100
def find_peaks_wrapper(x,widths=np.arange(1,20)):
peakind = signal.find_peaks_cwt(x, widths)
out = np.zeros(len(x))
out[peakind] = x[peakind]
out = out/np.max(out)
return out
def angle2q(two_theta, lbda=1.541838):
return (4*np.pi*np.sin((two_theta/2)*np.pi/180))/lbda
def interpolate_data(q, intensities, lbda=1.541838,ml_input_size=9000):
f = scipy.interpolate.interp1d(q, intensities, bounds_error=False, fill_value=intensities[0])
q_sim = angle2q(np.linspace(0, 90, ml_input_size), lbda)
intensities_interpolated = f(q_sim)
return intensities_interpolated
def add_axis_broaden(intensity_interpolated,sigma=3):
x = scipy.ndimage.gaussian_filter1d(intensity_interpolated, sigma=5)
x = x/np.max(x)
x = np.expand_dims(x, axis=1)
x = np.expand_dims(x, axis=0)
return x
def processExptData(Xdata, measured_wavelength=0.7293, showPlots=True, baseline=False):
q = angle2q(Xdata[0], lbda=measured_wavelength)
intensity = Xdata[1]
if baseline: # If data has a non-zero baseline, we can use autobaselining tools: https://scikit-ued.readthedocs.io/en/master/
intensity = intensity - baseline_dt(intensity, wavelet = 'qshift3', level = 9, max_iter = 1000)
intensity = intensity/np.max(intensity)
intensity[intensity < 0.001] = 0
intensity_interpolated = interpolate_data(q, intensity, lbda=1.54056,ml_input_size=9000) # Interpolate to 9000 range in corresponding q
intensity_interpolated = intensity_interpolated/np.max(intensity_interpolated) # normalize to 0,1
if showPlots:
plt.plot(np.linspace(0,90,9000),intensity_interpolated)
plt.show()
return intensity_interpolated
def predictExptDataPipeline(Xdata, y_true, crystal_system, measured_wavelength=0.7293, model=None, baseline=False,showPlots=True,printResults=True):
if model == None:
# Default model takes all augmentations
model = tf.keras.models.load_model("../models_ICSD_CSD/" + crystal_system + "_all")
intensity_interpolated = processExptData(Xdata, measured_wavelength=measured_wavelength, showPlots=showPlots, baseline=baseline)
y_pred = make_prediction(np.expand_dims(np.expand_dims(intensity_interpolated,axis=1),axis=0), model, crystal_system)
if printResults:
print(" ")
print("True LPs from Refined data: ", y_true)
print(" ")
print("Predicted LPs using ML: ", y_pred)
print("----------------------------------------------------------------------------------------------------------------")
print("----------------------------------------------------------------------------------------------------------------")
print(" ")
return y_pred
| [
"numpy.random.rand",
"scipy.interpolate.interp1d",
"numpy.array",
"tensorflow.keras.models.load_model",
"numpy.sin",
"numpy.arange",
"numpy.mean",
"numpy.reshape",
"numpy.max",
"numpy.linspace",
"numpy.min",
"scipy.ndimage.gaussian_filter1d",
"numpy.random.permutation",
"numpy.random.norma... | [((1843, 1857), 'numpy.array', 'np.array', (['Xnew'], {}), '(Xnew)\n', (1851, 1857), True, 'import numpy as np\n'), ((2665, 2707), 'numpy.reshape', 'np.reshape', (['X', '(X.shape[0], X.shape[1], 1)'], {}), '(X, (X.shape[0], X.shape[1], 1))\n', (2675, 2707), True, 'import numpy as np\n'), ((2985, 3001), 'numpy.empty_like', 'np.empty_like', (['X'], {}), '(X)\n', (2998, 3001), True, 'import numpy as np\n'), ((4556, 4579), 'numpy.random.uniform', 'np.random.uniform', (['(1)', '(5)'], {}), '(1, 5)\n', (4573, 4579), True, 'import numpy as np\n'), ((4883, 4899), 'numpy.arange', 'np.arange', (['(1)', '(20)'], {}), '(1, 20)\n', (4892, 4899), True, 'import numpy as np\n'), ((4915, 4947), 'scipy.signal.find_peaks_cwt', 'signal.find_peaks_cwt', (['x', 'widths'], {}), '(x, widths)\n', (4936, 4947), False, 'from scipy import signal\n'), ((5233, 5327), 'scipy.interpolate.interp1d', 'scipy.interpolate.interp1d', (['q', 'intensities'], {'bounds_error': '(False)', 'fill_value': 'intensities[0]'}), '(q, intensities, bounds_error=False, fill_value=\n intensities[0])\n', (5259, 5327), False, 'import scipy\n'), ((5523, 5587), 'scipy.ndimage.gaussian_filter1d', 'scipy.ndimage.gaussian_filter1d', (['intensity_interpolated'], {'sigma': '(5)'}), '(intensity_interpolated, sigma=5)\n', (5554, 5587), False, 'import scipy\n'), ((5616, 5641), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(1)'}), '(x, axis=1)\n', (5630, 5641), True, 'import numpy as np\n'), ((5650, 5675), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (5664, 5675), True, 'import numpy as np\n'), ((2241, 2280), 'numpy.reshape', 'np.reshape', (['X', '(X.shape[0], X.shape[1])'], {}), '(X, (X.shape[0], X.shape[1]))\n', (2251, 2280), True, 'import numpy as np\n'), ((2929, 2953), 'numpy.random.randint', 'np.random.randint', (['shift'], {}), '(shift)\n', (2946, 2953), True, 'import numpy as np\n'), ((4160, 4176), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (4174, 4176), True, 'import numpy as np\n'), ((4603, 4638), 'scipy.ndimage.gaussian_filter1d', 'gaussian_filter1d', (['X', 'sigma'], {'axis': '(1)'}), '(X, sigma, axis=1)\n', (4620, 4638), False, 'from scipy.ndimage import gaussian_filter1d\n'), ((4740, 4756), 'numpy.array', 'np.array', (['y_true'], {}), '(y_true)\n', (4748, 4756), True, 'import numpy as np\n'), ((4758, 4774), 'numpy.array', 'np.array', (['y_pred'], {}), '(y_pred)\n', (4766, 4774), True, 'import numpy as np\n'), ((5027, 5038), 'numpy.max', 'np.max', (['out'], {}), '(out)\n', (5033, 5038), True, 'import numpy as np\n'), ((5343, 5376), 'numpy.linspace', 'np.linspace', (['(0)', '(90)', 'ml_input_size'], {}), '(0, 90, ml_input_size)\n', (5354, 5376), True, 'import numpy as np\n'), ((5598, 5607), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (5604, 5607), True, 'import numpy as np\n'), ((6126, 6143), 'numpy.max', 'np.max', (['intensity'], {}), '(intensity)\n', (6132, 6143), True, 'import numpy as np\n'), ((6379, 6409), 'numpy.max', 'np.max', (['intensity_interpolated'], {}), '(intensity_interpolated)\n', (6385, 6409), True, 'import numpy as np\n'), ((6520, 6530), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6528, 6530), True, 'from matplotlib import pyplot as plt\n'), ((6812, 6887), 'tensorflow.keras.models.load_model', 'tf.keras.models.load_model', (["('../models_ICSD_CSD/' + crystal_system + '_all')"], {}), "('../models_ICSD_CSD/' + crystal_system + '_all')\n", (6838, 6887), True, 'import tensorflow as tf\n'), ((1522, 1541), 'numpy.mean', 'np.mean', (['prediction'], {}), '(prediction)\n', (1529, 1541), True, 'import numpy as np\n'), ((3366, 3438), 'numpy.random.uniform', 'np.random.uniform', (['(-percent_scale)', 'percent_scale'], {'size': '(X.shape[0], 100)'}), '(-percent_scale, percent_scale, size=(X.shape[0], 100))\n', (3383, 3438), True, 'import numpy as np\n'), ((3695, 3726), 'numpy.random.randint', 'np.random.randint', (['num_examples'], {}), '(num_examples)\n', (3712, 3726), True, 'import numpy as np\n'), ((3887, 3948), 'numpy.random.uniform', 'np.random.uniform', (['(0.05)', 'impurity_scale'], {'size': '(batch_size, 1)'}), '(0.05, impurity_scale, size=(batch_size, 1))\n', (3904, 3948), True, 'import numpy as np\n'), ((4205, 4260), 'numpy.random.uniform', 'np.random.uniform', (['(0)', 'noise_level'], {'size': '(X.shape[0], 1)'}), '(0, noise_level, size=(X.shape[0], 1))\n', (4222, 4260), True, 'import numpy as np\n'), ((4260, 4323), 'numpy.random.normal', 'np.random.normal', (['noise_level', '(1)'], {'size': '(X.shape[0], X.shape[1])'}), '(noise_level, 1, size=(X.shape[0], X.shape[1]))\n', (4276, 4323), True, 'import numpy as np\n'), ((4794, 4838), 'numpy.abs', 'np.abs', (['((y_true - y_pred) / (y_true + 1e-07))'], {}), '((y_true - y_pred) / (y_true + 1e-07))\n', (4800, 4838), True, 'import numpy as np\n'), ((5114, 5149), 'numpy.sin', 'np.sin', (['(two_theta / 2 * np.pi / 180)'], {}), '(two_theta / 2 * np.pi / 180)\n', (5120, 5149), True, 'import numpy as np\n'), ((6023, 6088), 'skued.baseline_dt', 'baseline_dt', (['intensity'], {'wavelet': '"""qshift3"""', 'level': '(9)', 'max_iter': '(1000)'}), "(intensity, wavelet='qshift3', level=9, max_iter=1000)\n", (6034, 6088), False, 'from skued import baseline_dt\n'), ((6465, 6489), 'numpy.linspace', 'np.linspace', (['(0)', '(90)', '(9000)'], {}), '(0, 90, 9000)\n', (6476, 6489), True, 'import numpy as np\n'), ((7075, 7121), 'numpy.expand_dims', 'np.expand_dims', (['intensity_interpolated'], {'axis': '(1)'}), '(intensity_interpolated, axis=1)\n', (7089, 7121), True, 'import numpy as np\n'), ((1748, 1760), 'numpy.min', 'np.min', (['X[i]'], {}), '(X[i])\n', (1754, 1760), True, 'import numpy as np\n'), ((3952, 3983), 'numpy.random.permutation', 'np.random.permutation', (['X_random'], {}), '(X_random)\n', (3973, 3983), True, 'import numpy as np\n'), ((1764, 1776), 'numpy.max', 'np.max', (['X[i]'], {}), '(X[i])\n', (1770, 1776), True, 'import numpy as np\n'), ((1779, 1791), 'numpy.min', 'np.min', (['X[i]'], {}), '(X[i])\n', (1785, 1791), True, 'import numpy as np\n')] |
"""
Phase Estimation Benchmark Program - Qiskit
"""
import sys
import time
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
sys.path[1:1] = ["_common", "_common/qiskit", "quantum-fourier-transform/qiskit"]
sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../quantum-fourier-transform/qiskit"]
import execute as ex
import metrics as metrics
from qft_benchmark import inv_qft_gate
np.random.seed(0)
verbose = False
# saved subcircuits circuits for printing
QC_ = None
QFTI_ = None
U_ = None
############### Circuit Definition
def PhaseEstimation(num_qubits, theta):
qr = QuantumRegister(num_qubits)
num_counting_qubits = num_qubits - 1 # only 1 state qubit
cr = ClassicalRegister(num_counting_qubits)
qc = QuantumCircuit(qr, cr)
# initialize counting qubits in superposition
for i in range(num_counting_qubits):
qc.h(qr[i])
# change to |1> in state qubit, so phase will be applied by cphase gate
qc.x(num_counting_qubits)
qc.barrier()
repeat = 1
for j in reversed(range(num_counting_qubits)):
# controlled operation: adds phase exp(i*2*pi*theta*repeat) to the state |1>
# does nothing to state |0>
cp, _ = CPhase(2*np.pi*theta, repeat)
qc.append(cp, [j, num_counting_qubits])
repeat *= 2
#Define global U operator as the phase operator
_, U = CPhase(2*np.pi*theta, 1)
qc.barrier()
# inverse quantum Fourier transform only on counting qubits
qc.append(inv_qft_gate(num_counting_qubits), qr[:num_counting_qubits])
qc.barrier()
# measure counting qubits
qc.measure([qr[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits)))
# save smaller circuit example for display
global QC_, U_, QFTI_
if QC_ == None or num_qubits <= 5:
if num_qubits < 9: QC_ = qc
if U_ == None or num_qubits <= 5:
if num_qubits < 9: U_ = U
if QFTI_ == None or num_qubits <= 5:
if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits)
return qc
#Construct the phase gates and include matching gate representation as readme circuit
def CPhase(angle, exponent):
qc = QuantumCircuit(1, name=f"U^{exponent}")
qc.p(angle*exponent, 0)
phase_gate = qc.to_gate().control(1)
return phase_gate, qc
# Analyze and print measured results
def analyze_and_print_result(qc, result, num_counting_qubits, theta, num_shots):
# get results as times a particular theta was measured
bit_counts = result.get_counts(qc)
counts = bitstring_to_theta(bit_counts, num_counting_qubits)
if verbose: print(f"For theta value {theta}, measured: {counts}")
# correct distribution is measuring theta 100% of the time
correct_dist = {theta: 1.0}
# calculate expected output histogram
bit_correct_dist = theta_to_bitstring(theta, num_counting_qubits)
# generate thermal_dist with amplitudes instead, to be comparable to correct_dist
bit_thermal_dist = metrics.uniform_dist(num_counting_qubits)
thermal_dist = bitstring_to_theta(bit_thermal_dist, num_counting_qubits)
# use our polarization fidelity rescaling
fidelity = metrics.polarization_fidelity(counts, correct_dist, thermal_dist)
aq_fidelity = metrics.hellinger_fidelity_with_expected(bit_counts, bit_correct_dist)
return counts, fidelity, aq_fidelity
def theta_to_bitstring(theta, num_counting_qubits):
counts = {format( int(theta * (2**num_counting_qubits)), "0"+str(num_counting_qubits)+"b"): 1.0}
return counts
def bitstring_to_theta(counts, num_counting_qubits):
theta_counts = {}
for key in counts.keys():
r = counts[key]
theta = int(key,2) / (2**num_counting_qubits)
if theta not in theta_counts.keys():
theta_counts[theta] = 0
theta_counts[theta] += r
return theta_counts
################ Benchmark Loop
# Execute program with default parameters
def run(min_qubits=3, max_qubits=8, max_circuits=3, num_shots=2500,
backend_id='qasm_simulator', provider_backend=None,
hub="ibm-q", group="open", project="main", exec_options=None):
print("Phase Estimation Benchmark Program - Qiskit")
num_state_qubits = 1 # default, not exposed to users, cannot be changed in current implementation
# validate parameters (smallest circuit is 3 qubits)
num_state_qubits = max(1, num_state_qubits)
if max_qubits < num_state_qubits + 2:
print(f"ERROR: PE Benchmark needs at least {num_state_qubits + 2} qubits to run")
return
min_qubits = max(max(3, min_qubits), num_state_qubits + 2)
#print(f"min, max, state = {min_qubits} {max_qubits} {num_state_qubits}")
# Initialize metrics module
metrics.init_metrics()
# Define custom result handler
def execution_handler(qc, result, num_qubits, theta, num_shots):
# determine fidelity of result set
num_counting_qubits = int(num_qubits) - 1
counts, fidelity, aq_fidelity = analyze_and_print_result(qc, result, num_counting_qubits, float(theta), num_shots)
metrics.store_metric(num_qubits, theta, 'fidelity', fidelity)
metrics.store_metric(num_qubits, theta, 'aq_fidelity', aq_fidelity)
# Initialize execution module using the execution result handler above and specified backend_id
ex.init_execution(execution_handler)
ex.set_execution_target(backend_id, provider_backend=provider_backend,
hub=hub, group=group, project=project, exec_options=exec_options)
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
for num_qubits in range(min_qubits, max_qubits + 1):
# reset random seed
np.random.seed(0)
# as circuit width grows, the number of counting qubits is increased
num_counting_qubits = num_qubits - num_state_qubits - 1
# determine number of circuits to execute for this group
num_circuits = min(2 ** (num_counting_qubits), max_circuits)
print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}")
# determine range of secret strings to loop over
if 2**(num_counting_qubits) <= max_circuits:
theta_range = [i/(2**(num_counting_qubits)) for i in list(range(num_circuits))]
else:
theta_range = [i/(2**(num_counting_qubits)) for i in np.random.choice(2**(num_counting_qubits), num_circuits, False)]
# loop over limited # of random theta choices
for theta in theta_range:
# create the circuit for given qubit size and theta, store time metric
ts = time.time()
qc = PhaseEstimation(num_qubits, theta)
metrics.store_metric(num_qubits, theta, 'create_time', time.time() - ts)
# collapse the 3 sub-circuit levels used in this benchmark (for qiskit)
qc2 = qc.decompose().decompose().decompose()
# submit circuit for execution on target (simulator, cloud simulator, or hardware)
ex.submit_circuit(qc2, num_qubits, theta, num_shots)
# Wait for some active circuits to complete; report metrics when groups complete
ex.throttle_execution(metrics.finalize_group)
# Wait for all active circuits to complete; report metrics when groups complete
ex.finalize_execution(metrics.finalize_group)
# print a sample circuit
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
print("\nPhase Operator 'U' = "); print(U_ if U_ != None else " ... too large!")
print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!")
# Plot metrics for all circuit sizes
metrics.plot_metrics_aq("Benchmark Results - Phase Estimation - Qiskit")
# if main, execute method
if __name__ == '__main__': run()
| [
"metrics.store_metric",
"execute.submit_circuit",
"metrics.uniform_dist",
"qiskit.ClassicalRegister",
"qft_benchmark.inv_qft_gate",
"metrics.init_metrics",
"execute.init_execution",
"numpy.random.choice",
"metrics.plot_metrics_aq",
"execute.finalize_execution",
"metrics.polarization_fidelity",
... | [((436, 453), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (450, 453), True, 'import numpy as np\n'), ((639, 666), 'qiskit.QuantumRegister', 'QuantumRegister', (['num_qubits'], {}), '(num_qubits)\n', (654, 666), False, 'from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\n'), ((748, 786), 'qiskit.ClassicalRegister', 'ClassicalRegister', (['num_counting_qubits'], {}), '(num_counting_qubits)\n', (765, 786), False, 'from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\n'), ((796, 818), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['qr', 'cr'], {}), '(qr, cr)\n', (810, 818), False, 'from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\n'), ((2253, 2292), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['(1)'], {'name': 'f"""U^{exponent}"""'}), "(1, name=f'U^{exponent}')\n", (2267, 2292), False, 'from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\n'), ((3066, 3107), 'metrics.uniform_dist', 'metrics.uniform_dist', (['num_counting_qubits'], {}), '(num_counting_qubits)\n', (3086, 3107), True, 'import metrics as metrics\n'), ((3247, 3312), 'metrics.polarization_fidelity', 'metrics.polarization_fidelity', (['counts', 'correct_dist', 'thermal_dist'], {}), '(counts, correct_dist, thermal_dist)\n', (3276, 3312), True, 'import metrics as metrics\n'), ((3331, 3401), 'metrics.hellinger_fidelity_with_expected', 'metrics.hellinger_fidelity_with_expected', (['bit_counts', 'bit_correct_dist'], {}), '(bit_counts, bit_correct_dist)\n', (3371, 3401), True, 'import metrics as metrics\n'), ((4805, 4827), 'metrics.init_metrics', 'metrics.init_metrics', ([], {}), '()\n', (4825, 4827), True, 'import metrics as metrics\n'), ((5401, 5437), 'execute.init_execution', 'ex.init_execution', (['execution_handler'], {}), '(execution_handler)\n', (5418, 5437), True, 'import execute as ex\n'), ((5442, 5583), 'execute.set_execution_target', 'ex.set_execution_target', (['backend_id'], {'provider_backend': 'provider_backend', 'hub': 'hub', 'group': 'group', 'project': 'project', 'exec_options': 'exec_options'}), '(backend_id, provider_backend=provider_backend, hub=\n hub, group=group, project=project, exec_options=exec_options)\n', (5465, 5583), True, 'import execute as ex\n'), ((7467, 7512), 'execute.finalize_execution', 'ex.finalize_execution', (['metrics.finalize_group'], {}), '(metrics.finalize_group)\n', (7488, 7512), True, 'import execute as ex\n'), ((7847, 7919), 'metrics.plot_metrics_aq', 'metrics.plot_metrics_aq', (['"""Benchmark Results - Phase Estimation - Qiskit"""'], {}), "('Benchmark Results - Phase Estimation - Qiskit')\n", (7870, 7919), True, 'import metrics as metrics\n'), ((1570, 1603), 'qft_benchmark.inv_qft_gate', 'inv_qft_gate', (['num_counting_qubits'], {}), '(num_counting_qubits)\n', (1582, 1603), False, 'from qft_benchmark import inv_qft_gate\n'), ((5158, 5219), 'metrics.store_metric', 'metrics.store_metric', (['num_qubits', 'theta', '"""fidelity"""', 'fidelity'], {}), "(num_qubits, theta, 'fidelity', fidelity)\n", (5178, 5219), True, 'import metrics as metrics\n'), ((5228, 5295), 'metrics.store_metric', 'metrics.store_metric', (['num_qubits', 'theta', '"""aq_fidelity"""', 'aq_fidelity'], {}), "(num_qubits, theta, 'aq_fidelity', aq_fidelity)\n", (5248, 5295), True, 'import metrics as metrics\n'), ((5822, 5839), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (5836, 5839), True, 'import numpy as np\n'), ((7332, 7377), 'execute.throttle_execution', 'ex.throttle_execution', (['metrics.finalize_group'], {}), '(metrics.finalize_group)\n', (7353, 7377), True, 'import execute as ex\n'), ((2079, 2112), 'qft_benchmark.inv_qft_gate', 'inv_qft_gate', (['num_counting_qubits'], {}), '(num_counting_qubits)\n', (2091, 2112), False, 'from qft_benchmark import inv_qft_gate\n'), ((6769, 6780), 'time.time', 'time.time', ([], {}), '()\n', (6778, 6780), False, 'import time\n'), ((7181, 7233), 'execute.submit_circuit', 'ex.submit_circuit', (['qc2', 'num_qubits', 'theta', 'num_shots'], {}), '(qc2, num_qubits, theta, num_shots)\n', (7198, 7233), True, 'import execute as ex\n'), ((6515, 6578), 'numpy.random.choice', 'np.random.choice', (['(2 ** num_counting_qubits)', 'num_circuits', '(False)'], {}), '(2 ** num_counting_qubits, num_circuits, False)\n', (6531, 6578), True, 'import numpy as np\n'), ((6901, 6912), 'time.time', 'time.time', ([], {}), '()\n', (6910, 6912), False, 'import time\n')] |
'''
Utility mesh function for batch generation
Author: <NAME>
Date: Novemebr 2019
Input: root : data path
num_faces : number of sampled faces, default 8000
nb_classes : number of classes, default 8
scale : scale to unite sphere for PointNet, default False
sampling : sampling method [random, fps, or knn], default random
mode : train or val, default train
Output: Class HessigheimDataset, get items: data numpy array NxF
label numpy array Nx1
weight numpy array Nx1
Dependencies: numpy - os - h5py - open3d - scipy - sklearn - matplotlib
'''
import numpy as np
import os
import h5py
import open3d
from scipy.spatial import cKDTree
from sklearn import preprocessing
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
class HessigheimDataset():
def __init__(self, root, num_faces=8000, nb_classes=8, scale=False, sampling='random', mode='train'):
self.root = root
self.num_faces = num_faces
self.mode = mode
self.sampling = sampling
self.nb_classes = nb_classes
self.scale = scale
files = os.listdir(self.root)
self.data_all = None
self.label_all = None
for file in files:
if file.endswith('h5'):
hdf = h5py.File(self.root + '/{}'.format(file), mode='r')
face_tile = np.array(hdf['data'])
label_tile = np.array(hdf['label'])
elif file.endswith('txt'):
data = np.loadtxt(self.root + '/{}'.format(file))
face_tile = data[:,:-1]
label_tile = data[:,-1]
else:
continue
if face_tile.shape[0] < self.num_faces:
continue
if self.sampling == 'random':
indices = np.random.choice(np.array(face_tile).shape[0], self.num_faces, replace=False)
face_cur = np.take(face_tile, indices, 0)
label_cur = np.take(label_tile, indices)
elif self.sampling == 'knn':
tree = cKDTree(face_tile[:,0:3])
center = [face_tile[:,0].mean(), face_tile[:,1].mean(), face_tile[:,2].mean()]
_, ind = tree.query(center, k=self.num_faces)
face_cur = face_tile[ind]
label_cur = label_tile[ind]
elif self.sampling == 'fps':
data_cur = np.concatenate((face_tile, np.expand_dims(label_tile, -1)), axis=1)
data_cur = self.graipher(data_cur, self.num_faces)
face_cur = data_cur[:, :-1]
label_cur = data_cur[:, -1]
face_cur = np.expand_dims(face_cur, axis=0)
label_cur = np.expand_dims(label_cur, axis=0)
if self.data_all is None:
self.data_all = face_cur
self.label_all = label_cur
else:
self.data_all = np.concatenate((self.data_all, face_cur), axis=0)
self.label_all = np.concatenate((self.label_all, label_cur))
if self.mode == 'train':
weights = np.zeros(self.nb_classes)
for sem in self.label_all:
tmp, _ = np.histogram(sem, range(self.nb_classes + 1))
weights += tmp
weights = weights.astype(np.float32)
weights = weights / np.sum(weights)
self.weights = weights ** -0.5
elif self.mode == 'val':
self.weights = np.ones(self.nb_classes)
@staticmethod
def graipher(pts, n):
'based on Grapher https://codereview.stackexchange.com/questions/179561/farthest-point-algorithm-in-python'
farthest_pts = np.zeros((n, pts.shape[1]))
farthest_pts[0] = pts[np.random.randint(len(pts))]
distances = ((farthest_pts[0,0:3] - pts[:,0:3]) ** 2).sum(axis=1)
for i in range(1, n):
farthest_pts[i] = pts[np.argmax(distances)]
distances = np.minimum(distances, ((farthest_pts[i,0:3] - pts[:,0:3]) ** 2).sum(axis=1))
return farthest_pts
def __getitem__(self, index):
if self.scale:
data = np.copy(self.data_all[index])
scaler = preprocessing.MinMaxScaler(feature_range=(-1, 1))
data[:, 0:3] = scaler.fit_transform(data[:, 0:3])
else:
data = self.data_all[index]
label = self.label_all[index].astype(np.int32)
weight = self.weights[label]
return data, label, weight
def __len__(self):
return len(self.data_all)
if __name__=='__main__':
root = '/'
data = HessigheimDataset(root, scale=False, num_faces=15000, nb_classes=8, sampling='knn', mode='val')
print('Number of batches: ', len(data))
is_plot = True
if is_plot:
rgb_color = [[255, 255, 0], [128, 0, 0], [255, 0, 255], [0, 255, 0], [0, 128, 0], [0, 255, 255],
[255, 128, 0], [128, 128, 128]]
for i in range(len(data)):
faces, labels, weights = data[i]
colors = np.zeros((faces.shape[0],3))
for i in range(faces.shape[0]):
ind = labels[i]
colors[i, 0:3] = rgb_color[int(ind)]
pcd_1 = open3d.PointCloud()
pcd_1.points = open3d.Vector3dVector(faces[:, :3])
pcd_1.colors = open3d.Vector3dVector(colors/255.)
open3d.draw_geometries([pcd_1])
# fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')
# xs = faces[:, 0]
# ys = faces[:, 1]
# zs = faces[:, 2]
# ax.scatter(xs,ys,zs, c=colors/255., s=0.2)
# ax.set_xlim(-1,1)
# ax.set_ylim(-1,1)
# ax.set_zlim(-1,1)
# ax.set_xticks([-1,1])
# ax.set_yticks([-1,1])
# ax.set_zticks([-1,1])
# ax.w_xaxis.set_pane_color((0, 0, 0, 1))
# ax.w_yaxis.set_pane_color((0, 0, 0, 1))
# ax.w_zaxis.set_pane_color((0, 0, 0, 1))
# plt.show() | [
"numpy.copy",
"os.listdir",
"numpy.ones",
"scipy.spatial.cKDTree",
"open3d.Vector3dVector",
"open3d.PointCloud",
"numpy.argmax",
"open3d.draw_geometries",
"numpy.array",
"numpy.zeros",
"numpy.take",
"numpy.sum",
"numpy.expand_dims",
"numpy.concatenate",
"sklearn.preprocessing.MinMaxScale... | [((1116, 1137), 'os.listdir', 'os.listdir', (['self.root'], {}), '(self.root)\n', (1126, 1137), False, 'import os\n'), ((3179, 3206), 'numpy.zeros', 'np.zeros', (['(n, pts.shape[1])'], {}), '((n, pts.shape[1]))\n', (3187, 3206), True, 'import numpy as np\n'), ((2337, 2369), 'numpy.expand_dims', 'np.expand_dims', (['face_cur'], {'axis': '(0)'}), '(face_cur, axis=0)\n', (2351, 2369), True, 'import numpy as np\n'), ((2385, 2418), 'numpy.expand_dims', 'np.expand_dims', (['label_cur'], {'axis': '(0)'}), '(label_cur, axis=0)\n', (2399, 2418), True, 'import numpy as np\n'), ((2694, 2719), 'numpy.zeros', 'np.zeros', (['self.nb_classes'], {}), '(self.nb_classes)\n', (2702, 2719), True, 'import numpy as np\n'), ((3573, 3602), 'numpy.copy', 'np.copy', (['self.data_all[index]'], {}), '(self.data_all[index])\n', (3580, 3602), True, 'import numpy as np\n'), ((3615, 3664), 'sklearn.preprocessing.MinMaxScaler', 'preprocessing.MinMaxScaler', ([], {'feature_range': '(-1, 1)'}), '(feature_range=(-1, 1))\n', (3641, 3664), False, 'from sklearn import preprocessing\n'), ((4349, 4378), 'numpy.zeros', 'np.zeros', (['(faces.shape[0], 3)'], {}), '((faces.shape[0], 3))\n', (4357, 4378), True, 'import numpy as np\n'), ((4487, 4506), 'open3d.PointCloud', 'open3d.PointCloud', ([], {}), '()\n', (4504, 4506), False, 'import open3d\n'), ((4525, 4560), 'open3d.Vector3dVector', 'open3d.Vector3dVector', (['faces[:, :3]'], {}), '(faces[:, :3])\n', (4546, 4560), False, 'import open3d\n'), ((4579, 4616), 'open3d.Vector3dVector', 'open3d.Vector3dVector', (['(colors / 255.0)'], {}), '(colors / 255.0)\n', (4600, 4616), False, 'import open3d\n'), ((4617, 4648), 'open3d.draw_geometries', 'open3d.draw_geometries', (['[pcd_1]'], {}), '([pcd_1])\n', (4639, 4648), False, 'import open3d\n'), ((1314, 1335), 'numpy.array', 'np.array', (["hdf['data']"], {}), "(hdf['data'])\n", (1322, 1335), True, 'import numpy as np\n'), ((1353, 1375), 'numpy.array', 'np.array', (["hdf['label']"], {}), "(hdf['label'])\n", (1361, 1375), True, 'import numpy as np\n'), ((1740, 1770), 'numpy.take', 'np.take', (['face_tile', 'indices', '(0)'], {}), '(face_tile, indices, 0)\n', (1747, 1770), True, 'import numpy as np\n'), ((1787, 1815), 'numpy.take', 'np.take', (['label_tile', 'indices'], {}), '(label_tile, indices)\n', (1794, 1815), True, 'import numpy as np\n'), ((2538, 2587), 'numpy.concatenate', 'np.concatenate', (['(self.data_all, face_cur)'], {'axis': '(0)'}), '((self.data_all, face_cur), axis=0)\n', (2552, 2587), True, 'import numpy as np\n'), ((2609, 2652), 'numpy.concatenate', 'np.concatenate', (['(self.label_all, label_cur)'], {}), '((self.label_all, label_cur))\n', (2623, 2652), True, 'import numpy as np\n'), ((2892, 2907), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (2898, 2907), True, 'import numpy as np\n'), ((2988, 3012), 'numpy.ones', 'np.ones', (['self.nb_classes'], {}), '(self.nb_classes)\n', (2995, 3012), True, 'import numpy as np\n'), ((3377, 3397), 'numpy.argmax', 'np.argmax', (['distances'], {}), '(distances)\n', (3386, 3397), True, 'import numpy as np\n'), ((1861, 1887), 'scipy.spatial.cKDTree', 'cKDTree', (['face_tile[:, 0:3]'], {}), '(face_tile[:, 0:3])\n', (1868, 1887), False, 'from scipy.spatial import cKDTree\n'), ((1663, 1682), 'numpy.array', 'np.array', (['face_tile'], {}), '(face_tile)\n', (1671, 1682), True, 'import numpy as np\n'), ((2161, 2191), 'numpy.expand_dims', 'np.expand_dims', (['label_tile', '(-1)'], {}), '(label_tile, -1)\n', (2175, 2191), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
import pytest
from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap
from plotnine import geom_abline, annotate
from plotnine.data import mpg
from plotnine.exceptions import PlotnineWarning
n = 10
df = pd.DataFrame({'x': range(n),
'y': range(n),
'var1': np.repeat(range(n//2), 2),
'var2': np.tile(['a', 'b'], n//2),
})
df['class'] = df['var1'] # python keyword as column
df['g'] = df['var1'] # variable as a column
g = (ggplot(df, aes('x', 'y')) +
geom_point(aes(color='factor(var1)'),
size=5, show_legend=False))
# facet_wrap
def test_facet_wrap_one_var():
p = g + facet_wrap('~var1')
p2 = g + facet_wrap('~class') # python keyword in formula
p3 = g + facet_wrap('~g') # variable in formula
assert p == 'facet_wrap_one_var'
assert p2 == 'facet_wrap_one_var'
assert p3 == 'facet_wrap_one_var'
# https://github.com/pandas-dev/pandas/issues/16276
@pytest.mark.xfail
def test_facet_wrap_expression():
p = g + facet_wrap('pd.cut(var1, (0, 2, 4), include_lowest=True)')
assert p == 'facet_wrap_expression'
def test_facet_wrap_two_vars():
p = g + facet_wrap('~var1+var2')
p2 = g + facet_wrap('~class+var2') # python keyword in formula
assert p == 'facet_wrap_two_vars'
assert p2 == 'facet_wrap_two_vars'
def test_facet_wrap_label_both():
p = g + facet_wrap('~var1+var2', labeller='label_both')
assert p == 'facet_wrap_label_both'
def test_facet_wrap_not_as_table():
p = g + facet_wrap('~var1', as_table=False)
assert p == 'facet_wrap_not_as_table'
def test_facet_wrap_direction_v():
p = g + facet_wrap('~var1', dir='v')
assert p == 'facet_wrap_direction_v'
def test_facet_wrap_not_as_table_direction_v():
p = g + facet_wrap('~var1', as_table=False, dir='v')
assert p == 'facet_wrap_not_as_table_direction_v'
def test_facet_wrap_axis_text_space_warning():
p = g + facet_wrap('~var1', scales='free_y')
with pytest.warns(PlotnineWarning) as record:
p.draw_test()
record = list(record) # iterate more than 1 time
assert any('wspace' in str(r.message) for r in record)
p = g + facet_wrap('~var1', scales='free_x')
with pytest.warns(PlotnineWarning) as record:
p.draw_test()
record = list(record) # iterate more than 1 time
assert any('hspace' in str(r.message) for r in record)
# facet_grid
def test_facet_grid_one_by_one_var():
p = g + facet_grid('var1~var2')
p2 = g + facet_grid('class~var2') # python keyword in formula
assert p == 'facet_grid_one_by_one_var'
assert p2 == 'facet_grid_one_by_one_var'
# https://github.com/pandas-dev/pandas/issues/16276
@pytest.mark.xfail
def test_facet_grid_expression():
p = g + facet_grid(
['var2', 'pd.cut(var1, (0, 2, 4), include_lowest=True)'])
assert p == 'facet_grid_expression'
def test_facet_grid_margins():
p = g + facet_grid('var1~var2', margins=True)
assert p == 'facet_grid_margins'
def test_facet_grid_scales_free_y():
p = g + facet_grid('var1>2 ~ x%2', scales='free_y')
assert p == 'facet_grid_scales_free_y'
def test_facet_grid_formula_with_dot():
p = g + facet_grid('. ~ var1>2')
assert p == 'facet_grid_formula_with_dot'
def test_facet_grid_formula_without_dot():
p = g + facet_grid('~var1>2')
assert p == 'facet_grid_formula_with_dot'
def test_facet_grid_scales_free_x():
p = g + facet_grid('var1>2 ~ x%2', scales='free_x')
assert p == 'facet_grid_scales_free_x'
# Edge cases
def test_non_mapped_facetting():
p = (g
+ geom_abline(intercept=0, slope=1, size=1)
+ facet_wrap('var1')
)
assert p == 'non_mapped_facetting'
def test_dir_v_ncol():
p = (ggplot(mpg)
+ aes(x='displ', y='hwy')
+ facet_wrap('class', dir='v', ncol=4, as_table=False)
+ geom_point()
)
assert p == 'dir_v_ncol'
def test_variable_and_annotate():
p = (g
+ annotate('point', x=4.5, y=5.5, color='cyan', size=10)
+ facet_wrap('~g')
)
assert p == 'variable_and_annotate'
| [
"plotnine.facet_grid",
"numpy.tile",
"plotnine.ggplot",
"plotnine.annotate",
"plotnine.aes",
"plotnine.facet_wrap",
"plotnine.geom_point",
"plotnine.geom_abline",
"pytest.warns"
] | [((401, 428), 'numpy.tile', 'np.tile', (["['a', 'b']", '(n // 2)'], {}), "(['a', 'b'], n // 2)\n", (408, 428), True, 'import numpy as np\n'), ((569, 582), 'plotnine.aes', 'aes', (['"""x"""', '"""y"""'], {}), "('x', 'y')\n", (572, 582), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((602, 627), 'plotnine.aes', 'aes', ([], {'color': '"""factor(var1)"""'}), "(color='factor(var1)')\n", (605, 627), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((732, 751), 'plotnine.facet_wrap', 'facet_wrap', (['"""~var1"""'], {}), "('~var1')\n", (742, 751), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((765, 785), 'plotnine.facet_wrap', 'facet_wrap', (['"""~class"""'], {}), "('~class')\n", (775, 785), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((828, 844), 'plotnine.facet_wrap', 'facet_wrap', (['"""~g"""'], {}), "('~g')\n", (838, 844), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((1104, 1162), 'plotnine.facet_wrap', 'facet_wrap', (['"""pd.cut(var1, (0, 2, 4), include_lowest=True)"""'], {}), "('pd.cut(var1, (0, 2, 4), include_lowest=True)')\n", (1114, 1162), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((1249, 1273), 'plotnine.facet_wrap', 'facet_wrap', (['"""~var1+var2"""'], {}), "('~var1+var2')\n", (1259, 1273), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((1287, 1312), 'plotnine.facet_wrap', 'facet_wrap', (['"""~class+var2"""'], {}), "('~class+var2')\n", (1297, 1312), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((1467, 1514), 'plotnine.facet_wrap', 'facet_wrap', (['"""~var1+var2"""'], {'labeller': '"""label_both"""'}), "('~var1+var2', labeller='label_both')\n", (1477, 1514), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((1605, 1640), 'plotnine.facet_wrap', 'facet_wrap', (['"""~var1"""'], {'as_table': '(False)'}), "('~var1', as_table=False)\n", (1615, 1640), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((1732, 1760), 'plotnine.facet_wrap', 'facet_wrap', (['"""~var1"""'], {'dir': '"""v"""'}), "('~var1', dir='v')\n", (1742, 1760), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((1864, 1908), 'plotnine.facet_wrap', 'facet_wrap', (['"""~var1"""'], {'as_table': '(False)', 'dir': '"""v"""'}), "('~var1', as_table=False, dir='v')\n", (1874, 1908), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((2024, 2060), 'plotnine.facet_wrap', 'facet_wrap', (['"""~var1"""'], {'scales': '"""free_y"""'}), "('~var1', scales='free_y')\n", (2034, 2060), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((2070, 2099), 'pytest.warns', 'pytest.warns', (['PlotnineWarning'], {}), '(PlotnineWarning)\n', (2082, 2099), False, 'import pytest\n'), ((2260, 2296), 'plotnine.facet_wrap', 'facet_wrap', (['"""~var1"""'], {'scales': '"""free_x"""'}), "('~var1', scales='free_x')\n", (2270, 2296), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((2306, 2335), 'pytest.warns', 'pytest.warns', (['PlotnineWarning'], {}), '(PlotnineWarning)\n', (2318, 2335), False, 'import pytest\n'), ((2549, 2572), 'plotnine.facet_grid', 'facet_grid', (['"""var1~var2"""'], {}), "('var1~var2')\n", (2559, 2572), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((2586, 2610), 'plotnine.facet_grid', 'facet_grid', (['"""class~var2"""'], {}), "('class~var2')\n", (2596, 2610), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((2848, 2916), 'plotnine.facet_grid', 'facet_grid', (["['var2', 'pd.cut(var1, (0, 2, 4), include_lowest=True)']"], {}), "(['var2', 'pd.cut(var1, (0, 2, 4), include_lowest=True)'])\n", (2858, 2916), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((3011, 3048), 'plotnine.facet_grid', 'facet_grid', (['"""var1~var2"""'], {'margins': '(True)'}), "('var1~var2', margins=True)\n", (3021, 3048), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((3137, 3180), 'plotnine.facet_grid', 'facet_grid', (['"""var1>2 ~ x%2"""'], {'scales': '"""free_y"""'}), "('var1>2 ~ x%2', scales='free_y')\n", (3147, 3180), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((3278, 3302), 'plotnine.facet_grid', 'facet_grid', (['""". ~ var1>2"""'], {}), "('. ~ var1>2')\n", (3288, 3302), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((3406, 3427), 'plotnine.facet_grid', 'facet_grid', (['"""~var1>2"""'], {}), "('~var1>2')\n", (3416, 3427), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((3525, 3568), 'plotnine.facet_grid', 'facet_grid', (['"""var1>2 ~ x%2"""'], {'scales': '"""free_x"""'}), "('var1>2 ~ x%2', scales='free_x')\n", (3535, 3568), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((3736, 3754), 'plotnine.facet_wrap', 'facet_wrap', (['"""var1"""'], {}), "('var1')\n", (3746, 3754), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((3961, 3973), 'plotnine.geom_point', 'geom_point', ([], {}), '()\n', (3971, 3973), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((4138, 4154), 'plotnine.facet_wrap', 'facet_wrap', (['"""~g"""'], {}), "('~g')\n", (4148, 4154), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((3683, 3724), 'plotnine.geom_abline', 'geom_abline', ([], {'intercept': '(0)', 'slope': '(1)', 'size': '(1)'}), '(intercept=0, slope=1, size=1)\n', (3694, 3724), False, 'from plotnine import geom_abline, annotate\n'), ((3897, 3949), 'plotnine.facet_wrap', 'facet_wrap', (['"""class"""'], {'dir': '"""v"""', 'ncol': '(4)', 'as_table': '(False)'}), "('class', dir='v', ncol=4, as_table=False)\n", (3907, 3949), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((4072, 4126), 'plotnine.annotate', 'annotate', (['"""point"""'], {'x': '(4.5)', 'y': '(5.5)', 'color': '"""cyan"""', 'size': '(10)'}), "('point', x=4.5, y=5.5, color='cyan', size=10)\n", (4080, 4126), False, 'from plotnine import geom_abline, annotate\n'), ((3839, 3850), 'plotnine.ggplot', 'ggplot', (['mpg'], {}), '(mpg)\n', (3845, 3850), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n'), ((3862, 3885), 'plotnine.aes', 'aes', ([], {'x': '"""displ"""', 'y': '"""hwy"""'}), "(x='displ', y='hwy')\n", (3865, 3885), False, 'from plotnine import ggplot, aes, geom_point, facet_grid, facet_wrap\n')] |
import json
import tempfile
from fastapi import Depends, FastAPI
import numpy as np
import requests
from requests.adapters import HTTPAdapter, Retry
from ray._private.test_utils import wait_for_condition
from ray.air.checkpoint import Checkpoint
from ray.air.predictor import DataBatchType, Predictor
from ray.serve.model_wrappers import ModelWrapperDeployment
from ray.serve.pipeline.api import build
from ray.serve.dag import InputNode
from ray.serve.deployment_graph import RayServeDAGHandle
from ray.serve.http_adapters import json_to_ndarray
import ray
from ray import serve
class AdderPredictor(Predictor):
def __init__(self, increment: int) -> None:
self.increment = increment
@classmethod
def from_checkpoint(cls, checkpoint: "AdderCheckpoint") -> "Predictor":
if checkpoint._data_dict:
return cls(checkpoint._data_dict["increment"])
elif checkpoint._local_path: # uri case
with open(checkpoint._local_path) as f:
return cls(json.load(f))
raise Exception("Unreachable")
def predict(self, data: DataBatchType) -> DataBatchType:
return [
{"value": val, "batch_size": len(data)}
for val in (np.array(data) + self.increment).tolist()
]
class AdderCheckpoint(Checkpoint):
pass
def adder_schema(query_param_arg: int) -> DataBatchType:
return np.array([query_param_arg])
@ray.remote
def send_request(**requests_kargs):
return requests.post("http://localhost:8000/Adder/", **requests_kargs).json()
def test_simple_adder(serve_instance):
ModelWrapperDeployment.options(name="Adder").deploy(
predictor_cls=AdderPredictor,
checkpoint=AdderCheckpoint.from_dict({"increment": 2}),
)
resp = ray.get(send_request.remote(json={"array": [40]}))
assert resp == {"value": [42], "batch_size": 1}
def test_batching(serve_instance):
ModelWrapperDeployment.options(name="Adder").deploy(
predictor_cls=AdderPredictor,
checkpoint=AdderCheckpoint.from_dict({"increment": 2}),
batching_params=dict(max_batch_size=2, batch_wait_timeout_s=1000),
)
refs = [send_request.remote(json={"array": [40]}) for _ in range(2)]
for resp in ray.get(refs):
assert resp == {"value": [42], "batch_size": 2}
app = FastAPI()
@serve.deployment(route_prefix="/ingress")
@serve.ingress(app)
class Ingress:
def __init__(self, dag: RayServeDAGHandle) -> None:
self.dag = dag
@app.post("/")
async def predict(self, data=Depends(json_to_ndarray)):
return await self.dag.remote(data)
def test_model_wrappers_in_pipeline(serve_instance):
_, path = tempfile.mkstemp()
with open(path, "w") as f:
json.dump(2, f)
predictor_cls = "ray.serve.tests.test_model_wrappers.AdderPredictor"
checkpoint_cls = "ray.serve.tests.test_model_wrappers.AdderCheckpoint"
with InputNode() as dag_input:
m1 = ModelWrapperDeployment.bind(
predictor_cls=predictor_cls, # TODO: can't be the raw class right now?
checkpoint={ # TODO: can't be the raw object right now?
"checkpoint_cls": checkpoint_cls,
"uri": path,
},
)
dag = m1.predict.bind(dag_input)
deployments = build(Ingress.bind(dag))
for d in deployments:
d.deploy()
resp = requests.post("http://1192.168.3.11:8000/ingress", json={"array": [40]})
print(resp.text)
resp.raise_for_status()
return resp.json() == {"value": [42], "batch_size": 1}
# NOTE(simon): Make sure this is the last test because the REST API will start
# controller and http proxy in another namespace.
def test_yaml_compatibility(serve_instance):
_, path = tempfile.mkstemp()
with open(path, "w") as f:
json.dump(2, f)
session = requests.Session()
retries = Retry(total=5, backoff_factor=0.1)
session.mount("http://", HTTPAdapter(max_retries=retries))
# TODO(simon): use ServeSubmissionClient when it's merged.
predictor_cls = "ray.serve.tests.test_model_wrappers.AdderPredictor"
checkpoint_cls = "ray.serve.tests.test_model_wrappers.AdderCheckpoint"
schema_func = "ray.serve.tests.test_model_wrappers.adder_schema"
resp = session.put(
"http://127.0.0.1:8265/api/serve/deployments/",
json={
"deployments": [
{
"name": "Adder",
"import_path": "ray.serve.model_wrappers.ModelWrapperDeployment",
"init_kwargs": {
"predictor_cls": predictor_cls,
"checkpoint": {
"checkpoint_cls": checkpoint_cls,
"uri": path,
},
"http_adapter": schema_func,
"batching_params": {"max_batch_size": 1},
},
}
]
},
)
resp.raise_for_status()
# Note(simon): The Serve HTTP deploy is non blocking,
# so we retries to make sure the deployment is up
def cond():
resp = ray.get(send_request.remote(params={"query_param_arg": 40}))
return resp == {"value": [42], "batch_size": 1}
wait_for_condition(cond)
| [
"ray.serve.ingress",
"fastapi.FastAPI",
"requests.post",
"requests.Session",
"ray.get",
"ray.serve.dag.InputNode",
"requests.adapters.HTTPAdapter",
"ray.serve.deployment",
"numpy.array",
"fastapi.Depends",
"ray.serve.model_wrappers.ModelWrapperDeployment.options",
"ray.serve.model_wrappers.Mod... | [((2317, 2326), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (2324, 2326), False, 'from fastapi import Depends, FastAPI\n'), ((2330, 2371), 'ray.serve.deployment', 'serve.deployment', ([], {'route_prefix': '"""/ingress"""'}), "(route_prefix='/ingress')\n", (2346, 2371), False, 'from ray import serve\n'), ((2373, 2391), 'ray.serve.ingress', 'serve.ingress', (['app'], {}), '(app)\n', (2386, 2391), False, 'from ray import serve\n'), ((1391, 1418), 'numpy.array', 'np.array', (['[query_param_arg]'], {}), '([query_param_arg])\n', (1399, 1418), True, 'import numpy as np\n'), ((2238, 2251), 'ray.get', 'ray.get', (['refs'], {}), '(refs)\n', (2245, 2251), False, 'import ray\n'), ((2678, 2696), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {}), '()\n', (2694, 2696), False, 'import tempfile\n'), ((3377, 3449), 'requests.post', 'requests.post', (['"""http://1192.168.3.11:8000/ingress"""'], {'json': "{'array': [40]}"}), "('http://1192.168.3.11:8000/ingress', json={'array': [40]})\n", (3390, 3449), False, 'import requests\n'), ((3748, 3766), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {}), '()\n', (3764, 3766), False, 'import tempfile\n'), ((3837, 3855), 'requests.Session', 'requests.Session', ([], {}), '()\n', (3853, 3855), False, 'import requests\n'), ((3870, 3904), 'requests.adapters.Retry', 'Retry', ([], {'total': '(5)', 'backoff_factor': '(0.1)'}), '(total=5, backoff_factor=0.1)\n', (3875, 3904), False, 'from requests.adapters import HTTPAdapter, Retry\n'), ((5263, 5287), 'ray._private.test_utils.wait_for_condition', 'wait_for_condition', (['cond'], {}), '(cond)\n', (5281, 5287), False, 'from ray._private.test_utils import wait_for_condition\n'), ((2539, 2563), 'fastapi.Depends', 'Depends', (['json_to_ndarray'], {}), '(json_to_ndarray)\n', (2546, 2563), False, 'from fastapi import Depends, FastAPI\n'), ((2736, 2751), 'json.dump', 'json.dump', (['(2)', 'f'], {}), '(2, f)\n', (2745, 2751), False, 'import json\n'), ((2911, 2922), 'ray.serve.dag.InputNode', 'InputNode', ([], {}), '()\n', (2920, 2922), False, 'from ray.serve.dag import InputNode\n'), ((2950, 3071), 'ray.serve.model_wrappers.ModelWrapperDeployment.bind', 'ModelWrapperDeployment.bind', ([], {'predictor_cls': 'predictor_cls', 'checkpoint': "{'checkpoint_cls': checkpoint_cls, 'uri': path}"}), "(predictor_cls=predictor_cls, checkpoint={\n 'checkpoint_cls': checkpoint_cls, 'uri': path})\n", (2977, 3071), False, 'from ray.serve.model_wrappers import ModelWrapperDeployment\n'), ((3806, 3821), 'json.dump', 'json.dump', (['(2)', 'f'], {}), '(2, f)\n', (3815, 3821), False, 'import json\n'), ((3934, 3966), 'requests.adapters.HTTPAdapter', 'HTTPAdapter', ([], {'max_retries': 'retries'}), '(max_retries=retries)\n', (3945, 3966), False, 'from requests.adapters import HTTPAdapter, Retry\n'), ((1480, 1543), 'requests.post', 'requests.post', (['"""http://localhost:8000/Adder/"""'], {}), "('http://localhost:8000/Adder/', **requests_kargs)\n", (1493, 1543), False, 'import requests\n'), ((1596, 1640), 'ray.serve.model_wrappers.ModelWrapperDeployment.options', 'ModelWrapperDeployment.options', ([], {'name': '"""Adder"""'}), "(name='Adder')\n", (1626, 1640), False, 'from ray.serve.model_wrappers import ModelWrapperDeployment\n'), ((1912, 1956), 'ray.serve.model_wrappers.ModelWrapperDeployment.options', 'ModelWrapperDeployment.options', ([], {'name': '"""Adder"""'}), "(name='Adder')\n", (1942, 1956), False, 'from ray.serve.model_wrappers import ModelWrapperDeployment\n'), ((1015, 1027), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1024, 1027), False, 'import json\n'), ((1223, 1237), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (1231, 1237), True, 'import numpy as np\n')] |
import cv2
from social_distancing import *
import numpy as np
birds_eye = cv2.imread('test_street_bird.jpg')
boxes_image = cv2.imread('test_street_boxes.jpg')
points = [[191, 487], [254, 388], [55, 387], [330, 370], [450, 330], [377, 274]]
birds, matrix = full_social_distancing(boxes_image, points, 80)
inv = np.linalg.inv(matrix)
inverted_image = cv2.warpPerspective(birds, inv, (960, 640))
added = cv2.add(boxes_image, inverted_image)
cv2.imshow('inverted', added)
cv2.imwrite('combined_street.jpg', added)
cv2.waitKey(0) | [
"cv2.imwrite",
"cv2.imshow",
"cv2.warpPerspective",
"numpy.linalg.inv",
"cv2.waitKey",
"cv2.imread",
"cv2.add"
] | [((75, 109), 'cv2.imread', 'cv2.imread', (['"""test_street_bird.jpg"""'], {}), "('test_street_bird.jpg')\n", (85, 109), False, 'import cv2\n'), ((124, 159), 'cv2.imread', 'cv2.imread', (['"""test_street_boxes.jpg"""'], {}), "('test_street_boxes.jpg')\n", (134, 159), False, 'import cv2\n'), ((312, 333), 'numpy.linalg.inv', 'np.linalg.inv', (['matrix'], {}), '(matrix)\n', (325, 333), True, 'import numpy as np\n'), ((352, 395), 'cv2.warpPerspective', 'cv2.warpPerspective', (['birds', 'inv', '(960, 640)'], {}), '(birds, inv, (960, 640))\n', (371, 395), False, 'import cv2\n'), ((404, 440), 'cv2.add', 'cv2.add', (['boxes_image', 'inverted_image'], {}), '(boxes_image, inverted_image)\n', (411, 440), False, 'import cv2\n'), ((441, 470), 'cv2.imshow', 'cv2.imshow', (['"""inverted"""', 'added'], {}), "('inverted', added)\n", (451, 470), False, 'import cv2\n'), ((471, 512), 'cv2.imwrite', 'cv2.imwrite', (['"""combined_street.jpg"""', 'added'], {}), "('combined_street.jpg', added)\n", (482, 512), False, 'import cv2\n'), ((514, 528), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (525, 528), False, 'import cv2\n')] |
import datetime
import os
import tempfile
from collections import OrderedDict
import boto3
import pandas as pd
import pytest
import yaml
from moto import mock_s3
from numpy.testing import assert_almost_equal
from pandas.testing import assert_frame_equal
from unittest import mock
from triage.component.catwalk.storage import (
MatrixStore,
CSVMatrixStore,
FSStore,
S3Store,
ProjectStorage,
ModelStorageEngine,
)
from tests.utils import CallSpy
class SomeClass:
def __init__(self, val):
self.val = val
def test_S3Store():
with mock_s3():
client = boto3.client("s3")
client.create_bucket(Bucket="test_bucket", ACL="public-read-write")
store = S3Store(f"s3://test_bucket/a_path")
assert not store.exists()
store.write("val".encode("utf-8"))
assert store.exists()
newVal = store.load()
assert newVal.decode("utf-8") == "val"
store.delete()
assert not store.exists()
@mock_s3
def test_S3Store_large():
client = boto3.client('s3')
client.create_bucket(Bucket='test_bucket', ACL='public-read-write')
store = S3Store('s3://test_bucket/a_path')
assert not store.exists()
# NOTE: The issue under test (currently) arises when too large a "part"
# NOTE: is sent to S3 for upload -- greater than its 5 GiB limit on any
# NOTE: single upload request.
#
# NOTE: Though s3fs uploads file parts as soon as its buffer reaches
# NOTE: 5+ MiB, it does not ensure that its buffer -- and resulting
# NOTE: upload "parts" -- remain under this limit (as the result of a
# NOTE: single "write()").
#
# NOTE: Therefore, until s3fs adds handling to ensure it never attempts
# NOTE: to upload such large payloads, we'll handle this in S3Store,
# NOTE: by chunking out writes to s3fs.
#
# NOTE: This is all not only to explain the raison d'etre of this test,
# NOTE: but also as context for the following warning: The
# NOTE: payload we'll attempt to write, below, is far less than 5 GiB!!
# NOTE: (Attempting to provision a 5 GiB string in RAM just for this
# NOTE: test would be an ENORMOUS drag on test runs, and a conceivable
# NOTE: disruption, depending on the test environment's resources.)
#
# NOTE: As such, this test *may* fall out of sync with either the code
# NOTE: that it means to test or with the reality of the S3 API -- even
# NOTE: to the point of self-invalidation. (But, this should do the
# NOTE: trick; and, we can always increase the payload size here, or
# NOTE: otherwise tweak configuration, as necessary.)
one_mb = 2 ** 20
payload = b"0" * (10 * one_mb) # 10MiB text of all zeros
with CallSpy('botocore.client.BaseClient._make_api_call') as spy:
store.write(payload)
call_args = [call[0] for call in spy.calls]
call_methods = [args[1] for args in call_args]
assert call_methods == [
'CreateMultipartUpload',
'UploadPart',
'UploadPart',
'CompleteMultipartUpload',
]
upload_args = call_args[1]
upload_body = upload_args[2]['Body']
# NOTE: Why is this a BufferIO rather than the underlying buffer?!
# NOTE: (Would have expected the result of BufferIO.read() -- str.)
body_length = len(upload_body.getvalue())
assert body_length == 5 * one_mb
assert store.exists()
assert store.load() == payload
store.delete()
assert not store.exists()
def test_FSStore():
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, "tmpfile")
store = FSStore(tmpfile)
assert not store.exists()
store.write("val".encode("utf-8"))
assert store.exists()
newVal = store.load()
assert newVal.decode("utf-8") == "val"
store.delete()
assert not store.exists()
def test_ModelStorageEngine_nocaching(project_storage):
mse = ModelStorageEngine(project_storage)
mse.write('testobject', 'myhash')
assert mse.exists('myhash')
assert mse.load('myhash') == 'testobject'
assert 'myhash' not in mse.cache
def test_ModelStorageEngine_caching(project_storage):
mse = ModelStorageEngine(project_storage)
with mse.cache_models():
mse.write('testobject', 'myhash')
with mock.patch.object(mse, "_get_store") as get_store_mock:
assert mse.load('myhash') == 'testobject'
assert not get_store_mock.called
assert 'myhash' in mse.cache
# when cache_models goes out of scope the cache should be empty
assert 'myhash' not in mse.cache
DATA_DICT = OrderedDict(
[
("entity_id", [1, 2]),
("as_of_date", [datetime.date(2017, 1, 1), datetime.date(2017, 1, 1)]),
("k_feature", [0.5, 0.4]),
("m_feature", [0.4, 0.5]),
("label", [0, 1]),
]
)
METADATA = {"label_name": "label"}
def matrix_stores():
df = pd.DataFrame.from_dict(DATA_DICT).set_index(MatrixStore.indices)
with tempfile.TemporaryDirectory() as tmpdir:
project_storage = ProjectStorage(tmpdir)
tmpcsv = os.path.join(tmpdir, "df.csv.gz")
tmpyaml = os.path.join(tmpdir, "df.yaml")
with open(tmpyaml, "w") as outfile:
yaml.dump(METADATA, outfile, default_flow_style=False)
df.to_csv(tmpcsv, compression="gzip")
csv = CSVMatrixStore(project_storage, [], "df")
# first test with caching
with csv.cache():
yield csv
# with the caching out of scope they will be nuked
# and this last version will not have any cache
yield csv
def test_MatrixStore_empty():
for matrix_store in matrix_stores():
assert not matrix_store.empty
def test_MatrixStore_metadata():
for matrix_store in matrix_stores():
assert matrix_store.metadata == METADATA
def test_MatrixStore_columns():
for matrix_store in matrix_stores():
assert matrix_store.columns() == ["k_feature", "m_feature"]
def test_MatrixStore_resort_columns():
for matrix_store in matrix_stores():
result = matrix_store.matrix_with_sorted_columns(
["m_feature", "k_feature"]
).values.tolist()
expected = [[0.4, 0.5], [0.5, 0.4]]
assert_almost_equal(expected, result)
def test_MatrixStore_already_sorted_columns():
for matrix_store in matrix_stores():
result = matrix_store.matrix_with_sorted_columns(
["k_feature", "m_feature"]
).values.tolist()
expected = [[0.5, 0.4], [0.4, 0.5]]
assert_almost_equal(expected, result)
def test_MatrixStore_sorted_columns_subset():
with pytest.raises(ValueError):
for matrix_store in matrix_stores():
matrix_store.matrix_with_sorted_columns(["m_feature"]).values.tolist()
def test_MatrixStore_sorted_columns_superset():
with pytest.raises(ValueError):
for matrix_store in matrix_stores():
matrix_store.matrix_with_sorted_columns(
["k_feature", "l_feature", "m_feature"]
).values.tolist()
def test_MatrixStore_sorted_columns_mismatch():
with pytest.raises(ValueError):
for matrix_store in matrix_stores():
matrix_store.matrix_with_sorted_columns(
["k_feature", "l_feature"]
).values.tolist()
def test_MatrixStore_labels_idempotency():
for matrix_store in matrix_stores():
assert matrix_store.labels.tolist() == [0, 1]
assert matrix_store.labels.tolist() == [0, 1]
def test_MatrixStore_save():
data = {
"entity_id": [1, 2],
"as_of_date": [pd.Timestamp(2017, 1, 1), pd.Timestamp(2017, 1, 1)],
"feature_one": [0.5, 0.6],
"feature_two": [0.5, 0.6],
"label": [1, 0]
}
df = pd.DataFrame.from_dict(data)
labels = df.pop("label")
for matrix_store in matrix_stores():
matrix_store.metadata = METADATA
matrix_store.matrix_label_tuple = df, labels
matrix_store.save()
assert_frame_equal(
matrix_store.design_matrix,
df
)
def test_MatrixStore_caching():
for matrix_store in matrix_stores():
with matrix_store.cache():
matrix = matrix_store.design_matrix
with mock.patch.object(matrix_store, "_load") as load_mock:
assert_frame_equal(matrix_store.design_matrix, matrix)
assert not load_mock.called
def test_as_of_dates(project_storage):
data = {
"entity_id": [1, 2, 1, 2],
"feature_one": [0.5, 0.6, 0.5, 0.6],
"feature_two": [0.5, 0.6, 0.5, 0.6],
"as_of_date": [
pd.Timestamp(2016, 1, 1),
pd.Timestamp(2016, 1, 1),
pd.Timestamp(2017, 1, 1),
pd.Timestamp(2017, 1, 1),
],
"label": [1, 0, 1, 0]
}
df = pd.DataFrame.from_dict(data)
matrix_store = CSVMatrixStore(
project_storage,
[],
"test",
matrix=df,
metadata={"indices": ["entity_id", "as_of_date"], "label_name": "label"}
)
assert matrix_store.as_of_dates == [datetime.date(2016, 1, 1), datetime.date(2017, 1, 1)]
def test_s3_save():
with mock_s3():
client = boto3.client("s3")
client.create_bucket(Bucket="fake-matrix-bucket", ACL="public-read-write")
for example in matrix_stores():
if not isinstance(example, CSVMatrixStore):
continue
project_storage = ProjectStorage("s3://fake-matrix-bucket")
tosave = CSVMatrixStore(project_storage, [], "test")
tosave.metadata = example.metadata
tosave.matrix_label_tuple = example.matrix_label_tuple
tosave.save()
tocheck = CSVMatrixStore(project_storage, [], "test")
assert tocheck.metadata == example.metadata
assert tocheck.design_matrix.to_dict() == example.design_matrix.to_dict()
| [
"triage.component.catwalk.storage.S3Store",
"tempfile.TemporaryDirectory",
"tests.utils.CallSpy",
"triage.component.catwalk.storage.ModelStorageEngine",
"boto3.client",
"yaml.dump",
"triage.component.catwalk.storage.ProjectStorage",
"triage.component.catwalk.storage.FSStore",
"os.path.join",
"pand... | [((1040, 1058), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (1052, 1058), False, 'import boto3\n'), ((1144, 1178), 'triage.component.catwalk.storage.S3Store', 'S3Store', (['"""s3://test_bucket/a_path"""'], {}), "('s3://test_bucket/a_path')\n", (1151, 1178), False, 'from triage.component.catwalk.storage import MatrixStore, CSVMatrixStore, FSStore, S3Store, ProjectStorage, ModelStorageEngine\n'), ((3960, 3995), 'triage.component.catwalk.storage.ModelStorageEngine', 'ModelStorageEngine', (['project_storage'], {}), '(project_storage)\n', (3978, 3995), False, 'from triage.component.catwalk.storage import MatrixStore, CSVMatrixStore, FSStore, S3Store, ProjectStorage, ModelStorageEngine\n'), ((4215, 4250), 'triage.component.catwalk.storage.ModelStorageEngine', 'ModelStorageEngine', (['project_storage'], {}), '(project_storage)\n', (4233, 4250), False, 'from triage.component.catwalk.storage import MatrixStore, CSVMatrixStore, FSStore, S3Store, ProjectStorage, ModelStorageEngine\n'), ((7811, 7839), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['data'], {}), '(data)\n', (7833, 7839), True, 'import pandas as pd\n'), ((8883, 8911), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['data'], {}), '(data)\n', (8905, 8911), True, 'import pandas as pd\n'), ((8931, 9063), 'triage.component.catwalk.storage.CSVMatrixStore', 'CSVMatrixStore', (['project_storage', '[]', '"""test"""'], {'matrix': 'df', 'metadata': "{'indices': ['entity_id', 'as_of_date'], 'label_name': 'label'}"}), "(project_storage, [], 'test', matrix=df, metadata={'indices':\n ['entity_id', 'as_of_date'], 'label_name': 'label'})\n", (8945, 9063), False, 'from triage.component.catwalk.storage import MatrixStore, CSVMatrixStore, FSStore, S3Store, ProjectStorage, ModelStorageEngine\n'), ((574, 583), 'moto.mock_s3', 'mock_s3', ([], {}), '()\n', (581, 583), False, 'from moto import mock_s3\n'), ((602, 620), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (614, 620), False, 'import boto3\n'), ((713, 748), 'triage.component.catwalk.storage.S3Store', 'S3Store', (['f"""s3://test_bucket/a_path"""'], {}), "(f's3://test_bucket/a_path')\n", (720, 748), False, 'from triage.component.catwalk.storage import MatrixStore, CSVMatrixStore, FSStore, S3Store, ProjectStorage, ModelStorageEngine\n'), ((2746, 2798), 'tests.utils.CallSpy', 'CallSpy', (['"""botocore.client.BaseClient._make_api_call"""'], {}), "('botocore.client.BaseClient._make_api_call')\n", (2753, 2798), False, 'from tests.utils import CallSpy\n'), ((3527, 3556), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (3554, 3556), False, 'import tempfile\n'), ((3586, 3617), 'os.path.join', 'os.path.join', (['tmpdir', '"""tmpfile"""'], {}), "(tmpdir, 'tmpfile')\n", (3598, 3617), False, 'import os\n'), ((3634, 3650), 'triage.component.catwalk.storage.FSStore', 'FSStore', (['tmpfile'], {}), '(tmpfile)\n', (3641, 3650), False, 'from triage.component.catwalk.storage import MatrixStore, CSVMatrixStore, FSStore, S3Store, ProjectStorage, ModelStorageEngine\n'), ((5024, 5053), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (5051, 5053), False, 'import tempfile\n'), ((5091, 5113), 'triage.component.catwalk.storage.ProjectStorage', 'ProjectStorage', (['tmpdir'], {}), '(tmpdir)\n', (5105, 5113), False, 'from triage.component.catwalk.storage import MatrixStore, CSVMatrixStore, FSStore, S3Store, ProjectStorage, ModelStorageEngine\n'), ((5131, 5164), 'os.path.join', 'os.path.join', (['tmpdir', '"""df.csv.gz"""'], {}), "(tmpdir, 'df.csv.gz')\n", (5143, 5164), False, 'import os\n'), ((5183, 5214), 'os.path.join', 'os.path.join', (['tmpdir', '"""df.yaml"""'], {}), "(tmpdir, 'df.yaml')\n", (5195, 5214), False, 'import os\n'), ((5386, 5427), 'triage.component.catwalk.storage.CSVMatrixStore', 'CSVMatrixStore', (['project_storage', '[]', '"""df"""'], {}), "(project_storage, [], 'df')\n", (5400, 5427), False, 'from triage.component.catwalk.storage import MatrixStore, CSVMatrixStore, FSStore, S3Store, ProjectStorage, ModelStorageEngine\n'), ((6279, 6316), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['expected', 'result'], {}), '(expected, result)\n', (6298, 6316), False, 'from numpy.testing import assert_almost_equal\n'), ((6582, 6619), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['expected', 'result'], {}), '(expected, result)\n', (6601, 6619), False, 'from numpy.testing import assert_almost_equal\n'), ((6677, 6702), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (6690, 6702), False, 'import pytest\n'), ((6891, 6916), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (6904, 6916), False, 'import pytest\n'), ((7161, 7186), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7174, 7186), False, 'import pytest\n'), ((8042, 8092), 'pandas.testing.assert_frame_equal', 'assert_frame_equal', (['matrix_store.design_matrix', 'df'], {}), '(matrix_store.design_matrix, df)\n', (8060, 8092), False, 'from pandas.testing import assert_frame_equal\n'), ((9231, 9240), 'moto.mock_s3', 'mock_s3', ([], {}), '()\n', (9238, 9240), False, 'from moto import mock_s3\n'), ((9259, 9277), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (9271, 9277), False, 'import boto3\n'), ((4335, 4371), 'unittest.mock.patch.object', 'mock.patch.object', (['mse', '"""_get_store"""'], {}), "(mse, '_get_store')\n", (4352, 4371), False, 'from unittest import mock\n'), ((4949, 4982), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['DATA_DICT'], {}), '(DATA_DICT)\n', (4971, 4982), True, 'import pandas as pd\n'), ((5271, 5325), 'yaml.dump', 'yaml.dump', (['METADATA', 'outfile'], {'default_flow_style': '(False)'}), '(METADATA, outfile, default_flow_style=False)\n', (5280, 5325), False, 'import yaml\n'), ((7649, 7673), 'pandas.Timestamp', 'pd.Timestamp', (['(2017)', '(1)', '(1)'], {}), '(2017, 1, 1)\n', (7661, 7673), True, 'import pandas as pd\n'), ((7675, 7699), 'pandas.Timestamp', 'pd.Timestamp', (['(2017)', '(1)', '(1)'], {}), '(2017, 1, 1)\n', (7687, 7699), True, 'import pandas as pd\n'), ((8687, 8711), 'pandas.Timestamp', 'pd.Timestamp', (['(2016)', '(1)', '(1)'], {}), '(2016, 1, 1)\n', (8699, 8711), True, 'import pandas as pd\n'), ((8725, 8749), 'pandas.Timestamp', 'pd.Timestamp', (['(2016)', '(1)', '(1)'], {}), '(2016, 1, 1)\n', (8737, 8749), True, 'import pandas as pd\n'), ((8763, 8787), 'pandas.Timestamp', 'pd.Timestamp', (['(2017)', '(1)', '(1)'], {}), '(2017, 1, 1)\n', (8775, 8787), True, 'import pandas as pd\n'), ((8801, 8825), 'pandas.Timestamp', 'pd.Timestamp', (['(2017)', '(1)', '(1)'], {}), '(2017, 1, 1)\n', (8813, 8825), True, 'import pandas as pd\n'), ((9146, 9171), 'datetime.date', 'datetime.date', (['(2016)', '(1)', '(1)'], {}), '(2016, 1, 1)\n', (9159, 9171), False, 'import datetime\n'), ((9173, 9198), 'datetime.date', 'datetime.date', (['(2017)', '(1)', '(1)'], {}), '(2017, 1, 1)\n', (9186, 9198), False, 'import datetime\n'), ((9512, 9553), 'triage.component.catwalk.storage.ProjectStorage', 'ProjectStorage', (['"""s3://fake-matrix-bucket"""'], {}), "('s3://fake-matrix-bucket')\n", (9526, 9553), False, 'from triage.component.catwalk.storage import MatrixStore, CSVMatrixStore, FSStore, S3Store, ProjectStorage, ModelStorageEngine\n'), ((9576, 9619), 'triage.component.catwalk.storage.CSVMatrixStore', 'CSVMatrixStore', (['project_storage', '[]', '"""test"""'], {}), "(project_storage, [], 'test')\n", (9590, 9619), False, 'from triage.component.catwalk.storage import MatrixStore, CSVMatrixStore, FSStore, S3Store, ProjectStorage, ModelStorageEngine\n'), ((9783, 9826), 'triage.component.catwalk.storage.CSVMatrixStore', 'CSVMatrixStore', (['project_storage', '[]', '"""test"""'], {}), "(project_storage, [], 'test')\n", (9797, 9826), False, 'from triage.component.catwalk.storage import MatrixStore, CSVMatrixStore, FSStore, S3Store, ProjectStorage, ModelStorageEngine\n'), ((4720, 4745), 'datetime.date', 'datetime.date', (['(2017)', '(1)', '(1)'], {}), '(2017, 1, 1)\n', (4733, 4745), False, 'import datetime\n'), ((4747, 4772), 'datetime.date', 'datetime.date', (['(2017)', '(1)', '(1)'], {}), '(2017, 1, 1)\n', (4760, 4772), False, 'import datetime\n'), ((8302, 8342), 'unittest.mock.patch.object', 'mock.patch.object', (['matrix_store', '"""_load"""'], {}), "(matrix_store, '_load')\n", (8319, 8342), False, 'from unittest import mock\n'), ((8373, 8427), 'pandas.testing.assert_frame_equal', 'assert_frame_equal', (['matrix_store.design_matrix', 'matrix'], {}), '(matrix_store.design_matrix, matrix)\n', (8391, 8427), False, 'from pandas.testing import assert_frame_equal\n')] |
import numpy
import matplotlib as mpl
mpl.use('Agg')
from matplotlib import pyplot as plt
import matplotlib as mpl
from libKMCUDA import kmeans_cuda
# numpy.random.seed(0)
# arr = numpy.empty((10000, 2), dtype=numpy.float32)
# arr[:2500] = numpy.random.rand(2500, 2) + [0, 2]
# arr[2500:5000] = numpy.random.rand(2500, 2) - [0, 2]
# arr[5000:7500] = numpy.random.rand(2500, 2) + [2, 0]
# arr[7500:] = numpy.random.rand(2500, 2) - [2, 0]
# centroids, assignments, ave = kmeans_cuda(arr, 4, verbosity=2, average_distance=True, seed=3)
# print("avearge distance:", ave)
# print(centroids)
# plt.scatter(arr[:, 0], arr[:, 1], c=assignments)
# plt.scatter(centroids[:, 0], centroids[:, 1], c="white", s=150)
# plt.savefig("km_ex1.png")
numpy.random.seed(0)
arr = numpy.empty((10000, 2), dtype=numpy.float32)
for i in range(10000):
arr[i, :] = numpy.random.normal(size=2) * 0.5 + numpy.array([i // 1000, i // 1000 + 1])
print(arr[:10, :])
centroids, assignments, avg_distance = kmeans_cuda(
arr, 10, tolerance=0, metric="l2", verbosity=1, seed=3, average_distance=True)
print("Average distance between centroids and members:", avg_distance)
print(centroids)
plt.figure()
plt.scatter(arr[:, 0], arr[:, 1], c=assignments)
plt.scatter(centroids[:, 0], centroids[:, 1], c="white", s=150)
plt.savefig("km_ex2.png")
# numpy.random.seed(0)
# arr = numpy.empty((10000, 2), dtype=numpy.float32)
# angs = numpy.random.rand(10000) * 2 * numpy.pi
# for i in range(10000):
# arr[i] = numpy.sin(angs[i]), numpy.cos(angs[i])
# centroids, assignments, avg_distance = kmeans_cuda(
# arr, 4, metric="l2", verbosity=1, seed=3, average_distance=True)
# print("Average distance between centroids and members:", avg_distance)
# print(centroids)
# plt.figure()
# plt.scatter(arr[:, 0], arr[:, 1], c=assignments)
# plt.scatter(centroids[:, 0], centroids[:, 1], c="white", s=150)
# plt.savefig("km_ex3.png")
| [
"numpy.random.normal",
"matplotlib.pyplot.savefig",
"matplotlib.use",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.empty",
"numpy.random.seed",
"matplotlib.pyplot.scatter",
"libKMCUDA.kmeans_cuda"
] | [((38, 52), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (45, 52), True, 'import matplotlib as mpl\n'), ((734, 754), 'numpy.random.seed', 'numpy.random.seed', (['(0)'], {}), '(0)\n', (751, 754), False, 'import numpy\n'), ((761, 805), 'numpy.empty', 'numpy.empty', (['(10000, 2)'], {'dtype': 'numpy.float32'}), '((10000, 2), dtype=numpy.float32)\n', (772, 805), False, 'import numpy\n'), ((980, 1074), 'libKMCUDA.kmeans_cuda', 'kmeans_cuda', (['arr', '(10)'], {'tolerance': '(0)', 'metric': '"""l2"""', 'verbosity': '(1)', 'seed': '(3)', 'average_distance': '(True)'}), "(arr, 10, tolerance=0, metric='l2', verbosity=1, seed=3,\n average_distance=True)\n", (991, 1074), False, 'from libKMCUDA import kmeans_cuda\n'), ((1164, 1176), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1174, 1176), True, 'from matplotlib import pyplot as plt\n'), ((1177, 1225), 'matplotlib.pyplot.scatter', 'plt.scatter', (['arr[:, 0]', 'arr[:, 1]'], {'c': 'assignments'}), '(arr[:, 0], arr[:, 1], c=assignments)\n', (1188, 1225), True, 'from matplotlib import pyplot as plt\n'), ((1226, 1289), 'matplotlib.pyplot.scatter', 'plt.scatter', (['centroids[:, 0]', 'centroids[:, 1]'], {'c': '"""white"""', 's': '(150)'}), "(centroids[:, 0], centroids[:, 1], c='white', s=150)\n", (1237, 1289), True, 'from matplotlib import pyplot as plt\n'), ((1290, 1315), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""km_ex2.png"""'], {}), "('km_ex2.png')\n", (1301, 1315), True, 'from matplotlib import pyplot as plt\n'), ((882, 921), 'numpy.array', 'numpy.array', (['[i // 1000, i // 1000 + 1]'], {}), '([i // 1000, i // 1000 + 1])\n', (893, 921), False, 'import numpy\n'), ((846, 873), 'numpy.random.normal', 'numpy.random.normal', ([], {'size': '(2)'}), '(size=2)\n', (865, 873), False, 'import numpy\n')] |
# -*- coding: utf-8 -*-
from __future__ import print_function
import time
import numpy as np
from acq4.devices.Stage import Stage, MoveFuture
from pyqtgraph import ptime
from acq4.util import Qt
from acq4.util.Mutex import Mutex
from acq4.util.Thread import Thread
class MockStage(Stage):
def __init__(self, dm, config, name):
Stage.__init__(self, dm, config, name)
self._lastMove = None
self.stageThread = MockStageThread()
self.stageThread.positionChanged.connect(self.posChanged)
self.stageThread.start()
dm.declareInterface(name, ['stage'], self)
# Global key press handling
self.modifierScales = {
Qt.Qt.Key_Control: 4.0,
Qt.Qt.Key_Alt: 0.25,
Qt.Qt.Key_Shift: 0.1,
}
self.keyDirections = np.array([
[0, 0, 1],
[0, 1, 0],
[0, 0, -1],
[-1, 0, 0],
[0, -1, 0],
[1, 0, 0],
])
self._directionKeys = set()
self._modifiers = set()
if 'keys' in config:
Qt.QCoreApplication.instance().installEventFilter(self)
self._quit = False
dm.sigAbortAll.connect(self.abort)
def capabilities(self):
"""Return a structure describing the capabilities of this device"""
if 'capabilities' in self.config:
return self.config['capabilities']
else:
return {
'getPos': (True, True, True),
'setPos': (True, True, True),
'limits': (False, False, False),
}
def axes(self):
return ('x', 'y', 'z')
def _move(self, pos, speed, linear, **kwds):
"""Called by base stage class when the user requests to move to an
posolute or relative position.
"""
with self.lock:
self._interruptMove()
pos = self._toAbsolutePosition(pos)
speed = self._interpretSpeed(speed)
self._lastMove = MockMoveFuture(self, pos, speed)
return self._lastMove
def eventFilter(self, obj, ev):
"""Catch key press/release events used for driving the stage.
"""
#if self._quit:
#return False
if ev.type() not in (Qt.QEvent.KeyPress, Qt.QEvent.KeyRelease, Qt.QEvent.ShortcutOverride):
return False
if ev.isAutoRepeat():
return False
key = str(ev.text()).lower()
keys = self.config.get('keys')
if key != '' and key in keys:
direction = keys.index(key)
if ev.type() == Qt.QEvent.KeyRelease:
self._directionKeys.discard(direction)
else:
self._directionKeys.add(direction)
elif ev.key() in self.modifierScales:
if ev.type() == Qt.QEvent.KeyRelease:
self._modifiers.discard(ev.key())
else:
self._modifiers.add(ev.key())
else:
return False
self._updateKeySpeed()
return False
def _updateKeySpeed(self):
s = 1000e-6
for mod in self._modifiers:
s = s * self.modifierScales[mod]
vec = np.array([0, 0, 0])
for key in self._directionKeys:
vec = vec + self.keyDirections[key] * s
self.startMoving(vec)
def stop(self):
with self.lock:
self.abort()
def abort(self):
self._interruptMove()
self.stageThread.stop()
def _interruptMove(self):
if self._lastMove is not None and not self._lastMove.isDone():
self._lastMove._interrupted = True
def setUserSpeed(self, v):
pass
def _getPosition(self):
return self.stageThread.getPosition()
def targetPosition(self):
with self.lock:
if self._lastMove is None or self._lastMove.isDone():
return self.getPosition()
else:
return self._lastMove.targetPos
def startMoving(self, vel):
"""Begin moving the stage at a continuous velocity.
"""
with self.lock:
self._interruptMove()
vel1 = np.zeros(3)
vel1[:len(vel)] = vel
self.stageThread.setVelocity(vel1)
def quit(self):
self.abort()
self.stageThread.quit()
self._quit = True
class MockMoveFuture(MoveFuture):
"""Provides access to a move-in-progress on a mock manipulator.
"""
def __init__(self, dev, pos, speed):
MoveFuture.__init__(self, dev, pos, speed)
self.targetPos = pos
self._finished = False
self._interrupted = False
self._errorMsg = None
self.dev.stageThread.setTarget(self, pos, speed)
def wasInterrupted(self):
"""Return True if the move was interrupted before completing.
"""
return self._interrupted
def isDone(self):
"""Return True if the move is complete or was interrupted.
"""
return self._finished or self._interrupted
def errorMessage(self):
return self._errorMsg
class MockStageThread(Thread):
"""Thread used to simulate stage hardware.
It is necessary for this to be in a thread because some stage users will
block while waiting for a stage movement to complete.
"""
positionChanged = Qt.Signal(object)
def __init__(self):
self.pos = np.zeros(3)
self.target = None
self.speed = None
self.velocity = None
self._quit = False
self.lock = Mutex()
self.interval = 30e-3
self.lastUpdate = None
self.currentMove = None
Thread.__init__(self)
def start(self):
self._quit = False
self.lastUpdate = ptime.time()
Thread.start(self)
def stop(self):
with self.lock:
self.target = None
self.speed = None
self.velocity = None
def quit(self):
with self.lock:
self._quit = True
def setTarget(self, future, target, speed):
"""Begin moving toward a target position.
"""
with self.lock:
self.currentMove = future
self.target = target
self.speed = speed
self.velocity = None
def setVelocity(self, vel):
with self.lock:
self.currentMove = None
self.target = None
self.speed = None
self.velocity = vel
def getPosition(self):
with self.lock:
return self.pos.copy()
def run(self):
lastUpdate = ptime.time()
while True:
with self.lock:
if self._quit:
break
target = self.target
speed = self.speed
velocity = self.velocity
currentMove = self.currentMove
pos = self.pos
now = ptime.time()
dt = now - lastUpdate
lastUpdate = now
if target is not None:
dif = target - pos
dist = np.linalg.norm(dif)
stepDist = speed * dt
if stepDist >= dist:
self._setPosition(target)
self.currentMove._finished = True
self.stop()
else:
unit = dif / dist
step = unit * stepDist
self._setPosition(pos + step)
elif self.velocity is not None and not np.all(velocity == 0):
self._setPosition(pos + velocity * dt)
time.sleep(self.interval)
def _setPosition(self, pos):
self.pos = np.array(pos)
self.positionChanged.emit(self.pos)
#class MockStageInterface(Qt.QWidget):
#def __init__(self, dev, win, keys=None):
#self.win = win
#self.dev = dev
#Qt.QWidget.__init__(self)
#self.layout = Qt.QGridLayout()
#self.setLayout(self.layout)
#self.btn = pg.JoystickButton()
#self.layout.addWidget(self.btn, 0, 0)
#self.label = Qt.QLabel()
#self.layout.addWidget(self.label)
#self.dev.sigPositionChanged.connect(self.update)
#self.btn.sigStateChanged.connect(self.btnChanged)
#self.label.setFixedWidth(300)
#def btnChanged(self, btn, state):
#self.dev.setSpeed((state[0] * 0.0001, state[1] * 0.0001))
#def update(self):
#pos = self.dev.getPosition()
#text = [pg.siFormat(x, suffix='m', precision=5) for x in pos]
#self.label.setText(", ".join(text))
| [
"acq4.util.Mutex.Mutex",
"numpy.all",
"acq4.util.Thread.Thread.__init__",
"pyqtgraph.ptime.time",
"acq4.util.Qt.QCoreApplication.instance",
"time.sleep",
"numpy.array",
"numpy.zeros",
"acq4.util.Thread.Thread.start",
"numpy.linalg.norm",
"acq4.devices.Stage.Stage.__init__",
"acq4.util.Qt.Signa... | [((5479, 5496), 'acq4.util.Qt.Signal', 'Qt.Signal', (['object'], {}), '(object)\n', (5488, 5496), False, 'from acq4.util import Qt\n'), ((345, 383), 'acq4.devices.Stage.Stage.__init__', 'Stage.__init__', (['self', 'dm', 'config', 'name'], {}), '(self, dm, config, name)\n', (359, 383), False, 'from acq4.devices.Stage import Stage, MoveFuture\n'), ((846, 925), 'numpy.array', 'np.array', (['[[0, 0, 1], [0, 1, 0], [0, 0, -1], [-1, 0, 0], [0, -1, 0], [1, 0, 0]]'], {}), '([[0, 0, 1], [0, 1, 0], [0, 0, -1], [-1, 0, 0], [0, -1, 0], [1, 0, 0]])\n', (854, 925), True, 'import numpy as np\n'), ((3258, 3277), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (3266, 3277), True, 'import numpy as np\n'), ((4625, 4667), 'acq4.devices.Stage.MoveFuture.__init__', 'MoveFuture.__init__', (['self', 'dev', 'pos', 'speed'], {}), '(self, dev, pos, speed)\n', (4644, 4667), False, 'from acq4.devices.Stage import Stage, MoveFuture\n'), ((5545, 5556), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (5553, 5556), True, 'import numpy as np\n'), ((5686, 5693), 'acq4.util.Mutex.Mutex', 'Mutex', ([], {}), '()\n', (5691, 5693), False, 'from acq4.util.Mutex import Mutex\n'), ((5795, 5816), 'acq4.util.Thread.Thread.__init__', 'Thread.__init__', (['self'], {}), '(self)\n', (5810, 5816), False, 'from acq4.util.Thread import Thread\n'), ((5900, 5912), 'pyqtgraph.ptime.time', 'ptime.time', ([], {}), '()\n', (5910, 5912), False, 'from pyqtgraph import ptime\n'), ((5921, 5939), 'acq4.util.Thread.Thread.start', 'Thread.start', (['self'], {}), '(self)\n', (5933, 5939), False, 'from acq4.util.Thread import Thread\n'), ((6782, 6794), 'pyqtgraph.ptime.time', 'ptime.time', ([], {}), '()\n', (6792, 6794), False, 'from pyqtgraph import ptime\n'), ((7929, 7942), 'numpy.array', 'np.array', (['pos'], {}), '(pos)\n', (7937, 7942), True, 'import numpy as np\n'), ((4255, 4266), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (4263, 4266), True, 'import numpy as np\n'), ((7126, 7138), 'pyqtgraph.ptime.time', 'ptime.time', ([], {}), '()\n', (7136, 7138), False, 'from pyqtgraph import ptime\n'), ((7846, 7871), 'time.sleep', 'time.sleep', (['self.interval'], {}), '(self.interval)\n', (7856, 7871), False, 'import time\n'), ((7308, 7327), 'numpy.linalg.norm', 'np.linalg.norm', (['dif'], {}), '(dif)\n', (7322, 7327), True, 'import numpy as np\n'), ((1118, 1148), 'acq4.util.Qt.QCoreApplication.instance', 'Qt.QCoreApplication.instance', ([], {}), '()\n', (1146, 1148), False, 'from acq4.util import Qt\n'), ((7739, 7760), 'numpy.all', 'np.all', (['(velocity == 0)'], {}), '(velocity == 0)\n', (7745, 7760), True, 'import numpy as np\n')] |
# Copyright 2020 The TensorFlow Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for OpenGL lookAt functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
from tensorflow_graphics.geometry.transformation import look_at
from tensorflow_graphics.util import test_case
class LookAtTest(test_case.TestCase):
def test_look_at_right_handed_preset(self):
"""Tests that look_at_right_handed generates expected results."""
camera_position = ((0.0, 0.0, 0.0), (0.1, 0.2, 0.3))
look_at_point = ((0.0, 0.0, 1.0), (0.4, 0.5, 0.6))
up_vector = ((0.0, 1.0, 0.0), (0.7, 0.8, 0.9))
pred = look_at.right_handed(camera_position, look_at_point, up_vector)
gt = (((-1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, -1.0, 0.0),
(0.0, 0.0, 0.0, 1.0)),
((4.08248186e-01, -8.16496551e-01, 4.08248395e-01, -2.98023224e-08),
(-7.07106888e-01, 1.19209290e-07, 7.07106769e-01, -1.41421378e-01),
(-5.77350318e-01, -5.77350318e-01, -5.77350318e-01,
3.46410215e-01), (0.0, 0.0, 0.0, 1.0)))
self.assertAllClose(pred, gt)
@parameterized.parameters(
((3,), (3,), (3,)),
((None, 3), (None, 3), (None, 3)),
((None, 2, 3), (None, 2, 3), (None, 2, 3)),
)
def test_look_at_right_handed_exception_not_raised(self, *shapes):
"""Tests that the shape exceptions are not raised."""
self.assert_exception_is_not_raised(look_at.right_handed, shapes)
@parameterized.parameters(
("must have exactly 3 dimensions in axis -1", (2,), (3,), (3,)),
("must have exactly 3 dimensions in axis -1", (3,), (2,), (3,)),
("must have exactly 3 dimensions in axis -1", (3,), (3,), (1,)),
("Not all batch dimensions are identical", (3,), (3, 3), (3, 3)),
)
def test_look_at_right_handed_exception_raised(self, error_msg, *shapes):
"""Tests that the shape exceptions are properly raised."""
self.assert_exception_is_raised(look_at.right_handed, error_msg, shapes)
def test_look_at_right_handed_jacobian_preset(self):
"""Tests the Jacobian of look_at_right_handed."""
camera_position_init = np.array(((0.0, 0.0, 0.0), (0.1, 0.2, 0.3)))
look_at_init = np.array(((0.0, 0.0, 1.0), (0.4, 0.5, 0.6)))
up_vector_init = np.array(((0.0, 1.0, 0.0), (0.7, 0.8, 0.9)))
self.assert_jacobian_is_correct_fn(
look_at.right_handed,
[camera_position_init, look_at_init, up_vector_init])
def test_look_at_right_handed_jacobian_random(self):
"""Tests the Jacobian of look_at_right_handed."""
tensor_size = np.random.randint(1, 3)
tensor_shape = np.random.randint(1, 5, size=(tensor_size)).tolist()
camera_position_init = np.random.uniform(size=tensor_shape + [3])
look_at_init = np.random.uniform(size=tensor_shape + [3])
up_vector_init = np.random.uniform(size=tensor_shape + [3])
self.assert_jacobian_is_correct_fn(
look_at.right_handed,
[camera_position_init, look_at_init, up_vector_init])
| [
"tensorflow_graphics.geometry.transformation.look_at.right_handed",
"absl.testing.parameterized.parameters",
"numpy.array",
"numpy.random.randint",
"numpy.random.uniform"
] | [((1729, 1857), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (['((3,), (3,), (3,))', '((None, 3), (None, 3), (None, 3))', '((None, 2, 3), (None, 2, 3), (None, 2, 3))'], {}), '(((3,), (3,), (3,)), ((None, 3), (None, 3), (None, \n 3)), ((None, 2, 3), (None, 2, 3), (None, 2, 3)))\n', (1753, 1857), False, 'from absl.testing import parameterized\n'), ((2077, 2374), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (["('must have exactly 3 dimensions in axis -1', (2,), (3,), (3,))", "('must have exactly 3 dimensions in axis -1', (3,), (2,), (3,))", "('must have exactly 3 dimensions in axis -1', (3,), (3,), (1,))", "('Not all batch dimensions are identical', (3,), (3, 3), (3, 3))"], {}), "(('must have exactly 3 dimensions in axis -1', (2,),\n (3,), (3,)), ('must have exactly 3 dimensions in axis -1', (3,), (2,),\n (3,)), ('must have exactly 3 dimensions in axis -1', (3,), (3,), (1,)),\n ('Not all batch dimensions are identical', (3,), (3, 3), (3, 3)))\n", (2101, 2374), False, 'from absl.testing import parameterized\n'), ((1240, 1303), 'tensorflow_graphics.geometry.transformation.look_at.right_handed', 'look_at.right_handed', (['camera_position', 'look_at_point', 'up_vector'], {}), '(camera_position, look_at_point, up_vector)\n', (1260, 1303), False, 'from tensorflow_graphics.geometry.transformation import look_at\n'), ((2745, 2789), 'numpy.array', 'np.array', (['((0.0, 0.0, 0.0), (0.1, 0.2, 0.3))'], {}), '(((0.0, 0.0, 0.0), (0.1, 0.2, 0.3)))\n', (2753, 2789), True, 'import numpy as np\n'), ((2809, 2853), 'numpy.array', 'np.array', (['((0.0, 0.0, 1.0), (0.4, 0.5, 0.6))'], {}), '(((0.0, 0.0, 1.0), (0.4, 0.5, 0.6)))\n', (2817, 2853), True, 'import numpy as np\n'), ((2875, 2919), 'numpy.array', 'np.array', (['((0.0, 1.0, 0.0), (0.7, 0.8, 0.9))'], {}), '(((0.0, 1.0, 0.0), (0.7, 0.8, 0.9)))\n', (2883, 2919), True, 'import numpy as np\n'), ((3181, 3204), 'numpy.random.randint', 'np.random.randint', (['(1)', '(3)'], {}), '(1, 3)\n', (3198, 3204), True, 'import numpy as np\n'), ((3304, 3346), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(tensor_shape + [3])'}), '(size=tensor_shape + [3])\n', (3321, 3346), True, 'import numpy as np\n'), ((3366, 3408), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(tensor_shape + [3])'}), '(size=tensor_shape + [3])\n', (3383, 3408), True, 'import numpy as np\n'), ((3430, 3472), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(tensor_shape + [3])'}), '(size=tensor_shape + [3])\n', (3447, 3472), True, 'import numpy as np\n'), ((3224, 3265), 'numpy.random.randint', 'np.random.randint', (['(1)', '(5)'], {'size': 'tensor_size'}), '(1, 5, size=tensor_size)\n', (3241, 3265), True, 'import numpy as np\n')] |
import cv2 as cv2
import numpy as np
import os
def getCoordinates(top_left, w, h, best_val):
bottom_right = (top_left[0] + w, top_left[1] + h)
center = (top_left[0] + (w/2), top_left[1] + (h/2))
return [
{
'top_left': top_left,
'bottom_right': bottom_right,
'center': center,
'tolerance': best_val,
}
]
def extractAlpha(img, hardedge = True):
if img.shape[2] <= 3:
return {'res':False,'image':img}
print('Mask detected')
channels = cv2.split(img)
mask = np.array(channels[3])
if hardedge:
for idx in xrange(len(mask[0])):
mask[0][idx] = 0 if mask[0][idx] <=128 else 255
mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
return {'res':True,'image':img,'mask':mask}
def twoSquaresDoOverlap(squareA,squareB):
#The two squares must have coordinates in the form of named list with name top_left and bottom_right
overlap = True
if squareA['top_left'][1] > squareB['bottom_right'][1] or \
squareA['top_left'][0] > squareB['bottom_right'][0] or \
squareA['bottom_right'][0] < squareB['top_left'][0] or \
squareA['bottom_right'][1] < squareB['top_left'][1]:
overlap = False
return overlap
def cropToCoords(img, coords):
(ulx,uly) = coords[0]
(brx,bry) = coords[1]
return img[uly:bry, ulx:brx]
def getMultiFullInfo(all_matches,w,h):
#This function will rearrange the data and calculate the tuple
# for the square and the center and the tolerance for each point
result = []
for match in all_matches:
tlx = match[0]
tly = match[1]
top_left = (tlx,tly)
brx = match[0] + w
bry = match[1] + h
bottom_right = (brx,bry)
centerx = match[0] + w/2
centery = match[1] + h/2
center = [centerx,centery]
result.append({'top_left':top_left,'bottom_right':bottom_right,'center':center,'tolerance':match[2]})
return result
def find_min_max(all_squares,axe,minormax):
coord = 0 if axe == 'x' else 1
best_result = {'res': all_squares['res'], 'points': []}
best_result['points'].append(all_squares['points'][0])
best_result['name'] = all_squares['name']
for point in all_squares['points']:
if minormax == 'max':
if point['center'][coord] > best_result['points'][0]['center'][coord]:
best_result['points'][0] = point
elif point['center'][coord] < best_result['points'][0]['center'][coord]:
best_result['points'][0] = point
return best_result
def findAllPictureFiles(base_filename,directory):
onlyfiles = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
return [
myfile
for myfile in onlyfiles
if myfile.startswith(base_filename)
and not myfile[len(base_filename) :].startswith('_')
]
def fromStringToTuple(string):
string = string.replace(' ', '')
string = string.replace('(', '')
string = string.replace(')', '')
string = string.split(',')
return int(string[0]), int(string[1])
def dictStringToInt(d):
for key, value in d.iteritems():
try:
d[key] = int(value)
except ValueError:
d[key] = str(value)
return d
# def getRange(sx,sy, range):
# start_x = sx - range
# end_x = sx + range
# start_y = sx - range
# end_y = sx + range
def my_range(start, end, step):
while start <= end:
yield start
start += step | [
"os.listdir",
"os.path.join",
"numpy.array",
"cv2.cvtColor",
"cv2.split"
] | [((535, 549), 'cv2.split', 'cv2.split', (['img'], {}), '(img)\n', (544, 549), True, 'import cv2 as cv2\n'), ((561, 582), 'numpy.array', 'np.array', (['channels[3]'], {}), '(channels[3])\n', (569, 582), True, 'import numpy as np\n'), ((712, 750), 'cv2.cvtColor', 'cv2.cvtColor', (['mask', 'cv2.COLOR_GRAY2BGR'], {}), '(mask, cv2.COLOR_GRAY2BGR)\n', (724, 750), True, 'import cv2 as cv2\n'), ((761, 798), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGRA2BGR'], {}), '(img, cv2.COLOR_BGRA2BGR)\n', (773, 798), True, 'import cv2 as cv2\n'), ((2766, 2787), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (2776, 2787), False, 'import os\n'), ((2806, 2832), 'os.path.join', 'os.path.join', (['directory', 'f'], {}), '(directory, f)\n', (2818, 2832), False, 'import os\n')] |
# Copyright 2019 Baidu Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Different filters as feature squeezer."""
import numpy as np
from scipy import ndimage
import cv2
class BinaryFilter():
"""Binary filter as feature squeezer as described in [1]_.
References
----------
.. [1] Weilin et: "Feature Squeezing: Detecting Adversarial
Examples in Deep Neural Networks.
"""
def __init__(self):
pass
def __call__(self, img_batch_np, threshold):
"""Squeeze image by binary filter
Parameters
----------
img_batch_np : array
Input image batch or image
threshold : float
Threshold for binarlize
"""
x_bin = np.maximum(np.sign(img_batch_np - threshold), 0)
return x_bin
class BinaryRandomFilter():
"""Binary filter with randomness."""
def __init__(self):
pass
def __call__(self, img_batch_np, threshold, stddev=0.125):
"""Squeeze noise added image by binary filter.
Parameters
----------
img_batch_np : array
Input image batch or image
threshold : float
Threshold for binarlize
stddev : float
Standard deviation for gaussian nosie
"""
if stddev == 0.:
rand_array = np.zeros(img_batch_np.shape)
else:
rand_array = np.random.normal(loc=0.,
scale=stddev,
size=img_batch_np.shape)
x_bin = np.maximum(np.sign(np.add(img_batch_np,
rand_array) - threshold), 0)
return x_bin
class MedianFilter():
"""Median filter as feature squeezer as described in [1]_.
References
----------
.. [1] Weilin et: "Feature Squeezing: Detecting Adversarial
Examples in Deep Neural Networks.
"""
def __init__(self):
pass
def __call__(self, img_batch_np, width, height=-1):
"""Squeeze image by meadia filter
Parameters
----------
img_batch_np : array
Input image batch or image
width : int
The width of the sliding window (number of pixels)
height : int
The height of the window. The same as width by default.
"""
if height == -1:
height = width
x_mid = ndimage.filters.median_filter(img_batch_np,
size=(1, width, height, 1),
mode='reflect'
)
return x_mid
| [
"numpy.random.normal",
"scipy.ndimage.filters.median_filter",
"numpy.add",
"numpy.zeros",
"numpy.sign"
] | [((3044, 3135), 'scipy.ndimage.filters.median_filter', 'ndimage.filters.median_filter', (['img_batch_np'], {'size': '(1, width, height, 1)', 'mode': '"""reflect"""'}), "(img_batch_np, size=(1, width, height, 1),\n mode='reflect')\n", (3073, 3135), False, 'from scipy import ndimage\n'), ((1295, 1328), 'numpy.sign', 'np.sign', (['(img_batch_np - threshold)'], {}), '(img_batch_np - threshold)\n', (1302, 1328), True, 'import numpy as np\n'), ((1909, 1937), 'numpy.zeros', 'np.zeros', (['img_batch_np.shape'], {}), '(img_batch_np.shape)\n', (1917, 1937), True, 'import numpy as np\n'), ((1979, 2043), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0.0)', 'scale': 'stddev', 'size': 'img_batch_np.shape'}), '(loc=0.0, scale=stddev, size=img_batch_np.shape)\n', (1995, 2043), True, 'import numpy as np\n'), ((2165, 2197), 'numpy.add', 'np.add', (['img_batch_np', 'rand_array'], {}), '(img_batch_np, rand_array)\n', (2171, 2197), True, 'import numpy as np\n')] |
import numpy as np
from tqdm import tqdm
# setup rpy2 on Windows
# edit the path here according to your machine
import platform
if platform.system() == 'Windows':
import os
os.environ['PATH'] = 'C:/Program Files/R/R-3.6.0/bin/' + os.pathsep + 'C:/Program Files/R/R-3.6.0/bin/x64/' + os.pathsep + os.environ['PATH']
import rpy2.robjects as robjects
def RData2npy(rdata_fn, keys, folder_output):
robjects.r['load'](rdata_fn)
for key in keys:
np.save(folder_output+key+'.npy', robjects.r[key])
def convert_rdata():
print('Convert original rdata to npy files...')
rdata_fn = './data/DATA_TRAINING.RData'
keys = ['anom.training', 'loc', 'year', 'month', 'day', 'index.validation'] # 'index.training' is not necessary
RData2npy(rdata_fn, keys, './data/')
rdata_fn = './data/TRUE_DATA_RANKING.RData'
keys = ['X.min.true']
RData2npy(rdata_fn, keys, './data/')
def export_yyyymmdd():
print('Process date...')
# The days have been sorted.
# Each year has exactly 365 days, no leap year.
year = np.load('./data/year.npy')
month = np.load('./data/month.npy')
day = np.load('./data/day.npy')
num_days = year.shape[0]
yyyymmdd = np.zeros((num_days, 3), dtype=np.int32)
yyyymmdd[:, 0] = year
yyyymmdd[:, 1] = month
yyyymmdd[:, 2] = day
np.save('./data/yyyymmdd.npy', yyyymmdd)
def export_location():
print('Process location...')
loc = np.load('./data/loc.npy')
x = np.unique(loc[:, 0])
y = np.unique(loc[:, 1])
loc_int = np.zeros_like(loc, dtype=np.int32)
x_int = np.zeros(loc.shape[0], dtype=np.int32)
y_int = np.zeros(loc.shape[0], dtype=np.int32)
for i in range(x.shape[0]):
loc_int[np.argwhere(loc[:, 0] == x[i]), 0] = i
for i in range(y.shape[0]):
loc_int[np.argwhere(loc[:, 1] == y[i]), 1] = i
np.save('./data/ind2sub.npy', loc_int)
num_row = x.shape[0]
num_col = y.shape[0]
int2loc_mat = -np.ones((num_row, num_col), dtype=np.int32)
for i in range(loc_int.shape[0]):
int2loc_mat[loc_int[i, 0], loc_int[i, 1]] = i
np.save('./data/sub2ind.npy', int2loc_mat)
# compute the distance in km from longitude/latitude coordinates
# https://github.com/cran/fields/blob/9ddd6d6d22827db57d1983021d5f85563d1a8112/R/rdist.earth.R
def rdist_earth_batch(x1, x2):
R = 6378.388
coslat1 = np.cos((x1[1] * np.pi)/180)
sinlat1 = np.sin((x1[1] * np.pi)/180)
coslon1 = np.cos((x1[0] * np.pi)/180)
sinlon1 = np.sin((x1[0] * np.pi)/180)
coslat2 = np.cos((x2[:, 1] * np.pi)/180)
sinlat2 = np.sin((x2[:, 1] * np.pi)/180)
coslon2 = np.cos((x2[:, 0] * np.pi)/180)
sinlon2 = np.sin((x2[:, 0] * np.pi)/180)
A = np.empty((x2.shape[0], 3))
A[:, 0] = coslat2 * coslon2
A[:, 1] = coslat2 * sinlon2
A[:, 2] = sinlat2
pp = A.dot(np.array([coslat1 * coslon1, coslat1 * sinlon1, sinlat1]))
pp[pp > 1] = 1
pp[pp < -1] = -1
return (R * np.arccos(pp))
def find_neighbors():
loc = np.load('./data/loc.npy')
radius = 50 # neighborhood radius in kilometers
# at most max_nei neightbors
max_nei = 1000
num_loc = loc.shape[0]
nei = -np.ones((num_loc, max_nei), dtype=np.int32)
for i in tqdm(range(num_loc)):
num_nei = 0
dist = rdist_earth_batch(loc[i, :], loc)
idx = np.where(dist < radius)[0]
nei[i, :idx.shape[0]] = idx
if idx.shape[0] > max_nei:
print('wrong!')
np.save('./data/neighbor.npy', nei)
def onebased2zerobased():
# 'index.training' is not necessary
#keys = ['index.training', 'index.validation']
keys = ['index.validation']
for key in keys:
a = np.load('./data/'+key+'.npy')
np.save('./data/'+key+'0.npy', a-1)
def export_true_observations():
X_min_true = np.load('./data/X.min.true.npy')
index_validation = np.load('./data/index.validation0.npy')
X_min_true = np.reshape(X_min_true, (-1, 1), order='F')
true_observations = X_min_true[index_validation].reshape(-1)
np.save('./data/true.observations.npy', true_observations)
if __name__ == '__main__':
convert_rdata()
export_yyyymmdd()
export_location()
find_neighbors()
onebased2zerobased()
export_true_observations()
| [
"numpy.reshape",
"numpy.unique",
"numpy.ones",
"numpy.arccos",
"numpy.where",
"numpy.array",
"platform.system",
"numpy.zeros",
"numpy.empty",
"numpy.cos",
"numpy.argwhere",
"numpy.sin",
"numpy.load",
"numpy.zeros_like",
"numpy.save"
] | [((132, 149), 'platform.system', 'platform.system', ([], {}), '()\n', (147, 149), False, 'import platform\n'), ((1064, 1090), 'numpy.load', 'np.load', (['"""./data/year.npy"""'], {}), "('./data/year.npy')\n", (1071, 1090), True, 'import numpy as np\n'), ((1103, 1130), 'numpy.load', 'np.load', (['"""./data/month.npy"""'], {}), "('./data/month.npy')\n", (1110, 1130), True, 'import numpy as np\n'), ((1141, 1166), 'numpy.load', 'np.load', (['"""./data/day.npy"""'], {}), "('./data/day.npy')\n", (1148, 1166), True, 'import numpy as np\n'), ((1211, 1250), 'numpy.zeros', 'np.zeros', (['(num_days, 3)'], {'dtype': 'np.int32'}), '((num_days, 3), dtype=np.int32)\n', (1219, 1250), True, 'import numpy as np\n'), ((1333, 1373), 'numpy.save', 'np.save', (['"""./data/yyyymmdd.npy"""', 'yyyymmdd'], {}), "('./data/yyyymmdd.npy', yyyymmdd)\n", (1340, 1373), True, 'import numpy as np\n'), ((1442, 1467), 'numpy.load', 'np.load', (['"""./data/loc.npy"""'], {}), "('./data/loc.npy')\n", (1449, 1467), True, 'import numpy as np\n'), ((1476, 1496), 'numpy.unique', 'np.unique', (['loc[:, 0]'], {}), '(loc[:, 0])\n', (1485, 1496), True, 'import numpy as np\n'), ((1505, 1525), 'numpy.unique', 'np.unique', (['loc[:, 1]'], {}), '(loc[:, 1])\n', (1514, 1525), True, 'import numpy as np\n'), ((1541, 1575), 'numpy.zeros_like', 'np.zeros_like', (['loc'], {'dtype': 'np.int32'}), '(loc, dtype=np.int32)\n', (1554, 1575), True, 'import numpy as np\n'), ((1588, 1626), 'numpy.zeros', 'np.zeros', (['loc.shape[0]'], {'dtype': 'np.int32'}), '(loc.shape[0], dtype=np.int32)\n', (1596, 1626), True, 'import numpy as np\n'), ((1639, 1677), 'numpy.zeros', 'np.zeros', (['loc.shape[0]'], {'dtype': 'np.int32'}), '(loc.shape[0], dtype=np.int32)\n', (1647, 1677), True, 'import numpy as np\n'), ((1857, 1895), 'numpy.save', 'np.save', (['"""./data/ind2sub.npy"""', 'loc_int'], {}), "('./data/ind2sub.npy', loc_int)\n", (1864, 1895), True, 'import numpy as np\n'), ((2106, 2148), 'numpy.save', 'np.save', (['"""./data/sub2ind.npy"""', 'int2loc_mat'], {}), "('./data/sub2ind.npy', int2loc_mat)\n", (2113, 2148), True, 'import numpy as np\n'), ((2374, 2401), 'numpy.cos', 'np.cos', (['(x1[1] * np.pi / 180)'], {}), '(x1[1] * np.pi / 180)\n', (2380, 2401), True, 'import numpy as np\n'), ((2416, 2443), 'numpy.sin', 'np.sin', (['(x1[1] * np.pi / 180)'], {}), '(x1[1] * np.pi / 180)\n', (2422, 2443), True, 'import numpy as np\n'), ((2458, 2485), 'numpy.cos', 'np.cos', (['(x1[0] * np.pi / 180)'], {}), '(x1[0] * np.pi / 180)\n', (2464, 2485), True, 'import numpy as np\n'), ((2500, 2527), 'numpy.sin', 'np.sin', (['(x1[0] * np.pi / 180)'], {}), '(x1[0] * np.pi / 180)\n', (2506, 2527), True, 'import numpy as np\n'), ((2543, 2573), 'numpy.cos', 'np.cos', (['(x2[:, 1] * np.pi / 180)'], {}), '(x2[:, 1] * np.pi / 180)\n', (2549, 2573), True, 'import numpy as np\n'), ((2588, 2618), 'numpy.sin', 'np.sin', (['(x2[:, 1] * np.pi / 180)'], {}), '(x2[:, 1] * np.pi / 180)\n', (2594, 2618), True, 'import numpy as np\n'), ((2633, 2663), 'numpy.cos', 'np.cos', (['(x2[:, 0] * np.pi / 180)'], {}), '(x2[:, 0] * np.pi / 180)\n', (2639, 2663), True, 'import numpy as np\n'), ((2678, 2708), 'numpy.sin', 'np.sin', (['(x2[:, 0] * np.pi / 180)'], {}), '(x2[:, 0] * np.pi / 180)\n', (2684, 2708), True, 'import numpy as np\n'), ((2718, 2744), 'numpy.empty', 'np.empty', (['(x2.shape[0], 3)'], {}), '((x2.shape[0], 3))\n', (2726, 2744), True, 'import numpy as np\n'), ((3010, 3035), 'numpy.load', 'np.load', (['"""./data/loc.npy"""'], {}), "('./data/loc.npy')\n", (3017, 3035), True, 'import numpy as np\n'), ((3471, 3506), 'numpy.save', 'np.save', (['"""./data/neighbor.npy"""', 'nei'], {}), "('./data/neighbor.npy', nei)\n", (3478, 3506), True, 'import numpy as np\n'), ((3816, 3848), 'numpy.load', 'np.load', (['"""./data/X.min.true.npy"""'], {}), "('./data/X.min.true.npy')\n", (3823, 3848), True, 'import numpy as np\n'), ((3872, 3911), 'numpy.load', 'np.load', (['"""./data/index.validation0.npy"""'], {}), "('./data/index.validation0.npy')\n", (3879, 3911), True, 'import numpy as np\n'), ((3929, 3971), 'numpy.reshape', 'np.reshape', (['X_min_true', '(-1, 1)'], {'order': '"""F"""'}), "(X_min_true, (-1, 1), order='F')\n", (3939, 3971), True, 'import numpy as np\n'), ((4041, 4099), 'numpy.save', 'np.save', (['"""./data/true.observations.npy"""', 'true_observations'], {}), "('./data/true.observations.npy', true_observations)\n", (4048, 4099), True, 'import numpy as np\n'), ((469, 523), 'numpy.save', 'np.save', (["(folder_output + key + '.npy')", 'robjects.r[key]'], {}), "(folder_output + key + '.npy', robjects.r[key])\n", (476, 523), True, 'import numpy as np\n'), ((1966, 2009), 'numpy.ones', 'np.ones', (['(num_row, num_col)'], {'dtype': 'np.int32'}), '((num_row, num_col), dtype=np.int32)\n', (1973, 2009), True, 'import numpy as np\n'), ((2846, 2903), 'numpy.array', 'np.array', (['[coslat1 * coslon1, coslat1 * sinlon1, sinlat1]'], {}), '([coslat1 * coslon1, coslat1 * sinlon1, sinlat1])\n', (2854, 2903), True, 'import numpy as np\n'), ((2961, 2974), 'numpy.arccos', 'np.arccos', (['pp'], {}), '(pp)\n', (2970, 2974), True, 'import numpy as np\n'), ((3179, 3222), 'numpy.ones', 'np.ones', (['(num_loc, max_nei)'], {'dtype': 'np.int32'}), '((num_loc, max_nei), dtype=np.int32)\n', (3186, 3222), True, 'import numpy as np\n'), ((3691, 3724), 'numpy.load', 'np.load', (["('./data/' + key + '.npy')"], {}), "('./data/' + key + '.npy')\n", (3698, 3724), True, 'import numpy as np\n'), ((3729, 3770), 'numpy.save', 'np.save', (["('./data/' + key + '0.npy')", '(a - 1)'], {}), "('./data/' + key + '0.npy', a - 1)\n", (3736, 3770), True, 'import numpy as np\n'), ((3341, 3364), 'numpy.where', 'np.where', (['(dist < radius)'], {}), '(dist < radius)\n', (3349, 3364), True, 'import numpy as np\n'), ((1726, 1756), 'numpy.argwhere', 'np.argwhere', (['(loc[:, 0] == x[i])'], {}), '(loc[:, 0] == x[i])\n', (1737, 1756), True, 'import numpy as np\n'), ((1813, 1843), 'numpy.argwhere', 'np.argwhere', (['(loc[:, 1] == y[i])'], {}), '(loc[:, 1] == y[i])\n', (1824, 1843), True, 'import numpy as np\n')] |
"""
Setup file for package `petitRADTRANS`.
"""
from setuptools import find_packages
from numpy.distutils.core import Extension, setup
import os
import warnings
use_compiler_flags = True
if use_compiler_flags:
extra_compile_args = ["-O3",
"-funroll-loops",
"-ftree-vectorize",
"-msse",
"-msse2",
"-m3dnow"]
else:
extra_compile_args = None
fort_spec = Extension(
name='petitRADTRANS.fort_spec',
sources=['petitRADTRANS/fort_spec.f90'],
extra_compile_args=extra_compile_args)
fort_input = Extension(
name='petitRADTRANS.fort_input',
sources=['petitRADTRANS/fort_input.f90'], \
extra_compile_args=extra_compile_args)
fort_rebin = Extension(
name='petitRADTRANS.fort_rebin',
sources=['petitRADTRANS/fort_rebin.f90'], \
extra_compile_args=extra_compile_args)
extensions = [fort_spec, fort_input, fort_rebin]
def setup_function(extensions):
setup(name='petitRADTRANS',
version="2.1.0",
description='Exoplanet spectral synthesis tool for retrievals',
long_description=open(os.path.join(
os.path.dirname(__file__), 'README.rst')).read(),
long_description_content_tpye='test/x-rst',
url='https://gitlab.com/mauricemolli/petitRADTRANS',
author='<NAME>',
author_email='<EMAIL>',
license='MIT License',
packages=find_packages(),
include_package_data=True,
install_requires=['scipy', 'numpy', 'matplotlib', 'h5py'],
zip_safe=False,
ext_modules=extensions,
)
setup_function(extensions)
| [
"os.path.dirname",
"numpy.distutils.core.Extension",
"setuptools.find_packages"
] | [((483, 609), 'numpy.distutils.core.Extension', 'Extension', ([], {'name': '"""petitRADTRANS.fort_spec"""', 'sources': "['petitRADTRANS/fort_spec.f90']", 'extra_compile_args': 'extra_compile_args'}), "(name='petitRADTRANS.fort_spec', sources=[\n 'petitRADTRANS/fort_spec.f90'], extra_compile_args=extra_compile_args)\n", (492, 609), False, 'from numpy.distutils.core import Extension, setup\n'), ((632, 760), 'numpy.distutils.core.Extension', 'Extension', ([], {'name': '"""petitRADTRANS.fort_input"""', 'sources': "['petitRADTRANS/fort_input.f90']", 'extra_compile_args': 'extra_compile_args'}), "(name='petitRADTRANS.fort_input', sources=[\n 'petitRADTRANS/fort_input.f90'], extra_compile_args=extra_compile_args)\n", (641, 760), False, 'from numpy.distutils.core import Extension, setup\n'), ((785, 913), 'numpy.distutils.core.Extension', 'Extension', ([], {'name': '"""petitRADTRANS.fort_rebin"""', 'sources': "['petitRADTRANS/fort_rebin.f90']", 'extra_compile_args': 'extra_compile_args'}), "(name='petitRADTRANS.fort_rebin', sources=[\n 'petitRADTRANS/fort_rebin.f90'], extra_compile_args=extra_compile_args)\n", (794, 913), False, 'from numpy.distutils.core import Extension, setup\n'), ((1481, 1496), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (1494, 1496), False, 'from setuptools import find_packages\n'), ((1201, 1226), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1216, 1226), False, 'import os\n')] |
import pandas as pd
import numpy as np
from autoscalingsim.load.regional_load_model.load_models.parsers.patterns_parsers.leveled_load_parser import LeveledLoadPatternParser
from autoscalingsim.utils.error_check import ErrorChecker
@LeveledLoadPatternParser.register('step')
class StepLoadPatternParser(LeveledLoadPatternParser):
""" Implements repeated step load change pattern over step_total_duration of time """
@classmethod
def parse(cls, pattern : dict, generation_bucket : pd.Timedelta):
"""
{
"load_kind": "leveled",
"regions_configs": [
{
"region_name": "eu",
"pattern": {
"type": "step",
"params": {
"step_duration": {
"value": 10,
"unit": "s"
},
"unit_of_time_for_requests_rate": {
"value": 1,
"unit": "s"
},
"values": [
{
"requests_count_level": 10,
"percentage_of_interval": 0.5
},
{
"requests_count_level": 20,
"percentage_of_interval": 0.5
},
]
}
}
}
]
}
"""
params = ErrorChecker.key_check_and_load('params', pattern)
step_total_duration_raw = ErrorChecker.key_check_and_load('step_duration', params, default = {'value': 1, 'unit': 'm'})
step_total_duration_value = ErrorChecker.key_check_and_load('value', step_total_duration_raw)
step_total_duration_unit = ErrorChecker.key_check_and_load('unit', step_total_duration_raw)
step_total_duration = pd.Timedelta(step_total_duration_value, unit = step_total_duration_unit)
if generation_bucket > step_total_duration:
raise ValueError('The simulation step should be smaller or equal to the interval of time, for which the requests are generated')
unit_of_time_for_requests_rate_raw = ErrorChecker.key_check_and_load('unit_of_time_for_requests_rate', params, default = {'value': 1, 'unit': 's'})
unit_of_time_for_requests_rate_value = ErrorChecker.key_check_and_load('value', unit_of_time_for_requests_rate_raw)
unit_of_time_for_requests_rate_unit = ErrorChecker.key_check_and_load('unit', unit_of_time_for_requests_rate_raw)
unit_of_time_for_requests_rate = pd.Timedelta(unit_of_time_for_requests_rate_value, unit = unit_of_time_for_requests_rate_unit)
buckets_in_rate_unit = unit_of_time_for_requests_rate // generation_bucket
load_distribution_in_steps_buckets = list()
step_values = ErrorChecker.key_check_and_load('values', params)
total_percentage_up_until_now = 0
for value_config in step_values:
requests_count_level_raw = ErrorChecker.key_check_and_load('requests_count_level', value_config)
requests_count_level = int(np.floor(requests_count_level_raw) + np.random.choice([0, 1], p = [1 - round(requests_count_level_raw % 1, 2), round(requests_count_level_raw % 1, 2)]))
percentage_of_interval = ErrorChecker.key_check_and_load('percentage_of_interval', value_config)
pattern_for_rate = [0] * buckets_in_rate_unit
for _ in range(requests_count_level):
selected_bucket = np.random.randint(0, buckets_in_rate_unit)
pattern_for_rate[selected_bucket] += 1
rate_pattern_repeats_count = step_total_duration * max(min(percentage_of_interval, 1 - total_percentage_up_until_now), 0) // unit_of_time_for_requests_rate
total_percentage_up_until_now += percentage_of_interval
load_distribution_in_steps_buckets += pattern_for_rate * rate_pattern_repeats_count
return (step_total_duration, load_distribution_in_steps_buckets)
| [
"pandas.Timedelta",
"numpy.floor",
"autoscalingsim.utils.error_check.ErrorChecker.key_check_and_load",
"numpy.random.randint",
"autoscalingsim.load.regional_load_model.load_models.parsers.patterns_parsers.leveled_load_parser.LeveledLoadPatternParser.register"
] | [((234, 275), 'autoscalingsim.load.regional_load_model.load_models.parsers.patterns_parsers.leveled_load_parser.LeveledLoadPatternParser.register', 'LeveledLoadPatternParser.register', (['"""step"""'], {}), "('step')\n", (267, 275), False, 'from autoscalingsim.load.regional_load_model.load_models.parsers.patterns_parsers.leveled_load_parser import LeveledLoadPatternParser\n'), ((1655, 1705), 'autoscalingsim.utils.error_check.ErrorChecker.key_check_and_load', 'ErrorChecker.key_check_and_load', (['"""params"""', 'pattern'], {}), "('params', pattern)\n", (1686, 1705), False, 'from autoscalingsim.utils.error_check import ErrorChecker\n'), ((1741, 1837), 'autoscalingsim.utils.error_check.ErrorChecker.key_check_and_load', 'ErrorChecker.key_check_and_load', (['"""step_duration"""', 'params'], {'default': "{'value': 1, 'unit': 'm'}"}), "('step_duration', params, default={'value': \n 1, 'unit': 'm'})\n", (1772, 1837), False, 'from autoscalingsim.utils.error_check import ErrorChecker\n'), ((1871, 1936), 'autoscalingsim.utils.error_check.ErrorChecker.key_check_and_load', 'ErrorChecker.key_check_and_load', (['"""value"""', 'step_total_duration_raw'], {}), "('value', step_total_duration_raw)\n", (1902, 1936), False, 'from autoscalingsim.utils.error_check import ErrorChecker\n'), ((1972, 2036), 'autoscalingsim.utils.error_check.ErrorChecker.key_check_and_load', 'ErrorChecker.key_check_and_load', (['"""unit"""', 'step_total_duration_raw'], {}), "('unit', step_total_duration_raw)\n", (2003, 2036), False, 'from autoscalingsim.utils.error_check import ErrorChecker\n'), ((2067, 2137), 'pandas.Timedelta', 'pd.Timedelta', (['step_total_duration_value'], {'unit': 'step_total_duration_unit'}), '(step_total_duration_value, unit=step_total_duration_unit)\n', (2079, 2137), True, 'import pandas as pd\n'), ((2380, 2492), 'autoscalingsim.utils.error_check.ErrorChecker.key_check_and_load', 'ErrorChecker.key_check_and_load', (['"""unit_of_time_for_requests_rate"""', 'params'], {'default': "{'value': 1, 'unit': 's'}"}), "('unit_of_time_for_requests_rate', params,\n default={'value': 1, 'unit': 's'})\n", (2411, 2492), False, 'from autoscalingsim.utils.error_check import ErrorChecker\n'), ((2538, 2614), 'autoscalingsim.utils.error_check.ErrorChecker.key_check_and_load', 'ErrorChecker.key_check_and_load', (['"""value"""', 'unit_of_time_for_requests_rate_raw'], {}), "('value', unit_of_time_for_requests_rate_raw)\n", (2569, 2614), False, 'from autoscalingsim.utils.error_check import ErrorChecker\n'), ((2661, 2736), 'autoscalingsim.utils.error_check.ErrorChecker.key_check_and_load', 'ErrorChecker.key_check_and_load', (['"""unit"""', 'unit_of_time_for_requests_rate_raw'], {}), "('unit', unit_of_time_for_requests_rate_raw)\n", (2692, 2736), False, 'from autoscalingsim.utils.error_check import ErrorChecker\n'), ((2778, 2875), 'pandas.Timedelta', 'pd.Timedelta', (['unit_of_time_for_requests_rate_value'], {'unit': 'unit_of_time_for_requests_rate_unit'}), '(unit_of_time_for_requests_rate_value, unit=\n unit_of_time_for_requests_rate_unit)\n', (2790, 2875), True, 'import pandas as pd\n'), ((3032, 3081), 'autoscalingsim.utils.error_check.ErrorChecker.key_check_and_load', 'ErrorChecker.key_check_and_load', (['"""values"""', 'params'], {}), "('values', params)\n", (3063, 3081), False, 'from autoscalingsim.utils.error_check import ErrorChecker\n'), ((3204, 3273), 'autoscalingsim.utils.error_check.ErrorChecker.key_check_and_load', 'ErrorChecker.key_check_and_load', (['"""requests_count_level"""', 'value_config'], {}), "('requests_count_level', value_config)\n", (3235, 3273), False, 'from autoscalingsim.utils.error_check import ErrorChecker\n'), ((3503, 3574), 'autoscalingsim.utils.error_check.ErrorChecker.key_check_and_load', 'ErrorChecker.key_check_and_load', (['"""percentage_of_interval"""', 'value_config'], {}), "('percentage_of_interval', value_config)\n", (3534, 3574), False, 'from autoscalingsim.utils.error_check import ErrorChecker\n'), ((3717, 3759), 'numpy.random.randint', 'np.random.randint', (['(0)', 'buckets_in_rate_unit'], {}), '(0, buckets_in_rate_unit)\n', (3734, 3759), True, 'import numpy as np\n'), ((3313, 3347), 'numpy.floor', 'np.floor', (['requests_count_level_raw'], {}), '(requests_count_level_raw)\n', (3321, 3347), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Mon May 13 16:54:33 2019
@author: TMaysGGS
"""
'''Updated on 07/31/2019 11:14'''
'''Problem
There is an intermediate layer that has the shape (m, m), which means a 26928 * 26928 matrix.
Each element takes 32 bit so that the total space needed is more than 21G, which way too much exceeds
the GPU memory.
'''
'''Loading the pre-trained model'''
import math
import os
import keras
import random
import cv2
import tensorflow as tf
import numpy as np
from keras import backend as K
from keras.models import Model
from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout
from keras.engine.topology import Layer
from keras.optimizers import Adam
from keras import initializers
from keras.utils import to_categorical
# import keras.backend.tensorflow_backend as KTF
# from keras.utils import plot_model
os.environ['CUDA_VISIBLE_DEVICES'] = '0' # 如需多张卡设置为:'1, 2, 3',使用CPU设置为:''
'''Set if the GPU memory needs to be restricted
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.85
session = tf.Session(config = config)
KTF.set_session(session)
'''
BATCH_SIZE = 512
old_m = 1416143
m = 6151666
DATA_SPLIT = 0.008
OLD_NUM_LABELS = 6181
NUM_LABELS = 26928
TOTAL_EPOCHS = 10000
IMG_DIR = '/data/daiwei/dataset'
'''Importing the data set (not appropriate when the data set is too large)
from keras.preprocessing.image import ImageDataGenerator
train_path = '/data/daiwei/dataset/'
train_datagen = ImageDataGenerator(rescale = 1. / 255, validation_split = DATA_SPLIT)
def mobilefacenet_input_generator(generator, directory, subset):
gen = generator.flow_from_directory(
directory,
target_size = (112, 112),
color_mode = 'rgb',
batch_size = BATCH_SIZE,
class_mode = 'categorical',
subset = subset)
while True:
X = gen.next()
yield [X[0], X[1]], X[1]
train_generator = mobilefacenet_input_generator(train_datagen, train_path, 'training')
validate_generator = mobilefacenet_input_generator(train_datagen, train_path, 'validation')
'''
'''Building Block Functions'''
def conv_block(inputs, filters, kernel_size, strides):
channel_axis = 1 if K.image_data_format() == 'channels_first' else -1
Z = Conv2D(filters, kernel_size, padding = "valid", strides = strides)(inputs)
Z = BatchNormalization(axis = channel_axis)(Z)
A = PReLU()(Z)
return A
def separable_conv_block(inputs, filters, kernel_size, strides):
channel_axis = 1 if K.image_data_format() == 'channels_first' else -1
Z = SeparableConv2D(filters = 64, kernel_size = 3, strides = (1, 1), padding = "same")(inputs)
Z = BatchNormalization(axis = channel_axis)(Z)
A = PReLU()(Z)
return A
def bottleneck(inputs, filters, kernel, t, s, r = False):
channel_axis = 1 if K.image_data_format() == 'channels_first' else -1
tchannel = K.int_shape(inputs)[channel_axis] * t
Z1 = conv_block(inputs, tchannel, (1, 1), (1, 1))
Z1 = DepthwiseConv2D(kernel_size = kernel, strides = s, padding = "same", depth_multiplier = 1)(Z1)
Z1 = BatchNormalization(axis = channel_axis)(Z1)
A1 = PReLU()(Z1)
Z2 = Conv2D(filters, kernel_size = 1, strides = 1, padding = "same")(A1)
Z2 = BatchNormalization(axis = channel_axis)(Z2)
if r:
Z2 = add([Z2, inputs])
return Z2
def inverted_residual_block(inputs, filters, kernel, t, strides, n):
Z = bottleneck(inputs, filters, kernel, t, strides)
for i in range(1, n):
Z = bottleneck(Z, filters, kernel, t, 1, True)
return Z
def linear_GD_conv_block(inputs, kernel_size, strides):
channel_axis = 1 if K.image_data_format() == 'channels_first' else -1
Z = DepthwiseConv2D(kernel_size = kernel_size, strides = strides, padding = "valid", depth_multiplier = 1)(inputs)
Z = BatchNormalization(axis = channel_axis)(Z)
return Z
# Arc Face Loss Layer (Class)
class ArcFaceLossLayer(Layer):
'''
Arguments:
inputs: the input embedding vectors
class_num: number of classes
s: scaler value (default as 64)
m: the margin value (default as 0.5)
Returns:
the final calculated outputs
'''
def __init__(self, class_num, s = 64., m = 0.5, **kwargs):
self.init = initializers.get('glorot_uniform') # Xavier uniform intializer
self.class_num = class_num
self.s = s
self.m = m
super(ArcFaceLossLayer, self).__init__(**kwargs)
def build(self, input_shape):
assert len(input_shape[0]) == 2 and len(input_shape[1]) == 2
self.W = self.add_weight((input_shape[0][-1], self.class_num), initializer = self.init, name = '{}_W'.format(self.name))
super(ArcFaceLossLayer, self).build(input_shape)
def call(self, inputs, mask = None):
cos_m = math.cos(self.m)
sin_m = math.sin(self.m)
mm = sin_m * self.m
threshold = math.cos(math.pi - self.m)
# features
X = inputs[0]
# 1-D or one-hot label works as mask
Y_mask = inputs[1]
# If Y_mask is not in one-hot form, transfer it to one-hot form.
if Y_mask.shape[-1] == 1:
Y_mask = K.cast(Y_mask, tf.int32)
Y_mask = K.reshape(K.one_hot(Y_mask, self.class_num), (-1, self.class_num))
X_normed = K.l2_normalize(X, axis = 1) # L2 Normalized X
self.W = K.l2_normalize(self.W, axis = 0) # L2 Normalized Weights
# cos(theta + m)
cos_theta = K.dot(X_normed, self.W)
cos_theta2 = K.square(cos_theta)
sin_theta2 = 1. - cos_theta2
sin_theta = K.sqrt(sin_theta2 + K.epsilon())
cos_tm = self.s * ((cos_theta * cos_m) - (sin_theta * sin_m))
# This condition controls the theta + m should in range [0, pi]
# 0 <= theta + m < = pi
# -m <= theta <= pi - m
cond_v = cos_theta - threshold
cond = K.cast(K.relu(cond_v), dtype = tf.bool)
keep_val = self.s * (cos_theta - mm)
cos_tm_temp = tf.where(cond, cos_tm, keep_val)
# mask by label
Y_mask =+ K.epsilon()
inv_mask = 1. - Y_mask
s_cos_theta = self.s * cos_theta
output = K.softmax((s_cos_theta * inv_mask) + (cos_tm_temp * Y_mask))
return output
def compute_output_shape(self, input_shape):
return input_shape[0], self.class_num
'''Building the MobileFaceNet Model'''
def mobile_face_net():
X = Input(shape = (112, 112, 3))
label = Input((OLD_NUM_LABELS, ))
M = conv_block(X, 64, 3, 2)
M = separable_conv_block(M, 64, 3, 1)
M = inverted_residual_block(M, 64, 3, t = 2, strides = 2, n = 5)
M = inverted_residual_block(M, 128, 3, t = 4, strides = 2, n = 1)
M = inverted_residual_block(M, 128, 3, t = 2, strides = 1, n = 6)
M = inverted_residual_block(M, 128, 3, t = 4, strides = 2, n = 1)
M = inverted_residual_block(M, 128, 3, t = 2, strides = 1, n = 2)
M = conv_block(M, 512, 1, 1)
M = linear_GD_conv_block(M, 7, 1) # kernel_size = 7 for 112 x 112; 4 for 64 x 64
M = conv_block(M, 128, 1, 1)
M = Dropout(rate = 0.1)(M)
M = Flatten()(M)
M = ArcFaceLossLayer(class_num = OLD_NUM_LABELS)([M, label])
Z_L = Dense(OLD_NUM_LABELS, activation = 'softmax')(M)
model = Model(inputs = [X, label], outputs = Z_L, name = 'mobile_face_net')
return model
model = mobile_face_net()
# model.summary()
# model.layers
'''Loading the model & re-defining'''
print("Reading the pre-trained model")
model.load_weights("/home/daiwei/Python_Coding/MobileFaceNet/tl_model1906100200.hdf5")
# model.load_weights("E:\\Python_Coding\\MobileFaceNet\\tl_model_1905270955.hdf5")
print("Reading done. ")
model.summary()
# model.layers
# Re-define the model
model.layers.pop() # Remove the last FC layer
model.layers.pop() # Remove the ArcFace Loss Layer
model.layers.pop() # Remove the Label Input Layer
model.summary()
model.layers[-1].outbound_nodes = []
model.outputs = [model.layers[-1].output] # Reset the output
output = model.get_layer(model.layers[-1].name).output
model.input
# The model used for prediction
pred_model = Model(model.input[0], output)
pred_model.summary()
# pred_model.save('pred_model.h5')
# Custom the model for continue training
label = Input((NUM_LABELS, ))
M = pred_model.output
M = ArcFaceLossLayer(class_num = NUM_LABELS)([M, label])
Z_L = Dense(NUM_LABELS, activation = 'softmax')(M)
customed_model = Model(inputs = [pred_model.input, label], outputs = Z_L, name = 'mobile_face_net_transfered')
customed_model.summary()
# customed_model.layers
# plot_model(customed_model, to_file='customed_model.png')
'''Setting configurations for training the Model'''
customed_model.compile(optimizer = Adam(lr = 0.01, epsilon = 1e-8), loss = 'categorical_crossentropy', metrics = ['accuracy'])
# Temporarily increase the learing rate to 0.01
# Save the model after every epoch
from keras.callbacks import ModelCheckpoint
check_pointer = ModelCheckpoint(filepath = 'MobileFaceNet.hdf5', verbose = 1, save_best_only = True)
# Interrupt the training when the validation loss is not decreasing
from keras.callbacks import EarlyStopping
early_stopping = EarlyStopping(monitor = 'val_loss', patience = 1000)
# Record the loss history
class LossHistory(keras.callbacks.Callback):
def on_train_begin(self, logs = {}):
self.losses = []
def on_batch_end(self, batch, logs = {}):
self.losses.append(logs.get('loss'))
history = LossHistory()
# Stream each epoch results into a .csv file
from keras.callbacks import CSVLogger
csv_logger = CSVLogger('training_log.csv', separator = ',', append = True)
# append = True append if file exists (useful for continuing training)
# append = False overwrite existing file
# Reduce learning rate when a metric has stopped improving
from keras.callbacks import ReduceLROnPlateau
reduce_lr = ReduceLROnPlateau(monitor = 'val_loss', factor = 0.2, patience = 20, min_lr = 0)
'''Importing the data & training the model'''
'''
hist = customed_model.fit_generator(
train_generator,
steps_per_epoch = (m * (1 - DATA_SPLIT)) // BATCH_SIZE,
epochs = 10000,
callbacks = [check_pointer, early_stopping, history, csv_logger, reduce_lr],
validation_data = validate_generator,
validation_steps = (m * DATA_SPLIT) // BATCH_SIZE)
'''
data_list = []
for label_directory in os.listdir(IMG_DIR):
for img_name in os.listdir(os.path.join(IMG_DIR, label_directory)):
data_list.append([os.path.join(IMG_DIR, label_directory, img_name), int(label_directory)])
for i in range(TOTAL_EPOCHS):
random.shuffle(data_list)
num_of_iters = len(data_list) // BATCH_SIZE
for j in range(num_of_iters):
training_data_list = data_list[BATCH_SIZE * j: BATCH_SIZE * (j + 1)]
X_batch_list = []
Y_batch_list = []
for info in training_data_list:
img = cv2.imread(info[0])
if img.shape != (112, 112, 3):
img = cv2.resize(img, (112, 112), interpolation = cv2.INTER_LINEAR)
# assert(img.shape == (112, 112, 3))
X_batch_list.append((img - 127.5) * 0.00784313725490196)
Y_batch_list.append(info[1])
X_batch = np.array(X_batch_list)
Y_batch = np.array(Y_batch_list)
Y_batch = to_categorical(Y_batch, num_classes = NUM_LABELS)
print("X_batch shape: " + str(X_batch.shape))
print("Y_batch shape: " + str(Y_batch.shape))
hist = customed_model.fit(
[X_batch, Y_batch], Y_batch,
epochs = 1,
callbacks = [check_pointer, history, csv_logger, reduce_lr])
print(hist.history)
| [
"keras.layers.Conv2D",
"keras.utils.to_categorical",
"keras.layers.PReLU",
"math.cos",
"numpy.array",
"keras.backend.dot",
"keras.layers.Dense",
"os.listdir",
"keras.backend.image_data_format",
"keras.backend.square",
"keras.models.Model",
"keras.callbacks.EarlyStopping",
"keras.backend.epsi... | [((8748, 8777), 'keras.models.Model', 'Model', (['model.input[0]', 'output'], {}), '(model.input[0], output)\n', (8753, 8777), False, 'from keras.models import Model\n'), ((8889, 8909), 'keras.layers.Input', 'Input', (['(NUM_LABELS,)'], {}), '((NUM_LABELS,))\n', (8894, 8909), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((9064, 9156), 'keras.models.Model', 'Model', ([], {'inputs': '[pred_model.input, label]', 'outputs': 'Z_L', 'name': '"""mobile_face_net_transfered"""'}), "(inputs=[pred_model.input, label], outputs=Z_L, name=\n 'mobile_face_net_transfered')\n", (9069, 9156), False, 'from keras.models import Model\n'), ((9603, 9681), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', ([], {'filepath': '"""MobileFaceNet.hdf5"""', 'verbose': '(1)', 'save_best_only': '(True)'}), "(filepath='MobileFaceNet.hdf5', verbose=1, save_best_only=True)\n", (9618, 9681), False, 'from keras.callbacks import ModelCheckpoint\n'), ((9820, 9868), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_loss"""', 'patience': '(1000)'}), "(monitor='val_loss', patience=1000)\n", (9833, 9868), False, 'from keras.callbacks import EarlyStopping\n'), ((10247, 10304), 'keras.callbacks.CSVLogger', 'CSVLogger', (['"""training_log.csv"""'], {'separator': '""","""', 'append': '(True)'}), "('training_log.csv', separator=',', append=True)\n", (10256, 10304), False, 'from keras.callbacks import CSVLogger\n'), ((10545, 10617), 'keras.callbacks.ReduceLROnPlateau', 'ReduceLROnPlateau', ([], {'monitor': '"""val_loss"""', 'factor': '(0.2)', 'patience': '(20)', 'min_lr': '(0)'}), "(monitor='val_loss', factor=0.2, patience=20, min_lr=0)\n", (10562, 10617), False, 'from keras.callbacks import ReduceLROnPlateau\n'), ((11076, 11095), 'os.listdir', 'os.listdir', (['IMG_DIR'], {}), '(IMG_DIR)\n', (11086, 11095), False, 'import os\n'), ((6958, 6984), 'keras.layers.Input', 'Input', ([], {'shape': '(112, 112, 3)'}), '(shape=(112, 112, 3))\n', (6963, 6984), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((7000, 7024), 'keras.layers.Input', 'Input', (['(OLD_NUM_LABELS,)'], {}), '((OLD_NUM_LABELS,))\n', (7005, 7024), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((7868, 7929), 'keras.models.Model', 'Model', ([], {'inputs': '[X, label]', 'outputs': 'Z_L', 'name': '"""mobile_face_net"""'}), "(inputs=[X, label], outputs=Z_L, name='mobile_face_net')\n", (7873, 7929), False, 'from keras.models import Model\n'), ((8999, 9038), 'keras.layers.Dense', 'Dense', (['NUM_LABELS'], {'activation': '"""softmax"""'}), "(NUM_LABELS, activation='softmax')\n", (9004, 9038), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((11333, 11358), 'random.shuffle', 'random.shuffle', (['data_list'], {}), '(data_list)\n', (11347, 11358), False, 'import random\n'), ((2458, 2520), 'keras.layers.Conv2D', 'Conv2D', (['filters', 'kernel_size'], {'padding': '"""valid"""', 'strides': 'strides'}), "(filters, kernel_size, padding='valid', strides=strides)\n", (2464, 2520), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((2542, 2579), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': 'channel_axis'}), '(axis=channel_axis)\n', (2560, 2579), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((2594, 2601), 'keras.layers.PReLU', 'PReLU', ([], {}), '()\n', (2599, 2601), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((2789, 2863), 'keras.layers.SeparableConv2D', 'SeparableConv2D', ([], {'filters': '(64)', 'kernel_size': '(3)', 'strides': '(1, 1)', 'padding': '"""same"""'}), "(filters=64, kernel_size=3, strides=(1, 1), padding='same')\n", (2804, 2863), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((2889, 2926), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': 'channel_axis'}), '(axis=channel_axis)\n', (2907, 2926), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((2941, 2948), 'keras.layers.PReLU', 'PReLU', ([], {}), '()\n', (2946, 2948), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((3245, 3331), 'keras.layers.DepthwiseConv2D', 'DepthwiseConv2D', ([], {'kernel_size': 'kernel', 'strides': 's', 'padding': '"""same"""', 'depth_multiplier': '(1)'}), "(kernel_size=kernel, strides=s, padding='same',\n depth_multiplier=1)\n", (3260, 3331), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((3350, 3387), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': 'channel_axis'}), '(axis=channel_axis)\n', (3368, 3387), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((3404, 3411), 'keras.layers.PReLU', 'PReLU', ([], {}), '()\n', (3409, 3411), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((3432, 3489), 'keras.layers.Conv2D', 'Conv2D', (['filters'], {'kernel_size': '(1)', 'strides': '(1)', 'padding': '"""same"""'}), "(filters, kernel_size=1, strides=1, padding='same')\n", (3438, 3489), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((3510, 3547), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': 'channel_axis'}), '(axis=channel_axis)\n', (3528, 3547), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((3585, 3602), 'keras.layers.add', 'add', (['[Z2, inputs]'], {}), '([Z2, inputs])\n', (3588, 3602), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((4023, 4121), 'keras.layers.DepthwiseConv2D', 'DepthwiseConv2D', ([], {'kernel_size': 'kernel_size', 'strides': 'strides', 'padding': '"""valid"""', 'depth_multiplier': '(1)'}), "(kernel_size=kernel_size, strides=strides, padding='valid',\n depth_multiplier=1)\n", (4038, 4121), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((4143, 4180), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': 'channel_axis'}), '(axis=channel_axis)\n', (4161, 4180), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((4622, 4656), 'keras.initializers.get', 'initializers.get', (['"""glorot_uniform"""'], {}), "('glorot_uniform')\n", (4638, 4656), False, 'from keras import initializers\n'), ((5211, 5227), 'math.cos', 'math.cos', (['self.m'], {}), '(self.m)\n', (5219, 5227), False, 'import math\n'), ((5245, 5261), 'math.sin', 'math.sin', (['self.m'], {}), '(self.m)\n', (5253, 5261), False, 'import math\n'), ((5312, 5338), 'math.cos', 'math.cos', (['(math.pi - self.m)'], {}), '(math.pi - self.m)\n', (5320, 5338), False, 'import math\n'), ((5744, 5769), 'keras.backend.l2_normalize', 'K.l2_normalize', (['X'], {'axis': '(1)'}), '(X, axis=1)\n', (5758, 5769), True, 'from keras import backend as K\n'), ((5808, 5838), 'keras.backend.l2_normalize', 'K.l2_normalize', (['self.W'], {'axis': '(0)'}), '(self.W, axis=0)\n', (5822, 5838), True, 'from keras import backend as K\n'), ((5922, 5945), 'keras.backend.dot', 'K.dot', (['X_normed', 'self.W'], {}), '(X_normed, self.W)\n', (5927, 5945), True, 'from keras import backend as K\n'), ((5968, 5987), 'keras.backend.square', 'K.square', (['cos_theta'], {}), '(cos_theta)\n', (5976, 5987), True, 'from keras import backend as K\n'), ((6469, 6501), 'tensorflow.where', 'tf.where', (['cond', 'cos_tm', 'keep_val'], {}), '(cond, cos_tm, keep_val)\n', (6477, 6501), True, 'import tensorflow as tf\n'), ((6670, 6726), 'keras.backend.softmax', 'K.softmax', (['(s_cos_theta * inv_mask + cos_tm_temp * Y_mask)'], {}), '(s_cos_theta * inv_mask + cos_tm_temp * Y_mask)\n', (6679, 6726), True, 'from keras import backend as K\n'), ((7671, 7688), 'keras.layers.Dropout', 'Dropout', ([], {'rate': '(0.1)'}), '(rate=0.1)\n', (7678, 7688), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((7703, 7712), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (7710, 7712), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((7799, 7842), 'keras.layers.Dense', 'Dense', (['OLD_NUM_LABELS'], {'activation': '"""softmax"""'}), "(OLD_NUM_LABELS, activation='softmax')\n", (7804, 7842), False, 'from keras.layers import BatchNormalization, Conv2D, PReLU, Input, SeparableConv2D, DepthwiseConv2D, add, Flatten, Dense, Dropout\n'), ((9361, 9389), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.01)', 'epsilon': '(1e-08)'}), '(lr=0.01, epsilon=1e-08)\n', (9365, 9389), False, 'from keras.optimizers import Adam\n'), ((11136, 11174), 'os.path.join', 'os.path.join', (['IMG_DIR', 'label_directory'], {}), '(IMG_DIR, label_directory)\n', (11148, 11174), False, 'import os\n'), ((12009, 12031), 'numpy.array', 'np.array', (['X_batch_list'], {}), '(X_batch_list)\n', (12017, 12031), True, 'import numpy as np\n'), ((12052, 12074), 'numpy.array', 'np.array', (['Y_batch_list'], {}), '(Y_batch_list)\n', (12060, 12074), True, 'import numpy as np\n'), ((12095, 12142), 'keras.utils.to_categorical', 'to_categorical', (['Y_batch'], {'num_classes': 'NUM_LABELS'}), '(Y_batch, num_classes=NUM_LABELS)\n', (12109, 12142), False, 'from keras.utils import to_categorical\n'), ((2393, 2414), 'keras.backend.image_data_format', 'K.image_data_format', ([], {}), '()\n', (2412, 2414), True, 'from keras import backend as K\n'), ((2724, 2745), 'keras.backend.image_data_format', 'K.image_data_format', ([], {}), '()\n', (2743, 2745), True, 'from keras import backend as K\n'), ((3064, 3085), 'keras.backend.image_data_format', 'K.image_data_format', ([], {}), '()\n', (3083, 3085), True, 'from keras import backend as K\n'), ((3130, 3149), 'keras.backend.int_shape', 'K.int_shape', (['inputs'], {}), '(inputs)\n', (3141, 3149), True, 'from keras import backend as K\n'), ((3958, 3979), 'keras.backend.image_data_format', 'K.image_data_format', ([], {}), '()\n', (3977, 3979), True, 'from keras import backend as K\n'), ((5600, 5624), 'keras.backend.cast', 'K.cast', (['Y_mask', 'tf.int32'], {}), '(Y_mask, tf.int32)\n', (5606, 5624), True, 'from keras import backend as K\n'), ((6367, 6381), 'keras.backend.relu', 'K.relu', (['cond_v'], {}), '(cond_v)\n', (6373, 6381), True, 'from keras import backend as K\n'), ((6556, 6567), 'keras.backend.epsilon', 'K.epsilon', ([], {}), '()\n', (6565, 6567), True, 'from keras import backend as K\n'), ((11674, 11693), 'cv2.imread', 'cv2.imread', (['info[0]'], {}), '(info[0])\n', (11684, 11693), False, 'import cv2\n'), ((5657, 5690), 'keras.backend.one_hot', 'K.one_hot', (['Y_mask', 'self.class_num'], {}), '(Y_mask, self.class_num)\n', (5666, 5690), True, 'from keras import backend as K\n'), ((6067, 6078), 'keras.backend.epsilon', 'K.epsilon', ([], {}), '()\n', (6076, 6078), True, 'from keras import backend as K\n'), ((11215, 11263), 'os.path.join', 'os.path.join', (['IMG_DIR', 'label_directory', 'img_name'], {}), '(IMG_DIR, label_directory, img_name)\n', (11227, 11263), False, 'import os\n'), ((11763, 11822), 'cv2.resize', 'cv2.resize', (['img', '(112, 112)'], {'interpolation': 'cv2.INTER_LINEAR'}), '(img, (112, 112), interpolation=cv2.INTER_LINEAR)\n', (11773, 11822), False, 'import cv2\n')] |
# Draw 3d plots of LUT cube file.
# Usage: python plot_cube.py [lut file] [skip(optional)]
# -Only LUT_3D type of cube format is supported.
# -If the generated plot is too messy, try larger skip value (default 4) to generate sparse meshgrid.
import sys
import os.path
import re
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
# Default & Global values
sTitle = ""
sLut_3d_size = 33
sVal_max = 1.0
sVal_min = 0.0
sR_index = 0
sG_index = 0
sB_index = 0
sLut = 0.
sLutSizeSpecified = False
sSkip = 4
def parse_line(line):
global sTitle
global sLut_3d_size
global sVal_max
global sVal_min
global sR_index
global sG_index
global sB_index
global sLut
global sLutSizeSpecified
# Title
pattern = r"^[ \t]*TITLE[ \t]+\"[\w ]+\""
match = re.match(pattern , line)
if match is not None:
t = re.search(r"\"[\w ]+\"" , match.group())
sTitle = t.group()
print("TITLE:",sTitle)
return
# LUT_3D_SIZE
pattern = r"^[ \t]*(LUT_3D_SIZE)[ \t]+[\d]+"
match = re.match(pattern , line)
if match is not None:
t = re.search(r"[ \t][\d]+" , match.group())
sLut_3d_size = int(t.group())
sR_index = 0
sG_index = 0
sB_index = 0
sLut = np.zeros((sLut_3d_size,sLut_3d_size,sLut_3d_size,3), dtype=np.float64)
sLutSizeSpecified = True
print("LUT_3D_SIZE:",sLut_3d_size)
return
# Reject LUT_1D_SIZE
pattern = r"^[ \t]*LUT_1D_SIZE[ \t][\d]+"
match = re.match(pattern , line)
if match is not None:
print("Error: LUT_1D_SIZE is not supported.")
quit()
# LUT values
# also supports exponential expressions such as 1.23456e-05
number = r"([\d]*[\.]?[\d]*)(e(\-)?[\d]+)?"
space = r"[ \t]+"
pattern = r"^[ \t]*" + number + space + number + space + number
match = re.match(pattern , line)
if match is not None:
t = match.group().split()
if len(t) != 3:
print("Error: bad format")
quit()
if (sB_index >= sLut_3d_size) and (sG_index >= sLut_3d_size) and (sR_index >= sLut_3d_size):
print("Error: bad format")
quit()
sLut[sR_index][sG_index][sB_index][0] = np.float64(t[0])
sLut[sR_index][sG_index][sB_index][1] = np.float64(t[1])
sLut[sR_index][sG_index][sB_index][2] = np.float64(t[2])
sB_index += 1
if sB_index >= sLut_3d_size:
sB_index = 0
sG_index += 1
if sG_index >= sLut_3d_size:
sG_index = 0
sR_index += 1
return
def import_lut(fn):
f = open(fn)
lines2 = f.readlines()
f.close()
l = 1
for line in lines2:
parse_line(line)
l += 1
def draw_outerbox(fig,ax):
# Draw outer box
X_start = float(sVal_min)
X_end = float(sVal_max)
Y_start = float(sVal_min)
Y_end = float(sVal_max)
Z_start = float(sVal_min)
Z_end = float(sVal_max)
X, Y = np.meshgrid([X_start,X_end], [Y_start,Y_end])
ax.plot_wireframe(X,Y,Z_start, color='black')
ax.plot_wireframe(X,Y,Z_end, color='black')
Y, Z = np.meshgrid([Y_start,Y_end],[Z_start,Z_end])
ax.plot_wireframe(X_start, Y,Z,color='black')
ax.plot_wireframe(X_end, Y,Z,color='black')
X, Z = np.meshgrid([X_start,X_end],[Z_start,Z_end])
ax.plot_wireframe(X,Y_start,Z,color='black')
ax.plot_wireframe(X,Y_end, Z,color='black')
def draw_meshgrid(fig,ax):
# Draw mesh for each red with skipping
for i in range(0,sLut_3d_size,sSkip):
ax.plot_wireframe(sLut[i,0:
sLut_3d_size:sSkip,0:sLut_3d_size:sSkip,0],
sLut[i,0:sLut_3d_size:sSkip,0:sLut_3d_size:sSkip,1],
sLut[i,0:sLut_3d_size:sSkip,0:sLut_3d_size:sSkip,2],
color=cm.hsv(float(i)/float(sLut_3d_size)))
# Draw last mesh if skipped in the loop above
if((sLut_3d_size - 1) % sSkip):
ax.plot_wireframe(sLut[sLut_3d_size - 1,0:
sLut_3d_size:sSkip,0:sLut_3d_size:sSkip,0],
sLut[sLut_3d_size - 1,0:sLut_3d_size:sSkip,0:sLut_3d_size:sSkip,1],
sLut[sLut_3d_size - 1,0:sLut_3d_size:sSkip,0:sLut_3d_size:sSkip,2],
color=cm.hsv(1.0))
def draw_labels(fig,ax):
ax.set_xlabel('R')
ax.set_ylabel('G')
ax.set_zlabel('B')
ax.set_title(sTitle)
if __name__ == "__main__":
argvs = sys.argv
argc = len(argvs)
if(argc < 2) or (argc > 3):
print ("Usage: python plot_cube.py [lut file] [skip(optional)]")
quit()
if(argc == 3):
sSkip = int(argvs[2])
if(sSkip == 0):
print("Error: Skip value must be >= 1")
quit()
if not os.path.exists(argvs[1]):
print("Error: ",argvs[1]," not exists.")
quit()
import_lut(argvs[1])
if not sLutSizeSpecified:
print("Error: LUT size not specified in cube file.")
quit()
fig = plt.figure()
ax = Axes3D(fig)
# Draw outer box
draw_outerbox(fig,ax)
# Draw meshgrids
draw_meshgrid(fig,ax)
# Labelling
draw_labels(fig,ax)
plt.show()
| [
"numpy.float64",
"re.match",
"matplotlib.cm.hsv",
"matplotlib.pyplot.figure",
"numpy.zeros",
"numpy.meshgrid",
"mpl_toolkits.mplot3d.Axes3D",
"matplotlib.pyplot.show"
] | [((858, 881), 're.match', 're.match', (['pattern', 'line'], {}), '(pattern, line)\n', (866, 881), False, 'import re\n'), ((1123, 1146), 're.match', 're.match', (['pattern', 'line'], {}), '(pattern, line)\n', (1131, 1146), False, 'import re\n'), ((1593, 1616), 're.match', 're.match', (['pattern', 'line'], {}), '(pattern, line)\n', (1601, 1616), False, 'import re\n'), ((1953, 1976), 're.match', 're.match', (['pattern', 'line'], {}), '(pattern, line)\n', (1961, 1976), False, 'import re\n'), ((3142, 3189), 'numpy.meshgrid', 'np.meshgrid', (['[X_start, X_end]', '[Y_start, Y_end]'], {}), '([X_start, X_end], [Y_start, Y_end])\n', (3153, 3189), True, 'import numpy as np\n'), ((3302, 3349), 'numpy.meshgrid', 'np.meshgrid', (['[Y_start, Y_end]', '[Z_start, Z_end]'], {}), '([Y_start, Y_end], [Z_start, Z_end])\n', (3313, 3349), True, 'import numpy as np\n'), ((3461, 3508), 'numpy.meshgrid', 'np.meshgrid', (['[X_start, X_end]', '[Z_start, Z_end]'], {}), '([X_start, X_end], [Z_start, Z_end])\n', (3472, 3508), True, 'import numpy as np\n'), ((5120, 5132), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5130, 5132), True, 'import matplotlib.pyplot as plt\n'), ((5142, 5153), 'mpl_toolkits.mplot3d.Axes3D', 'Axes3D', (['fig'], {}), '(fig)\n', (5148, 5153), False, 'from mpl_toolkits.mplot3d import Axes3D\n'), ((5308, 5318), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5316, 5318), True, 'import matplotlib.pyplot as plt\n'), ((1343, 1416), 'numpy.zeros', 'np.zeros', (['(sLut_3d_size, sLut_3d_size, sLut_3d_size, 3)'], {'dtype': 'np.float64'}), '((sLut_3d_size, sLut_3d_size, sLut_3d_size, 3), dtype=np.float64)\n', (1351, 1416), True, 'import numpy as np\n'), ((2345, 2361), 'numpy.float64', 'np.float64', (['t[0]'], {}), '(t[0])\n', (2355, 2361), True, 'import numpy as np\n'), ((2410, 2426), 'numpy.float64', 'np.float64', (['t[1]'], {}), '(t[1])\n', (2420, 2426), True, 'import numpy as np\n'), ((2475, 2491), 'numpy.float64', 'np.float64', (['t[2]'], {}), '(t[2])\n', (2485, 2491), True, 'import numpy as np\n'), ((4375, 4386), 'matplotlib.cm.hsv', 'cm.hsv', (['(1.0)'], {}), '(1.0)\n', (4381, 4386), True, 'import matplotlib.cm as cm\n')] |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
@author: ogouvert
x_l \sim Log(p) (logarithmic distribution)
which implies: y \sim sumLog(n,p)
"""
import numpy as np
import scipy.special as special
import scipy.sparse as sparse
import dcpf
class dcpf_Log(dcpf.dcpf):
def __init__(self, K, p, t=1.,
alphaW=1., alphaH=1., betaW=1., betaH=1.):
"""
p (float) - p=exp(\theta) where \theta is the natural parameter of the EDM
"""
assert p>=0 and p<=1
self.p = p
dcpf.dcpf.__init__(self,K=K, t=t,
alphaW = alphaW, alphaH = alphaH, betaW = betaW, betaH = betaW)
self.classname = 'dcpf_Log'
def c_en(self,Y,s):
y = Y.data
# Limit cases
if self.p==0: # PF on raw data
en = Y.data
elbo = - np.sum(special.gammaln(y+1)) + np.sum(y*np.log(s))
elif self.p==1: # PF on binary data
en = np.ones_like(y, dtype=np.float)
elbo = np.sum(np.log(s))
else: # 0 < p < 1 - Trade-off
r = s/(-np.log(1-self.p))
en = np.ones_like(y, dtype=np.float)
en[y>1] = r[y>1]*(special.digamma(y[y>1]+r[y>1])-special.digamma(r[y>1]))
# ELBO
elbo_cst = -np.sum(special.gammaln(y+1)) + Y.sum()*np.log(self.p)
elbo = elbo_cst + np.sum(special.gammaln(y+r) - special.gammaln(r))
return en, elbo
def opt_param_xl(self,s_en,s_y):
"""" Hyper-parameter optimization : Newton algortithm """
ratio = float(s_en)/s_y
p = self.p
cost_init = s_y*np.log(p) - s_en*np.log(-np.log(1.-p))
for n in range(10):
f = (1.-p)/p*(-np.log(1-p))
grad = np.log(1-p)/(p**2) + 1/p
delta = (f-ratio)/grad
while p - delta < 0 or p - delta > 1:
delta = delta/2
p = p - delta
cost = s_y*np.log(p) - s_en*np.log(-np.log(1.-p))
# Is the p better?
if cost>cost_init:
self.p = p
def generate(self):
pc = np.random.negative_binomial(
-np.dot(self.Ew,self.Eh.T)/np.log(1.-self.p),
self.p)
return sparse.csr_matrix(pc)
#%% Synthetic example
if False:
import matplotlib.pyplot as plt
U = 1000
I = 1000
K = 3
np.random.seed(93)
W = np.random.gamma(1.,.1, (U,K))
H = np.random.gamma(1.,.1, (I,K))
L = np.dot(W,H.T)
Ya = np.random.poisson(L)
Y = sparse.csr_matrix(Ya)
#%%
model = dcpf_Log(K=K,p=0.2)
model.fit(Y,verbose=True, opt_hyper=['p','beta'], save=False)
#%%
Ew = model.Ew
Eh = model.Eh
Yr = np.dot(Ew,Eh.T)
#%%
plt.figure('Obs')
plt.imshow(Ya,interpolation='nearest')
plt.colorbar()
plt.figure('Truth')
plt.imshow(L,interpolation='nearest')
plt.colorbar()
plt.figure('Reconstruction')
plt.imshow(Yr,interpolation='nearest')
plt.colorbar()
#%%
plt.figure('elbo')
plt.plot(model.Elbo)
| [
"matplotlib.pyplot.imshow",
"numpy.ones_like",
"scipy.special.digamma",
"numpy.random.poisson",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.plot",
"numpy.log",
"numpy.dot",
"numpy.random.gamma",
"matplotlib.pyplot.figure",
"numpy.random.seed",
"scipy.sparse.csr_matrix",
"dcpf.dcpf.__ini... | [((2368, 2386), 'numpy.random.seed', 'np.random.seed', (['(93)'], {}), '(93)\n', (2382, 2386), True, 'import numpy as np\n'), ((2395, 2428), 'numpy.random.gamma', 'np.random.gamma', (['(1.0)', '(0.1)', '(U, K)'], {}), '(1.0, 0.1, (U, K))\n', (2410, 2428), True, 'import numpy as np\n'), ((2433, 2466), 'numpy.random.gamma', 'np.random.gamma', (['(1.0)', '(0.1)', '(I, K)'], {}), '(1.0, 0.1, (I, K))\n', (2448, 2466), True, 'import numpy as np\n'), ((2471, 2485), 'numpy.dot', 'np.dot', (['W', 'H.T'], {}), '(W, H.T)\n', (2477, 2485), True, 'import numpy as np\n'), ((2494, 2514), 'numpy.random.poisson', 'np.random.poisson', (['L'], {}), '(L)\n', (2511, 2514), True, 'import numpy as np\n'), ((2523, 2544), 'scipy.sparse.csr_matrix', 'sparse.csr_matrix', (['Ya'], {}), '(Ya)\n', (2540, 2544), True, 'import scipy.sparse as sparse\n'), ((2730, 2746), 'numpy.dot', 'np.dot', (['Ew', 'Eh.T'], {}), '(Ew, Eh.T)\n', (2736, 2746), True, 'import numpy as np\n'), ((2763, 2780), 'matplotlib.pyplot.figure', 'plt.figure', (['"""Obs"""'], {}), "('Obs')\n", (2773, 2780), True, 'import matplotlib.pyplot as plt\n'), ((2785, 2824), 'matplotlib.pyplot.imshow', 'plt.imshow', (['Ya'], {'interpolation': '"""nearest"""'}), "(Ya, interpolation='nearest')\n", (2795, 2824), True, 'import matplotlib.pyplot as plt\n'), ((2828, 2842), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (2840, 2842), True, 'import matplotlib.pyplot as plt\n'), ((2847, 2866), 'matplotlib.pyplot.figure', 'plt.figure', (['"""Truth"""'], {}), "('Truth')\n", (2857, 2866), True, 'import matplotlib.pyplot as plt\n'), ((2871, 2909), 'matplotlib.pyplot.imshow', 'plt.imshow', (['L'], {'interpolation': '"""nearest"""'}), "(L, interpolation='nearest')\n", (2881, 2909), True, 'import matplotlib.pyplot as plt\n'), ((2913, 2927), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (2925, 2927), True, 'import matplotlib.pyplot as plt\n'), ((2932, 2960), 'matplotlib.pyplot.figure', 'plt.figure', (['"""Reconstruction"""'], {}), "('Reconstruction')\n", (2942, 2960), True, 'import matplotlib.pyplot as plt\n'), ((2965, 3004), 'matplotlib.pyplot.imshow', 'plt.imshow', (['Yr'], {'interpolation': '"""nearest"""'}), "(Yr, interpolation='nearest')\n", (2975, 3004), True, 'import matplotlib.pyplot as plt\n'), ((3008, 3022), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (3020, 3022), True, 'import matplotlib.pyplot as plt\n'), ((3036, 3054), 'matplotlib.pyplot.figure', 'plt.figure', (['"""elbo"""'], {}), "('elbo')\n", (3046, 3054), True, 'import matplotlib.pyplot as plt\n'), ((3059, 3079), 'matplotlib.pyplot.plot', 'plt.plot', (['model.Elbo'], {}), '(model.Elbo)\n', (3067, 3079), True, 'import matplotlib.pyplot as plt\n'), ((537, 632), 'dcpf.dcpf.__init__', 'dcpf.dcpf.__init__', (['self'], {'K': 'K', 't': 't', 'alphaW': 'alphaW', 'alphaH': 'alphaH', 'betaW': 'betaW', 'betaH': 'betaW'}), '(self, K=K, t=t, alphaW=alphaW, alphaH=alphaH, betaW=\n betaW, betaH=betaW)\n', (555, 632), False, 'import dcpf\n'), ((2231, 2252), 'scipy.sparse.csr_matrix', 'sparse.csr_matrix', (['pc'], {}), '(pc)\n', (2248, 2252), True, 'import scipy.sparse as sparse\n'), ((959, 990), 'numpy.ones_like', 'np.ones_like', (['y'], {'dtype': 'np.float'}), '(y, dtype=np.float)\n', (971, 990), True, 'import numpy as np\n'), ((1121, 1152), 'numpy.ones_like', 'np.ones_like', (['y'], {'dtype': 'np.float'}), '(y, dtype=np.float)\n', (1133, 1152), True, 'import numpy as np\n'), ((1625, 1634), 'numpy.log', 'np.log', (['p'], {}), '(p)\n', (1631, 1634), True, 'import numpy as np\n'), ((1938, 1947), 'numpy.log', 'np.log', (['p'], {}), '(p)\n', (1944, 1947), True, 'import numpy as np\n'), ((2172, 2192), 'numpy.log', 'np.log', (['(1.0 - self.p)'], {}), '(1.0 - self.p)\n', (2178, 2192), True, 'import numpy as np\n'), ((1017, 1026), 'numpy.log', 'np.log', (['s'], {}), '(s)\n', (1023, 1026), True, 'import numpy as np\n'), ((1719, 1732), 'numpy.log', 'np.log', (['(1 - p)'], {}), '(1 - p)\n', (1725, 1732), True, 'import numpy as np\n'), ((1751, 1764), 'numpy.log', 'np.log', (['(1 - p)'], {}), '(1 - p)\n', (1757, 1764), True, 'import numpy as np\n'), ((2146, 2172), 'numpy.dot', 'np.dot', (['self.Ew', 'self.Eh.T'], {}), '(self.Ew, self.Eh.T)\n', (2152, 2172), True, 'import numpy as np\n'), ((853, 875), 'scipy.special.gammaln', 'special.gammaln', (['(y + 1)'], {}), '(y + 1)\n', (868, 875), True, 'import scipy.special as special\n'), ((886, 895), 'numpy.log', 'np.log', (['s'], {}), '(s)\n', (892, 895), True, 'import numpy as np\n'), ((1086, 1104), 'numpy.log', 'np.log', (['(1 - self.p)'], {}), '(1 - self.p)\n', (1092, 1104), True, 'import numpy as np\n'), ((1183, 1219), 'scipy.special.digamma', 'special.digamma', (['(y[y > 1] + r[y > 1])'], {}), '(y[y > 1] + r[y > 1])\n', (1198, 1219), True, 'import scipy.special as special\n'), ((1214, 1239), 'scipy.special.digamma', 'special.digamma', (['r[y > 1]'], {}), '(r[y > 1])\n', (1229, 1239), True, 'import scipy.special as special\n'), ((1323, 1337), 'numpy.log', 'np.log', (['self.p'], {}), '(self.p)\n', (1329, 1337), True, 'import numpy as np\n'), ((1650, 1665), 'numpy.log', 'np.log', (['(1.0 - p)'], {}), '(1.0 - p)\n', (1656, 1665), True, 'import numpy as np\n'), ((1963, 1978), 'numpy.log', 'np.log', (['(1.0 - p)'], {}), '(1.0 - p)\n', (1969, 1978), True, 'import numpy as np\n'), ((1291, 1313), 'scipy.special.gammaln', 'special.gammaln', (['(y + 1)'], {}), '(y + 1)\n', (1306, 1313), True, 'import scipy.special as special\n'), ((1375, 1397), 'scipy.special.gammaln', 'special.gammaln', (['(y + r)'], {}), '(y + r)\n', (1390, 1397), True, 'import scipy.special as special\n'), ((1398, 1416), 'scipy.special.gammaln', 'special.gammaln', (['r'], {}), '(r)\n', (1413, 1416), True, 'import scipy.special as special\n')] |
import os
import tempfile
import zipfile
from io import BytesIO
import cv2
import click
import numpy as np
from skimage import filters
from tqdm import tqdm
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from dataset import rtranspose
from loader import get_loaders
from loss import fmicro_th, dice_th, fmicro_np, dice_np
imsize = 512
def predict(net, loader, verbose=0):
ypred = torch.zeros([len(loader.dataset), imsize, imsize])
ytrue = torch.zeros([len(loader.dataset), imsize, imsize])
ypath = [''] * len(loader.dataset)
ytidx = torch.zeros(len(loader.dataset))
gen = enumerate(loader, 0)
if verbose == 1:
gen = tqdm(list(gen))
for i, data in gen:
images, ytrues, paths, ts = data
images = Variable(images.cuda(), volatile=True)
ypreds = net(images).select(1, 0)
ypred[i * loader.batch_size:(i + 1) * loader.batch_size] = ypreds.data.cpu()
if ytrues is not None:
ytrue[i * loader.batch_size:(i + 1) * loader.batch_size] = ytrues.select(1, 0)
ypath[i * loader.batch_size:(i + 1) * loader.batch_size] = paths
ytidx[i * loader.batch_size:(i + 1) * loader.batch_size] = ts
return ypred, ytrue, ypath, ytidx
@click.command()
@click.option('-n', '--name', default='invalid9000', help='Model name')
@click.option('-m', '--mode', default='best', help='Checkpoint to use')
@click.option('-f', '--nfolds', type=int, prompt=True, help='Number of folds')
@click.option('-b', '--batch-size', default=16, help='Batch size')
def main(name, mode, nfolds, batch_size):
out_root = f'output/{name}/'
os.makedirs(out_root, exist_ok=True)
paths = []
tomix = []
trues = []
probs = []
tidxs = []
EXCLUDED = ['quading/i628806.tif_i282989.tif_i417677.tif_i659777.tif.tif',
'quading/i933123.tif_i154348.tif_i435969.tif_i385761.tif.tif']
enames = sum([os.path.splitext(os.path.basename(p))[0].split('_') for p in EXCLUDED], [])
tmpzip = BytesIO()
with zipfile.ZipFile(tmpzip, 'w', zipfile.ZIP_DEFLATED) as zipf:
# for fold in range(nfolds):
# print(f'fold{fold}:')
#
# mpath = f'weights/{name}/{name}_fold{fold}_{mode}.pth'
# model = torch.load(mpath)
# model.cuda()
# model.eval()
#
# splits = ['train', 'valid', 'test']
#
# for split, loader in zip(splits, get_loaders(batch_size, nfolds, fold, training=False)):
# ypred, ytrue, ypath, ts = predict(model, loader, verbose=1)
# ypred = ypred[:, 6:-6, 6:-6].contiguous()
# ytrue = ytrue[:, 6:-6, 6:-6].contiguous()
# yprob = torch.sigmoid(ypred)
#
# if split != 'test':
# vprob = Variable(yprob, volatile=True).cuda()
# vtrue = Variable(ytrue, volatile=True).cuda()
# ll = F.binary_cross_entropy(vprob, vtrue).data[0]
#
# f1 = fmicro_th(vprob > 0.5, vtrue)
# dc = dice_th(vprob > 0.5, vtrue)
# sc = int(round(1e8 * (f1 + dc) / 2)) / 100
# print(f'[{0.5:0.1f}] '
# f'loss {ll:0.3f} f1 {f1:0.4f} '
# f'dice {dc:0.4f} score {sc:0.2f}')
#
# if split != 'train':
# store = [True for _ in ypath]
# else:
# store = [split == 'valid' or
# fold == 1 and np.any([p.find(str(name)) != -1 for name in enames])
# for p in ypath]
#
# tomix.extend(np.array([split == 'valid' for _ in store])[store])
# paths.extend(np.array(ypath)[store])
# trues.extend(ytrue.numpy()[store])
# probs.extend(yprob.numpy()[store])
# tidxs.extend(ts.numpy()[store])
#
# # untranspose
# for i, (true, prob, t) in enumerate(zip(trues, probs, tidxs)):
# trues[i] = rtranspose(true, t)
# probs[i] = rtranspose(prob, t)
#
# tomix = np.stack(tomix)
# paths = np.stack(paths)
# trues = np.stack(trues)
# probs = np.stack(probs)
#
# np.save(out_root + f'{name}_{mode}_tomix.npy', tomix)
# np.save(out_root + f'{name}_{mode}_paths.npy', paths)
# np.save(out_root + f'{name}_{mode}_trues.npy', trues)
# np.save(out_root + f'{name}_{mode}_probs.npy', probs)
tomix = np.load(out_root + f'{name}_{mode}_tomix.npy')
paths = np.load(out_root + f'{name}_{mode}_paths.npy')
trues = np.load(out_root + f'{name}_{mode}_trues.npy')
probs = np.load(out_root + f'{name}_{mode}_probs.npy')
print('CVOOF:')
cvpaths = paths[tomix]
cvtrues = trues[tomix]
cvprobs = probs[tomix]
meantrues = []
meanprobs = []
for cvpath in np.unique(cvpaths):
thiscvtrues = cvtrues[cvpaths == cvpath]
assert np.alltrue(np.std(thiscvtrues, 0) == 0) # all rotated
thiscvprobs = cvprobs[cvpaths == cvpath]
meantrues.append(np.mean(thiscvtrues, 0))
meanprobs.append(np.mean(thiscvprobs, 0))
meantrue = np.stack(meantrues)
meanprob = np.stack(meanprobs)
for thr in [0.4, 0.5]:
for i, (prob, true) in enumerate(zip(meanprob, meantrue)):
cv2.imwrite(f'rounds/pred/{i}_{thr}.png', (np.uint8(prob > thr) * 255))
f1 = fmicro_np(meanprob > thr, meantrue)
dc = dice_np(meanprob > thr, meantrue)
sc = int(round(1e8 * (f1 + dc) / 2)) / 100
print(f'[{thr:0.1f}] '
f'loss f1 {f1:0.4f} '
f'dice {dc:0.4f} score {sc:0.2f}')
meanpred = np.zeros_like(meanprob)
for i, prob in enumerate(meanprob):
meanpred[i] = cv2.adaptiveThreshold(np.uint8(prob * 255), 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2)
f1 = fmicro_np(meanpred, meantrue)
dc = dice_np(meanpred, meantrue)
sc = int(round(1e8 * (f1 + dc) / 2)) / 100
print(f'[cv2] '
f'loss f1 {f1:0.4f} '
f'dice {dc:0.4f} score {sc:0.2f}')
for method in [filters.threshold_isodata]:
print(method)
meanpred = np.zeros_like(meanprob)
for i, (prob, true) in enumerate(zip(meanprob, meantrue)):
thr = method(prob)
meanpred[i] = prob > thr
cv2.imwrite(f'rounds/pred/{i}_prob.png', np.uint8(prob * 255))
cv2.imwrite(f'rounds/pred/{i}_true.png', np.uint8(true) * 255)
cv2.imwrite(f'rounds/pred/{i}_iso.png', np.uint8(meanpred[i]) * 255)
f1 = fmicro_np(meanpred, meantrue)
dc = dice_np(meanpred, meantrue)
sc = int(round(1e8 * (f1 + dc) / 2)) / 100
print(f'[thr] '
f'loss f1 {f1:0.4f} '
f'dice {dc:0.4f} score {sc:0.2f}')
for path in np.unique(paths):
thistrues = trues[paths == path]
assert np.alltrue(np.std(thistrues, 0) == 0) # all rotated
thisprobs = probs[paths == path]
prob = np.mean(thisprobs, 0)
pred = np.greater(prob, 0.5)
with tempfile.NamedTemporaryFile() as tmpmask:
np.savetxt(tmpmask.name, pred.T, fmt='%d', delimiter='')
zipf.write(tmpmask.name, os.path.basename(path).replace('.tif', '_mask.txt'))
tmpzip.seek(0)
with open(out_root + f'{name}_{mode}.zip', 'wb') as out:
out.write(tmpzip.read())
if __name__ == '__main__':
main()
| [
"numpy.uint8",
"numpy.mean",
"numpy.greater",
"numpy.unique",
"zipfile.ZipFile",
"os.makedirs",
"click.option",
"numpy.std",
"io.BytesIO",
"numpy.stack",
"loss.fmicro_np",
"loss.dice_np",
"os.path.basename",
"numpy.savetxt",
"tempfile.NamedTemporaryFile",
"click.command",
"numpy.zero... | [((1262, 1277), 'click.command', 'click.command', ([], {}), '()\n', (1275, 1277), False, 'import click\n'), ((1279, 1349), 'click.option', 'click.option', (['"""-n"""', '"""--name"""'], {'default': '"""invalid9000"""', 'help': '"""Model name"""'}), "('-n', '--name', default='invalid9000', help='Model name')\n", (1291, 1349), False, 'import click\n'), ((1351, 1421), 'click.option', 'click.option', (['"""-m"""', '"""--mode"""'], {'default': '"""best"""', 'help': '"""Checkpoint to use"""'}), "('-m', '--mode', default='best', help='Checkpoint to use')\n", (1363, 1421), False, 'import click\n'), ((1423, 1500), 'click.option', 'click.option', (['"""-f"""', '"""--nfolds"""'], {'type': 'int', 'prompt': '(True)', 'help': '"""Number of folds"""'}), "('-f', '--nfolds', type=int, prompt=True, help='Number of folds')\n", (1435, 1500), False, 'import click\n'), ((1502, 1567), 'click.option', 'click.option', (['"""-b"""', '"""--batch-size"""'], {'default': '(16)', 'help': '"""Batch size"""'}), "('-b', '--batch-size', default=16, help='Batch size')\n", (1514, 1567), False, 'import click\n'), ((1647, 1683), 'os.makedirs', 'os.makedirs', (['out_root'], {'exist_ok': '(True)'}), '(out_root, exist_ok=True)\n', (1658, 1683), False, 'import os\n'), ((2027, 2036), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (2034, 2036), False, 'from io import BytesIO\n'), ((2046, 2096), 'zipfile.ZipFile', 'zipfile.ZipFile', (['tmpzip', '"""w"""', 'zipfile.ZIP_DEFLATED'], {}), "(tmpzip, 'w', zipfile.ZIP_DEFLATED)\n", (2061, 2096), False, 'import zipfile\n'), ((4635, 4681), 'numpy.load', 'np.load', (["(out_root + f'{name}_{mode}_tomix.npy')"], {}), "(out_root + f'{name}_{mode}_tomix.npy')\n", (4642, 4681), True, 'import numpy as np\n'), ((4698, 4744), 'numpy.load', 'np.load', (["(out_root + f'{name}_{mode}_paths.npy')"], {}), "(out_root + f'{name}_{mode}_paths.npy')\n", (4705, 4744), True, 'import numpy as np\n'), ((4761, 4807), 'numpy.load', 'np.load', (["(out_root + f'{name}_{mode}_trues.npy')"], {}), "(out_root + f'{name}_{mode}_trues.npy')\n", (4768, 4807), True, 'import numpy as np\n'), ((4824, 4870), 'numpy.load', 'np.load', (["(out_root + f'{name}_{mode}_probs.npy')"], {}), "(out_root + f'{name}_{mode}_probs.npy')\n", (4831, 4870), True, 'import numpy as np\n'), ((5057, 5075), 'numpy.unique', 'np.unique', (['cvpaths'], {}), '(cvpaths)\n', (5066, 5075), True, 'import numpy as np\n'), ((5384, 5403), 'numpy.stack', 'np.stack', (['meantrues'], {}), '(meantrues)\n', (5392, 5403), True, 'import numpy as np\n'), ((5423, 5442), 'numpy.stack', 'np.stack', (['meanprobs'], {}), '(meanprobs)\n', (5431, 5442), True, 'import numpy as np\n'), ((5949, 5972), 'numpy.zeros_like', 'np.zeros_like', (['meanprob'], {}), '(meanprob)\n', (5962, 5972), True, 'import numpy as np\n'), ((6259, 6288), 'loss.fmicro_np', 'fmicro_np', (['meanpred', 'meantrue'], {}), '(meanpred, meantrue)\n', (6268, 6288), False, 'from loss import fmicro_th, dice_th, fmicro_np, dice_np\n'), ((6302, 6329), 'loss.dice_np', 'dice_np', (['meanpred', 'meantrue'], {}), '(meanpred, meantrue)\n', (6309, 6329), False, 'from loss import fmicro_th, dice_th, fmicro_np, dice_np\n'), ((7312, 7328), 'numpy.unique', 'np.unique', (['paths'], {}), '(paths)\n', (7321, 7328), True, 'import numpy as np\n'), ((5650, 5685), 'loss.fmicro_np', 'fmicro_np', (['(meanprob > thr)', 'meantrue'], {}), '(meanprob > thr, meantrue)\n', (5659, 5685), False, 'from loss import fmicro_th, dice_th, fmicro_np, dice_np\n'), ((5703, 5736), 'loss.dice_np', 'dice_np', (['(meanprob > thr)', 'meantrue'], {}), '(meanprob > thr, meantrue)\n', (5710, 5736), False, 'from loss import fmicro_th, dice_th, fmicro_np, dice_np\n'), ((6600, 6623), 'numpy.zeros_like', 'np.zeros_like', (['meanprob'], {}), '(meanprob)\n', (6613, 6623), True, 'import numpy as np\n'), ((7031, 7060), 'loss.fmicro_np', 'fmicro_np', (['meanpred', 'meantrue'], {}), '(meanpred, meantrue)\n', (7040, 7060), False, 'from loss import fmicro_th, dice_th, fmicro_np, dice_np\n'), ((7078, 7105), 'loss.dice_np', 'dice_np', (['meanpred', 'meantrue'], {}), '(meanpred, meantrue)\n', (7085, 7105), False, 'from loss import fmicro_th, dice_th, fmicro_np, dice_np\n'), ((7511, 7532), 'numpy.mean', 'np.mean', (['thisprobs', '(0)'], {}), '(thisprobs, 0)\n', (7518, 7532), True, 'import numpy as np\n'), ((7552, 7573), 'numpy.greater', 'np.greater', (['prob', '(0.5)'], {}), '(prob, 0.5)\n', (7562, 7573), True, 'import numpy as np\n'), ((5286, 5309), 'numpy.mean', 'np.mean', (['thiscvtrues', '(0)'], {}), '(thiscvtrues, 0)\n', (5293, 5309), True, 'import numpy as np\n'), ((5340, 5363), 'numpy.mean', 'np.mean', (['thiscvprobs', '(0)'], {}), '(thiscvprobs, 0)\n', (5347, 5363), True, 'import numpy as np\n'), ((6065, 6085), 'numpy.uint8', 'np.uint8', (['(prob * 255)'], {}), '(prob * 255)\n', (6073, 6085), True, 'import numpy as np\n'), ((7591, 7620), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {}), '()\n', (7618, 7620), False, 'import tempfile\n'), ((7649, 7705), 'numpy.savetxt', 'np.savetxt', (['tmpmask.name', 'pred.T'], {'fmt': '"""%d"""', 'delimiter': '""""""'}), "(tmpmask.name, pred.T, fmt='%d', delimiter='')\n", (7659, 7705), True, 'import numpy as np\n'), ((5160, 5182), 'numpy.std', 'np.std', (['thiscvtrues', '(0)'], {}), '(thiscvtrues, 0)\n', (5166, 5182), True, 'import numpy as np\n'), ((6828, 6848), 'numpy.uint8', 'np.uint8', (['(prob * 255)'], {}), '(prob * 255)\n', (6836, 6848), True, 'import numpy as np\n'), ((7405, 7425), 'numpy.std', 'np.std', (['thistrues', '(0)'], {}), '(thistrues, 0)\n', (7411, 7425), True, 'import numpy as np\n'), ((5604, 5624), 'numpy.uint8', 'np.uint8', (['(prob > thr)'], {}), '(prob > thr)\n', (5612, 5624), True, 'import numpy as np\n'), ((6907, 6921), 'numpy.uint8', 'np.uint8', (['true'], {}), '(true)\n', (6915, 6921), True, 'import numpy as np\n'), ((6985, 7006), 'numpy.uint8', 'np.uint8', (['meanpred[i]'], {}), '(meanpred[i])\n', (6993, 7006), True, 'import numpy as np\n'), ((1954, 1973), 'os.path.basename', 'os.path.basename', (['p'], {}), '(p)\n', (1970, 1973), False, 'import os\n'), ((7747, 7769), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (7763, 7769), False, 'import os\n')] |
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import math
import numpy
HSBK_HUE = 0
HSBK_SAT = 1
HSBK_BR = 2
HSBK_KELV = 3
N_HSBK = 4
KELV_MIN = 1500
KELV_MAX = 9000
EPSILON = 1e-6
# define hues as red->yellow->green->cyan->blue->magenta->red again
# across is hue 0, 60, 120, 180, 240, 300, 360, down is R, G, B
# for interpolation, e.g. hue of 10 = column 1 + 10/60 * (column 2 - column 1)
hue_sequence = numpy.array(
[
[1., 1., 0., 0., 0., 1., 1.],
[0., 1., 1., 1., 0., 0., 0.],
[0., 0., 0., 1., 1., 1., 0.]
],
numpy.double
)
EPSILON = 1e-6
class HSBKToRGB:
def __init__(self, mired_to_rgb):
self.mired_to_rgb = mired_to_rgb
def convert(self, hsbk):
# validate inputs, allowing a little slack
# the hue does not matter as it will be normalized modulo 360
hue = hsbk[HSBK_HUE]
sat = hsbk[HSBK_SAT]
assert sat >= -EPSILON and sat < 1. + EPSILON
br = hsbk[HSBK_BR]
assert br >= -EPSILON and br < 1. + EPSILON
kelv = hsbk[HSBK_KELV]
assert kelv >= KELV_MIN - EPSILON and kelv < KELV_MAX + EPSILON
# this section computes hue_rgb from hue
# put it in the form hue = (i + j) * 60 where i is integer, j is fraction
hue /= 60.
i = math.floor(hue)
j = hue - i
i %= 6
# interpolate from the table
# interpolation is done in gamma-encoded space, as Photoshop HSV does it
# the result of this interpolation will have at least one of R, G, B = 1
hue_rgb = (
hue_sequence[:, i] +
j * (hue_sequence[:, i + 1] - hue_sequence[:, i])
)
# this section computes kelv_rgb from kelv
kelv_rgb = self.mired_to_rgb.convert(1e6 / kelv)
# this section applies the saturation
# do the mixing in gamma-encoded RGB space
# this is not very principled and can corrupt the chromaticities
rgb = kelv_rgb + sat * (hue_rgb - kelv_rgb)
# normalize the brightness again
# this is needed because SRGB produces the brightest colours near the white
# point, so if hue_rgb and kelv_rgb are on opposite sides of the white point,
# then rgb could land near the white point, but not be as bright as possible
rgb /= numpy.max(rgb)
# this section applies the brightness
# do the scaling in gamma-encoded RGB space
# this is not very principled and can corrupt the chromaticities
rgb *= br
return rgb
def standalone(hsbk_to_rgb):
import sys
EXIT_SUCCESS = 0
EXIT_FAILURE = 1
RGB_RED = 0
RGB_GREEN = 1
RGB_BLUE = 2
N_RGB = 3
if len(sys.argv) < 4:
print(f'usage: {sys.argv[0]:s} hue sat br [kelv]')
print('hue = hue in degrees (0 to 360)')
print('sat = saturation as fraction (0 to 1)')
print('br = brightness as fraction (0 to 1)')
print('kelv = white point in degrees Kelvin (defaults to 6504K)')
sys.exit(EXIT_FAILURE)
hsbk = numpy.array(
[
float(sys.argv[1]),
float(sys.argv[2]),
float(sys.argv[3]),
float(sys.argv[4]) if len(sys.argv) >= 5 else 6504.
],
numpy.double
)
rgb = hsbk_to_rgb.convert(hsbk)
print(
f'HSBK ({hsbk[HSBK_HUE]:.3f}, {hsbk[HSBK_SAT]:.6f}, {hsbk[HSBK_BR]:.6f}, {hsbk[HSBK_KELV]:.3f}) -> RGB ({rgb[RGB_RED]:.6f}, {rgb[RGB_GREEN]:.6f}, {rgb[RGB_BLUE]:.6f})'
)
| [
"numpy.max",
"numpy.array",
"sys.exit",
"math.floor"
] | [((1451, 1593), 'numpy.array', 'numpy.array', (['[[1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0]]', 'numpy.double'], {}), '([[1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 1.0, 1.0, 0.0,\n 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0]], numpy.double)\n', (1462, 1593), False, 'import numpy\n'), ((2253, 2268), 'math.floor', 'math.floor', (['hue'], {}), '(hue)\n', (2263, 2268), False, 'import math\n'), ((3193, 3207), 'numpy.max', 'numpy.max', (['rgb'], {}), '(rgb)\n', (3202, 3207), False, 'import numpy\n'), ((3839, 3861), 'sys.exit', 'sys.exit', (['EXIT_FAILURE'], {}), '(EXIT_FAILURE)\n', (3847, 3861), False, 'import sys\n')] |
from sklearn import neural_network
import numpy as np
from sklearn.metrics import accuracy_score, precision_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from plots import makeAndPlotLearningCurve, plotConfusionMatrix, plotPerformance, plotValidationCurve
from load_data import PenDigitsDataset, SpamBaseDataset
import matplotlib.pyplot as plt
def experiment(pipe, dataset):
num_neighbors = range(1, 50)
train_sizes = np.linspace(0.1, 1, 40, endpoint=True)
best_estimator = pipe
alphas = [10 ** -x for x in np.arange(0, 5, 0.25)]
makeAndPlotLearningCurve(best_estimator, "decisionTree", dataset.xtrain, dataset.ytrain,
train_sizes, "accuracy", "Accuracy", "ANN", dataset.name, "DefaultBase")
makeAndPlotLearningCurve(best_estimator, "decisionTree", dataset.xtrain, dataset.ytrain,
train_sizes, "balanced_accuracy", "Accuracy", "ANN", dataset.name, "BaseBalanced")
makeAndPlotLearningCurve(best_estimator, "decisionTree", dataset.xtrain, dataset.ytrain,
train_sizes, "f1_micro", "F1 Score", "ANN", dataset.name, "BaseF1")
print(alphas)
plotValidationCurve(best_estimator, "KNN", dataset.xtrain, dataset.ytrain,
"ann__alpha", alphas, "accuracy", None, "Accuracy", "ANN", dataset.name, "alpha")
plotValidationCurve(best_estimator, "KNN", dataset.xtrain, dataset.ytrain, "ann__alpha",
alphas, "f1_micro", None, "F1 Score", "ANN", dataset.name, "alphaF1")
pipe.fit(dataset.xtrain, dataset.ytrain)
plotConfusionMatrix(best_estimator, dataset.xtest,
dataset.ytest, dataset.classes, "ANN", dataset.name)
num_hiddens = [(100,), (100, 100), (100, 100, 100), (100, 100, 100, 100)]
size_hidden = [(16,), (32,), (64,), (128,)]
plt.clf()
for layer, hidden in enumerate(num_hiddens):
params = {'ann__hidden_layer_sizes': hidden}
pipe.set_params(**params)
pipe.fit(dataset.xtrain, dataset.ytrain)
plt.plot(pipe["ann"].validation_scores_, label=str(layer+1))
plt.title("Performance for varying Number of Hidden Layers")
plt.xlabel("Iterations")
plt.ylabel("Accuracy")
plt.legend()
plt.savefig(f'ANN/{dataset.name}/numLayers.png')
plt.clf()
for layer, hidden in enumerate(num_hiddens):
params = {'ann__hidden_layer_sizes': hidden}
pipe.set_params(**params)
pipe.fit(dataset.xtrain, dataset.ytrain)
plt.plot(pipe["ann"].loss_curve_, label=str(layer))
plt.title("Loss curve for varying Number of Hidden Layers")
plt.xlabel("Iterations")
plt.ylabel("Loss")
plt.legend()
plt.savefig(f'ANN/{dataset.name}/numLayersLoss.png')
plt.clf()
for layer, hidden in enumerate(size_hidden):
params = {'ann__hidden_layer_sizes': hidden}
pipe.set_params(**params)
pipe.fit(dataset.xtrain, dataset.ytrain)
plt.plot(pipe["ann"].validation_scores_, "o-", label=str(hidden[0]))
plt.title("Performance for varying size of hidden layer")
plt.xlabel("Iterations")
plt.ylabel("Accuracy")
plt.legend()
plt.savefig(f'ANN/{dataset.name}/sizeLayers.png')
plt.clf()
for layer, hidden in enumerate(num_hiddens):
params = {'ann__hidden_layer_sizes': hidden}
pipe.set_params(**params)
pipe.fit(dataset.xtrain, dataset.ytrain)
plt.plot(pipe["ann"].loss_curve_, "o-", label=str(hidden[0]))
plt.title("Performance for varying size of hidden layer")
plt.xlabel("Iterations")
plt.ylabel("Loss")
plt.legend()
plt.savefig(f'ANN/{dataset.name}/sizeLayersLoss.png')
#plotValidationCurve(best_estimator, "KNN", dataset.xtrain, dataset.ytrain, "ann__hidden_layer_sizes", hiddens , "accuracy", None, "Accuracy", "ANN", dataset.name, "numLayers")
#plotValidationCurve(best_estimator, "KNN", dataset.xtrain, dataset.ytrain, "ann__hidden_layer_sizes", size_hidden, "accuracy", None, "Accuracy", "ANN", dataset.name, "sizeLayers")
def plotAnnCurves(mlp, X_train, Y_train,):
epochs = 5000
for epoch in range(1, epochs):
mlp.fit(X_train, Y_train)
Y_pred = mlp.predict(X_train)
curr_train_score = mean_squared_error(
Y_train, Y_pred) # training performances
Y_pred = mlp.predict(X_valid)
curr_valid_score = mean_squared_error(
Y_valid, Y_pred) # validation performances
training_mse.append(curr_train_score) # list of training perf to plot
validation_mse.append(curr_valid_score) # list of valid perf to plot
plt.plot(training_mse, label="train")
plt.plot(validation_mse, label="validation")
plt.legend()
def main():
Pendataset = PenDigitsDataset()
ann = neural_network.MLPClassifier(
max_iter=5000, early_stopping=True, random_state=42,)
dataset = SpamBaseDataset()
pipe = Pipeline([("scaler", StandardScaler()),
("ann", ann)])
#neighborsComplexity(pipe, dataset)
#neighborsComplexity(pipe, Pendataset)
#distanceMetric(pipe, Pendataset)
#distanceMetric(pipe, dataset)
d = dataset.xtrain.shape[1]
hiddens = [(h,) * l for l in [1, 2, 3] for h in [d, d // 2, d * 2]]
print(hiddens)
experiment(pipe, dataset)
experiment(pipe, Pendataset)
if __name__ == "__main__":
main()
| [
"matplotlib.pyplot.savefig",
"sklearn.neural_network.MLPClassifier",
"matplotlib.pyplot.ylabel",
"numpy.arange",
"plots.plotValidationCurve",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.clf",
"plots.makeAndPlotLearningCurve",
"matplotlib.pyplot.plot",
"load_data.PenDigitsDataset",
"sklearn.pr... | [((475, 513), 'numpy.linspace', 'np.linspace', (['(0.1)', '(1)', '(40)'], {'endpoint': '(True)'}), '(0.1, 1, 40, endpoint=True)\n', (486, 513), True, 'import numpy as np\n'), ((600, 770), 'plots.makeAndPlotLearningCurve', 'makeAndPlotLearningCurve', (['best_estimator', '"""decisionTree"""', 'dataset.xtrain', 'dataset.ytrain', 'train_sizes', '"""accuracy"""', '"""Accuracy"""', '"""ANN"""', 'dataset.name', '"""DefaultBase"""'], {}), "(best_estimator, 'decisionTree', dataset.xtrain,\n dataset.ytrain, train_sizes, 'accuracy', 'Accuracy', 'ANN', dataset.\n name, 'DefaultBase')\n", (624, 770), False, 'from plots import makeAndPlotLearningCurve, plotConfusionMatrix, plotPerformance, plotValidationCurve\n'), ((795, 974), 'plots.makeAndPlotLearningCurve', 'makeAndPlotLearningCurve', (['best_estimator', '"""decisionTree"""', 'dataset.xtrain', 'dataset.ytrain', 'train_sizes', '"""balanced_accuracy"""', '"""Accuracy"""', '"""ANN"""', 'dataset.name', '"""BaseBalanced"""'], {}), "(best_estimator, 'decisionTree', dataset.xtrain,\n dataset.ytrain, train_sizes, 'balanced_accuracy', 'Accuracy', 'ANN',\n dataset.name, 'BaseBalanced')\n", (819, 974), False, 'from plots import makeAndPlotLearningCurve, plotConfusionMatrix, plotPerformance, plotValidationCurve\n'), ((1000, 1165), 'plots.makeAndPlotLearningCurve', 'makeAndPlotLearningCurve', (['best_estimator', '"""decisionTree"""', 'dataset.xtrain', 'dataset.ytrain', 'train_sizes', '"""f1_micro"""', '"""F1 Score"""', '"""ANN"""', 'dataset.name', '"""BaseF1"""'], {}), "(best_estimator, 'decisionTree', dataset.xtrain,\n dataset.ytrain, train_sizes, 'f1_micro', 'F1 Score', 'ANN', dataset.\n name, 'BaseF1')\n", (1024, 1165), False, 'from plots import makeAndPlotLearningCurve, plotConfusionMatrix, plotPerformance, plotValidationCurve\n'), ((1209, 1373), 'plots.plotValidationCurve', 'plotValidationCurve', (['best_estimator', '"""KNN"""', 'dataset.xtrain', 'dataset.ytrain', '"""ann__alpha"""', 'alphas', '"""accuracy"""', 'None', '"""Accuracy"""', '"""ANN"""', 'dataset.name', '"""alpha"""'], {}), "(best_estimator, 'KNN', dataset.xtrain, dataset.ytrain,\n 'ann__alpha', alphas, 'accuracy', None, 'Accuracy', 'ANN', dataset.name,\n 'alpha')\n", (1228, 1373), False, 'from plots import makeAndPlotLearningCurve, plotConfusionMatrix, plotPerformance, plotValidationCurve\n'), ((1394, 1560), 'plots.plotValidationCurve', 'plotValidationCurve', (['best_estimator', '"""KNN"""', 'dataset.xtrain', 'dataset.ytrain', '"""ann__alpha"""', 'alphas', '"""f1_micro"""', 'None', '"""F1 Score"""', '"""ANN"""', 'dataset.name', '"""alphaF1"""'], {}), "(best_estimator, 'KNN', dataset.xtrain, dataset.ytrain,\n 'ann__alpha', alphas, 'f1_micro', None, 'F1 Score', 'ANN', dataset.name,\n 'alphaF1')\n", (1413, 1560), False, 'from plots import makeAndPlotLearningCurve, plotConfusionMatrix, plotPerformance, plotValidationCurve\n'), ((1627, 1735), 'plots.plotConfusionMatrix', 'plotConfusionMatrix', (['best_estimator', 'dataset.xtest', 'dataset.ytest', 'dataset.classes', '"""ANN"""', 'dataset.name'], {}), "(best_estimator, dataset.xtest, dataset.ytest, dataset.\n classes, 'ANN', dataset.name)\n", (1646, 1735), False, 'from plots import makeAndPlotLearningCurve, plotConfusionMatrix, plotPerformance, plotValidationCurve\n'), ((1886, 1895), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1893, 1895), True, 'import matplotlib.pyplot as plt\n'), ((2154, 2214), 'matplotlib.pyplot.title', 'plt.title', (['"""Performance for varying Number of Hidden Layers"""'], {}), "('Performance for varying Number of Hidden Layers')\n", (2163, 2214), True, 'import matplotlib.pyplot as plt\n'), ((2219, 2243), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Iterations"""'], {}), "('Iterations')\n", (2229, 2243), True, 'import matplotlib.pyplot as plt\n'), ((2248, 2270), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Accuracy"""'], {}), "('Accuracy')\n", (2258, 2270), True, 'import matplotlib.pyplot as plt\n'), ((2275, 2287), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2285, 2287), True, 'import matplotlib.pyplot as plt\n'), ((2292, 2340), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""ANN/{dataset.name}/numLayers.png"""'], {}), "(f'ANN/{dataset.name}/numLayers.png')\n", (2303, 2340), True, 'import matplotlib.pyplot as plt\n'), ((2346, 2355), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (2353, 2355), True, 'import matplotlib.pyplot as plt\n'), ((2605, 2664), 'matplotlib.pyplot.title', 'plt.title', (['"""Loss curve for varying Number of Hidden Layers"""'], {}), "('Loss curve for varying Number of Hidden Layers')\n", (2614, 2664), True, 'import matplotlib.pyplot as plt\n'), ((2669, 2693), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Iterations"""'], {}), "('Iterations')\n", (2679, 2693), True, 'import matplotlib.pyplot as plt\n'), ((2698, 2716), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss"""'], {}), "('Loss')\n", (2708, 2716), True, 'import matplotlib.pyplot as plt\n'), ((2721, 2733), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2731, 2733), True, 'import matplotlib.pyplot as plt\n'), ((2739, 2791), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""ANN/{dataset.name}/numLayersLoss.png"""'], {}), "(f'ANN/{dataset.name}/numLayersLoss.png')\n", (2750, 2791), True, 'import matplotlib.pyplot as plt\n'), ((2797, 2806), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (2804, 2806), True, 'import matplotlib.pyplot as plt\n'), ((3073, 3130), 'matplotlib.pyplot.title', 'plt.title', (['"""Performance for varying size of hidden layer"""'], {}), "('Performance for varying size of hidden layer')\n", (3082, 3130), True, 'import matplotlib.pyplot as plt\n'), ((3135, 3159), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Iterations"""'], {}), "('Iterations')\n", (3145, 3159), True, 'import matplotlib.pyplot as plt\n'), ((3164, 3186), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Accuracy"""'], {}), "('Accuracy')\n", (3174, 3186), True, 'import matplotlib.pyplot as plt\n'), ((3191, 3203), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3201, 3203), True, 'import matplotlib.pyplot as plt\n'), ((3208, 3257), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""ANN/{dataset.name}/sizeLayers.png"""'], {}), "(f'ANN/{dataset.name}/sizeLayers.png')\n", (3219, 3257), True, 'import matplotlib.pyplot as plt\n'), ((3263, 3272), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (3270, 3272), True, 'import matplotlib.pyplot as plt\n'), ((3532, 3589), 'matplotlib.pyplot.title', 'plt.title', (['"""Performance for varying size of hidden layer"""'], {}), "('Performance for varying size of hidden layer')\n", (3541, 3589), True, 'import matplotlib.pyplot as plt\n'), ((3594, 3618), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Iterations"""'], {}), "('Iterations')\n", (3604, 3618), True, 'import matplotlib.pyplot as plt\n'), ((3623, 3641), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss"""'], {}), "('Loss')\n", (3633, 3641), True, 'import matplotlib.pyplot as plt\n'), ((3646, 3658), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3656, 3658), True, 'import matplotlib.pyplot as plt\n'), ((3664, 3717), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""ANN/{dataset.name}/sizeLayersLoss.png"""'], {}), "(f'ANN/{dataset.name}/sizeLayersLoss.png')\n", (3675, 3717), True, 'import matplotlib.pyplot as plt\n'), ((4657, 4694), 'matplotlib.pyplot.plot', 'plt.plot', (['training_mse'], {'label': '"""train"""'}), "(training_mse, label='train')\n", (4665, 4694), True, 'import matplotlib.pyplot as plt\n'), ((4699, 4743), 'matplotlib.pyplot.plot', 'plt.plot', (['validation_mse'], {'label': '"""validation"""'}), "(validation_mse, label='validation')\n", (4707, 4743), True, 'import matplotlib.pyplot as plt\n'), ((4748, 4760), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4758, 4760), True, 'import matplotlib.pyplot as plt\n'), ((4793, 4811), 'load_data.PenDigitsDataset', 'PenDigitsDataset', ([], {}), '()\n', (4809, 4811), False, 'from load_data import PenDigitsDataset, SpamBaseDataset\n'), ((4823, 4908), 'sklearn.neural_network.MLPClassifier', 'neural_network.MLPClassifier', ([], {'max_iter': '(5000)', 'early_stopping': '(True)', 'random_state': '(42)'}), '(max_iter=5000, early_stopping=True,\n random_state=42)\n', (4851, 4908), False, 'from sklearn import neural_network\n'), ((4929, 4946), 'load_data.SpamBaseDataset', 'SpamBaseDataset', ([], {}), '()\n', (4944, 4946), False, 'from load_data import PenDigitsDataset, SpamBaseDataset\n'), ((572, 593), 'numpy.arange', 'np.arange', (['(0)', '(5)', '(0.25)'], {}), '(0, 5, 0.25)\n', (581, 593), True, 'import numpy as np\n'), ((4979, 4995), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (4993, 4995), False, 'from sklearn.preprocessing import StandardScaler\n')] |
# -*- coding: utf-8 -*-
"""
Tests for the audiotsm.io.array package.
"""
import pytest
import numpy as np
from numpy.testing import assert_almost_equal
from audiotsm.io.array import ArrayReader, ArrayWriter, FixedArrayWriter
@pytest.mark.parametrize("data_in, read_out, n_out, data_out", [
([[]], [[]], 0, [[]]),
([[]], [[0]], 0, [[]]),
([[1, 2, 3], [4, 5, 6]], [[], []], 0, [[1, 2, 3], [4, 5, 6]]),
([[1, 2, 3], [4, 5, 6]], [[1], [4]], 1, [[2, 3], [5, 6]]),
([[1, 2, 3], [4, 5, 6]], [[1, 2], [4, 5]], 2, [[3], [6]]),
([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]], 3, [[], []]),
([[1, 2, 3], [4, 5, 6]], [[1, 2, 3, 0], [4, 5, 6, 0]], 3, [[], []]),
])
def test_read(data_in, read_out, n_out, data_out):
"""Run tests for the ArrayReader.read method."""
reader = ArrayReader(np.array(data_in))
buffer = np.zeros_like(read_out, dtype=np.float32)
n = reader.read(buffer)
assert_almost_equal(buffer, read_out)
assert n == n_out
# Check the data remaining in the reader
buffer = np.zeros_like(data_out)
reader.read(buffer)
assert_almost_equal(buffer, data_out)
# Check that there is no more data in the reader
buffer = np.zeros_like(data_in)
n = reader.read(buffer)
assert not buffer.any()
assert n == 0
@pytest.mark.parametrize("data_in, n_in, n_out, data_out", [
([[]], 0, 0, [[]]),
([[]], 1, 0, [[]]),
([[1, 2, 3], [4, 5, 6]], 0, 0, [[1, 2, 3], [4, 5, 6]]),
([[1, 2, 3], [4, 5, 6]], 1, 1, [[2, 3], [5, 6]]),
([[1, 2, 3], [4, 5, 6]], 2, 2, [[3], [6]]),
([[1, 2, 3], [4, 5, 6]], 3, 3, [[], []]),
([[1, 2, 3], [4, 5, 6]], 4, 3, [[], []]),
])
def test_skip(data_in, n_in, n_out, data_out):
"""Run tests for the ArrayReader.skip method."""
reader = ArrayReader(np.array(data_in))
n = reader.skip(n_in)
assert n == n_out
# Check the data remaining in the reader
buffer = np.zeros_like(data_out)
reader.read(buffer)
assert_almost_equal(buffer, data_out)
# Check that there is no more data in the reader
buffer = np.zeros_like(data_in)
n = reader.read(buffer)
assert not buffer.any()
assert n == 0
@pytest.mark.parametrize("write1, write2, n1_out, n2_out, buffer_out", [
([[], []], [[], []], 0, 0, [[], []]),
([[1, 2, 3], [4, 5, 6]], [[], []], 3, 0, [[1, 2, 3], [4, 5, 6]]),
([[1, 2], [4, 5]], [[3], [6]], 2, 1, [[1, 2, 3], [4, 5, 6]]),
([[1], [4]], [[2, 3], [5, 6]], 1, 2, [[1, 2, 3], [4, 5, 6]]),
([[], []], [[1, 2, 3], [4, 5, 6]], 0, 3, [[1, 2, 3], [4, 5, 6]]),
([[1, 2, 3], [4, 5, 6]], [[7], [8]], 3, 0, [[1, 2, 3], [4, 5, 6]]),
([[1, 2, 3], [4, 5, 6]], [[7], [8]], 2, 0, [[1, 2], [4, 5]]),
([[1, 2], [4, 5]], [[], []], 2, 0, [[1, 2, 0], [4, 5, 0]]),
])
def test_fixed_array_write(write1, write2, n1_out, n2_out, buffer_out):
"""Run tests for the FixedArrayWriter.write method."""
buffer = np.zeros_like(buffer_out, dtype=np.float32)
writer = FixedArrayWriter(buffer)
n = writer.write(np.array(write1, dtype=np.float32))
assert n == n1_out
n = writer.write(np.array(write2, dtype=np.float32))
assert n == n2_out
assert_almost_equal(buffer, buffer_out)
@pytest.mark.parametrize("write1, write2, n1_out, n2_out, buffer_out", [
([[], []], [[], []], 0, 0, [[], []]),
([[1, 2, 3], [4, 5, 6]], [[], []], 3, 0, [[1, 2, 3], [4, 5, 6]]),
([[1, 2], [4, 5]], [[3], [6]], 2, 1, [[1, 2, 3], [4, 5, 6]]),
([[1], [4]], [[2, 3], [5, 6]], 1, 2, [[1, 2, 3], [4, 5, 6]]),
([[], []], [[1, 2, 3], [4, 5, 6]], 0, 3, [[1, 2, 3], [4, 5, 6]]),
([[1, 2], [4, 5]], [[], []], 2, 0, [[1, 2], [4, 5]]),
])
def test_array_write(write1, write2, n1_out, n2_out, buffer_out):
"""Run tests for the ArrayWriter.write method."""
writer = ArrayWriter(len(write1))
n = writer.write(np.array(write1, dtype=np.float32))
assert n == n1_out
n = writer.write(np.array(write2, dtype=np.float32))
assert n == n2_out
assert_almost_equal(writer.data, buffer_out)
| [
"audiotsm.io.array.FixedArrayWriter",
"pytest.mark.parametrize",
"numpy.array",
"numpy.testing.assert_almost_equal",
"numpy.zeros_like"
] | [((231, 675), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data_in, read_out, n_out, data_out"""', '[([[]], [[]], 0, [[]]), ([[]], [[0]], 0, [[]]), ([[1, 2, 3], [4, 5, 6]], [[\n ], []], 0, [[1, 2, 3], [4, 5, 6]]), ([[1, 2, 3], [4, 5, 6]], [[1], [4]],\n 1, [[2, 3], [5, 6]]), ([[1, 2, 3], [4, 5, 6]], [[1, 2], [4, 5]], 2, [[3\n ], [6]]), ([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]], 3, [[], []]),\n ([[1, 2, 3], [4, 5, 6]], [[1, 2, 3, 0], [4, 5, 6, 0]], 3, [[], []])]'], {}), "('data_in, read_out, n_out, data_out', [([[]], [[]],\n 0, [[]]), ([[]], [[0]], 0, [[]]), ([[1, 2, 3], [4, 5, 6]], [[], []], 0,\n [[1, 2, 3], [4, 5, 6]]), ([[1, 2, 3], [4, 5, 6]], [[1], [4]], 1, [[2, 3\n ], [5, 6]]), ([[1, 2, 3], [4, 5, 6]], [[1, 2], [4, 5]], 2, [[3], [6]]),\n ([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]], 3, [[], []]), ([[1, 2,\n 3], [4, 5, 6]], [[1, 2, 3, 0], [4, 5, 6, 0]], 3, [[], []])])\n", (254, 675), False, 'import pytest\n'), ((1298, 1649), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data_in, n_in, n_out, data_out"""', '[([[]], 0, 0, [[]]), ([[]], 1, 0, [[]]), ([[1, 2, 3], [4, 5, 6]], 0, 0, [[1,\n 2, 3], [4, 5, 6]]), ([[1, 2, 3], [4, 5, 6]], 1, 1, [[2, 3], [5, 6]]), (\n [[1, 2, 3], [4, 5, 6]], 2, 2, [[3], [6]]), ([[1, 2, 3], [4, 5, 6]], 3, \n 3, [[], []]), ([[1, 2, 3], [4, 5, 6]], 4, 3, [[], []])]'], {}), "('data_in, n_in, n_out, data_out', [([[]], 0, 0, [[]\n ]), ([[]], 1, 0, [[]]), ([[1, 2, 3], [4, 5, 6]], 0, 0, [[1, 2, 3], [4, \n 5, 6]]), ([[1, 2, 3], [4, 5, 6]], 1, 1, [[2, 3], [5, 6]]), ([[1, 2, 3],\n [4, 5, 6]], 2, 2, [[3], [6]]), ([[1, 2, 3], [4, 5, 6]], 3, 3, [[], []]),\n ([[1, 2, 3], [4, 5, 6]], 4, 3, [[], []])])\n", (1321, 1649), False, 'import pytest\n'), ((2172, 2757), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""write1, write2, n1_out, n2_out, buffer_out"""', '[([[], []], [[], []], 0, 0, [[], []]), ([[1, 2, 3], [4, 5, 6]], [[], []], 3,\n 0, [[1, 2, 3], [4, 5, 6]]), ([[1, 2], [4, 5]], [[3], [6]], 2, 1, [[1, 2,\n 3], [4, 5, 6]]), ([[1], [4]], [[2, 3], [5, 6]], 1, 2, [[1, 2, 3], [4, 5,\n 6]]), ([[], []], [[1, 2, 3], [4, 5, 6]], 0, 3, [[1, 2, 3], [4, 5, 6]]),\n ([[1, 2, 3], [4, 5, 6]], [[7], [8]], 3, 0, [[1, 2, 3], [4, 5, 6]]), ([[\n 1, 2, 3], [4, 5, 6]], [[7], [8]], 2, 0, [[1, 2], [4, 5]]), ([[1, 2], [4,\n 5]], [[], []], 2, 0, [[1, 2, 0], [4, 5, 0]])]'], {}), "('write1, write2, n1_out, n2_out, buffer_out', [([[],\n []], [[], []], 0, 0, [[], []]), ([[1, 2, 3], [4, 5, 6]], [[], []], 3, 0,\n [[1, 2, 3], [4, 5, 6]]), ([[1, 2], [4, 5]], [[3], [6]], 2, 1, [[1, 2, 3\n ], [4, 5, 6]]), ([[1], [4]], [[2, 3], [5, 6]], 1, 2, [[1, 2, 3], [4, 5,\n 6]]), ([[], []], [[1, 2, 3], [4, 5, 6]], 0, 3, [[1, 2, 3], [4, 5, 6]]),\n ([[1, 2, 3], [4, 5, 6]], [[7], [8]], 3, 0, [[1, 2, 3], [4, 5, 6]]), ([[\n 1, 2, 3], [4, 5, 6]], [[7], [8]], 2, 0, [[1, 2], [4, 5]]), ([[1, 2], [4,\n 5]], [[], []], 2, 0, [[1, 2, 0], [4, 5, 0]])])\n", (2195, 2757), False, 'import pytest\n'), ((3201, 3641), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""write1, write2, n1_out, n2_out, buffer_out"""', '[([[], []], [[], []], 0, 0, [[], []]), ([[1, 2, 3], [4, 5, 6]], [[], []], 3,\n 0, [[1, 2, 3], [4, 5, 6]]), ([[1, 2], [4, 5]], [[3], [6]], 2, 1, [[1, 2,\n 3], [4, 5, 6]]), ([[1], [4]], [[2, 3], [5, 6]], 1, 2, [[1, 2, 3], [4, 5,\n 6]]), ([[], []], [[1, 2, 3], [4, 5, 6]], 0, 3, [[1, 2, 3], [4, 5, 6]]),\n ([[1, 2], [4, 5]], [[], []], 2, 0, [[1, 2], [4, 5]])]'], {}), "('write1, write2, n1_out, n2_out, buffer_out', [([[],\n []], [[], []], 0, 0, [[], []]), ([[1, 2, 3], [4, 5, 6]], [[], []], 3, 0,\n [[1, 2, 3], [4, 5, 6]]), ([[1, 2], [4, 5]], [[3], [6]], 2, 1, [[1, 2, 3\n ], [4, 5, 6]]), ([[1], [4]], [[2, 3], [5, 6]], 1, 2, [[1, 2, 3], [4, 5,\n 6]]), ([[], []], [[1, 2, 3], [4, 5, 6]], 0, 3, [[1, 2, 3], [4, 5, 6]]),\n ([[1, 2], [4, 5]], [[], []], 2, 0, [[1, 2], [4, 5]])])\n", (3224, 3641), False, 'import pytest\n'), ((848, 889), 'numpy.zeros_like', 'np.zeros_like', (['read_out'], {'dtype': 'np.float32'}), '(read_out, dtype=np.float32)\n', (861, 889), True, 'import numpy as np\n'), ((922, 959), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['buffer', 'read_out'], {}), '(buffer, read_out)\n', (941, 959), False, 'from numpy.testing import assert_almost_equal\n'), ((1041, 1064), 'numpy.zeros_like', 'np.zeros_like', (['data_out'], {}), '(data_out)\n', (1054, 1064), True, 'import numpy as np\n'), ((1093, 1130), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['buffer', 'data_out'], {}), '(buffer, data_out)\n', (1112, 1130), False, 'from numpy.testing import assert_almost_equal\n'), ((1198, 1220), 'numpy.zeros_like', 'np.zeros_like', (['data_in'], {}), '(data_in)\n', (1211, 1220), True, 'import numpy as np\n'), ((1915, 1938), 'numpy.zeros_like', 'np.zeros_like', (['data_out'], {}), '(data_out)\n', (1928, 1938), True, 'import numpy as np\n'), ((1967, 2004), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['buffer', 'data_out'], {}), '(buffer, data_out)\n', (1986, 2004), False, 'from numpy.testing import assert_almost_equal\n'), ((2072, 2094), 'numpy.zeros_like', 'np.zeros_like', (['data_in'], {}), '(data_in)\n', (2085, 2094), True, 'import numpy as np\n'), ((2910, 2953), 'numpy.zeros_like', 'np.zeros_like', (['buffer_out'], {'dtype': 'np.float32'}), '(buffer_out, dtype=np.float32)\n', (2923, 2953), True, 'import numpy as np\n'), ((2967, 2991), 'audiotsm.io.array.FixedArrayWriter', 'FixedArrayWriter', (['buffer'], {}), '(buffer)\n', (2983, 2991), False, 'from audiotsm.io.array import ArrayReader, ArrayWriter, FixedArrayWriter\n'), ((3158, 3197), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['buffer', 'buffer_out'], {}), '(buffer, buffer_out)\n', (3177, 3197), False, 'from numpy.testing import assert_almost_equal\n'), ((3974, 4018), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['writer.data', 'buffer_out'], {}), '(writer.data, buffer_out)\n', (3993, 4018), False, 'from numpy.testing import assert_almost_equal\n'), ((815, 832), 'numpy.array', 'np.array', (['data_in'], {}), '(data_in)\n', (823, 832), True, 'import numpy as np\n'), ((1788, 1805), 'numpy.array', 'np.array', (['data_in'], {}), '(data_in)\n', (1796, 1805), True, 'import numpy as np\n'), ((3014, 3048), 'numpy.array', 'np.array', (['write1'], {'dtype': 'np.float32'}), '(write1, dtype=np.float32)\n', (3022, 3048), True, 'import numpy as np\n'), ((3094, 3128), 'numpy.array', 'np.array', (['write2'], {'dtype': 'np.float32'}), '(write2, dtype=np.float32)\n', (3102, 3128), True, 'import numpy as np\n'), ((3830, 3864), 'numpy.array', 'np.array', (['write1'], {'dtype': 'np.float32'}), '(write1, dtype=np.float32)\n', (3838, 3864), True, 'import numpy as np\n'), ((3910, 3944), 'numpy.array', 'np.array', (['write2'], {'dtype': 'np.float32'}), '(write2, dtype=np.float32)\n', (3918, 3944), True, 'import numpy as np\n')] |
import torch
import random
import numpy as np
from sklearn.model_selection import KFold
from Reader import Reader
from NejiAnnotator import readPickle
from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries
from models.clinicalBERT.utils import BERT_ENTITY_CLASSES, loadModelConfigs, clinicalBERTutils, createOutputTask1
from models.clinicalBERT.model import Model
def runModel(settings, trainTXT, trainXML):
""" Trains the model in the FULL training dataset, saves it in .pth files, and computes predictions for the FULL test set
:param settings: settings from settings.ini file
:param trainTXT: train txts
:param trainXML: train xml annotations
:return: finalFamilyMemberDict, finalObservationsDict: dicts indexed by filename with detected entities
"""
seed = [35899,54377,66449,77417,29,229,1229,88003,99901,11003]
random_seed = seed[9]
random.seed(random_seed)
np.random.seed(random_seed)
torch.manual_seed(random_seed)
torch.cuda.is_available()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
if device.type == 'cuda':
print(torch.cuda.get_device_name(0))
print('Memory Usage:')
print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')
print('Cached: ', round(torch.cuda.memory_cached(0)/1024**3,1), 'GB')
print("Loading and preprocessing data.\n")
if settings["ALBERT"]["add_special_tokens"] == "True":
addSpecialTokens = True
else:
addSpecialTokens = False
clinicalBERTUtils = clinicalBERTutils(addSpecialTokens)
_, encodedTokenizedSentences, sentenceToDocList = clinicalBERTUtils.getSentenceListWithMapping(trainTXT)
trainEncodedSentences = []
for sentence in encodedTokenizedSentences:
trainEncodedSentences.append(torch.LongTensor(sentence).to(device=device))
trainClassesDict = clinicalBERTUtils.createTrueClasses(trainTXT, trainXML)
trainClasses = classDictToList(trainClassesDict)
trainClasses = [classListToTensor(sentenceClasses, datatype=torch.long) for sentenceClasses in trainClasses]
if settings["neji"]["use_neji_annotations"] == "True":
nejiClassesDict = readPickle(settings["neji"]["neji_train_pickle_clinicalbert"])
nejiTrainClasses = classDictToList(nejiClassesDict)
nejiTrainClasses = [classListToTensor(sentenceClasses, datatype=torch.float) for sentenceClasses in nejiTrainClasses]
else:
nejiTrainClasses = None
# 100 is the default size used in embedding creation
max_length = 100
print("Loaded data successfully.\n")
modelConfigs = loadModelConfigs(settings)
DL_model = Model(modelConfigs, BERT_ENTITY_CLASSES, max_length, device)
print("Model created. Starting training.\n")
DL_model.train(trainEncodedSentences, trainClasses, neji_classes=nejiTrainClasses)
print("Writing model files to disk.\n")
DL_model.write_model_files(random_seed)
print("Starting the testing phase.\n")
reader = Reader(dataSettings=settings, corpus="test")
testTXT = reader.loadDataSet()
testBERTtokenizedSentences, encodedTokenizedSentences, sentenceToDocList = clinicalBERTUtils.getSentenceListWithMapping(testTXT)
testEncodedSentences = []
for sentence in encodedTokenizedSentences:
testEncodedSentences.append(torch.LongTensor(sentence).to(device))
testClassesDict = clinicalBERTUtils.createDefaultClasses(testTXT)
testClasses = classDictToList(testClassesDict)
testClasses = [classListToTensor(sentenceClasses, datatype=torch.long) for sentenceClasses in testClasses]
if settings["neji"]["use_neji_annotations"] == "True":
nejiTestClassesDict = readPickle(settings["neji"]["neji_test_pickle_clinicalbert"])
nejiTestClasses = classDictToList(nejiTestClassesDict)
nejiTestClasses = [classListToTensor(sentenceClasses, datatype=torch.float) for sentenceClasses in nejiTestClasses]
else:
nejiTestClasses = None
predFamilyMemberDict, predObservationDict = createOutputTask1(DL_model, testBERTtokenizedSentences, testEncodedSentences,
testClasses, sentenceToDocList, clinicalBERTUtils, neji_classes=nejiTestClasses)
return predFamilyMemberDict, predObservationDict
def runModelDevelopment(settings, trainTXT, trainXML, cvFolds):
""" Trains the model with K-fold cross validation, using K-1 splits to train and 1 to validate (and generate output), in K possible combinations.
:param settings: settings from settings.ini file
:param trainTXT: train txts
:param trainXML: train xml annotations
:param cvFolds: number of folds for cross validation
:return: finalFamilyMemberDict, finalObservationsDict: dicts indexed by filename with detected entities
"""
seed = [35899,54377,66449,77417,29,229,1229,88003,99901,11003]
random_seed = seed[9]
random.seed(random_seed)
np.random.seed(random_seed)
torch.manual_seed(random_seed)
torch.cuda.is_available()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
if device.type == 'cuda':
print(torch.cuda.get_device_name(0))
print('Memory Usage:')
print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')
print('Cached: ', round(torch.cuda.memory_cached(0)/1024**3,1), 'GB')
print("Loading and preprocessing data.\n")
if settings["ALBERT"]["add_special_tokens"] == "True":
addSpecialTokens = True
else:
addSpecialTokens = False
clinicalBERTUtils = clinicalBERTutils(addSpecialTokens)
BERTtokenizedSentences, encodedTokenizedSentences, sentenceToDocList = clinicalBERTUtils.getSentenceListWithMapping(trainTXT)
tensorEncodedSentences = []
for sentence in encodedTokenizedSentences:
tensorEncodedSentences.append(torch.LongTensor(sentence).to(device=device))
classesDict = clinicalBERTUtils.createTrueClasses(trainTXT, trainXML)
classes = classDictToList(classesDict)
classes = [classListToTensor(sentenceClasses, datatype=torch.long) for sentenceClasses in classes]
if settings["neji"]["use_neji_annotations"] == "True":
nejiClassesDict = readPickle(settings["neji"]["neji_train_pickle_clinicalbert"])
nejiClasses = classDictToList(nejiClassesDict)
nejiClasses = [classListToTensor(sentenceClasses, datatype=torch.float) for sentenceClasses in nejiClasses]
kFolds = KFold(n_splits=cvFolds)
predFamilyMemberDicts = []
predObservationsDicts = []
print("Beginning KFold cross validation.\n")
for trainIdx, testIdx in kFolds.split(encodedTokenizedSentences):
trainEncodedSentences = [tensorEncodedSentences[idx] for idx in trainIdx]
trainClasses = [classes[idx] for idx in trainIdx]
testTokenizedSentences = [BERTtokenizedSentences[idx] for idx in testIdx]
testEncodedSentences = [tensorEncodedSentences[idx] for idx in testIdx]
testClasses = [classes[idx] for idx in testIdx]
testDocMapping = [sentenceToDocList[idx] for idx in testIdx]
if settings["neji"]["use_neji_annotations"] == "True":
nejiTrainClasses = [nejiClasses[idx] for idx in trainIdx]
nejiTestClasses = [nejiClasses[idx] for idx in testIdx]
else:
nejiTrainClasses = None
nejiTestClasses = None
# 100 is the default size used in embedding creation
max_length = 100
print("Loaded data successfully.\n")
modelConfigs = loadModelConfigs(settings)
DL_model = Model(modelConfigs, BERT_ENTITY_CLASSES, max_length, device)
print("Model created. Starting training.\n")
DL_model.train(trainEncodedSentences, trainClasses, neji_classes=nejiTrainClasses)
print("Starting the testing phase.\n")
testLabelPred, testLabelTrue = DL_model.test(testEncodedSentences, testClasses, neji_classes=nejiTestClasses)
print("Finished the testing phase. Evaluating test results\n")
DL_model.evaluate_test(testLabelPred, testLabelTrue)
# # print("Writing model files to disk.\n")
# # DL_model.write_model_files(testLabelPred, testLabelTrue, seed)
print("Generating prediction output for final tsv.\n")
predFamilyMemberDict, predObservationDict = createOutputTask1(DL_model, testTokenizedSentences,
testEncodedSentences, testClasses,
testDocMapping, clinicalBERTUtils, neji_classes=nejiTestClasses)
predFamilyMemberDicts.append(predFamilyMemberDict)
predObservationsDicts.append(predObservationDict)
finalFamilyMemberDict = mergeDictionaries(predFamilyMemberDicts)
finalObservationsDict = mergeDictionaries(predObservationsDicts)
return finalFamilyMemberDict, finalObservationsDict
def runModel_LoadAndTest(settings, linear_path):
""" Loads the model trained in the FULL training dataset and computes predictions for the FULL test set
:param settings: settings from settings.ini file
:param linear_path: path for the file with linear layer state dict
:return: finalFamilyMemberDict, finalObservationsDict: dicts indexed by filename with detected entities
"""
seed = [35899,54377,66449,77417,29,229,1229,88003,99901,11003]
random_seed = seed[9]
random.seed(random_seed)
np.random.seed(random_seed)
torch.manual_seed(random_seed)
torch.cuda.is_available()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
if device.type == 'cuda':
print(torch.cuda.get_device_name(0))
print('Memory Usage:')
print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')
print('Cached: ', round(torch.cuda.memory_cached(0)/1024**3,1), 'GB')
if settings["ALBERT"]["add_special_tokens"] == "True":
addSpecialTokens = True
else:
addSpecialTokens = False
clinicalBERTUtils = clinicalBERTutils(addSpecialTokens)
# 100 is the default size used in embedding creation
max_length = 100
modelConfigs = loadModelConfigs(settings)
DL_model = Model(modelConfigs, BERT_ENTITY_CLASSES, max_length, device)
DL_model.load_model_files(linear_path)
print("Loaded model successfully.\n")
print("Starting the testing phase.\n")
reader = Reader(dataSettings=settings, corpus="test")
testTXT = reader.loadDataSet()
testBERTtokenizedSentences, encodedTokenizedSentences, sentenceToDocList = clinicalBERTUtils.getSentenceListWithMapping(testTXT)
testEncodedSentences = []
for sentence in encodedTokenizedSentences:
testEncodedSentences.append(torch.LongTensor(sentence).to(device))
testClassesDict = clinicalBERTUtils.createDefaultClasses(testTXT)
testClasses = classDictToList(testClassesDict)
testClasses = [classListToTensor(sentenceClasses, datatype=torch.long) for sentenceClasses in testClasses]
if settings["neji"]["use_neji_annotations"] == "True":
nejiTestClassesDict = readPickle(settings["neji"]["neji_test_pickle_clinicalbert"])
nejiTestClasses = classDictToList(nejiTestClassesDict)
nejiTestClasses = [classListToTensor(sentenceClasses, datatype=torch.float) for sentenceClasses in nejiTestClasses]
else:
nejiTestClasses = None
predFamilyMemberDict, predObservationDict = createOutputTask1(DL_model, testBERTtokenizedSentences, testEncodedSentences,
testClasses, sentenceToDocList, clinicalBERTUtils, neji_classes=nejiTestClasses)
return predFamilyMemberDict, predObservationDict | [
"models.utils.mergeDictionaries",
"torch.manual_seed",
"torch.cuda.get_device_name",
"models.utils.classListToTensor",
"torch.cuda.memory_allocated",
"torch.LongTensor",
"torch.cuda.memory_cached",
"random.seed",
"sklearn.model_selection.KFold",
"Reader.Reader",
"NejiAnnotator.readPickle",
"to... | [((921, 945), 'random.seed', 'random.seed', (['random_seed'], {}), '(random_seed)\n', (932, 945), False, 'import random\n'), ((950, 977), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (964, 977), True, 'import numpy as np\n'), ((982, 1012), 'torch.manual_seed', 'torch.manual_seed', (['random_seed'], {}), '(random_seed)\n', (999, 1012), False, 'import torch\n'), ((1018, 1043), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1041, 1043), False, 'import torch\n'), ((1630, 1665), 'models.clinicalBERT.utils.clinicalBERTutils', 'clinicalBERTutils', (['addSpecialTokens'], {}), '(addSpecialTokens)\n', (1647, 1665), False, 'from models.clinicalBERT.utils import BERT_ENTITY_CLASSES, loadModelConfigs, clinicalBERTutils, createOutputTask1\n'), ((2036, 2069), 'models.utils.classDictToList', 'classDictToList', (['trainClassesDict'], {}), '(trainClassesDict)\n', (2051, 2069), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((2700, 2726), 'models.clinicalBERT.utils.loadModelConfigs', 'loadModelConfigs', (['settings'], {}), '(settings)\n', (2716, 2726), False, 'from models.clinicalBERT.utils import BERT_ENTITY_CLASSES, loadModelConfigs, clinicalBERTutils, createOutputTask1\n'), ((2743, 2803), 'models.clinicalBERT.model.Model', 'Model', (['modelConfigs', 'BERT_ENTITY_CLASSES', 'max_length', 'device'], {}), '(modelConfigs, BERT_ENTITY_CLASSES, max_length, device)\n', (2748, 2803), False, 'from models.clinicalBERT.model import Model\n'), ((3086, 3130), 'Reader.Reader', 'Reader', ([], {'dataSettings': 'settings', 'corpus': '"""test"""'}), "(dataSettings=settings, corpus='test')\n", (3092, 3130), False, 'from Reader import Reader\n'), ((3542, 3574), 'models.utils.classDictToList', 'classDictToList', (['testClassesDict'], {}), '(testClassesDict)\n', (3557, 3574), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((4115, 4281), 'models.clinicalBERT.utils.createOutputTask1', 'createOutputTask1', (['DL_model', 'testBERTtokenizedSentences', 'testEncodedSentences', 'testClasses', 'sentenceToDocList', 'clinicalBERTUtils'], {'neji_classes': 'nejiTestClasses'}), '(DL_model, testBERTtokenizedSentences,\n testEncodedSentences, testClasses, sentenceToDocList, clinicalBERTUtils,\n neji_classes=nejiTestClasses)\n', (4132, 4281), False, 'from models.clinicalBERT.utils import BERT_ENTITY_CLASSES, loadModelConfigs, clinicalBERTutils, createOutputTask1\n'), ((5009, 5033), 'random.seed', 'random.seed', (['random_seed'], {}), '(random_seed)\n', (5020, 5033), False, 'import random\n'), ((5038, 5065), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (5052, 5065), True, 'import numpy as np\n'), ((5070, 5100), 'torch.manual_seed', 'torch.manual_seed', (['random_seed'], {}), '(random_seed)\n', (5087, 5100), False, 'import torch\n'), ((5106, 5131), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (5129, 5131), False, 'import torch\n'), ((5718, 5753), 'models.clinicalBERT.utils.clinicalBERTutils', 'clinicalBERTutils', (['addSpecialTokens'], {}), '(addSpecialTokens)\n', (5735, 5753), False, 'from models.clinicalBERT.utils import BERT_ENTITY_CLASSES, loadModelConfigs, clinicalBERTutils, createOutputTask1\n'), ((6137, 6165), 'models.utils.classDictToList', 'classDictToList', (['classesDict'], {}), '(classesDict)\n', (6152, 6165), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((6603, 6626), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'cvFolds'}), '(n_splits=cvFolds)\n', (6608, 6626), False, 'from sklearn.model_selection import KFold\n'), ((8911, 8951), 'models.utils.mergeDictionaries', 'mergeDictionaries', (['predFamilyMemberDicts'], {}), '(predFamilyMemberDicts)\n', (8928, 8951), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((8980, 9020), 'models.utils.mergeDictionaries', 'mergeDictionaries', (['predObservationsDicts'], {}), '(predObservationsDicts)\n', (8997, 9020), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((9575, 9599), 'random.seed', 'random.seed', (['random_seed'], {}), '(random_seed)\n', (9586, 9599), False, 'import random\n'), ((9604, 9631), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (9618, 9631), True, 'import numpy as np\n'), ((9636, 9666), 'torch.manual_seed', 'torch.manual_seed', (['random_seed'], {}), '(random_seed)\n', (9653, 9666), False, 'import torch\n'), ((9672, 9697), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (9695, 9697), False, 'import torch\n'), ((10236, 10271), 'models.clinicalBERT.utils.clinicalBERTutils', 'clinicalBERTutils', (['addSpecialTokens'], {}), '(addSpecialTokens)\n', (10253, 10271), False, 'from models.clinicalBERT.utils import BERT_ENTITY_CLASSES, loadModelConfigs, clinicalBERTutils, createOutputTask1\n'), ((10370, 10396), 'models.clinicalBERT.utils.loadModelConfigs', 'loadModelConfigs', (['settings'], {}), '(settings)\n', (10386, 10396), False, 'from models.clinicalBERT.utils import BERT_ENTITY_CLASSES, loadModelConfigs, clinicalBERTutils, createOutputTask1\n'), ((10412, 10472), 'models.clinicalBERT.model.Model', 'Model', (['modelConfigs', 'BERT_ENTITY_CLASSES', 'max_length', 'device'], {}), '(modelConfigs, BERT_ENTITY_CLASSES, max_length, device)\n', (10417, 10472), False, 'from models.clinicalBERT.model import Model\n'), ((10615, 10659), 'Reader.Reader', 'Reader', ([], {'dataSettings': 'settings', 'corpus': '"""test"""'}), "(dataSettings=settings, corpus='test')\n", (10621, 10659), False, 'from Reader import Reader\n'), ((11071, 11103), 'models.utils.classDictToList', 'classDictToList', (['testClassesDict'], {}), '(testClassesDict)\n', (11086, 11103), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((11644, 11810), 'models.clinicalBERT.utils.createOutputTask1', 'createOutputTask1', (['DL_model', 'testBERTtokenizedSentences', 'testEncodedSentences', 'testClasses', 'sentenceToDocList', 'clinicalBERTUtils'], {'neji_classes': 'nejiTestClasses'}), '(DL_model, testBERTtokenizedSentences,\n testEncodedSentences, testClasses, sentenceToDocList, clinicalBERTUtils,\n neji_classes=nejiTestClasses)\n', (11661, 11810), False, 'from models.clinicalBERT.utils import BERT_ENTITY_CLASSES, loadModelConfigs, clinicalBERTutils, createOutputTask1\n'), ((2090, 2145), 'models.utils.classListToTensor', 'classListToTensor', (['sentenceClasses'], {'datatype': 'torch.long'}), '(sentenceClasses, datatype=torch.long)\n', (2107, 2145), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((2269, 2331), 'NejiAnnotator.readPickle', 'readPickle', (["settings['neji']['neji_train_pickle_clinicalbert']"], {}), "(settings['neji']['neji_train_pickle_clinicalbert'])\n", (2279, 2331), False, 'from NejiAnnotator import readPickle\n'), ((2359, 2391), 'models.utils.classDictToList', 'classDictToList', (['nejiClassesDict'], {}), '(nejiClassesDict)\n', (2374, 2391), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((3594, 3649), 'models.utils.classListToTensor', 'classListToTensor', (['sentenceClasses'], {'datatype': 'torch.long'}), '(sentenceClasses, datatype=torch.long)\n', (3611, 3649), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((3776, 3837), 'NejiAnnotator.readPickle', 'readPickle', (["settings['neji']['neji_test_pickle_clinicalbert']"], {}), "(settings['neji']['neji_test_pickle_clinicalbert'])\n", (3786, 3837), False, 'from NejiAnnotator import readPickle\n'), ((3864, 3900), 'models.utils.classDictToList', 'classDictToList', (['nejiTestClassesDict'], {}), '(nejiTestClassesDict)\n', (3879, 3900), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((6181, 6236), 'models.utils.classListToTensor', 'classListToTensor', (['sentenceClasses'], {'datatype': 'torch.long'}), '(sentenceClasses, datatype=torch.long)\n', (6198, 6236), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((6355, 6417), 'NejiAnnotator.readPickle', 'readPickle', (["settings['neji']['neji_train_pickle_clinicalbert']"], {}), "(settings['neji']['neji_train_pickle_clinicalbert'])\n", (6365, 6417), False, 'from NejiAnnotator import readPickle\n'), ((6440, 6472), 'models.utils.classDictToList', 'classDictToList', (['nejiClassesDict'], {}), '(nejiClassesDict)\n', (6455, 6472), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((7682, 7708), 'models.clinicalBERT.utils.loadModelConfigs', 'loadModelConfigs', (['settings'], {}), '(settings)\n', (7698, 7708), False, 'from models.clinicalBERT.utils import BERT_ENTITY_CLASSES, loadModelConfigs, clinicalBERTutils, createOutputTask1\n'), ((7729, 7789), 'models.clinicalBERT.model.Model', 'Model', (['modelConfigs', 'BERT_ENTITY_CLASSES', 'max_length', 'device'], {}), '(modelConfigs, BERT_ENTITY_CLASSES, max_length, device)\n', (7734, 7789), False, 'from models.clinicalBERT.model import Model\n'), ((8473, 8633), 'models.clinicalBERT.utils.createOutputTask1', 'createOutputTask1', (['DL_model', 'testTokenizedSentences', 'testEncodedSentences', 'testClasses', 'testDocMapping', 'clinicalBERTUtils'], {'neji_classes': 'nejiTestClasses'}), '(DL_model, testTokenizedSentences, testEncodedSentences,\n testClasses, testDocMapping, clinicalBERTUtils, neji_classes=\n nejiTestClasses)\n', (8490, 8633), False, 'from models.clinicalBERT.utils import BERT_ENTITY_CLASSES, loadModelConfigs, clinicalBERTutils, createOutputTask1\n'), ((11123, 11178), 'models.utils.classListToTensor', 'classListToTensor', (['sentenceClasses'], {'datatype': 'torch.long'}), '(sentenceClasses, datatype=torch.long)\n', (11140, 11178), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((11305, 11366), 'NejiAnnotator.readPickle', 'readPickle', (["settings['neji']['neji_test_pickle_clinicalbert']"], {}), "(settings['neji']['neji_test_pickle_clinicalbert'])\n", (11315, 11366), False, 'from NejiAnnotator import readPickle\n'), ((11393, 11429), 'models.utils.classDictToList', 'classDictToList', (['nejiTestClassesDict'], {}), '(nejiTestClassesDict)\n', (11408, 11429), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((1080, 1105), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1103, 1105), False, 'import torch\n'), ((1197, 1226), 'torch.cuda.get_device_name', 'torch.cuda.get_device_name', (['(0)'], {}), '(0)\n', (1223, 1226), False, 'import torch\n'), ((2420, 2476), 'models.utils.classListToTensor', 'classListToTensor', (['sentenceClasses'], {'datatype': 'torch.float'}), '(sentenceClasses, datatype=torch.float)\n', (2437, 2476), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((3928, 3984), 'models.utils.classListToTensor', 'classListToTensor', (['sentenceClasses'], {'datatype': 'torch.float'}), '(sentenceClasses, datatype=torch.float)\n', (3945, 3984), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((5168, 5193), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (5191, 5193), False, 'import torch\n'), ((5285, 5314), 'torch.cuda.get_device_name', 'torch.cuda.get_device_name', (['(0)'], {}), '(0)\n', (5311, 5314), False, 'import torch\n'), ((6496, 6552), 'models.utils.classListToTensor', 'classListToTensor', (['sentenceClasses'], {'datatype': 'torch.float'}), '(sentenceClasses, datatype=torch.float)\n', (6513, 6552), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((9734, 9759), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (9757, 9759), False, 'import torch\n'), ((9851, 9880), 'torch.cuda.get_device_name', 'torch.cuda.get_device_name', (['(0)'], {}), '(0)\n', (9877, 9880), False, 'import torch\n'), ((11457, 11513), 'models.utils.classListToTensor', 'classListToTensor', (['sentenceClasses'], {'datatype': 'torch.float'}), '(sentenceClasses, datatype=torch.float)\n', (11474, 11513), False, 'from models.utils import classListToTensor, classDictToList, getSentenceList, mergeDictionaries\n'), ((1293, 1323), 'torch.cuda.memory_allocated', 'torch.cuda.memory_allocated', (['(0)'], {}), '(0)\n', (1320, 1323), False, 'import torch\n'), ((1376, 1403), 'torch.cuda.memory_cached', 'torch.cuda.memory_cached', (['(0)'], {}), '(0)\n', (1400, 1403), False, 'import torch\n'), ((1891, 1917), 'torch.LongTensor', 'torch.LongTensor', (['sentence'], {}), '(sentence)\n', (1907, 1917), False, 'import torch\n'), ((3414, 3440), 'torch.LongTensor', 'torch.LongTensor', (['sentence'], {}), '(sentence)\n', (3430, 3440), False, 'import torch\n'), ((5381, 5411), 'torch.cuda.memory_allocated', 'torch.cuda.memory_allocated', (['(0)'], {}), '(0)\n', (5408, 5411), False, 'import torch\n'), ((5464, 5491), 'torch.cuda.memory_cached', 'torch.cuda.memory_cached', (['(0)'], {}), '(0)\n', (5488, 5491), False, 'import torch\n'), ((6002, 6028), 'torch.LongTensor', 'torch.LongTensor', (['sentence'], {}), '(sentence)\n', (6018, 6028), False, 'import torch\n'), ((9947, 9977), 'torch.cuda.memory_allocated', 'torch.cuda.memory_allocated', (['(0)'], {}), '(0)\n', (9974, 9977), False, 'import torch\n'), ((10030, 10057), 'torch.cuda.memory_cached', 'torch.cuda.memory_cached', (['(0)'], {}), '(0)\n', (10054, 10057), False, 'import torch\n'), ((10943, 10969), 'torch.LongTensor', 'torch.LongTensor', (['sentence'], {}), '(sentence)\n', (10959, 10969), False, 'import torch\n')] |
# -*- coding: utf-8 -*-
# Copyright 2022, SERTIT-ICube - France, https://sertit.unistra.fr/
# This file is part of eoreader project
# https://github.com/sertit/eoreader
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
COSMO-SkyMed 2nd Generation products.
More info `here <https://egeos.my.salesforce.com/sfc/p/#1r000000qoOc/a/69000000JXxZ/WEEbowzi5cmY8vLqyfAAMKZ064iN1eWw_qZAgUkTtXI>`_.
"""
import logging
import warnings
from datetime import datetime
from enum import unique
from pathlib import Path
from typing import Union
import geopandas as gpd
import numpy as np
import rasterio
from cloudpathlib import AnyPath, CloudPath
from lxml import etree
from sertit import files, strings, vectors
from sertit.misc import ListEnum
from shapely.geometry import Polygon, box
from eoreader import cache, cached_property
from eoreader.exceptions import InvalidProductError
from eoreader.products import SarProduct, SarProductType
from eoreader.utils import DATETIME_FMT, EOREADER_NAME
LOGGER = logging.getLogger(EOREADER_NAME)
# Disable georef warnings here as the SAR products are not georeferenced
warnings.filterwarnings("ignore", category=rasterio.errors.NotGeoreferencedWarning)
@unique
class CosmoProductType(ListEnum):
"""
COSMO-SkyMed (both generations) products types.
The product classed are not specified here.
More info
`here <https://egeos.my.salesforce.com/sfc/p/#1r000000qoOc/a/69000000JXxZ/WEEbowzi5cmY8vLqyfAAMKZ064iN1eWw_qZAgUkTtXI>`_.
"""
RAW = "RAW"
"""Level 0"""
SCS = "SCS"
"""Level 1A, Single-look Complex Slant"""
DGM = "DGM"
"""Level 1B, Detected Ground Multi-look"""
GEC = "GEC"
"""Level 1C, Geocoded Ellipsoid Corrected"""
GTC = "GTC"
"""Level 1D, Geocoded Terrain Corrected"""
@unique
class CosmoPolarization(ListEnum):
"""
COSMO-SkyMed (both generations) polarizations used during the acquisition.
More info
`here <https://egeos.my.salesforce.com/sfc/p/#1r000000qoOc/a/69000000JXxZ/WEEbowzi5cmY8vLqyfAAMKZ064iN1eWw_qZAgUkTtXI>`_.
"""
HH = "HH"
"""Horizontal Tx/Horizontal Rx for Himage, ScanSAR and Spotlight modes"""
VV = "VV"
"""Vertical Tx/Vertical Rx for Himage, ScanSAR and Spotlight modes"""
HV = "HV"
"""Horizontal Tx/Vertical Rx for Himage, ScanSAR"""
VH = "VH"
"""Vertical Tx/Horizontal Rx for Himage, ScanSAR"""
class CosmoProduct(SarProduct):
"""
Class for COSMO-SkyMed (both generations) Products
More info
`here <https://egeos.my.salesforce.com/sfc/p/#1r000000qoOc/a/69000000JXxZ/WEEbowzi5cmY8vLqyfAAMKZ064iN1eWw_qZAgUkTtXI>`_.
"""
def __init__(
self,
product_path: Union[str, CloudPath, Path],
archive_path: Union[str, CloudPath, Path] = None,
output_path: Union[str, CloudPath, Path] = None,
remove_tmp: bool = False,
) -> None:
try:
product_path = AnyPath(product_path)
self._img_path = next(product_path.glob("*.h5"))
except IndexError as ex:
raise InvalidProductError(
f"Image file (*.h5) not found in {product_path}"
) from ex
self._real_name = files.get_filename(self._img_path)
# Initialization from the super class
super().__init__(product_path, archive_path, output_path, remove_tmp)
def _pre_init(self) -> None:
"""
Function used to pre_init the products
(setting needs_extraction and so on)
"""
# Private attributes
self._raw_band_regex = "*_{}_*.h5"
self._band_folder = self.path
self._snap_path = self._img_path.name
# SNAP cannot process its archive
self.needs_extraction = True
# Post init done by the super class
super()._pre_init()
def _post_init(self) -> None:
"""
Function used to post_init the products
(setting product-type, band names and so on)
"""
# Post init done by the super class
super()._post_init()
@cached_property
def wgs84_extent(self) -> gpd.GeoDataFrame:
"""
Get the WGS84 extent of the file before any reprojection.
This is useful when the SAR pre-process has not been done yet.
.. code-block:: python
>>> from eoreader.reader import Reader
>>> path = r"1011117-766193"
>>> prod = Reader().open(path)
>>> prod.wgs84_extent
geometry
0 POLYGON ((108.09797 15.61011, 108.48224 15.678...
Returns:
gpd.GeoDataFrame: WGS84 extent as a gpd.GeoDataFrame
"""
root, _ = self.read_mtd()
# Open zenith and azimuth angle
try:
def from_str_to_arr(geo_coord: str):
return np.array(strings.str_to_list(geo_coord), dtype=float)[:2][::-1]
bl_corner = from_str_to_arr(root.findtext(".//GeoCoordBottomLeft"))
br_corner = from_str_to_arr(root.findtext(".//GeoCoordBottomRight"))
tl_corner = from_str_to_arr(root.findtext(".//GeoCoordTopLeft"))
tr_corner = from_str_to_arr(root.findtext(".//GeoCoordTopRight"))
if bl_corner is None:
raise InvalidProductError("Invalid XML: missing extent.")
extent_wgs84 = gpd.GeoDataFrame(
geometry=[Polygon([tl_corner, tr_corner, br_corner, bl_corner])],
crs=vectors.WGS84,
)
except ValueError:
def from_str_to_arr(geo_coord: str):
str_list = [
it
for it in strings.str_to_list(geo_coord, additional_separator="\n")
if "+" not in it
]
# Create tuples of 2D coords
coord_list = []
coord = np.zeros((2, 1), dtype=float)
for it_id, it in enumerate(str_list):
if it_id % 3 == 0:
# Invert lat and lon
coord[1] = float(it)
elif it_id % 3 == 1:
# Invert lat and lon
coord[0] = float(it)
elif it_id % 3 == 2:
# Z coordinates: do not store it
# Append the last coordinates
coord_list.append(coord.copy())
# And reinit it
coord = np.zeros((2, 1), dtype=float)
return coord_list
bl_corners = from_str_to_arr(root.findtext(".//GeoCoordBottomLeft"))
br_corners = from_str_to_arr(root.findtext(".//GeoCoordBottomRight"))
tl_corners = from_str_to_arr(root.findtext(".//GeoCoordTopLeft"))
tr_corners = from_str_to_arr(root.findtext(".//GeoCoordTopRight"))
if not bl_corners:
raise InvalidProductError("Invalid XML: missing extent.")
assert (
len(bl_corners) == len(br_corners) == len(tl_corners) == len(tr_corners)
)
polygons = [
Polygon(
[
tl_corners[coord_id],
tr_corners[coord_id],
br_corners[coord_id],
bl_corners[coord_id],
]
)
for coord_id in range(len(bl_corners))
]
extents_wgs84 = gpd.GeoDataFrame(
geometry=polygons,
crs=vectors.WGS84,
)
extent_wgs84 = gpd.GeoDataFrame(
geometry=[box(*extents_wgs84.total_bounds)],
crs=vectors.WGS84,
)
return extent_wgs84
def _set_product_type(self) -> None:
"""Set products type"""
# Get MTD XML file
root, _ = self.read_mtd()
# Open identifier
try:
# DGM_B, or SCS_B -> remove last 2 characters
prod_type = root.findtext(".//ProductType")[:-2]
except TypeError:
raise InvalidProductError("mode not found in metadata!")
self.product_type = CosmoProductType.from_value(prod_type)
if self.product_type == CosmoProductType.DGM:
self.sar_prod_type = SarProductType.GDRG
elif self.product_type == CosmoProductType.SCS:
self.sar_prod_type = SarProductType.CPLX
else:
raise NotImplementedError(
f"{self.product_type.value} product type is not available for {self.name}"
)
def get_datetime(self, as_datetime: bool = False) -> Union[str, datetime]:
"""
Get the product's acquisition datetime, with format :code:`YYYYMMDDTHHMMSS` <-> :code:`%Y%m%dT%H%M%S`
.. code-block:: python
>>> from eoreader.reader import Reader
>>> path = r"1011117-766193"
>>> prod = Reader().open(path)
>>> prod.get_datetime(as_datetime=True)
datetime.datetime(2020, 10, 28, 22, 46, 25)
>>> prod.get_datetime(as_datetime=False)
'20201028T224625'
Args:
as_datetime (bool): Return the date as a datetime.datetime. If false, returns a string.
Returns:
Union[str, datetime.datetime]: Its acquisition datetime
"""
if self.datetime is None:
# Get MTD XML file
root, _ = self.read_mtd()
# Open identifier
try:
acq_date = root.findtext(".//SceneSensingStartUTC")
except TypeError:
raise InvalidProductError("SceneSensingStartUTC not found in metadata!")
# Convert to datetime
# 2020-10-28 22:46:24.808662850
# To many milliseconds (strptime accepts max 6 digits) -> needs to be cropped
date = datetime.strptime(acq_date[:-3], "%Y-%m-%d %H:%M:%S.%f")
else:
date = self.datetime
if not as_datetime:
date = date.strftime(DATETIME_FMT)
return date
def _get_name(self) -> str:
"""
Set product real name from metadata
Returns:
str: True name of the product (from metadata)
"""
if self.name is None:
# Get MTD XML file
root, _ = self.read_mtd()
# Open identifier
try:
name = files.get_filename(root.findtext(".//ProductName"))
except TypeError:
raise InvalidProductError("ProductName not found in metadata!")
else:
name = self.name
return name
@cache
def _read_mtd(self) -> (etree._Element, dict):
"""
Read metadata and outputs the metadata XML root and its namespaces as a dict
.. code-block:: python
>>> from eoreader.reader import Reader
>>> path = r"1001513-735093"
>>> prod = Reader().open(path)
>>> prod.read_mtd()
(<Element DeliveryNote at 0x2454ad4ee88>, {})
Returns:
(etree._Element, dict): Metadata XML root and its namespaces
"""
mtd_from_path = "DFDN_*.h5.xml"
return self._read_mtd_xml(mtd_from_path)
| [
"logging.getLogger",
"datetime.datetime.strptime",
"cloudpathlib.AnyPath",
"shapely.geometry.box",
"numpy.zeros",
"shapely.geometry.Polygon",
"sertit.strings.str_to_list",
"sertit.files.get_filename",
"geopandas.GeoDataFrame",
"warnings.filterwarnings",
"eoreader.exceptions.InvalidProductError"
... | [((1496, 1528), 'logging.getLogger', 'logging.getLogger', (['EOREADER_NAME'], {}), '(EOREADER_NAME)\n', (1513, 1528), False, 'import logging\n'), ((1603, 1691), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'rasterio.errors.NotGeoreferencedWarning'}), "('ignore', category=rasterio.errors.\n NotGeoreferencedWarning)\n", (1626, 1691), False, 'import warnings\n'), ((3686, 3720), 'sertit.files.get_filename', 'files.get_filename', (['self._img_path'], {}), '(self._img_path)\n', (3704, 3720), False, 'from sertit import files, strings, vectors\n'), ((3418, 3439), 'cloudpathlib.AnyPath', 'AnyPath', (['product_path'], {}), '(product_path)\n', (3425, 3439), False, 'from cloudpathlib import AnyPath, CloudPath\n'), ((10445, 10501), 'datetime.datetime.strptime', 'datetime.strptime', (['acq_date[:-3]', '"""%Y-%m-%d %H:%M:%S.%f"""'], {}), "(acq_date[:-3], '%Y-%m-%d %H:%M:%S.%f')\n", (10462, 10501), False, 'from datetime import datetime\n'), ((3552, 3621), 'eoreader.exceptions.InvalidProductError', 'InvalidProductError', (['f"""Image file (*.h5) not found in {product_path}"""'], {}), "(f'Image file (*.h5) not found in {product_path}')\n", (3571, 3621), False, 'from eoreader.exceptions import InvalidProductError\n'), ((5785, 5836), 'eoreader.exceptions.InvalidProductError', 'InvalidProductError', (['"""Invalid XML: missing extent."""'], {}), "('Invalid XML: missing extent.')\n", (5804, 5836), False, 'from eoreader.exceptions import InvalidProductError\n'), ((8025, 8079), 'geopandas.GeoDataFrame', 'gpd.GeoDataFrame', ([], {'geometry': 'polygons', 'crs': 'vectors.WGS84'}), '(geometry=polygons, crs=vectors.WGS84)\n', (8041, 8079), True, 'import geopandas as gpd\n'), ((8650, 8700), 'eoreader.exceptions.InvalidProductError', 'InvalidProductError', (['"""mode not found in metadata!"""'], {}), "('mode not found in metadata!')\n", (8669, 8700), False, 'from eoreader.exceptions import InvalidProductError\n'), ((6388, 6417), 'numpy.zeros', 'np.zeros', (['(2, 1)'], {'dtype': 'float'}), '((2, 1), dtype=float)\n', (6396, 6417), True, 'import numpy as np\n'), ((7454, 7505), 'eoreader.exceptions.InvalidProductError', 'InvalidProductError', (['"""Invalid XML: missing extent."""'], {}), "('Invalid XML: missing extent.')\n", (7473, 7505), False, 'from eoreader.exceptions import InvalidProductError\n'), ((7673, 7774), 'shapely.geometry.Polygon', 'Polygon', (['[tl_corners[coord_id], tr_corners[coord_id], br_corners[coord_id],\n bl_corners[coord_id]]'], {}), '([tl_corners[coord_id], tr_corners[coord_id], br_corners[coord_id],\n bl_corners[coord_id]])\n', (7680, 7774), False, 'from shapely.geometry import Polygon, box\n'), ((10190, 10256), 'eoreader.exceptions.InvalidProductError', 'InvalidProductError', (['"""SceneSensingStartUTC not found in metadata!"""'], {}), "('SceneSensingStartUTC not found in metadata!')\n", (10209, 10256), False, 'from eoreader.exceptions import InvalidProductError\n'), ((11097, 11154), 'eoreader.exceptions.InvalidProductError', 'InvalidProductError', (['"""ProductName not found in metadata!"""'], {}), "('ProductName not found in metadata!')\n", (11116, 11154), False, 'from eoreader.exceptions import InvalidProductError\n'), ((5909, 5962), 'shapely.geometry.Polygon', 'Polygon', (['[tl_corner, tr_corner, br_corner, bl_corner]'], {}), '([tl_corner, tr_corner, br_corner, bl_corner])\n', (5916, 5962), False, 'from shapely.geometry import Polygon, box\n'), ((5356, 5386), 'sertit.strings.str_to_list', 'strings.str_to_list', (['geo_coord'], {}), '(geo_coord)\n', (5375, 5386), False, 'from sertit import files, strings, vectors\n'), ((6173, 6230), 'sertit.strings.str_to_list', 'strings.str_to_list', (['geo_coord'], {'additional_separator': '"""\n"""'}), "(geo_coord, additional_separator='\\n')\n", (6192, 6230), False, 'from sertit import files, strings, vectors\n'), ((8199, 8231), 'shapely.geometry.box', 'box', (['*extents_wgs84.total_bounds'], {}), '(*extents_wgs84.total_bounds)\n', (8202, 8231), False, 'from shapely.geometry import Polygon, box\n'), ((7014, 7043), 'numpy.zeros', 'np.zeros', (['(2, 1)'], {'dtype': 'float'}), '((2, 1), dtype=float)\n', (7022, 7043), True, 'import numpy as np\n')] |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import os
from io import open
import sys
import platform
from setuptools import setup, find_packages, Extension
from setuptools.command.build_ext import build_ext as _build_ext
class build_ext(_build_ext):
def finalize_options(self):
_build_ext.finalize_options(self)
# Prevent numpy from thinking it is still in its setup process:
if sys.version_info[0] >= 3:
import builtins
if hasattr(builtins, '__NUMPY_SETUP__'):
del builtins.__NUMPY_SETUP__
import importlib
import numpy
importlib.reload(numpy)
else:
import __builtin__
if hasattr(__builtin__, '__NUMPY_SETUP__'):
del __builtin__.__NUMPY_SETUP__
import imp
import numpy
imp.reload(numpy)
self.include_dirs.append(numpy.get_include())
SETUP_PTH = os.path.dirname(__file__)
extra_link_args = []
if sys.platform.startswith('win') and platform.machine().endswith('64'):
extra_link_args.append('-Wl,--allow-multiple-definition')
with open(os.path.join(SETUP_PTH, "README.rst")) as f:
long_desc = f.read()
ind = long_desc.find("\n")
long_desc = long_desc[ind + 1:]
setup(
name="pymatgen",
packages=find_packages(),
version="4.6.0",
cmdclass={'build_ext': build_ext},
setup_requires=['numpy', 'setuptools>=18.0'],
install_requires=["numpy>=1.9", "six", "requests", "pyyaml>=3.11",
"monty>=0.9.6", "scipy>=0.14", "pydispatcher>=2.0.5",
"tabulate", "spglib>=1.9.8.7",
"matplotlib>=1.5", "palettable>=2.1.1"],
extras_require={
':python_version == "2.7"': [
'enum34',
'pathlib2',
],
"matproj.snl": ["pybtex"],
"pourbaix diagrams, bandstructure": ["pyhull>=1.5.3"],
"ase_adaptor": ["ase>=3.3"],
"vis": ["vtk>=6.0.0"],
"abinit": ["pydispatcher>=2.0.5", "apscheduler==2.1.0"]},
package_data={"pymatgen.core": ["*.json"],
"pymatgen.analysis": ["*.yaml", "*.csv"],
"pymatgen.analysis.chemenv.coordination_environments.coordination_geometries_files": ["*.txt", "*.json"],
"pymatgen.analysis.chemenv.coordination_environments.strategy_files": ["*.json"],
"pymatgen.io.vasp": ["*.yaml"],
"pymatgen.io.feff": ["*.yaml"],
"pymatgen.symmetry": ["*.yaml", "*.json"],
"pymatgen.entries": ["*.yaml"],
"pymatgen.structure_prediction": ["data/*.json"],
"pymatgen.vis": ["ElementColorSchemes.yaml"],
"pymatgen.command_line": ["OxideTersoffPotentials"],
"pymatgen.analysis.defects": ["*.json"],
"pymatgen.analysis.diffraction": ["*.json"],
"pymatgen.util": ["structures/*.json"]},
author="Pymatgen Development Team",
author_email="<EMAIL>",
maintainer="<NAME>",
maintainer_email="<EMAIL>",
url="http://www.pymatgen.org",
license="MIT",
description="Python Materials Genomics is a robust materials "
"analysis code that defines core object representations for "
"structures and molecules with support for many electronic "
"structure codes. It is currently the core analysis code "
"powering the Materials Project "
"(https://www.materialsproject.org).",
long_description=long_desc,
keywords=["VASP", "gaussian", "ABINIT", "nwchem", "materials", "project",
"electronic", "structure", "analysis", "phase", "diagrams"],
classifiers=[
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Development Status :: 4 - Beta",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Scientific/Engineering :: Information Analysis",
"Topic :: Scientific/Engineering :: Physics",
"Topic :: Scientific/Engineering :: Chemistry",
"Topic :: Software Development :: Libraries :: Python Modules"
],
ext_modules=[Extension("pymatgen.optimization.linear_assignment",
["pymatgen/optimization/linear_assignment.c"],
extra_link_args=extra_link_args),
Extension("pymatgen.util.coord_utils_cython",
["pymatgen/util/coord_utils_cython.c"],
extra_link_args=extra_link_args)],
entry_points={
'console_scripts': [
'pmg = pymatgen.cli.pmg:main',
'feff_input_generation = pymatgen.cli.feff_input_generation:main',
'feff_plot_cross_section = pymatgen.cli.feff_plot_cross_section:main',
'feff_plot_dos = pymatgen.cli.feff_plot_dos:main',
'gaussian_analyzer = pymatgen.cli.gaussian_analyzer:main',
'get_environment = pymatgen.cli.get_environment:main',
'pydii = pymatgen.cli.pydii:main',
]
}
)
| [
"setuptools.find_packages",
"os.path.join",
"sys.platform.startswith",
"imp.reload",
"setuptools.Extension",
"os.path.dirname",
"importlib.reload",
"numpy.get_include",
"platform.machine",
"setuptools.command.build_ext.build_ext.finalize_options"
] | [((1013, 1038), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1028, 1038), False, 'import os\n'), ((1064, 1094), 'sys.platform.startswith', 'sys.platform.startswith', (['"""win"""'], {}), "('win')\n", (1087, 1094), False, 'import sys\n'), ((359, 392), 'setuptools.command.build_ext.build_ext.finalize_options', '_build_ext.finalize_options', (['self'], {}), '(self)\n', (386, 392), True, 'from setuptools.command.build_ext import build_ext as _build_ext\n'), ((1207, 1244), 'os.path.join', 'os.path.join', (['SETUP_PTH', '"""README.rst"""'], {}), "(SETUP_PTH, 'README.rst')\n", (1219, 1244), False, 'import os\n'), ((1386, 1401), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (1399, 1401), False, 'from setuptools import setup, find_packages, Extension\n'), ((694, 717), 'importlib.reload', 'importlib.reload', (['numpy'], {}), '(numpy)\n', (710, 717), False, 'import importlib\n'), ((927, 944), 'imp.reload', 'imp.reload', (['numpy'], {}), '(numpy)\n', (937, 944), False, 'import imp\n'), ((979, 998), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (996, 998), False, 'import numpy\n'), ((1099, 1117), 'platform.machine', 'platform.machine', ([], {}), '()\n', (1115, 1117), False, 'import platform\n'), ((4534, 4676), 'setuptools.Extension', 'Extension', (['"""pymatgen.optimization.linear_assignment"""', "['pymatgen/optimization/linear_assignment.c']"], {'extra_link_args': 'extra_link_args'}), "('pymatgen.optimization.linear_assignment', [\n 'pymatgen/optimization/linear_assignment.c'], extra_link_args=\n extra_link_args)\n", (4543, 4676), False, 'from setuptools import setup, find_packages, Extension\n'), ((4739, 4862), 'setuptools.Extension', 'Extension', (['"""pymatgen.util.coord_utils_cython"""', "['pymatgen/util/coord_utils_cython.c']"], {'extra_link_args': 'extra_link_args'}), "('pymatgen.util.coord_utils_cython', [\n 'pymatgen/util/coord_utils_cython.c'], extra_link_args=extra_link_args)\n", (4748, 4862), False, 'from setuptools import setup, find_packages, Extension\n')] |
# -*- coding: utf-8 -*-
import numpy as np
from mabwiser.mab import LearningPolicy, NeighborhoodPolicy
from tests.test_base import BaseTest
class ParallelTest(BaseTest):
def test_greedy_t1(self):
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 1, 1, 3, 2, 2, 3, 1, 3],
rewards=[0, 1, 1, 0, 1, 0, 1, 1, 1],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=0),
seed=123456,
num_run=4,
is_predict=True,
n_jobs=1)
self.assertEqual(arms, [1, 1, 1, 1])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 1, 1, 3, 2, 2, 3, 1, 3],
rewards=[0, 1, 1, 0, 1, 0, 1, 1, 1],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=0),
seed=123456,
num_run=4,
is_predict=True,
n_jobs=2)
self.assertEqual(arms, [1, 1, 1, 1])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 1, 1, 3, 2, 2, 3, 1, 3],
rewards=[0, 1, 1, 0, 1, 0, 1, 1, 1],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=0),
seed=123456,
num_run=4,
is_predict=True,
n_jobs=3)
self.assertEqual(arms, [1, 1, 1, 1])
def test_popularity(self):
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 1, 1, 3, 2, 2, 3, 1, 3],
rewards=[0, 1, 1, 0, 1, 0, 1, 1, 1],
learning_policy=LearningPolicy.Popularity(),
seed=123456,
num_run=4,
is_predict=True,
n_jobs=1)
self.assertEqual(arms, [3, 2, 3, 3])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 1, 1, 3, 2, 2, 3, 1, 3],
rewards=[0, 1, 1, 0, 1, 0, 1, 1, 1],
learning_policy=LearningPolicy.Popularity(),
seed=123456,
num_run=4,
is_predict=True,
n_jobs=2)
self.assertEqual(arms, [3, 2, 3, 3])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 1, 1, 3, 2, 2, 3, 1, 3],
rewards=[0, 1, 1, 0, 1, 0, 1, 1, 1],
learning_policy=LearningPolicy.Popularity(),
seed=123456,
num_run=4,
is_predict=True,
n_jobs=3)
self.assertEqual(arms, [3, 2, 3, 3])
def test_greedy_t2(self):
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 1, 1, 3, 2, 2, 3, 1, 3],
rewards=[0, 1, 1, 0, 1, 0, 1, 1, 1],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=0.25),
seed=123456,
num_run=4,
is_predict=True,
n_jobs=1)
self.assertEqual(arms, [1, 1, 1, 1])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 1, 1, 3, 2, 2, 3, 1, 3],
rewards=[0, 1, 1, 0, 1, 0, 1, 1, 1],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=0.25),
seed=123456,
num_run=4,
is_predict=True,
n_jobs=2)
self.assertEqual(arms, [1, 1, 1, 1])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 1, 1, 3, 2, 2, 3, 1, 3],
rewards=[0, 1, 1, 0, 1, 0, 1, 1, 1],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=0.25),
seed=123456,
num_run=4,
is_predict=True,
n_jobs=3)
self.assertEqual(arms, [1, 1, 1, 1])
def test_greedy_t3(self):
arms, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 3, 2, 2, 3, 1, 3],
rewards=[0, 1, 1, 0, 1, 0, 1, 1, 1],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=0.9),
seed=123456,
num_run=6,
is_predict=True,
n_jobs=1)
self.assertEqual(arms, [3, 3, 3, 1, 2, 3])
arms, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 3, 2, 2, 3, 1, 3],
rewards=[0, 1, 1, 0, 1, 0, 1, 1, 1],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=0.9),
seed=123456,
num_run=6,
is_predict=True,
n_jobs=2)
self.assertEqual(arms, [3, 3, 3, 1, 2, 3])
arms, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 3, 2, 2, 3, 1, 3],
rewards=[0, 1, 1, 0, 1, 0, 1, 1, 1],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=0.9),
seed=123456,
num_run=6,
is_predict=True,
n_jobs=4)
self.assertEqual(arms, [3, 3, 3, 1, 2, 3])
def test_UCB1_t1(self):
arms, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4],
rewards=[1, 0, 0, 1, 1, 0, 1, 0, 0, 0],
learning_policy=LearningPolicy.UCB1(alpha=0.1),
seed=123456,
num_run=4,
is_predict=True,
n_jobs=1)
self.assertEqual(arms, [2, 2, 2, 2])
arms, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4],
rewards=[1, 0, 0, 1, 1, 0, 1, 0, 0, 0],
learning_policy=LearningPolicy.UCB1(alpha=0.1),
seed=123456,
num_run=4,
is_predict=True,
n_jobs=2)
self.assertEqual(arms, [2, 2, 2, 2])
arms, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4],
rewards=[1, 0, 0, 1, 1, 0, 1, 0, 0, 0],
learning_policy=LearningPolicy.UCB1(alpha=0.1),
seed=123456,
num_run=4,
is_predict=True,
n_jobs=4)
self.assertEqual(arms, [2, 2, 2, 2])
def test_thompson_t1(self):
arms, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4],
rewards=[1, 0, 0, 1, 0, 0, 1, 0, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
seed=123456,
num_run=8,
is_predict=True,
n_jobs=1)
self.assertEqual(arms, [3, 3, 3, 3, 4, 4, 4, 3])
arms, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4],
rewards=[1, 0, 0, 1, 0, 0, 1, 0, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
seed=123456,
num_run=8,
is_predict=True,
n_jobs=2)
self.assertEqual(arms, [3, 3, 3, 3, 4, 4, 4, 3])
arms, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4],
rewards=[1, 0, 0, 1, 0, 0, 1, 0, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
seed=123456,
num_run=8,
is_predict=True,
n_jobs=-1)
self.assertEqual(arms, [3, 3, 3, 3, 4, 4, 4, 3])
def test_UCB1_c2(self):
rng = np.random.RandomState(seed=111)
contexts_history = rng.randint(0, 5, (10, 5))
contexts = rng.randint(0, 5, (10, 5))
arm, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4],
rewards=[1, 0, 0, 1, 0, 0, 1, 0, 0, 0],
learning_policy=LearningPolicy.UCB1(alpha=0.1),
neighborhood_policy=NeighborhoodPolicy.Clusters(2),
context_history=contexts_history,
contexts=contexts,
seed=123456,
num_run=5,
is_predict=True,
n_jobs=1)
self.assertEqual(arm, [[3, 3, 1, 1, 1, 1, 3, 1, 3, 3] for _ in range(5)])
arm, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4],
rewards=[1, 0, 0, 1, 0, 0, 1, 0, 0, 0],
learning_policy=LearningPolicy.UCB1(alpha=0.1),
neighborhood_policy=NeighborhoodPolicy.Clusters(2),
context_history=contexts_history,
contexts=contexts,
seed=123456,
num_run=5,
is_predict=True,
n_jobs=2)
self.assertEqual(arm, [[3, 3, 1, 1, 1, 1, 3, 1, 3, 3] for _ in range(5)])
arm, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4],
rewards=[1, 0, 0, 1, 0, 0, 1, 0, 0, 0],
learning_policy=LearningPolicy.UCB1(alpha=0.1),
neighborhood_policy=NeighborhoodPolicy.Clusters(2),
context_history=contexts_history,
contexts=contexts,
seed=123456,
num_run=5,
is_predict=True,
n_jobs=100)
self.assertEqual(arm, [[3, 3, 1, 1, 1, 1, 3, 1, 3, 3] for _ in range(5)])
def test_greedy1_k2(self):
rng = np.random.RandomState(seed=7)
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.KNearest(2),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=1)
self.assertListEqual(arms, [2, 1, 1, 2, 3, 3, 3, 1, 3, 2])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.KNearest(2),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2)
self.assertListEqual(arms, [2, 1, 1, 2, 3, 3, 3, 1, 3, 2])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.KNearest(2),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=-1)
self.assertListEqual(arms, [2, 1, 1, 2, 3, 3, 3, 1, 3, 2])
def test_greedy1_r2(self):
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.Radius(2),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=1)
self.assertListEqual(arms, [3, 1, 1, 3, 1, 3, 3, 1, 3, 1])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.Radius(2),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2)
self.assertListEqual(arms, [3, 1, 1, 3, 1, 3, 3, 1, 3, 1])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.Radius(2),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=-1)
self.assertListEqual(arms, [3, 1, 1, 3, 1, 3, 3, 1, 3, 1])
def test_greedy1_n3(self):
rng = np.random.RandomState(seed=7)
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.Clusters(3),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=1)
self.assertListEqual(arms, [2, 1, 1, 2, 3, 3, 3, 1, 3, 2])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.Clusters(3),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2)
self.assertListEqual(arms, [2, 1, 1, 2, 3, 3, 3, 1, 3, 2])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.Clusters(3),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=-1)
self.assertListEqual(arms, [2, 1, 1, 2, 3, 3, 3, 1, 3, 2])
def test_greedy1_a2(self):
rng = np.random.RandomState(seed=7)
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.LSHNearest(),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=1)
self.assertListEqual(arms, [1, 3, 3, 3, 1, 2, 1, 1, 2, 2])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.LSHNearest(),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2)
self.assertListEqual(arms, [1, 3, 3, 3, 1, 2, 1, 1, 2, 2])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.LSHNearest(),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=-1)
self.assertListEqual(arms, [1, 3, 3, 3, 1, 2, 1, 1, 2, 2])
def test_thompson_k2(self):
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
neighborhood_policy=NeighborhoodPolicy.KNearest(2),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=1)
self.assertListEqual(arms, [2, 1, 1, 2, 1, 1, 1, 2, 2, 1])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
neighborhood_policy=NeighborhoodPolicy.KNearest(2),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2)
self.assertListEqual(arms, [2, 1, 1, 2, 1, 1, 1, 2, 2, 1])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
neighborhood_policy=NeighborhoodPolicy.KNearest(2),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=-1)
self.assertListEqual(arms, [2, 1, 1, 2, 1, 1, 1, 2, 2, 1])
def test_thompson_r2(self):
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
neighborhood_policy=NeighborhoodPolicy.Radius(2),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=1)
self.assertListEqual(arms, [3, 1, 1, 3, 1, 3, 3, 1, 3, 1])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
neighborhood_policy=NeighborhoodPolicy.Radius(2),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2)
self.assertListEqual(arms, [3, 1, 1, 3, 1, 3, 3, 1, 3, 1])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
neighborhood_policy=NeighborhoodPolicy.Radius(2),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=-1)
self.assertListEqual(arms, [3, 1, 1, 3, 1, 3, 3, 1, 3, 1])
def test_thompson_n3(self):
rng = np.random.RandomState(seed=7)
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
neighborhood_policy=NeighborhoodPolicy.Clusters(3),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=1)
self.assertListEqual(arms, [1, 2, 3, 3, 2, 1, 3, 1, 1, 3])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
neighborhood_policy=NeighborhoodPolicy.Clusters(3),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2)
self.assertListEqual(arms, [3, 1, 1, 2, 1, 1, 1, 1, 1, 3])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
neighborhood_policy=NeighborhoodPolicy.Clusters(3),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=-1)
self.assertListEqual(arms, [3, 2, 3, 2, 2, 2, 3, 3, 2, 3])
def test_thompson_a2(self):
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
neighborhood_policy=NeighborhoodPolicy.LSHNearest(),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=1)
self.assertListEqual(arms, [3, 1, 2, 2, 2, 3, 1, 2, 3, 1])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
neighborhood_policy=NeighborhoodPolicy.LSHNearest(),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2)
self.assertListEqual(arms, [3, 1, 2, 2, 2, 3, 1, 2, 3, 1])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.ThompsonSampling(),
neighborhood_policy=NeighborhoodPolicy.LSHNearest(),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=-1)
self.assertListEqual(arms, [3, 1, 2, 2, 2, 3, 1, 2, 3, 1])
def test_linUCB(self):
rng = np.random.RandomState(seed=111)
contexts = rng.randint(0, 5, (10, 5))
arm, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinUCB(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=True,
n_jobs=1)
self.assertEqual(arm, [4, 4, 3, 3, 4, 4, 4, 3, 4, 3])
arm, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinUCB(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2)
self.assertEqual(arm, [4, 4, 3, 3, 4, 4, 4, 3, 4, 3])
arm, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinUCB(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=True,
n_jobs=-1)
self.assertEqual(arm, [4, 4, 3, 3, 4, 4, 4, 3, 4, 3])
def test_linUCB_expectations(self):
rng = np.random.RandomState(seed=111)
contexts = rng.randint(0, 5, (8, 5))
expected_pred = [[1.1923304881612438, 0.386812974778054, 2.036795075137375],
[1.1383448695075555, 0.16604895162348998, 0.7454336659862624],
[0.39044990078495967, 0.32572728761335573, 1.0533787080477959],
[-0.9557496857893883, 0.4393900133310143, 1.4663248923093817],
[-0.4630963822269796, 0.44282983853389307, 1.4430098512988918],
[0.26667599463140623, 0.34807480426506293, 1.008245109800643],
[1.3255310649960248, 0.43761043197507354, 0.9787023941693738],
[0.33267910305673676, 0.29690114350965546, 1.460951676645638]]
exps, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinUCB(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=False,
n_jobs=1)
for i in range(len(expected_pred)):
self.assertListAlmostEqual(exps[i].values(), expected_pred[i])
exps, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinUCB(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=False,
n_jobs=2)
for i in range(len(expected_pred)):
self.assertListAlmostEqual(exps[i].values(), expected_pred[i])
exps, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinUCB(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=False,
n_jobs=-1)
for i in range(len(expected_pred)):
self.assertListAlmostEqual(exps[i].values(), expected_pred[i])
def test_linTS(self):
rng = np.random.RandomState(seed=111)
contexts = rng.randint(0, 5, (10, 5))
arm, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinTS(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=True,
n_jobs=1)
self.assertEqual(arm, [4, 4, 3, 3, 4, 4, 4, 3, 4, 5])
arm, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinTS(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2)
self.assertEqual(arm, [4, 4, 3, 3, 4, 4, 4, 3, 4, 5])
arm, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinTS(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=True,
n_jobs=-1)
self.assertEqual(arm, [4, 4, 3, 3, 4, 4, 4, 3, 4, 5])
def test_linTS_expectations(self):
rng = np.random.RandomState(seed=111)
contexts = rng.randint(0, 5, (5, 5))
expected_pred = [[0.9167267352065508, 0.6800548963827412, 1.4147481760827891,
2.061680527026926, -0.6516833696912612],
[0.8104296620172513, 0.26691232761493117, 0.6503604017431508,
0.9977263420741849, -0.6447229745688157],
[-0.009581460000014294, 0.881059511216882, 1.0576520008395551,
0.4150322121520029, -0.26918983719229994],
[-0.38164469675190177, -0.3264960369736939, 1.3695993885284545,
0.55178010066725, 0.021790663220199458],
[-1.2613045626465647, -0.7305818793806982, 0.41438283892450944,
0.5208181269433911, -0.2673124934389858]]
exps, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinTS(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=False,
n_jobs=1)
for i in range(len(expected_pred)):
self.assertListAlmostEqual(exps[i].values(), expected_pred[i])
exps, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinTS(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=False,
n_jobs=2)
for i in range(len(expected_pred)):
self.assertListAlmostEqual(exps[i].values(), expected_pred[i])
exps, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinTS(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=False,
n_jobs=-1)
for i in range(len(expected_pred)):
self.assertListAlmostEqual(exps[i].values(), expected_pred[i])
def test_UCB1_c2_backend(self):
rng = np.random.RandomState(seed=111)
contexts_history = rng.randint(0, 5, (10, 5))
contexts = rng.randint(0, 5, (10, 5))
arm, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4],
rewards=[1, 0, 0, 1, 0, 0, 1, 0, 0, 0],
learning_policy=LearningPolicy.UCB1(alpha=0.1),
neighborhood_policy=NeighborhoodPolicy.Clusters(2),
context_history=contexts_history,
contexts=contexts,
seed=123456,
num_run=5,
is_predict=True,
n_jobs=2,
backend=None)
self.assertEqual(arm, [[3, 3, 1, 1, 1, 1, 3, 1, 3, 3] for _ in range(5)])
arm, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4],
rewards=[1, 0, 0, 1, 0, 0, 1, 0, 0, 0],
learning_policy=LearningPolicy.UCB1(alpha=0.1),
neighborhood_policy=NeighborhoodPolicy.Clusters(2),
context_history=contexts_history,
contexts=contexts,
seed=123456,
num_run=5,
is_predict=True,
n_jobs=2,
backend='loky')
self.assertEqual(arm, [[3, 3, 1, 1, 1, 1, 3, 1, 3, 3] for _ in range(5)])
arm, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4],
rewards=[1, 0, 0, 1, 0, 0, 1, 0, 0, 0],
learning_policy=LearningPolicy.UCB1(alpha=0.1),
neighborhood_policy=NeighborhoodPolicy.Clusters(2),
context_history=contexts_history,
contexts=contexts,
seed=123456,
num_run=5,
is_predict=True,
n_jobs=2,
backend='threading')
self.assertEqual(arm, [[3, 3, 1, 1, 1, 1, 3, 1, 3, 3] for _ in range(5)])
def test_greedy1_k2_backend(self):
rng = np.random.RandomState(seed=7)
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.KNearest(2),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2,
backend=None)
self.assertListEqual(arms, [2, 1, 1, 2, 3, 3, 3, 1, 3, 2])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.KNearest(2),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2,
backend='loky')
self.assertListEqual(arms, [2, 1, 1, 2, 3, 3, 3, 1, 3, 2])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.KNearest(2),
context_history=[[rng.random_sample() for _ in range(5)] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2,
backend='threading')
self.assertListEqual(arms, [2, 1, 1, 2, 3, 3, 3, 1, 3, 2])
def test_greedy1_r2_backend(self):
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.Radius(2),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2,
backend=None)
self.assertListEqual(arms, [3, 1, 1, 3, 1, 3, 3, 1, 3, 1])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.Radius(2),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2,
backend='loky')
self.assertListEqual(arms, [3, 1, 1, 3, 1, 3, 3, 1, 3, 1])
arms, mab = self.predict(arms=[1, 2, 3],
decisions=[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
rewards=[1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=1),
neighborhood_policy=NeighborhoodPolicy.Radius(2),
context_history=[[0, 0, 0, 0, 0] for _ in range(10)],
contexts=[[1, 1, 1, 1, 1] for _ in range(10)],
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2,
backend='threading')
self.assertListEqual(arms, [3, 1, 1, 3, 1, 3, 3, 1, 3, 1])
def test_linUCB_backend(self):
rng = np.random.RandomState(seed=111)
contexts = rng.randint(0, 5, (10, 5))
arm, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinUCB(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=True,
n_jobs=1,
backend=None)
self.assertEqual(arm, [4, 4, 3, 3, 4, 4, 4, 3, 4, 3])
arm, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinUCB(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2,
backend=None)
self.assertEqual(arm, [4, 4, 3, 3, 4, 4, 4, 3, 4, 3])
arm, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinUCB(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2,
backend='loky')
self.assertEqual(arm, [4, 4, 3, 3, 4, 4, 4, 3, 4, 3])
arm, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinUCB(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2,
backend='threading')
self.assertEqual(arm, [4, 4, 3, 3, 4, 4, 4, 3, 4, 3])
def test_linTS_backend(self):
rng = np.random.RandomState(seed=111)
contexts = rng.randint(0, 5, (10, 5))
arm, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinTS(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2,
backend=None)
self.assertEqual(arm, [4, 4, 3, 3, 4, 4, 4, 3, 4, 5])
arm, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinTS(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2,
backend='loky')
self.assertEqual(arm, [4, 4, 3, 3, 4, 4, 4, 3, 4, 5])
arm, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=[1, 1, 4, 2, 2, 2, 3, 3, 3, 1],
rewards=[0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
learning_policy=LearningPolicy.LinTS(alpha=0.1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=contexts,
seed=123456,
num_run=1,
is_predict=True,
n_jobs=2,
backend='threading')
self.assertEqual(arm, [4, 4, 3, 3, 4, 4, 4, 3, 4, 5])
| [
"mabwiser.mab.NeighborhoodPolicy.KNearest",
"mabwiser.mab.LearningPolicy.UCB1",
"mabwiser.mab.NeighborhoodPolicy.Clusters",
"mabwiser.mab.LearningPolicy.LinUCB",
"mabwiser.mab.LearningPolicy.Popularity",
"mabwiser.mab.LearningPolicy.ThompsonSampling",
"mabwiser.mab.NeighborhoodPolicy.Radius",
"mabwise... | [((9655, 9686), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(111)'}), '(seed=111)\n', (9676, 9686), True, 'import numpy as np\n'), ((12061, 12090), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(7)'}), '(seed=7)\n', (12082, 12090), True, 'import numpy as np\n'), ((16983, 17012), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(7)'}), '(seed=7)\n', (17004, 17012), True, 'import numpy as np\n'), ((19505, 19534), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(7)'}), '(seed=7)\n', (19526, 19534), True, 'import numpy as np\n'), ((26803, 26832), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(7)'}), '(seed=7)\n', (26824, 26832), True, 'import numpy as np\n'), ((31697, 31728), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(111)'}), '(seed=111)\n', (31718, 31728), True, 'import numpy as np\n'), ((34661, 34692), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(111)'}), '(seed=111)\n', (34682, 34692), True, 'import numpy as np\n'), ((38514, 38545), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(111)'}), '(seed=111)\n', (38535, 38545), True, 'import numpy as np\n'), ((41474, 41505), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(111)'}), '(seed=111)\n', (41495, 41505), True, 'import numpy as np\n'), ((45422, 45453), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(111)'}), '(seed=111)\n', (45443, 45453), True, 'import numpy as np\n'), ((47978, 48007), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(7)'}), '(seed=7)\n', (47999, 48007), True, 'import numpy as np\n'), ((53210, 53241), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(111)'}), '(seed=111)\n', (53231, 53241), True, 'import numpy as np\n'), ((57303, 57334), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(111)'}), '(seed=111)\n', (57324, 57334), True, 'import numpy as np\n'), ((446, 485), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(0)'}), '(epsilon=0)\n', (474, 485), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((957, 996), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(0)'}), '(epsilon=0)\n', (985, 996), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((1468, 1507), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(0)'}), '(epsilon=0)\n', (1496, 1507), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((2011, 2038), 'mabwiser.mab.LearningPolicy.Popularity', 'LearningPolicy.Popularity', ([], {}), '()\n', (2036, 2038), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((2510, 2537), 'mabwiser.mab.LearningPolicy.Popularity', 'LearningPolicy.Popularity', ([], {}), '()\n', (2535, 2537), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((3009, 3036), 'mabwiser.mab.LearningPolicy.Popularity', 'LearningPolicy.Popularity', ([], {}), '()\n', (3034, 3036), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((3539, 3581), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(0.25)'}), '(epsilon=0.25)\n', (3567, 3581), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((4053, 4095), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(0.25)'}), '(epsilon=0.25)\n', (4081, 4095), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((4567, 4609), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(0.25)'}), '(epsilon=0.25)\n', (4595, 4609), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((5115, 5156), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(0.9)'}), '(epsilon=0.9)\n', (5143, 5156), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((5637, 5678), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(0.9)'}), '(epsilon=0.9)\n', (5665, 5678), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((6159, 6200), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(0.9)'}), '(epsilon=0.9)\n', (6187, 6200), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((6716, 6746), 'mabwiser.mab.LearningPolicy.UCB1', 'LearningPolicy.UCB1', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (6735, 6746), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((7227, 7257), 'mabwiser.mab.LearningPolicy.UCB1', 'LearningPolicy.UCB1', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (7246, 7257), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((7738, 7768), 'mabwiser.mab.LearningPolicy.UCB1', 'LearningPolicy.UCB1', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (7757, 7768), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((8282, 8315), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (8313, 8315), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((8808, 8841), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (8839, 8841), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((9334, 9367), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (9365, 9367), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((10033, 10063), 'mabwiser.mab.LearningPolicy.UCB1', 'LearningPolicy.UCB1', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (10052, 10063), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((10117, 10147), 'mabwiser.mab.NeighborhoodPolicy.Clusters', 'NeighborhoodPolicy.Clusters', (['(2)'], {}), '(2)\n', (10144, 10147), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((10775, 10805), 'mabwiser.mab.LearningPolicy.UCB1', 'LearningPolicy.UCB1', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (10794, 10805), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((10859, 10889), 'mabwiser.mab.NeighborhoodPolicy.Clusters', 'NeighborhoodPolicy.Clusters', (['(2)'], {}), '(2)\n', (10886, 10889), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((11517, 11547), 'mabwiser.mab.LearningPolicy.UCB1', 'LearningPolicy.UCB1', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (11536, 11547), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((11601, 11631), 'mabwiser.mab.NeighborhoodPolicy.Clusters', 'NeighborhoodPolicy.Clusters', (['(2)'], {}), '(2)\n', (11628, 11631), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((12338, 12377), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (12366, 12377), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((12432, 12462), 'mabwiser.mab.NeighborhoodPolicy.KNearest', 'NeighborhoodPolicy.KNearest', (['(2)'], {}), '(2)\n', (12459, 12462), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((13153, 13192), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (13181, 13192), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((13247, 13277), 'mabwiser.mab.NeighborhoodPolicy.KNearest', 'NeighborhoodPolicy.KNearest', (['(2)'], {}), '(2)\n', (13274, 13277), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((13968, 14007), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (13996, 14007), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((14062, 14092), 'mabwiser.mab.NeighborhoodPolicy.KNearest', 'NeighborhoodPolicy.KNearest', (['(2)'], {}), '(2)\n', (14089, 14092), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((14816, 14855), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (14844, 14855), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((14910, 14938), 'mabwiser.mab.NeighborhoodPolicy.Radius', 'NeighborhoodPolicy.Radius', (['(2)'], {}), '(2)\n', (14935, 14938), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((15605, 15644), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (15633, 15644), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((15699, 15727), 'mabwiser.mab.NeighborhoodPolicy.Radius', 'NeighborhoodPolicy.Radius', (['(2)'], {}), '(2)\n', (15724, 15727), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((16394, 16433), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (16422, 16433), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((16488, 16516), 'mabwiser.mab.NeighborhoodPolicy.Radius', 'NeighborhoodPolicy.Radius', (['(2)'], {}), '(2)\n', (16513, 16516), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((17260, 17299), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (17288, 17299), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((17354, 17384), 'mabwiser.mab.NeighborhoodPolicy.Clusters', 'NeighborhoodPolicy.Clusters', (['(3)'], {}), '(3)\n', (17381, 17384), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((18075, 18114), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (18103, 18114), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((18169, 18199), 'mabwiser.mab.NeighborhoodPolicy.Clusters', 'NeighborhoodPolicy.Clusters', (['(3)'], {}), '(3)\n', (18196, 18199), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((18890, 18929), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (18918, 18929), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((18984, 19014), 'mabwiser.mab.NeighborhoodPolicy.Clusters', 'NeighborhoodPolicy.Clusters', (['(3)'], {}), '(3)\n', (19011, 19014), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((19782, 19821), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (19810, 19821), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((19876, 19907), 'mabwiser.mab.NeighborhoodPolicy.LSHNearest', 'NeighborhoodPolicy.LSHNearest', ([], {}), '()\n', (19905, 19907), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((20598, 20637), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (20626, 20637), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((20692, 20723), 'mabwiser.mab.NeighborhoodPolicy.LSHNearest', 'NeighborhoodPolicy.LSHNearest', ([], {}), '()\n', (20721, 20723), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((21414, 21453), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (21442, 21453), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((21508, 21539), 'mabwiser.mab.NeighborhoodPolicy.LSHNearest', 'NeighborhoodPolicy.LSHNearest', ([], {}), '()\n', (21537, 21539), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((22264, 22297), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (22295, 22297), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((22352, 22382), 'mabwiser.mab.NeighborhoodPolicy.KNearest', 'NeighborhoodPolicy.KNearest', (['(2)'], {}), '(2)\n', (22379, 22382), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((23049, 23082), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (23080, 23082), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((23137, 23167), 'mabwiser.mab.NeighborhoodPolicy.KNearest', 'NeighborhoodPolicy.KNearest', (['(2)'], {}), '(2)\n', (23164, 23167), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((23834, 23867), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (23865, 23867), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((23922, 23952), 'mabwiser.mab.NeighborhoodPolicy.KNearest', 'NeighborhoodPolicy.KNearest', (['(2)'], {}), '(2)\n', (23949, 23952), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((24653, 24686), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (24684, 24686), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((24741, 24769), 'mabwiser.mab.NeighborhoodPolicy.Radius', 'NeighborhoodPolicy.Radius', (['(2)'], {}), '(2)\n', (24766, 24769), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((25436, 25469), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (25467, 25469), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((25524, 25552), 'mabwiser.mab.NeighborhoodPolicy.Radius', 'NeighborhoodPolicy.Radius', (['(2)'], {}), '(2)\n', (25549, 25552), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((26219, 26252), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (26250, 26252), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((26307, 26335), 'mabwiser.mab.NeighborhoodPolicy.Radius', 'NeighborhoodPolicy.Radius', (['(2)'], {}), '(2)\n', (26332, 26335), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((27080, 27113), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (27111, 27113), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((27168, 27198), 'mabwiser.mab.NeighborhoodPolicy.Clusters', 'NeighborhoodPolicy.Clusters', (['(3)'], {}), '(3)\n', (27195, 27198), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((27889, 27922), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (27920, 27922), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((27977, 28007), 'mabwiser.mab.NeighborhoodPolicy.Clusters', 'NeighborhoodPolicy.Clusters', (['(3)'], {}), '(3)\n', (28004, 28007), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((28698, 28731), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (28729, 28731), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((28786, 28816), 'mabwiser.mab.NeighborhoodPolicy.Clusters', 'NeighborhoodPolicy.Clusters', (['(3)'], {}), '(3)\n', (28813, 28816), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((29541, 29574), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (29572, 29574), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((29629, 29660), 'mabwiser.mab.NeighborhoodPolicy.LSHNearest', 'NeighborhoodPolicy.LSHNearest', ([], {}), '()\n', (29658, 29660), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((30327, 30360), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (30358, 30360), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((30415, 30446), 'mabwiser.mab.NeighborhoodPolicy.LSHNearest', 'NeighborhoodPolicy.LSHNearest', ([], {}), '()\n', (30444, 30446), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((31113, 31146), 'mabwiser.mab.LearningPolicy.ThompsonSampling', 'LearningPolicy.ThompsonSampling', ([], {}), '()\n', (31144, 31146), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((31201, 31232), 'mabwiser.mab.NeighborhoodPolicy.LSHNearest', 'NeighborhoodPolicy.LSHNearest', ([], {}), '()\n', (31230, 31232), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((32024, 32056), 'mabwiser.mab.LearningPolicy.LinUCB', 'LearningPolicy.LinUCB', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (32045, 32056), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((32967, 32999), 'mabwiser.mab.LearningPolicy.LinUCB', 'LearningPolicy.LinUCB', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (32988, 32999), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((33910, 33942), 'mabwiser.mab.LearningPolicy.LinUCB', 'LearningPolicy.LinUCB', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (33931, 33942), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((35694, 35726), 'mabwiser.mab.LearningPolicy.LinUCB', 'LearningPolicy.LinUCB', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (35715, 35726), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((36702, 36734), 'mabwiser.mab.LearningPolicy.LinUCB', 'LearningPolicy.LinUCB', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (36723, 36734), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((37710, 37742), 'mabwiser.mab.LearningPolicy.LinUCB', 'LearningPolicy.LinUCB', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (37731, 37742), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((38841, 38872), 'mabwiser.mab.LearningPolicy.LinTS', 'LearningPolicy.LinTS', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (38861, 38872), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((39783, 39814), 'mabwiser.mab.LearningPolicy.LinTS', 'LearningPolicy.LinTS', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (39803, 39814), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((40725, 40756), 'mabwiser.mab.LearningPolicy.LinTS', 'LearningPolicy.LinTS', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (40745, 40756), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((42583, 42614), 'mabwiser.mab.LearningPolicy.LinTS', 'LearningPolicy.LinTS', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (42603, 42614), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((43596, 43627), 'mabwiser.mab.LearningPolicy.LinTS', 'LearningPolicy.LinTS', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (43616, 43627), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((44610, 44641), 'mabwiser.mab.LearningPolicy.LinTS', 'LearningPolicy.LinTS', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (44630, 44641), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((45800, 45830), 'mabwiser.mab.LearningPolicy.UCB1', 'LearningPolicy.UCB1', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (45819, 45830), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((45884, 45914), 'mabwiser.mab.NeighborhoodPolicy.Clusters', 'NeighborhoodPolicy.Clusters', (['(2)'], {}), '(2)\n', (45911, 45914), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((46587, 46617), 'mabwiser.mab.LearningPolicy.UCB1', 'LearningPolicy.UCB1', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (46606, 46617), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((46671, 46701), 'mabwiser.mab.NeighborhoodPolicy.Clusters', 'NeighborhoodPolicy.Clusters', (['(2)'], {}), '(2)\n', (46698, 46701), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((47376, 47406), 'mabwiser.mab.LearningPolicy.UCB1', 'LearningPolicy.UCB1', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (47395, 47406), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((47460, 47490), 'mabwiser.mab.NeighborhoodPolicy.Clusters', 'NeighborhoodPolicy.Clusters', (['(2)'], {}), '(2)\n', (47487, 47490), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((48255, 48294), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (48283, 48294), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((48349, 48379), 'mabwiser.mab.NeighborhoodPolicy.KNearest', 'NeighborhoodPolicy.KNearest', (['(2)'], {}), '(2)\n', (48376, 48379), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((49117, 49156), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (49145, 49156), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((49211, 49241), 'mabwiser.mab.NeighborhoodPolicy.KNearest', 'NeighborhoodPolicy.KNearest', (['(2)'], {}), '(2)\n', (49238, 49241), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((49981, 50020), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (50009, 50020), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((50075, 50105), 'mabwiser.mab.NeighborhoodPolicy.KNearest', 'NeighborhoodPolicy.KNearest', (['(2)'], {}), '(2)\n', (50102, 50105), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((50889, 50928), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (50917, 50928), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((50983, 51011), 'mabwiser.mab.NeighborhoodPolicy.Radius', 'NeighborhoodPolicy.Radius', (['(2)'], {}), '(2)\n', (51008, 51011), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((51725, 51764), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (51753, 51764), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((51819, 51847), 'mabwiser.mab.NeighborhoodPolicy.Radius', 'NeighborhoodPolicy.Radius', (['(2)'], {}), '(2)\n', (51844, 51847), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((52563, 52602), 'mabwiser.mab.LearningPolicy.EpsilonGreedy', 'LearningPolicy.EpsilonGreedy', ([], {'epsilon': '(1)'}), '(epsilon=1)\n', (52591, 52602), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((52657, 52685), 'mabwiser.mab.NeighborhoodPolicy.Radius', 'NeighborhoodPolicy.Radius', (['(2)'], {}), '(2)\n', (52682, 52685), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((53537, 53569), 'mabwiser.mab.LearningPolicy.LinUCB', 'LearningPolicy.LinUCB', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (53558, 53569), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((54526, 54558), 'mabwiser.mab.LearningPolicy.LinUCB', 'LearningPolicy.LinUCB', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (54547, 54558), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((55515, 55547), 'mabwiser.mab.LearningPolicy.LinUCB', 'LearningPolicy.LinUCB', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (55536, 55547), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((56506, 56538), 'mabwiser.mab.LearningPolicy.LinUCB', 'LearningPolicy.LinUCB', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (56527, 56538), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((57630, 57661), 'mabwiser.mab.LearningPolicy.LinTS', 'LearningPolicy.LinTS', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (57650, 57661), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((58618, 58649), 'mabwiser.mab.LearningPolicy.LinTS', 'LearningPolicy.LinTS', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (58638, 58649), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n'), ((59608, 59639), 'mabwiser.mab.LearningPolicy.LinTS', 'LearningPolicy.LinTS', ([], {'alpha': '(0.1)'}), '(alpha=0.1)\n', (59628, 59639), False, 'from mabwiser.mab import LearningPolicy, NeighborhoodPolicy\n')] |
# -*- coding: utf-8 -*-
import argparse
import logging
import random
from collections import Counter
import math
import numpy as np
import pandas as pd
import torch
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
from pytorch_lightning.core.lightning import LightningModule
from torch.utils.data import DataLoader, Dataset
from torch.utils.tensorboard import SummaryWriter
from transformers.optimization import AdamW, get_cosine_schedule_with_warmup
from transformers import PreTrainedTokenizerFast, GPT2LMHeadModel
parser = argparse.ArgumentParser(description='Simsimi based on KoGPT-2')
parser.add_argument('--chat',
action='store_true',
default=False,
help='response generation on given user input')
parser.add_argument('--sentiment',
type=str,
default='0',
help='sentiment for system. 0 is neutral, 1 is negative, 2 is positive.')
parser.add_argument('--model_params',
type=str,
default='model_chp/model_-last.ckpt',
help='model binary for starting chat')
parser.add_argument('--train',
action='store_true',
default=False,
help='for training')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
U_TKN = '<usr>'
S_TKN = '<sys>'
BOS = '</s>'
EOS = '</s>'
MASK = '<unused0>'
SENT = '<unused1>'
PAD = '<pad>'
TOKENIZER = PreTrainedTokenizerFast.from_pretrained("skt/kogpt2-base-v2",
bos_token=BOS, eos_token=EOS, unk_token='<unk>',
pad_token=PAD, mask_token=MASK)
class CharDataset(Dataset):
def __init__(self, chats, max_len=32):
self._data = chats
self.first = True
self.q_token = U_TKN
self.a_token = S_TKN
self.sent_token = SENT
self.bos = BOS
self.eos = EOS
self.mask = MASK
self.pad = PAD
self.max_len = max_len
self.tokenizer = TOKENIZER
def __len__(self):
return len(self._data)
def __getitem__(self, idx):
turn = self._data.iloc[idx]
q = turn['Q']
a = turn['A']
sentiment = str(turn['label'])
q_toked = self.tokenizer.tokenize(self.q_token + q + \
self.sent_token + sentiment)
q_len = len(q_toked)
#print(type(q_len)) -> labels 안에 담기는 값 추적하기1
a_toked = self.tokenizer.tokenize(self.a_token + a + self.eos)
a_len = len(a_toked)
if q_len + a_len > self.max_len:
a_len = self.max_len - q_len
if a_len <= 0:
q_toked = q_toked[-(int(self.max_len/2)):]
q_len = len(q_toked)
a_len = self.max_len - q_len
assert a_len > 0
a_toked = a_toked[:a_len]
a_len = len(a_toked)
assert a_len == len(a_toked), f'{a_len} ==? {len(a_toked)}'
# [mask, mask, ...., mask, ..., <bos>,..A.. <eos>, <pad>....]
labels = [
self.mask,
] * q_len + a_toked[1:]
if self.first:
logging.info("contexts : {}".format(q))
logging.info("toked ctx: {}".format(q_toked))
logging.info("response : {}".format(a))
logging.info("toked response : {}".format(a_toked))
logging.info('labels {}'.format(labels))
self.first = False
mask = [0] * q_len + [1] * a_len + [0] * (self.max_len - q_len - a_len)
self.max_len
labels_ids = self.tokenizer.convert_tokens_to_ids(labels)
while len(labels_ids) < self.max_len:
labels_ids += [self.tokenizer.pad_token_id]
token_ids = self.tokenizer.convert_tokens_to_ids(q_toked + a_toked)
while len(token_ids) < self.max_len:
token_ids += [self.tokenizer.pad_token_id]
return(token_ids, np.array(mask),
labels_ids)
class KoGPT2Chat(LightningModule):
def __init__(self, hparams, **kwargs):
super(KoGPT2Chat, self).__init__()
self.hparams = hparams
self.neg = -1e18
self.kogpt2 = GPT2LMHeadModel.from_pretrained('skt/kogpt2-base-v2')
self.loss_function = torch.nn.CrossEntropyLoss(reduction='none')
@staticmethod
def add_model_specific_args(parent_parser):
# add model specific args
parser = argparse.ArgumentParser(parents=[parent_parser], add_help=False)
parser.add_argument('--max-len',
type=int,
default=100,
help='max sentence length on input (default: 32)')
parser.add_argument('--batch-size',
type=int,
default=32,
help='batch size for training (default: 96)')
parser.add_argument('--lr',
type=float,
default=5e-5,
help='The initial learning rate')
parser.add_argument('--warmup_ratio',
type=float,
default=0.1,
help='warmup ratio')
return parser
def forward(self, inputs):
# (batch, seq_len, hiddens)
output = self.kogpt2(inputs, return_dict=True)
return output.logits
def training_step(self, batch, batch_idx):
token_ids, mask, label = batch
out = self(token_ids)
mask_3d = mask.unsqueeze(dim=2).repeat_interleave(repeats=out.shape[2], dim=2)
mask_out = torch.where(mask_3d == 1, out, self.neg * torch.ones_like(out))
loss = self.loss_function(mask_out.transpose(2, 1), label)
loss_avg = loss.sum() / mask.sum()
ppl=torch.exp(loss)
ppl_avg = ppl.sum() / mask.sum()
self.log('train_loss', loss_avg, on_step=True, on_epoch=True)
self.log('train_ppl', ppl_avg, on_step=True, on_epoch=True)
tensorboard_logs = {'train_loss':loss_avg,'train_ppl':ppl_avg}
return {'loss':loss_avg, 'train_ppl':ppl_avg, 'log':tensorboard_logs}
def training_epoch_end(self, outputs):
avg_loss = torch.stack([x['loss'] for x in outputs]).mean()
avg_ppl = torch.stack([x['train_ppl'] for x in outputs]).mean()
self.logger.experiment.add_scalar("Loss/Train",avg_loss,self.current_epoch)
self.logger.experiment.add_scalar("PPL/Train",avg_ppl,self.current_epoch)
def validation_step(self, batch, batch_idx):
token_ids, mask, label = batch
out = self(token_ids)
mask_3d = mask.unsqueeze(dim=2).repeat_interleave(repeats=out.shape[2], dim=2)
mask_out = torch.where(mask_3d == 1, out, self.neg * torch.ones_like(out))
val_loss = self.loss_function(mask_out.transpose(2, 1), label)
loss_avg = val_loss.sum() / mask.sum()
ppl=torch.exp(val_loss)
ppl_avg = ppl.sum() / mask.sum()
self.log('val_loss', loss_avg, on_step=True, on_epoch=True)
self.log('val_ppl', ppl_avg, on_step=True, on_epoch=True)
tensorboard_logs = {'val_loss':loss_avg,'val_ppl':ppl_avg}
# return loss_avg
return {'loss':loss_avg, 'val_ppl':ppl_avg, 'log':tensorboard_logs}
def validation_epoch_end(self, outputs):
avg_loss = torch.stack([x['loss'] for x in outputs]).mean()
avg_ppl = torch.stack([x['val_ppl'] for x in outputs]).mean()
self.logger.experiment.add_scalar("Loss/Val",avg_loss,self.current_epoch)
self.logger.experiment.add_scalar("PPL/Val",avg_ppl,self.current_epoch)
def configure_optimizers(self):
# Prepare optimizer
param_optimizer = list(self.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
{'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
optimizer = AdamW(optimizer_grouped_parameters,
lr=self.hparams.lr, correct_bias=False)
# warm up lr
num_train_steps = len(self.train_dataloader()) * self.hparams.max_epochs
num_warmup_steps = int(num_train_steps * self.hparams.warmup_ratio)
scheduler = get_cosine_schedule_with_warmup(
optimizer,
num_warmup_steps=num_warmup_steps, num_training_steps=num_train_steps)
lr_scheduler = {'scheduler': scheduler, 'name': 'cosine_schedule_with_warmup',
'monitor': 'loss', 'interval': 'step',
'frequency': 1}
return [optimizer], [lr_scheduler]
def _collate_fn(self, batch):
data = [item[0] for item in batch]
mask = [item[1] for item in batch]
label = [item[2] for item in batch]
return torch.LongTensor(data), torch.LongTensor(mask), torch.LongTensor(label)
def train_dataloader(self):
data = pd.read_csv('data/SDRW_long.csv')
train_len = int(0.9*len(data))
data = data.loc[0:train_len]
self.train_set = CharDataset(data, max_len=self.hparams.max_len)
train_dataloader = DataLoader(
self.train_set, batch_size=self.hparams.batch_size, num_workers=2,
shuffle=True, collate_fn=self._collate_fn)
return train_dataloader
def val_dataloader(self):
data = pd.read_csv('data/SDRW_long.csv')
train_len = int(0.9*len(data))
data = data.loc[train_len:]
self.val_set = CharDataset(data, max_len=self.hparams.max_len)
val_dataloader = DataLoader(
self.val_set, batch_size=self.hparams.batch_size, num_workers=2,
shuffle=True, collate_fn=self._collate_fn)
return val_dataloader
def generate(self,input_ids,max_length=40, do_sample=True, repetition_penalty=2.0):
output = self.kogpt2.generate(input_ids,
max_length=max_length,
do_sample=do_sample,
repetition_penalty=repetition_penalty)
return output
def chat(self,m, sent='0'):
tok = TOKENIZER
with torch.no_grad():
while 1:
q = input('user > ').strip()
if q == 'quit':
break
input_ids = torch.LongTensor(tok.encode(U_TKN + q + SENT + sent + S_TKN)).unsqueeze(dim=0)
outputs = m.generate(input_ids,
max_length=60,
do_sample=True,
repetition_penalty=2.0)
a = tok.decode(outputs[0], skip_special_tokens=True).split('0')[1:][0].strip()
if a.count('.') == 0:
idx = a.rfind(' ')
a = a.replace(a[idx:], ".")
else:
a = a.split('.')[0] + '.' + a.split('.')[1] + '...메에'
print("Wagle > {}".format(a.strip()))
parser = KoGPT2Chat.add_model_specific_args(parser)
parser = Trainer.add_argparse_args(parser)
args = parser.parse_args()
logging.info(args)
if __name__ == "__main__":
if args.train:
checkpoint_callback = ModelCheckpoint(
dirpath='model_chp',
filename='{epoch:02d}-{train_loss:.2f}',
verbose=True,
save_top_k=3,
save_last=True,
monitor='train_loss',
mode='min',
prefix='model_'
)
# python train_torch.py --train --gpus 1 --max_epochs 3
model = KoGPT2Chat(args)
model.train()
# trainer = Trainer(resume_from_checkpoint='model_chp/model_-last.ckpt', gpus=[0], checkpoint_callback=checkpoint_callback, gradient_clip_val=1.0)
trainer = Trainer.from_argparse_args(
args,
checkpoint_callback=checkpoint_callback, gradient_clip_val=1.0)
trainer.fit(model)
logging.info('best model path {}'.format(checkpoint_callback.best_model_path))
#after training init cuda
# torch.cuda.init() # cuda 초기화
# torch.cuda.empty_cache() # 사용중이 아닌 cuda 캐시메모리 해제
if args.chat:
model = KoGPT2Chat.load_from_checkpoint(args.model_params)
model.chat(m=model)
| [
"logging.getLogger",
"torch.nn.CrossEntropyLoss",
"pandas.read_csv",
"torch.LongTensor",
"torch.exp",
"numpy.array",
"transformers.GPT2LMHeadModel.from_pretrained",
"pytorch_lightning.Trainer.from_argparse_args",
"logging.info",
"pytorch_lightning.callbacks.ModelCheckpoint",
"pytorch_lightning.T... | [((588, 651), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Simsimi based on KoGPT-2"""'}), "(description='Simsimi based on KoGPT-2')\n", (611, 651), False, 'import argparse\n'), ((1365, 1384), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (1382, 1384), False, 'import logging\n'), ((1539, 1685), 'transformers.PreTrainedTokenizerFast.from_pretrained', 'PreTrainedTokenizerFast.from_pretrained', (['"""skt/kogpt2-base-v2"""'], {'bos_token': 'BOS', 'eos_token': 'EOS', 'unk_token': '"""<unk>"""', 'pad_token': 'PAD', 'mask_token': 'MASK'}), "('skt/kogpt2-base-v2', bos_token=BOS,\n eos_token=EOS, unk_token='<unk>', pad_token=PAD, mask_token=MASK)\n", (1578, 1685), False, 'from transformers import PreTrainedTokenizerFast, GPT2LMHeadModel\n'), ((11380, 11413), 'pytorch_lightning.Trainer.add_argparse_args', 'Trainer.add_argparse_args', (['parser'], {}), '(parser)\n', (11405, 11413), False, 'from pytorch_lightning import Trainer\n'), ((11441, 11459), 'logging.info', 'logging.info', (['args'], {}), '(args)\n', (11453, 11459), False, 'import logging\n'), ((4227, 4280), 'transformers.GPT2LMHeadModel.from_pretrained', 'GPT2LMHeadModel.from_pretrained', (['"""skt/kogpt2-base-v2"""'], {}), "('skt/kogpt2-base-v2')\n", (4258, 4280), False, 'from transformers import PreTrainedTokenizerFast, GPT2LMHeadModel\n'), ((4310, 4353), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {'reduction': '"""none"""'}), "(reduction='none')\n", (4335, 4353), False, 'import torch\n'), ((4472, 4536), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'parents': '[parent_parser]', 'add_help': '(False)'}), '(parents=[parent_parser], add_help=False)\n', (4495, 4536), False, 'import argparse\n'), ((5872, 5887), 'torch.exp', 'torch.exp', (['loss'], {}), '(loss)\n', (5881, 5887), False, 'import torch\n'), ((7010, 7029), 'torch.exp', 'torch.exp', (['val_loss'], {}), '(val_loss)\n', (7019, 7029), False, 'import torch\n'), ((8216, 8291), 'transformers.optimization.AdamW', 'AdamW', (['optimizer_grouped_parameters'], {'lr': 'self.hparams.lr', 'correct_bias': '(False)'}), '(optimizer_grouped_parameters, lr=self.hparams.lr, correct_bias=False)\n', (8221, 8291), False, 'from transformers.optimization import AdamW, get_cosine_schedule_with_warmup\n'), ((8516, 8634), 'transformers.optimization.get_cosine_schedule_with_warmup', 'get_cosine_schedule_with_warmup', (['optimizer'], {'num_warmup_steps': 'num_warmup_steps', 'num_training_steps': 'num_train_steps'}), '(optimizer, num_warmup_steps=\n num_warmup_steps, num_training_steps=num_train_steps)\n', (8547, 8634), False, 'from transformers.optimization import AdamW, get_cosine_schedule_with_warmup\n'), ((9188, 9221), 'pandas.read_csv', 'pd.read_csv', (['"""data/SDRW_long.csv"""'], {}), "('data/SDRW_long.csv')\n", (9199, 9221), True, 'import pandas as pd\n'), ((9398, 9523), 'torch.utils.data.DataLoader', 'DataLoader', (['self.train_set'], {'batch_size': 'self.hparams.batch_size', 'num_workers': '(2)', 'shuffle': '(True)', 'collate_fn': 'self._collate_fn'}), '(self.train_set, batch_size=self.hparams.batch_size, num_workers=\n 2, shuffle=True, collate_fn=self._collate_fn)\n', (9408, 9523), False, 'from torch.utils.data import DataLoader, Dataset\n'), ((9626, 9659), 'pandas.read_csv', 'pd.read_csv', (['"""data/SDRW_long.csv"""'], {}), "('data/SDRW_long.csv')\n", (9637, 9659), True, 'import pandas as pd\n'), ((9831, 9953), 'torch.utils.data.DataLoader', 'DataLoader', (['self.val_set'], {'batch_size': 'self.hparams.batch_size', 'num_workers': '(2)', 'shuffle': '(True)', 'collate_fn': 'self._collate_fn'}), '(self.val_set, batch_size=self.hparams.batch_size, num_workers=2,\n shuffle=True, collate_fn=self._collate_fn)\n', (9841, 9953), False, 'from torch.utils.data import DataLoader, Dataset\n'), ((11537, 11719), 'pytorch_lightning.callbacks.ModelCheckpoint', 'ModelCheckpoint', ([], {'dirpath': '"""model_chp"""', 'filename': '"""{epoch:02d}-{train_loss:.2f}"""', 'verbose': '(True)', 'save_top_k': '(3)', 'save_last': '(True)', 'monitor': '"""train_loss"""', 'mode': '"""min"""', 'prefix': '"""model_"""'}), "(dirpath='model_chp', filename=\n '{epoch:02d}-{train_loss:.2f}', verbose=True, save_top_k=3, save_last=\n True, monitor='train_loss', mode='min', prefix='model_')\n", (11552, 11719), False, 'from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping\n'), ((12125, 12225), 'pytorch_lightning.Trainer.from_argparse_args', 'Trainer.from_argparse_args', (['args'], {'checkpoint_callback': 'checkpoint_callback', 'gradient_clip_val': '(1.0)'}), '(args, checkpoint_callback=checkpoint_callback,\n gradient_clip_val=1.0)\n', (12151, 12225), False, 'from pytorch_lightning import Trainer\n'), ((3983, 3997), 'numpy.array', 'np.array', (['mask'], {}), '(mask)\n', (3991, 3997), True, 'import numpy as np\n'), ((9068, 9090), 'torch.LongTensor', 'torch.LongTensor', (['data'], {}), '(data)\n', (9084, 9090), False, 'import torch\n'), ((9092, 9114), 'torch.LongTensor', 'torch.LongTensor', (['mask'], {}), '(mask)\n', (9108, 9114), False, 'import torch\n'), ((9116, 9139), 'torch.LongTensor', 'torch.LongTensor', (['label'], {}), '(label)\n', (9132, 9139), False, 'import torch\n'), ((10448, 10463), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (10461, 10463), False, 'import torch\n'), ((5728, 5748), 'torch.ones_like', 'torch.ones_like', (['out'], {}), '(out)\n', (5743, 5748), False, 'import torch\n'), ((6283, 6324), 'torch.stack', 'torch.stack', (["[x['loss'] for x in outputs]"], {}), "([x['loss'] for x in outputs])\n", (6294, 6324), False, 'import torch\n'), ((6350, 6396), 'torch.stack', 'torch.stack', (["[x['train_ppl'] for x in outputs]"], {}), "([x['train_ppl'] for x in outputs])\n", (6361, 6396), False, 'import torch\n'), ((6858, 6878), 'torch.ones_like', 'torch.ones_like', (['out'], {}), '(out)\n', (6873, 6878), False, 'import torch\n'), ((7438, 7479), 'torch.stack', 'torch.stack', (["[x['loss'] for x in outputs]"], {}), "([x['loss'] for x in outputs])\n", (7449, 7479), False, 'import torch\n'), ((7505, 7549), 'torch.stack', 'torch.stack', (["[x['val_ppl'] for x in outputs]"], {}), "([x['val_ppl'] for x in outputs])\n", (7516, 7549), False, 'import torch\n')] |
#!/usr/bin/env python
import numpy
from functools import reduce
from pyscf.pbc import gto, scf
from pyscf.pbc import tools as pbctools
alat0 = 3.6
cell = gto.Cell()
cell.a = (numpy.ones((3,3))-numpy.eye(3))*alat0/2.0
cell.atom = (('C',0,0,0),('C',numpy.array([0.25,0.25,0.25])*alat0))
cell.basis = 'gth-dzvp'
cell.pseudo = 'gth-pade'
cell.gs = [10]*3
cell.verbose = 4
cell.build()
mf = scf.RHF(cell)
mf.chkfile = 'scf.gamma.dump'
ehf = mf.kernel()
from pyscf import tools
c = mf.mo_coeff
h1e = reduce(numpy.dot, (c.T, mf.get_hcore(), c))
eri = mf.with_df.ao2mo(c,compact=True)
madelung = pbctools.pbc.madelung(cell, numpy.zeros(3))
e0 = cell.energy_nuc() + madelung*cell.nelectron * -.5
tools.fcidump.from_integrals('fcidump.gamma.dat', h1e, eri, c.shape[1],
cell.nelectron, nuc = e0, ms=0, tol=1e-10)
| [
"pyscf.pbc.scf.RHF",
"numpy.eye",
"numpy.ones",
"pyscf.tools.fcidump.from_integrals",
"numpy.array",
"numpy.zeros",
"pyscf.pbc.gto.Cell"
] | [((158, 168), 'pyscf.pbc.gto.Cell', 'gto.Cell', ([], {}), '()\n', (166, 168), False, 'from pyscf.pbc import gto, scf\n'), ((393, 406), 'pyscf.pbc.scf.RHF', 'scf.RHF', (['cell'], {}), '(cell)\n', (400, 406), False, 'from pyscf.pbc import gto, scf\n'), ((700, 816), 'pyscf.tools.fcidump.from_integrals', 'tools.fcidump.from_integrals', (['"""fcidump.gamma.dat"""', 'h1e', 'eri', 'c.shape[1]', 'cell.nelectron'], {'nuc': 'e0', 'ms': '(0)', 'tol': '(1e-10)'}), "('fcidump.gamma.dat', h1e, eri, c.shape[1],\n cell.nelectron, nuc=e0, ms=0, tol=1e-10)\n", (728, 816), False, 'from pyscf import tools\n'), ((628, 642), 'numpy.zeros', 'numpy.zeros', (['(3)'], {}), '(3)\n', (639, 642), False, 'import numpy\n'), ((179, 197), 'numpy.ones', 'numpy.ones', (['(3, 3)'], {}), '((3, 3))\n', (189, 197), False, 'import numpy\n'), ((197, 209), 'numpy.eye', 'numpy.eye', (['(3)'], {}), '(3)\n', (206, 209), False, 'import numpy\n'), ((251, 282), 'numpy.array', 'numpy.array', (['[0.25, 0.25, 0.25]'], {}), '([0.25, 0.25, 0.25])\n', (262, 282), False, 'import numpy\n')] |
# coding=utf-8
import numpy as np
from bilstm_crf_add_word import BiLSTM_CRF
from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, \
TensorBoard
from keras.optimizers import Adam, Nadam
import os
# os.environ["CUDA_VISIBLE_DEVICES"] = "1"
char_embedding_mat = np.load('data/char_embedding_matrix.npy')
word_embedding_mat = np.load('data/word_embedding_matrix.npy')
# word_embedding_mat = np.random.randn(157142, 200)
X_train = np.load('data/X_train.npy')
train_add = np.load('data/word_train_add.npy') # add word_embedding
X_dev = np.load('data/X_dev.npy')
dev_add = np.load('data/word_dev_add.npy')
y_train = np.load('data/y_train.npy')
y_dev = np.load('data/y_dev.npy')
X_test = np.load('data/X_test.npy')
test_add = np.load('data/word_test_add.npy') # add word_embedding
# print(X_test, X_test.shape)
y_test = np.load('data/y_test.npy')
adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, clipvalue=0.01)
# nadam = Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, schedule_decay=0.004)
# ner_model = BiLSTM_CRF(n_input_char=200, char_embedding_mat=char_embedding_mat,
# n_input_word=200, word_embedding_mat=word_embedding_mat,
# keep_prob=0.7, n_lstm=256, keep_prob_lstm=0.6, n_entity=7,
# optimizer=adam, batch_size=32, epochs=500)
ner_model = BiLSTM_CRF(n_input_char=200, char_embedding_mat=char_embedding_mat,
n_input_word=200, word_embedding_mat=word_embedding_mat,
keep_prob=0.7, n_lstm=256, keep_prob_lstm=0.6, n_entity=7,
optimizer=adam, batch_size=32, epochs=10,
n_filter=128, kernel_size=3)
cp_folder, cp_file = 'checkpoints', 'bilstm_crf_add_word_weights_best_128.hdf5'
log_filepath = os.getcwd() + '/logs/concat_drop'
cb = [ModelCheckpoint(os.path.join(cp_folder, cp_file), monitor='val_loss',
verbose=1, save_best_only=True, save_weights_only=True, mode='min'),
EarlyStopping(monitor='val_loss', min_delta=1e-8, patience=0, mode='min'),
TensorBoard(log_dir=log_filepath, write_graph=True, write_images=True,
histogram_freq=0),
ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, mode='min',
epsilon=1e-4, cooldown=2, min_lr=1e-8)]
# ner_model.train2([X_train, train_add], y_train, [X_dev, dev_add], y_dev, cb)
ner_model.train_char_cnn_word_rnn([X_train,train_add],y_train,cb)
# print(ner_model.model2.evaluate([X_test,test_add],y_test)) | [
"keras.optimizers.Adam",
"keras.callbacks.ReduceLROnPlateau",
"os.path.join",
"os.getcwd",
"keras.callbacks.TensorBoard",
"keras.callbacks.EarlyStopping",
"bilstm_crf_add_word.BiLSTM_CRF",
"numpy.load"
] | [((291, 332), 'numpy.load', 'np.load', (['"""data/char_embedding_matrix.npy"""'], {}), "('data/char_embedding_matrix.npy')\n", (298, 332), True, 'import numpy as np\n'), ((354, 395), 'numpy.load', 'np.load', (['"""data/word_embedding_matrix.npy"""'], {}), "('data/word_embedding_matrix.npy')\n", (361, 395), True, 'import numpy as np\n'), ((459, 486), 'numpy.load', 'np.load', (['"""data/X_train.npy"""'], {}), "('data/X_train.npy')\n", (466, 486), True, 'import numpy as np\n'), ((499, 533), 'numpy.load', 'np.load', (['"""data/word_train_add.npy"""'], {}), "('data/word_train_add.npy')\n", (506, 533), True, 'import numpy as np\n'), ((564, 589), 'numpy.load', 'np.load', (['"""data/X_dev.npy"""'], {}), "('data/X_dev.npy')\n", (571, 589), True, 'import numpy as np\n'), ((600, 632), 'numpy.load', 'np.load', (['"""data/word_dev_add.npy"""'], {}), "('data/word_dev_add.npy')\n", (607, 632), True, 'import numpy as np\n'), ((643, 670), 'numpy.load', 'np.load', (['"""data/y_train.npy"""'], {}), "('data/y_train.npy')\n", (650, 670), True, 'import numpy as np\n'), ((679, 704), 'numpy.load', 'np.load', (['"""data/y_dev.npy"""'], {}), "('data/y_dev.npy')\n", (686, 704), True, 'import numpy as np\n'), ((715, 741), 'numpy.load', 'np.load', (['"""data/X_test.npy"""'], {}), "('data/X_test.npy')\n", (722, 741), True, 'import numpy as np\n'), ((753, 786), 'numpy.load', 'np.load', (['"""data/word_test_add.npy"""'], {}), "('data/word_test_add.npy')\n", (760, 786), True, 'import numpy as np\n'), ((848, 874), 'numpy.load', 'np.load', (['"""data/y_test.npy"""'], {}), "('data/y_test.npy')\n", (855, 874), True, 'import numpy as np\n'), ((885, 956), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.001)', 'beta_1': '(0.9)', 'beta_2': '(0.999)', 'epsilon': '(1e-08)', 'clipvalue': '(0.01)'}), '(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, clipvalue=0.01)\n', (889, 956), False, 'from keras.optimizers import Adam, Nadam\n'), ((1374, 1641), 'bilstm_crf_add_word.BiLSTM_CRF', 'BiLSTM_CRF', ([], {'n_input_char': '(200)', 'char_embedding_mat': 'char_embedding_mat', 'n_input_word': '(200)', 'word_embedding_mat': 'word_embedding_mat', 'keep_prob': '(0.7)', 'n_lstm': '(256)', 'keep_prob_lstm': '(0.6)', 'n_entity': '(7)', 'optimizer': 'adam', 'batch_size': '(32)', 'epochs': '(10)', 'n_filter': '(128)', 'kernel_size': '(3)'}), '(n_input_char=200, char_embedding_mat=char_embedding_mat,\n n_input_word=200, word_embedding_mat=word_embedding_mat, keep_prob=0.7,\n n_lstm=256, keep_prob_lstm=0.6, n_entity=7, optimizer=adam, batch_size=\n 32, epochs=10, n_filter=128, kernel_size=3)\n', (1384, 1641), False, 'from bilstm_crf_add_word import BiLSTM_CRF\n'), ((1816, 1827), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1825, 1827), False, 'import os\n'), ((2024, 2098), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_loss"""', 'min_delta': '(1e-08)', 'patience': '(0)', 'mode': '"""min"""'}), "(monitor='val_loss', min_delta=1e-08, patience=0, mode='min')\n", (2037, 2098), False, 'from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TensorBoard\n'), ((2105, 2197), 'keras.callbacks.TensorBoard', 'TensorBoard', ([], {'log_dir': 'log_filepath', 'write_graph': '(True)', 'write_images': '(True)', 'histogram_freq': '(0)'}), '(log_dir=log_filepath, write_graph=True, write_images=True,\n histogram_freq=0)\n', (2116, 2197), False, 'from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TensorBoard\n'), ((2219, 2338), 'keras.callbacks.ReduceLROnPlateau', 'ReduceLROnPlateau', ([], {'monitor': '"""val_loss"""', 'factor': '(0.2)', 'patience': '(3)', 'mode': '"""min"""', 'epsilon': '(0.0001)', 'cooldown': '(2)', 'min_lr': '(1e-08)'}), "(monitor='val_loss', factor=0.2, patience=3, mode='min',\n epsilon=0.0001, cooldown=2, min_lr=1e-08)\n", (2236, 2338), False, 'from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TensorBoard\n'), ((1873, 1905), 'os.path.join', 'os.path.join', (['cp_folder', 'cp_file'], {}), '(cp_folder, cp_file)\n', (1885, 1905), False, 'import os\n')] |
from typing import List, Dict, DefaultDict
from pathlib import Path
import joblib
import collections
from tqdm import trange
import yaml
import datetime
import numpy as np
from scipy import stats
from poker_ai.games.short_deck.state import ShortDeckPokerState, new_game
from poker_ai.poker.card import Card
def _calculate_strategy(
state: ShortDeckPokerState,
I: str,
strategy: DefaultDict[str, DefaultDict[str, float]],
count=None,
total_count=None
) -> str:
sigma = collections.defaultdict(
lambda: collections.defaultdict(lambda: 1 / 3)
)
try:
# If strategy is empty, go to other block
sigma[I] = strategy[I].copy()
if sigma[I] == {}:
raise KeyError
norm = sum(sigma[I].values())
for a in sigma[I].keys():
sigma[I][a] /= norm
a = np.random.choice(
list(sigma[I].keys()), 1, p=list(sigma[I].values()),
)[0]
except KeyError:
if count is not None:
count += 1
p = 1 / len(state.legal_actions)
probabilities = np.full(len(state.legal_actions), p)
a = np.random.choice(state.legal_actions, p=probabilities)
sigma[I] = {action: p for action in state.legal_actions}
if total_count is not None:
total_count += 1
return a, count, total_count
def _create_dir(folder_id: str) -> Path:
"""Create and get a unique dir path to save to using a timestamp."""
time = str(datetime.datetime.now())
for char in ":- .":
time = time.replace(char, "_")
path: Path = Path(f"./{folder_id}_results_{time}")
path.mkdir(parents=True, exist_ok=True)
return path
def agent_test(
hero_strategy_path: str,
opponent_strategy_path: str,
real_time_est: bool = False,
action_sequence: List[str] = None,
public_cards: List[Card] = [],
n_outer_iters: int = 30,
n_inner_iters: int = 100,
n_players: int = 3,
hero_count=None,
hero_total_count=None,
):
config: Dict[str, int] = {**locals()}
save_path: Path = _create_dir('bt')
with open(save_path / "config.yaml", "w") as steam:
yaml.dump(config, steam)
# Load unnormalized strategy for hero
hero_strategy = joblib.load(hero_strategy_path)['strategy']
# Load unnormalized strategy for opponents
opponent_strategy = joblib.load(opponent_strategy_path)['strategy']
# Loading game state we used RTS on
if real_time_est:
state: ShortDeckPokerState = new_game(
n_players, real_time_test=real_time_est, public_cards=public_cards
)
current_game_state: ShortDeckPokerState = state.load_game_state(
opponent_strategy, action_sequence
)
# TODO: Right now, this can only be used for loading states if the two
# strategies are averaged. Even averaging strategies is risky. Loading a
# game state should be used with caution. It will work only if the
# probability of reach is identical across strategies. Use the average
# strategy.
card_info_lut = {}
EVs = np.array([])
for _ in trange(1, n_outer_iters):
EV = np.array([]) # Expected value for player 0 (hero)
for t in trange(1, n_inner_iters + 1, desc="train iter"):
for p_i in range(n_players):
if real_time_est:
# Deal hole cards based on bayesian updating of hole card
# probabilities
state: ShortDeckPokerState = current_game_state.deal_bayes()
else:
state: ShortDeckPokerState = new_game(
n_players,
card_info_lut
)
card_info_lut = state.card_info_lut
while True:
player_not_in_hand = not state.players[p_i].is_active
if state.is_terminal or player_not_in_hand:
EV = np.append(EV, state.payout[p_i])
break
if state.player_i == p_i:
random_action, hero_count, hero_total_count = \
_calculate_strategy(
state,
state.info_set,
hero_strategy,
count=hero_count,
total_count=hero_total_count
)
else:
random_action, oc, otc = _calculate_strategy(
state,
state.info_set,
opponent_strategy,
)
state = state.apply_action(random_action)
EVs = np.append(EVs, EV.mean())
t_stat = (EVs.mean() - 0) / (EVs.std() / np.sqrt(n_outer_iters))
p_val = stats.t.sf(np.abs(t_stat), n_outer_iters - 1)
results_dict = {
'Expected Value': float(EVs.mean()),
'T Statistic': float(t_stat),
'P Value': float(p_val),
'Standard Deviation': float(EVs.std()),
'N': int(len(EVs)),
'Random Moves Hero': hero_count,
'Total Moves Hero': hero_total_count
}
with open(save_path / 'results.yaml', "w") as stream:
yaml.safe_dump(results_dict, stream=stream, default_flow_style=False)
if __name__ == "__main__":
agent_test(
hero_strategy_path="random_strategy/random_strategy.gz",
opponent_strategy_path="./_2020_07_02_20_38_58_085649/agent.joblib",
real_time_est=False,
public_cards=[],
action_sequence=None,
n_inner_iters=25,
n_outer_iters=75,
hero_count=0,
hero_total_count=0
)
| [
"numpy.abs",
"yaml.safe_dump",
"numpy.sqrt",
"yaml.dump",
"pathlib.Path",
"numpy.random.choice",
"poker_ai.games.short_deck.state.new_game",
"numpy.array",
"datetime.datetime.now",
"numpy.append",
"collections.defaultdict",
"joblib.load",
"tqdm.trange"
] | [((1599, 1636), 'pathlib.Path', 'Path', (['f"""./{folder_id}_results_{time}"""'], {}), "(f'./{folder_id}_results_{time}')\n", (1603, 1636), False, 'from pathlib import Path\n'), ((3093, 3105), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3101, 3105), True, 'import numpy as np\n'), ((3119, 3143), 'tqdm.trange', 'trange', (['(1)', 'n_outer_iters'], {}), '(1, n_outer_iters)\n', (3125, 3143), False, 'from tqdm import trange\n'), ((1494, 1517), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1515, 1517), False, 'import datetime\n'), ((2164, 2188), 'yaml.dump', 'yaml.dump', (['config', 'steam'], {}), '(config, steam)\n', (2173, 2188), False, 'import yaml\n'), ((2252, 2283), 'joblib.load', 'joblib.load', (['hero_strategy_path'], {}), '(hero_strategy_path)\n', (2263, 2283), False, 'import joblib\n'), ((2367, 2402), 'joblib.load', 'joblib.load', (['opponent_strategy_path'], {}), '(opponent_strategy_path)\n', (2378, 2402), False, 'import joblib\n'), ((2515, 2591), 'poker_ai.games.short_deck.state.new_game', 'new_game', (['n_players'], {'real_time_test': 'real_time_est', 'public_cards': 'public_cards'}), '(n_players, real_time_test=real_time_est, public_cards=public_cards)\n', (2523, 2591), False, 'from poker_ai.games.short_deck.state import ShortDeckPokerState, new_game\n'), ((3158, 3170), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3166, 3170), True, 'import numpy as np\n'), ((3226, 3273), 'tqdm.trange', 'trange', (['(1)', '(n_inner_iters + 1)'], {'desc': '"""train iter"""'}), "(1, n_inner_iters + 1, desc='train iter')\n", (3232, 3273), False, 'from tqdm import trange\n'), ((4915, 4929), 'numpy.abs', 'np.abs', (['t_stat'], {}), '(t_stat)\n', (4921, 4929), True, 'import numpy as np\n'), ((5321, 5390), 'yaml.safe_dump', 'yaml.safe_dump', (['results_dict'], {'stream': 'stream', 'default_flow_style': '(False)'}), '(results_dict, stream=stream, default_flow_style=False)\n', (5335, 5390), False, 'import yaml\n'), ((557, 596), 'collections.defaultdict', 'collections.defaultdict', (['(lambda : 1 / 3)'], {}), '(lambda : 1 / 3)\n', (580, 596), False, 'import collections\n'), ((1153, 1207), 'numpy.random.choice', 'np.random.choice', (['state.legal_actions'], {'p': 'probabilities'}), '(state.legal_actions, p=probabilities)\n', (1169, 1207), True, 'import numpy as np\n'), ((4868, 4890), 'numpy.sqrt', 'np.sqrt', (['n_outer_iters'], {}), '(n_outer_iters)\n', (4875, 4890), True, 'import numpy as np\n'), ((3616, 3650), 'poker_ai.games.short_deck.state.new_game', 'new_game', (['n_players', 'card_info_lut'], {}), '(n_players, card_info_lut)\n', (3624, 3650), False, 'from poker_ai.games.short_deck.state import ShortDeckPokerState, new_game\n'), ((3972, 4004), 'numpy.append', 'np.append', (['EV', 'state.payout[p_i]'], {}), '(EV, state.payout[p_i])\n', (3981, 4004), True, 'import numpy as np\n')] |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from logging import getLogger
from random import randrange
import os
import numpy as np
from sklearn.feature_extraction import image
import torch
import torch.nn as nn
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data.sampler import Sampler
from .YFCC100M import YFCC100M_dataset
logger = getLogger()
def load_data(args):
"""
Load dataset.
"""
if 'yfcc100m' in args.data_path:
return YFCC100M_dataset(args.data_path, size=args.size_dataset)
return datasets.ImageFolder(args.data_path)
def get_data_transformations(rotation=0):
"""
Return data transformations for clustering and for training
"""
tr_normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225],
)
final_process = [transforms.ToTensor(), tr_normalize]
# for clustering stage
tr_central_crop = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
lambda x: np.asarray(x),
Rotate(0)
] + final_process)
# for training stage
tr_dataug = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
lambda x: np.asarray(x),
Rotate(rotation)
] + final_process)
return tr_central_crop, tr_dataug
class Rotate(object):
def __init__(self, rot):
self.rot = rot
def __call__(self, img):
return rotate_img(img, self.rot)
def rotate_img(img, rot):
if rot == 0: # 0 degrees rotation
return img
elif rot == 90: # 90 degrees rotation
return np.flipud(np.transpose(img, (1, 0, 2))).copy()
elif rot == 180: # 90 degrees rotation
return np.fliplr(np.flipud(img)).copy()
elif rot == 270: # 270 degrees rotation / or -90
return np.transpose(np.flipud(img), (1, 0, 2)).copy()
else:
return
class KFoldSampler(Sampler):
def __init__(self, im_per_target, shuffle):
self.im_per_target = im_per_target
N = 0
for tar in im_per_target:
N = N + len(im_per_target[tar])
self.N = N
self.shuffle = shuffle
def __iter__(self):
indices = np.zeros(self.N).astype(int)
c = 0
for tar in self.im_per_target:
indices[c: c + len(self.im_per_target[tar])] = self.im_per_target[tar]
c = c + len(self.im_per_target[tar])
if self.shuffle:
np.random.shuffle(indices)
return iter(indices)
def __len__(self):
return self.N
class KFold():
"""Class to perform k-fold cross-validation.
Args:
im_per_target (Dict): key (target), value (list of data with this target)
i (int): index of the round of cross validation to perform
K (int): dataset randomly partitioned into K equal sized subsamples
Attributes:
val (KFoldSampler): validation sampler
train (KFoldSampler): training sampler
"""
def __init__(self, im_per_target, i, K):
assert(i<K)
per_target = {}
for tar in im_per_target:
per_target[tar] = int(len(im_per_target[tar]) // K)
im_per_target_train = {}
im_per_target_val = {}
for k in range(K):
for L in im_per_target:
if k==i:
im_per_target_val[L] = im_per_target[L][k * per_target[L]: (k + 1) * per_target[L]]
else:
if not L in im_per_target_train:
im_per_target_train[L] = []
im_per_target_train[L] = im_per_target_train[L] + im_per_target[L][k * per_target[L]: (k + 1) * per_target[L]]
self.val = KFoldSampler(im_per_target_val, False)
self.train = KFoldSampler(im_per_target_train, True)
def per_target(imgs):
"""Arrange samples per target.
Args:
imgs (list): List of (_, target) tuples.
Returns:
dict: key (target), value (list of data with this target)
"""
res = {}
for index in range(len(imgs)):
_, target = imgs[index]
if target not in res:
res[target] = []
res[target].append(index)
return res
| [
"logging.getLogger",
"torchvision.transforms.CenterCrop",
"numpy.flipud",
"torchvision.transforms.RandomHorizontalFlip",
"numpy.asarray",
"torchvision.datasets.ImageFolder",
"numpy.zeros",
"torchvision.transforms.Normalize",
"torchvision.transforms.Resize",
"torchvision.transforms.ToTensor",
"nu... | [((547, 558), 'logging.getLogger', 'getLogger', ([], {}), '()\n', (556, 558), False, 'from logging import getLogger\n'), ((736, 772), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['args.data_path'], {}), '(args.data_path)\n', (756, 772), True, 'import torchvision.datasets as datasets\n'), ((917, 992), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (937, 992), True, 'import torchvision.transforms as transforms\n'), ((1037, 1058), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1056, 1058), True, 'import torchvision.transforms as transforms\n'), ((2681, 2707), 'numpy.random.shuffle', 'np.random.shuffle', (['indices'], {}), '(indices)\n', (2698, 2707), True, 'import numpy as np\n'), ((1153, 1175), 'torchvision.transforms.Resize', 'transforms.Resize', (['(256)'], {}), '(256)\n', (1170, 1175), True, 'import torchvision.transforms as transforms\n'), ((1185, 1211), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (1206, 1211), True, 'import torchvision.transforms as transforms\n'), ((1358, 1391), 'torchvision.transforms.RandomResizedCrop', 'transforms.RandomResizedCrop', (['(224)'], {}), '(224)\n', (1386, 1391), True, 'import torchvision.transforms as transforms\n'), ((1401, 1434), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (1432, 1434), True, 'import torchvision.transforms as transforms\n'), ((2429, 2445), 'numpy.zeros', 'np.zeros', (['self.N'], {}), '(self.N)\n', (2437, 2445), True, 'import numpy as np\n'), ((1231, 1244), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (1241, 1244), True, 'import numpy as np\n'), ((1454, 1467), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (1464, 1467), True, 'import numpy as np\n'), ((1854, 1882), 'numpy.transpose', 'np.transpose', (['img', '(1, 0, 2)'], {}), '(img, (1, 0, 2))\n', (1866, 1882), True, 'import numpy as np\n'), ((1959, 1973), 'numpy.flipud', 'np.flipud', (['img'], {}), '(img)\n', (1968, 1973), True, 'import numpy as np\n'), ((2063, 2077), 'numpy.flipud', 'np.flipud', (['img'], {}), '(img)\n', (2072, 2077), True, 'import numpy as np\n')] |
"""
simPlot.py
<NAME>
Date of creation 17. feb 2016
"""
import springMassSystem as sms
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm #Color map
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import gridspec
import matplotlib.tri as tri
import time
#Data plot update function
CONST_STEP = 0.0002
CONST_FRAMES = 100
CONST_X = 7
CONST_Y = 7
def data(i,c,surf,triang):
global t
global xp
global yp1
global yp2
global yp3
global yp4
#global ypt
#Obtain coordinates of points
x = c.X[:,0]
y = c.X[:,1]
z = c.X[:,2]
ax1.clear() # Clear plot
###ax_tmp = fig.gca(projection='3d')
###plt.hold(True)
x_s = np.transpose(x.reshape((CONST_X,CONST_Y)))
y_s = np.transpose(y.reshape((CONST_X,CONST_Y)))
z_s = np.transpose(z.reshape((CONST_X,CONST_Y)))
###ax_tmp.plot_surface(x_s, y_s, z_s,rstride=1, cstride=1, cmap=cm.coolwarm,linewidth=0.4)
###plt.show()
#Plot tri mesh
surf = ax1.plot_trisurf(x,y,z,triangles=triang.triangles,cmap=cm.jet,linewidth=0.4)
#surf = ax1.plot_surface(x_s, y_s, z_s,rstride=1, cstride=1, cmap=cm.coolwarm,linewidth=0.4)
# Limit plot for better data visualization
ax1.set_zlim(0.0 , 1.01)
ax1.set_xlim(-0.01 , 1.1)
ax1.set_ylim(-0.01 , 1.16)
#Calculate system energy
u0, u1, u2, u3 = c.Energy()
xp = np.append(xp,t)
yp1 = np.append(yp1,u0)
yp2 = np.append(yp2,u1)
yp3 = np.append(yp3,u2)
yp4 = np.append(yp4,u3)
#ypt = np.append(ypt,(u0+u1+u2+u3))
#Plot energy
pU0.set_data(xp,yp1)
pU1.set_data(xp,yp2)
pU2.set_data(xp,yp3)
pU3.set_data(xp,yp4)
#pUT.set_data(xp,ypt)
#Update simulation
for i in range(0,20):
#c.simUpdateExplicit(0.0001,sms.explicit_method.rk4)
c.semiImplictEuler(CONST_STEP)
t = t+CONST_STEP
"""
for i in range(0,3):
c.ImplictEuler(0.0003)
"""
return surf,pU0#, pEnergy
c = sms.Cloth(CONST_X,CONST_Y,0.3,0.1)
constr = np.arange(2*c.dY)
#constr = np.array([0,1,2,3,4,5,6, 7,8,9,10,11,12,13])
#constr = np.array([5,6,12,13,19,20,26,27,33,34,40,41,47,48])
#constr = np.array([4,24])
c.constrain(constr) #Constrain specific particles
x = []
y = []
z = []
for p in c.X:
x.append(p[0])
y.append(p[1])
z.append(p[2])
#Setup which points should be connected in the trimesh
triang = tri.Triangulation(x, y)
#Create figure
fig = plt.figure(figsize=(16,10))
ax1 = fig.add_subplot(131, projection='3d')
ax2 = fig.add_subplot(232)
ax3 = fig.add_subplot(233)
ax4 = fig.add_subplot(235)
ax5 = fig.add_subplot(236)
surf = ax1.plot(x,y)#plot_trisurf(x, y, z,color= 'b')
ax2.set_xlim(0.0, CONST_FRAMES*CONST_STEP*10)
ax3.set_xlim(0.0, CONST_FRAMES*CONST_STEP*10)
ax4.set_xlim(0.0, CONST_FRAMES*CONST_STEP*10)
ax5.set_xlim(0.0, CONST_FRAMES*CONST_STEP*10)
yp1 = np.zeros(0)
yp2 = np.zeros(0)
yp3 = np.zeros(0)
yp4 = np.zeros(0)
xp = np.zeros(0)
t = 0
pU0, = ax2.plot(xp,yp1,'b-')
pU1, = ax3.plot(xp,yp2,'b-')
pU2, = ax4.plot(xp,yp3,'b-')
pU3, = ax5.plot(xp,yp4,'b-')
ax2.set_ylim(0.0, 0.006)
ax3.set_ylim(-2e-3, 4.9e-04)
ax4.set_ylim(0.0, 10.0)
ax5.set_ylim(0.0, 0.4e-7)
#Title
ax2.set_title("Kinetic energy")
ax3.set_title("Gravitational energy")
ax4.set_title("Torsion spring energy")
ax5.set_title("Tension spring energy")
#axt.set_title("Total energy")
#Animate!
ani = animation.FuncAnimation(fig, data, fargs=(c, surf, triang),frames=CONST_FRAMES, interval=30, blit=False,repeat=False)
#ani.save(filename='sim.mp4',fps=30,dpi=300) #Save animation
plt.show()
| [
"springMassSystem.Cloth",
"matplotlib.animation.FuncAnimation",
"matplotlib.tri.Triangulation",
"numpy.append",
"matplotlib.pyplot.figure",
"numpy.zeros",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((2024, 2061), 'springMassSystem.Cloth', 'sms.Cloth', (['CONST_X', 'CONST_Y', '(0.3)', '(0.1)'], {}), '(CONST_X, CONST_Y, 0.3, 0.1)\n', (2033, 2061), True, 'import springMassSystem as sms\n'), ((2068, 2087), 'numpy.arange', 'np.arange', (['(2 * c.dY)'], {}), '(2 * c.dY)\n', (2077, 2087), True, 'import numpy as np\n'), ((2437, 2460), 'matplotlib.tri.Triangulation', 'tri.Triangulation', (['x', 'y'], {}), '(x, y)\n', (2454, 2460), True, 'import matplotlib.tri as tri\n'), ((2484, 2512), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 10)'}), '(figsize=(16, 10))\n', (2494, 2512), True, 'import matplotlib.pyplot as plt\n'), ((2911, 2922), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (2919, 2922), True, 'import numpy as np\n'), ((2929, 2940), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (2937, 2940), True, 'import numpy as np\n'), ((2947, 2958), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (2955, 2958), True, 'import numpy as np\n'), ((2965, 2976), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (2973, 2976), True, 'import numpy as np\n'), ((2983, 2994), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (2991, 2994), True, 'import numpy as np\n'), ((3426, 3550), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['fig', 'data'], {'fargs': '(c, surf, triang)', 'frames': 'CONST_FRAMES', 'interval': '(30)', 'blit': '(False)', 'repeat': '(False)'}), '(fig, data, fargs=(c, surf, triang), frames=\n CONST_FRAMES, interval=30, blit=False, repeat=False)\n', (3449, 3550), True, 'import matplotlib.animation as animation\n'), ((3606, 3616), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3614, 3616), True, 'import matplotlib.pyplot as plt\n'), ((1422, 1438), 'numpy.append', 'np.append', (['xp', 't'], {}), '(xp, t)\n', (1431, 1438), True, 'import numpy as np\n'), ((1448, 1466), 'numpy.append', 'np.append', (['yp1', 'u0'], {}), '(yp1, u0)\n', (1457, 1466), True, 'import numpy as np\n'), ((1476, 1494), 'numpy.append', 'np.append', (['yp2', 'u1'], {}), '(yp2, u1)\n', (1485, 1494), True, 'import numpy as np\n'), ((1504, 1522), 'numpy.append', 'np.append', (['yp3', 'u2'], {}), '(yp3, u2)\n', (1513, 1522), True, 'import numpy as np\n'), ((1532, 1550), 'numpy.append', 'np.append', (['yp4', 'u3'], {}), '(yp4, u3)\n', (1541, 1550), True, 'import numpy as np\n')] |
# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for Permute bijector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import tensorflow as tf
from tensorflow_probability.python import bijectors as tfb
from tensorflow_probability.python.bijectors import bijector_test_util
from tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import,g-import-not-at-top
@test_util.run_all_in_graph_and_eager_modes
class PermuteBijectorTest(tf.test.TestCase):
"""Tests correctness of the Permute bijector."""
def assertRaisesError(self, msg):
return self.assertRaisesRegexp(Exception, msg)
def setUp(self):
self._rng = np.random.RandomState(42)
def testBijector(self):
expected_permutation = np.int32([2, 0, 1])
expected_x = np.random.randn(4, 2, 3)
expected_y = expected_x[..., expected_permutation]
permutation_ph = tf.compat.v1.placeholder_with_default(
expected_permutation, shape=None)
bijector = tfb.Permute(permutation=permutation_ph, validate_args=True)
[
permutation_,
x_,
y_,
fldj,
ildj,
] = self.evaluate([
bijector.permutation,
bijector.inverse(expected_y),
bijector.forward(expected_x),
bijector.forward_log_det_jacobian(expected_x, event_ndims=1),
bijector.inverse_log_det_jacobian(expected_y, event_ndims=1),
])
self.assertEqual("permute", bijector.name)
self.assertAllEqual(expected_permutation, permutation_)
self.assertAllClose(expected_y, y_, rtol=1e-6, atol=0)
self.assertAllClose(expected_x, x_, rtol=1e-6, atol=0)
self.assertAllClose(0., fldj, rtol=1e-6, atol=0)
self.assertAllClose(0., ildj, rtol=1e-6, atol=0)
def testRaisesOpError(self):
with self.assertRaisesError("Permutation over `d` must contain"):
permutation = tf.compat.v1.placeholder_with_default([1, 2], shape=None)
bijector = tfb.Permute(permutation=permutation, validate_args=True)
self.evaluate(bijector.inverse([1.]))
def testBijectiveAndFinite(self):
permutation = np.int32([2, 0, 1])
x = np.random.randn(4, 2, 3)
y = x[..., permutation]
bijector = tfb.Permute(permutation=permutation, validate_args=True)
bijector_test_util.assert_bijective_and_finite(
bijector, x, y, eval_func=self.evaluate, event_ndims=1, rtol=1e-6,
atol=0)
def testBijectiveAndFiniteAxis(self):
permutation = np.int32([1, 0])
x = np.random.randn(4, 2, 3)
y = x[..., permutation, :]
bijector = tfb.Permute(
permutation=permutation,
axis=-2,
validate_args=True)
bijector_test_util.assert_bijective_and_finite(
bijector, x, y, eval_func=self.evaluate, event_ndims=2, rtol=1e-6,
atol=0)
def testPreservesShape(self):
# TODO(b/131157549, b/131124359): Test should not be needed. Consider
# deleting when underlying issue with constant eager tensors is fixed.
permutation = [2, 1, 0]
x = tf.keras.Input((3,), batch_size=None)
bijector = tfb.Permute(permutation=permutation, axis=-1, validate_args=True)
y = bijector.forward(x)
self.assertAllEqual(y.shape.as_list(), [None, 3])
inverse_y = bijector.inverse(x)
self.assertAllEqual(inverse_y.shape.as_list(), [None, 3])
if __name__ == "__main__":
tf.test.main()
| [
"tensorflow_probability.python.bijectors.bijector_test_util.assert_bijective_and_finite",
"numpy.int32",
"tensorflow_probability.python.bijectors.Permute",
"tensorflow.test.main",
"tensorflow.keras.Input",
"tensorflow.compat.v1.placeholder_with_default",
"numpy.random.randn",
"numpy.random.RandomState... | [((4051, 4065), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (4063, 4065), True, 'import tensorflow as tf\n'), ((1400, 1425), 'numpy.random.RandomState', 'np.random.RandomState', (['(42)'], {}), '(42)\n', (1421, 1425), True, 'import numpy as np\n'), ((1480, 1499), 'numpy.int32', 'np.int32', (['[2, 0, 1]'], {}), '([2, 0, 1])\n', (1488, 1499), True, 'import numpy as np\n'), ((1517, 1541), 'numpy.random.randn', 'np.random.randn', (['(4)', '(2)', '(3)'], {}), '(4, 2, 3)\n', (1532, 1541), True, 'import numpy as np\n'), ((1619, 1690), 'tensorflow.compat.v1.placeholder_with_default', 'tf.compat.v1.placeholder_with_default', (['expected_permutation'], {'shape': 'None'}), '(expected_permutation, shape=None)\n', (1656, 1690), True, 'import tensorflow as tf\n'), ((1715, 1774), 'tensorflow_probability.python.bijectors.Permute', 'tfb.Permute', ([], {'permutation': 'permutation_ph', 'validate_args': '(True)'}), '(permutation=permutation_ph, validate_args=True)\n', (1726, 1774), True, 'from tensorflow_probability.python import bijectors as tfb\n'), ((2816, 2835), 'numpy.int32', 'np.int32', (['[2, 0, 1]'], {}), '([2, 0, 1])\n', (2824, 2835), True, 'import numpy as np\n'), ((2844, 2868), 'numpy.random.randn', 'np.random.randn', (['(4)', '(2)', '(3)'], {}), '(4, 2, 3)\n', (2859, 2868), True, 'import numpy as np\n'), ((2912, 2968), 'tensorflow_probability.python.bijectors.Permute', 'tfb.Permute', ([], {'permutation': 'permutation', 'validate_args': '(True)'}), '(permutation=permutation, validate_args=True)\n', (2923, 2968), True, 'from tensorflow_probability.python import bijectors as tfb\n'), ((2973, 3100), 'tensorflow_probability.python.bijectors.bijector_test_util.assert_bijective_and_finite', 'bijector_test_util.assert_bijective_and_finite', (['bijector', 'x', 'y'], {'eval_func': 'self.evaluate', 'event_ndims': '(1)', 'rtol': '(1e-06)', 'atol': '(0)'}), '(bijector, x, y, eval_func=\n self.evaluate, event_ndims=1, rtol=1e-06, atol=0)\n', (3019, 3100), False, 'from tensorflow_probability.python.bijectors import bijector_test_util\n'), ((3171, 3187), 'numpy.int32', 'np.int32', (['[1, 0]'], {}), '([1, 0])\n', (3179, 3187), True, 'import numpy as np\n'), ((3196, 3220), 'numpy.random.randn', 'np.random.randn', (['(4)', '(2)', '(3)'], {}), '(4, 2, 3)\n', (3211, 3220), True, 'import numpy as np\n'), ((3267, 3332), 'tensorflow_probability.python.bijectors.Permute', 'tfb.Permute', ([], {'permutation': 'permutation', 'axis': '(-2)', 'validate_args': '(True)'}), '(permutation=permutation, axis=-2, validate_args=True)\n', (3278, 3332), True, 'from tensorflow_probability.python import bijectors as tfb\n'), ((3362, 3489), 'tensorflow_probability.python.bijectors.bijector_test_util.assert_bijective_and_finite', 'bijector_test_util.assert_bijective_and_finite', (['bijector', 'x', 'y'], {'eval_func': 'self.evaluate', 'event_ndims': '(2)', 'rtol': '(1e-06)', 'atol': '(0)'}), '(bijector, x, y, eval_func=\n self.evaluate, event_ndims=2, rtol=1e-06, atol=0)\n', (3408, 3489), False, 'from tensorflow_probability.python.bijectors import bijector_test_util\n'), ((3719, 3756), 'tensorflow.keras.Input', 'tf.keras.Input', (['(3,)'], {'batch_size': 'None'}), '((3,), batch_size=None)\n', (3733, 3756), True, 'import tensorflow as tf\n'), ((3772, 3837), 'tensorflow_probability.python.bijectors.Permute', 'tfb.Permute', ([], {'permutation': 'permutation', 'axis': '(-1)', 'validate_args': '(True)'}), '(permutation=permutation, axis=-1, validate_args=True)\n', (3783, 3837), True, 'from tensorflow_probability.python import bijectors as tfb\n'), ((2585, 2642), 'tensorflow.compat.v1.placeholder_with_default', 'tf.compat.v1.placeholder_with_default', (['[1, 2]'], {'shape': 'None'}), '([1, 2], shape=None)\n', (2622, 2642), True, 'import tensorflow as tf\n'), ((2660, 2716), 'tensorflow_probability.python.bijectors.Permute', 'tfb.Permute', ([], {'permutation': 'permutation', 'validate_args': '(True)'}), '(permutation=permutation, validate_args=True)\n', (2671, 2716), True, 'from tensorflow_probability.python import bijectors as tfb\n')] |
import os
import numpy as np
import pytest
import torch
import torch.nn.functional as F
import torchvision.transforms as transforms
import ignite.distributed as idist
from ignite.metrics.gan.inception_score import InceptionScore
torch.manual_seed(42)
class IgnoreLabelDataset(torch.utils.data.Dataset):
def __init__(self, dataset):
self.dataset = dataset
def __getitem__(self, index):
return self.dataset[index][0]
def __len__(self):
return len(self.dataset)
def _test_distrib_integration(device):
def _test_score(metric_device):
from torchvision import models
from torchvision.datasets import FakeData
from ignite.engine import Engine
inception_model = models.inception_v3(pretrained=True).eval().to(metric_device)
dataset = FakeData(size=64, transform=transforms.Compose([transforms.Resize(299), transforms.ToTensor()]))
dataset = IgnoreLabelDataset(dataset)
dataloader = idist.auto_dataloader(dataset, batch_size=32)
def np_compute(dataloader, splits):
def get_pred(x):
x = inception_model(x)
return F.softmax(x).detach().cpu().numpy()
preds = []
for i, batch in enumerate(dataloader):
preds.append(get_pred(batch))
split_scores = np.zeros((splits,))
preds = np.vstack(preds)
N = preds.shape[0]
for i in range(splits):
part = preds[i * N // splits : (i + 1) * N // splits, :]
kl = part * (np.log(part) - np.log(np.mean(part, axis=0, keepdims=True)))
kl = np.mean(np.sum(kl, axis=1))
split_scores[i] = np.exp(kl)
return np.mean(split_scores)
def process_func(engine, batch):
return batch
inception_score = InceptionScore(device=metric_device)
test_engine = Engine(process_func)
inception_score.attach(test_engine, "score")
np_is = np_compute(dataloader, 10)
state = test_engine.run(dataloader)
computed_is = state.metrics["score"]
assert pytest.approx(computed_is, 0.1) == np_is
_test_score("cpu")
if device.type != "xla":
_test_score(idist.device())
@pytest.mark.distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
@pytest.mark.skipif(torch.cuda.device_count() < 1, reason="Skip if no GPU")
def test_distrib_gpu(local_rank, distributed_context_single_node_nccl):
device = torch.device(f"cuda:{local_rank}")
_test_distrib_integration(device)
@pytest.mark.distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
def test_distrib_cpu(distributed_context_single_node_gloo):
device = torch.device("cpu")
_test_distrib_integration(device)
@pytest.mark.distributed
@pytest.mark.skipif(not idist.has_hvd_support, reason="Skip if no Horovod dist support")
@pytest.mark.skipif("WORLD_SIZE" in os.environ, reason="Skip if launched as multiproc")
def test_distrib_hvd(gloo_hvd_executor):
device = torch.device("cpu" if not torch.cuda.is_available() else "cuda")
nproc = 4 if not torch.cuda.is_available() else torch.cuda.device_count()
gloo_hvd_executor(_test_distrib_integration, (device,), np=nproc, do_init=True)
@pytest.mark.multinode_distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
@pytest.mark.skipif("MULTINODE_DISTRIB" not in os.environ, reason="Skip if not multi-node distributed")
def test_multinode_distrib_cpu(distributed_context_multi_node_gloo):
device = torch.device("cpu")
_test_distrib_integration(device)
@pytest.mark.multinode_distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
@pytest.mark.skipif("GPU_MULTINODE_DISTRIB" not in os.environ, reason="Skip if not multi-node distributed")
def test_multinode_distrib_gpu(distributed_context_multi_node_nccl):
device = torch.device(f"cuda:{distributed_context_multi_node_nccl['local_rank']}")
_test_distrib_integration(device)
@pytest.mark.tpu
@pytest.mark.skipif("NUM_TPU_WORKERS" in os.environ, reason="Skip if NUM_TPU_WORKERS is in env vars")
@pytest.mark.skipif(not idist.has_xla_support, reason="Skip if no PyTorch XLA package")
def test_distrib_single_device_xla():
device = idist.device()
_test_distrib_integration(device)
def _test_distrib_xla_nprocs(index):
device = idist.device()
_test_distrib_integration(device)
@pytest.mark.tpu
@pytest.mark.skipif("NUM_TPU_WORKERS" not in os.environ, reason="Skip if no NUM_TPU_WORKERS in env vars")
@pytest.mark.skipif(not idist.has_xla_support, reason="Skip if no PyTorch XLA package")
def test_distrib_xla_nprocs(xmp_executor):
n = int(os.environ["NUM_TPU_WORKERS"])
xmp_executor(_test_distrib_xla_nprocs, args=(), nprocs=n)
| [
"numpy.log",
"torch.cuda.device_count",
"ignite.engine.Engine",
"torch.cuda.is_available",
"torchvision.models.inception_v3",
"ignite.distributed.device",
"torch.nn.functional.softmax",
"numpy.mean",
"numpy.exp",
"numpy.vstack",
"pytest.mark.skipif",
"torchvision.transforms.ToTensor",
"torch... | [((232, 253), 'torch.manual_seed', 'torch.manual_seed', (['(42)'], {}), '(42)\n', (249, 253), False, 'import torch\n'), ((2303, 2402), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not idist.has_native_dist_support)'], {'reason': '"""Skip if no native dist support"""'}), "(not idist.has_native_dist_support, reason=\n 'Skip if no native dist support')\n", (2321, 2402), False, 'import pytest\n'), ((2660, 2759), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not idist.has_native_dist_support)'], {'reason': '"""Skip if no native dist support"""'}), "(not idist.has_native_dist_support, reason=\n 'Skip if no native dist support')\n", (2678, 2759), False, 'import pytest\n'), ((2914, 3006), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not idist.has_hvd_support)'], {'reason': '"""Skip if no Horovod dist support"""'}), "(not idist.has_hvd_support, reason=\n 'Skip if no Horovod dist support')\n", (2932, 3006), False, 'import pytest\n'), ((3003, 3094), 'pytest.mark.skipif', 'pytest.mark.skipif', (["('WORLD_SIZE' in os.environ)"], {'reason': '"""Skip if launched as multiproc"""'}), "('WORLD_SIZE' in os.environ, reason=\n 'Skip if launched as multiproc')\n", (3021, 3094), False, 'import pytest\n'), ((3411, 3510), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not idist.has_native_dist_support)'], {'reason': '"""Skip if no native dist support"""'}), "(not idist.has_native_dist_support, reason=\n 'Skip if no native dist support')\n", (3429, 3510), False, 'import pytest\n'), ((3507, 3614), 'pytest.mark.skipif', 'pytest.mark.skipif', (["('MULTINODE_DISTRIB' not in os.environ)"], {'reason': '"""Skip if not multi-node distributed"""'}), "('MULTINODE_DISTRIB' not in os.environ, reason=\n 'Skip if not multi-node distributed')\n", (3525, 3614), False, 'import pytest\n'), ((3788, 3887), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not idist.has_native_dist_support)'], {'reason': '"""Skip if no native dist support"""'}), "(not idist.has_native_dist_support, reason=\n 'Skip if no native dist support')\n", (3806, 3887), False, 'import pytest\n'), ((3884, 3995), 'pytest.mark.skipif', 'pytest.mark.skipif', (["('GPU_MULTINODE_DISTRIB' not in os.environ)"], {'reason': '"""Skip if not multi-node distributed"""'}), "('GPU_MULTINODE_DISTRIB' not in os.environ, reason=\n 'Skip if not multi-node distributed')\n", (3902, 3995), False, 'import pytest\n'), ((4205, 4310), 'pytest.mark.skipif', 'pytest.mark.skipif', (["('NUM_TPU_WORKERS' in os.environ)"], {'reason': '"""Skip if NUM_TPU_WORKERS is in env vars"""'}), "('NUM_TPU_WORKERS' in os.environ, reason=\n 'Skip if NUM_TPU_WORKERS is in env vars')\n", (4223, 4310), False, 'import pytest\n'), ((4307, 4398), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not idist.has_xla_support)'], {'reason': '"""Skip if no PyTorch XLA package"""'}), "(not idist.has_xla_support, reason=\n 'Skip if no PyTorch XLA package')\n", (4325, 4398), False, 'import pytest\n'), ((4623, 4732), 'pytest.mark.skipif', 'pytest.mark.skipif', (["('NUM_TPU_WORKERS' not in os.environ)"], {'reason': '"""Skip if no NUM_TPU_WORKERS in env vars"""'}), "('NUM_TPU_WORKERS' not in os.environ, reason=\n 'Skip if no NUM_TPU_WORKERS in env vars')\n", (4641, 4732), False, 'import pytest\n'), ((4729, 4820), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not idist.has_xla_support)'], {'reason': '"""Skip if no PyTorch XLA package"""'}), "(not idist.has_xla_support, reason=\n 'Skip if no PyTorch XLA package')\n", (4747, 4820), False, 'import pytest\n'), ((2559, 2593), 'torch.device', 'torch.device', (['f"""cuda:{local_rank}"""'], {}), "(f'cuda:{local_rank}')\n", (2571, 2593), False, 'import torch\n'), ((2828, 2847), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2840, 2847), False, 'import torch\n'), ((3692, 3711), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (3704, 3711), False, 'import torch\n'), ((4073, 4146), 'torch.device', 'torch.device', (['f"""cuda:{distributed_context_multi_node_nccl[\'local_rank\']}"""'], {}), '(f"cuda:{distributed_context_multi_node_nccl[\'local_rank\']}")\n', (4085, 4146), False, 'import torch\n'), ((4445, 4459), 'ignite.distributed.device', 'idist.device', ([], {}), '()\n', (4457, 4459), True, 'import ignite.distributed as idist\n'), ((4550, 4564), 'ignite.distributed.device', 'idist.device', ([], {}), '()\n', (4562, 4564), True, 'import ignite.distributed as idist\n'), ((981, 1026), 'ignite.distributed.auto_dataloader', 'idist.auto_dataloader', (['dataset'], {'batch_size': '(32)'}), '(dataset, batch_size=32)\n', (1002, 1026), True, 'import ignite.distributed as idist\n'), ((1865, 1901), 'ignite.metrics.gan.inception_score.InceptionScore', 'InceptionScore', ([], {'device': 'metric_device'}), '(device=metric_device)\n', (1879, 1901), False, 'from ignite.metrics.gan.inception_score import InceptionScore\n'), ((1924, 1944), 'ignite.engine.Engine', 'Engine', (['process_func'], {}), '(process_func)\n', (1930, 1944), False, 'from ignite.engine import Engine\n'), ((2418, 2443), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (2441, 2443), False, 'import torch\n'), ((3262, 3287), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (3285, 3287), False, 'import torch\n'), ((1348, 1367), 'numpy.zeros', 'np.zeros', (['(splits,)'], {}), '((splits,))\n', (1356, 1367), True, 'import numpy as np\n'), ((1388, 1404), 'numpy.vstack', 'np.vstack', (['preds'], {}), '(preds)\n', (1397, 1404), True, 'import numpy as np\n'), ((1749, 1770), 'numpy.mean', 'np.mean', (['split_scores'], {}), '(split_scores)\n', (1756, 1770), True, 'import numpy as np\n'), ((2145, 2176), 'pytest.approx', 'pytest.approx', (['computed_is', '(0.1)'], {}), '(computed_is, 0.1)\n', (2158, 2176), False, 'import pytest\n'), ((2259, 2273), 'ignite.distributed.device', 'idist.device', ([], {}), '()\n', (2271, 2273), True, 'import ignite.distributed as idist\n'), ((3231, 3256), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3254, 3256), False, 'import torch\n'), ((1718, 1728), 'numpy.exp', 'np.exp', (['kl'], {}), '(kl)\n', (1724, 1728), True, 'import numpy as np\n'), ((3171, 3196), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3194, 3196), False, 'import torch\n'), ((1664, 1682), 'numpy.sum', 'np.sum', (['kl'], {'axis': '(1)'}), '(kl, axis=1)\n', (1670, 1682), True, 'import numpy as np\n'), ((737, 773), 'torchvision.models.inception_v3', 'models.inception_v3', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (756, 773), False, 'from torchvision import models\n'), ((865, 887), 'torchvision.transforms.Resize', 'transforms.Resize', (['(299)'], {}), '(299)\n', (882, 887), True, 'import torchvision.transforms as transforms\n'), ((889, 910), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (908, 910), True, 'import torchvision.transforms as transforms\n'), ((1574, 1586), 'numpy.log', 'np.log', (['part'], {}), '(part)\n', (1580, 1586), True, 'import numpy as np\n'), ((1596, 1632), 'numpy.mean', 'np.mean', (['part'], {'axis': '(0)', 'keepdims': '(True)'}), '(part, axis=0, keepdims=True)\n', (1603, 1632), True, 'import numpy as np\n'), ((1163, 1175), 'torch.nn.functional.softmax', 'F.softmax', (['x'], {}), '(x)\n', (1172, 1175), True, 'import torch.nn.functional as F\n')] |
#
# Experiment class
#
import numpy as np
examples = """
Discharge at 1C for 0.5 hours,
Discharge at C/20 for 0.5 hours,
Charge at 0.5 C for 45 minutes,
Discharge at 1 A for 90 seconds,
Charge at 200mA for 45 minutes (1 minute period),
Discharge at 1 W for 0.5 hours,
Charge at 200 mW for 45 minutes,
Rest for 10 minutes (5 minute period),
Hold at 1 V for 20 seconds,
Charge at 1 C until 4.1V,
Hold at 4.1 V until 50 mA,
Hold at 3V until C/50,
Run US06 (A),
Run US06 (A) for 20 seconds,
Run US06 (V) for 45 minutes,
Run US06 (W) for 2 hours,
"""
class Experiment:
"""
Base class for experimental conditions under which to run the model. In general, a
list of operating conditions should be passed in. Each operating condition should
be of the form "Do this for this long" or "Do this until this happens". For example,
"Charge at 1 C for 1 hour", or "Charge at 1 C until 4.2 V", or "Charge at 1 C for 1
hour or until 4.2 V". The instructions can be of the form "(Dis)charge at x A/C/W",
"Rest", or "Hold at x V". The running time should be a time in seconds, minutes or
hours, e.g. "10 seconds", "3 minutes" or "1 hour". The stopping conditions should be
a circuit state, e.g. "1 A", "C/50" or "3 V". The parameter drive_cycles is
mandatory to run drive cycle. For example, "Run x", then x must be the key
of drive_cycles dictionary.
Parameters
----------
operating_conditions : list
List of operating conditions
parameters : dict
Dictionary of parameters to use for this experiment, replacing default
parameters as appropriate
period : string, optional
Period (1/frequency) at which to record outputs. Default is 1 minute. Can be
overwritten by individual operating conditions.
termination : list, optional
List of conditions under which to terminate the experiment. Default is None.
use_simulation_setup_type : str
Whether to use the "new" (default) or "old" simulation set-up type. "new" is
faster at simulating individual steps but has higher set-up overhead
drive_cycles : dict
Dictionary of drive cycles to use for this experiment.
cccv_handling : str, optional
How to handle CCCV. If "two-step" (default), then the experiment is run in
two steps (CC then CV). If "ode", then the experiment is run in a single step
using an ODE for current: see
:class:`pybamm.external_circuit.CCCVFunctionControl` for details.
"""
def __init__(
self,
operating_conditions,
parameters=None,
period="1 minute",
termination=None,
use_simulation_setup_type="new",
drive_cycles={},
cccv_handling="two-step",
):
if cccv_handling not in ["two-step", "ode"]:
raise ValueError("cccv_handling should be either 'two-step' or 'ode'")
self.cccv_handling = cccv_handling
self.period = self.convert_time_to_seconds(period.split())
operating_conditions_cycles = []
for cycle in operating_conditions:
# Check types and convert strings to 1-tuples
if (isinstance(cycle, tuple) or isinstance(cycle, str)) and all(
[isinstance(cond, str) for cond in cycle]
):
if isinstance(cycle, str):
processed_cycle = (cycle,)
else:
processed_cycle = []
idx = 0
finished = False
while not finished:
step = cycle[idx]
if idx < len(cycle) - 1:
next_step = cycle[idx + 1]
else:
next_step = None
finished = True
if self.is_cccv(step, next_step):
processed_cycle.append(step + " then " + next_step)
idx += 2
else:
processed_cycle.append(step)
idx += 1
if idx >= len(cycle):
finished = True
operating_conditions_cycles.append(tuple(processed_cycle))
else:
try:
# Condition is not a string
badly_typed_conditions = [
cond for cond in cycle if not isinstance(cond, str)
]
except TypeError:
# Cycle is not a tuple or string
badly_typed_conditions = []
badly_typed_conditions = badly_typed_conditions or [cycle]
raise TypeError(
"""Operating conditions should be strings or tuples of strings, not {}. For example: {}
""".format(
type(badly_typed_conditions[0]), examples
)
)
self.cycle_lengths = [len(cycle) for cycle in operating_conditions_cycles]
operating_conditions = [
cond for cycle in operating_conditions_cycles for cond in cycle
]
self.operating_conditions_cycles = operating_conditions_cycles
self.operating_conditions_strings = operating_conditions
self.operating_conditions, self.events = self.read_operating_conditions(
operating_conditions, drive_cycles
)
parameters = parameters or {}
if isinstance(parameters, dict):
self.parameters = parameters
else:
raise TypeError("experimental parameters should be a dictionary")
self.termination_string = termination
self.termination = self.read_termination(termination)
self.use_simulation_setup_type = use_simulation_setup_type
def __str__(self):
return str(self.operating_conditions_strings)
def __repr__(self):
return "pybamm.Experiment({!s})".format(self)
def read_operating_conditions(self, operating_conditions, drive_cycles):
"""
Convert operating conditions to the appropriate format
Parameters
----------
operating_conditions : list
List of operating conditions
drive_cycles : dictionary
Dictionary of Drive Cycles
Returns
-------
operating_conditions : list
Operating conditions in the tuple format
"""
converted_operating_conditions = []
events = []
for cond in operating_conditions:
next_op, next_event = self.read_string(cond, drive_cycles)
converted_operating_conditions.append(next_op)
events.append(next_event)
return converted_operating_conditions, events
def read_string(self, cond, drive_cycles):
"""
Convert a string to a tuple of the right format
Parameters
----------
cond : str
String of appropriate form for example "Charge at x C for y hours". x and y
must be numbers, 'C' denotes the unit of the external circuit (can be A for
current, C for C-rate, V for voltage or W for power), and 'hours' denotes
the unit of time (can be second(s), minute(s) or hour(s))
drive_cycles: dict
A map specifying the drive cycles
"""
if " then " in cond:
# If the string contains " then ", then this is a two-step CCCV experiment
# and we need to split it into two strings
cond_CC, cond_CV = cond.split(" then ")
op_CC, _ = self.read_string(cond_CC, drive_cycles)
op_CV, event_CV = self.read_string(cond_CV, drive_cycles)
return {
"electric": op_CC["electric"] + op_CV["electric"],
"time": op_CV["time"],
"period": op_CV["period"],
}, event_CV
# Read period
if " period)" in cond:
cond, time_period = cond.split("(")
time, _ = time_period.split(" period)")
period = self.convert_time_to_seconds(time.split())
else:
period = self.period
# Read instructions
if "Run" in cond:
cond_list = cond.split()
if "at" in cond:
raise ValueError(f"Instruction must be of the form: {examples}")
dc_types = ["(A)", "(V)", "(W)"]
if all(x not in cond for x in dc_types):
raise ValueError(
"Type of drive cycle must be specified using '(A)', '(V)' or '(W)'."
f" For example: {examples}"
)
# Check for Events
elif "for" in cond:
# e.g. for 3 hours
idx = cond_list.index("for")
end_time = self.convert_time_to_seconds(cond_list[idx + 1 :])
ext_drive_cycle = self.extend_drive_cycle(
drive_cycles[cond_list[1]], end_time
)
# Drive cycle as numpy array
dc_data = ext_drive_cycle
# Find the type of drive cycle ("A", "V", or "W")
typ = cond_list[2][1]
electric = (dc_data, typ)
time = ext_drive_cycle[:, 0][-1]
period = np.min(np.diff(ext_drive_cycle[:, 0]))
events = None
else:
# e.g. Run US06
# Drive cycle as numpy array
dc_data = drive_cycles[cond_list[1]]
# Find the type of drive cycle ("A", "V", or "W")
typ = cond_list[2][1]
electric = (dc_data, typ)
# Set time and period to 1 second for first step and
# then calculate the difference in consecutive time steps
time = drive_cycles[cond_list[1]][:, 0][-1]
period = np.min(np.diff(drive_cycles[cond_list[1]][:, 0]))
events = None
else:
if "for" in cond and "or until" in cond:
# e.g. for 3 hours or until 4.2 V
cond_list = cond.split()
idx_for = cond_list.index("for")
idx_until = cond_list.index("or")
electric = self.convert_electric(cond_list[:idx_for])
time = self.convert_time_to_seconds(cond_list[idx_for + 1 : idx_until])
events = self.convert_electric(cond_list[idx_until + 2 :])
elif "for" in cond:
# e.g. for 3 hours
cond_list = cond.split()
idx = cond_list.index("for")
electric = self.convert_electric(cond_list[:idx])
time = self.convert_time_to_seconds(cond_list[idx + 1 :])
events = None
elif "until" in cond:
# e.g. until 4.2 V
cond_list = cond.split()
idx = cond_list.index("until")
electric = self.convert_electric(cond_list[:idx])
time = None
events = self.convert_electric(cond_list[idx + 1 :])
else:
raise ValueError(
"""Operating conditions must contain keyword 'for' or 'until' or 'Run'.
For example: {}""".format(
examples
)
)
return {"electric": electric, "time": time, "period": period}, events
def extend_drive_cycle(self, drive_cycle, end_time):
"Extends the drive cycle to enable for event"
temp_time = []
temp_time.append(drive_cycle[:, 0])
loop_end_time = temp_time[0][-1]
i = 1
while loop_end_time <= end_time:
# Extend the drive cycle until the drive cycle time
# becomes greater than specified end time
temp_time.append(
np.append(temp_time[i - 1], temp_time[0] + temp_time[i - 1][-1] + 1)
)
loop_end_time = temp_time[i][-1]
i += 1
time = temp_time[-1]
drive_data = np.tile(drive_cycle[:, 1], i)
# Combine the drive cycle time and data
ext_drive_cycle = np.column_stack((time, drive_data))
# Limit the drive cycle to the specified end_time
ext_drive_cycle = ext_drive_cycle[ext_drive_cycle[:, 0] <= end_time]
del temp_time
return ext_drive_cycle
def convert_electric(self, electric):
"""Convert electrical instructions to consistent output"""
# Rest == zero current
if electric[0].lower() == "rest":
return (0, "A")
else:
if len(electric) in [3, 4]:
if len(electric) == 4:
# e.g. Charge at 4 A, Hold at 3 V
instruction, _, value, unit = electric
elif len(electric) == 3:
# e.g. Discharge at C/2, Charge at 1A
instruction, _, value_unit = electric
if value_unit[0] == "C":
# e.g. C/2
unit = value_unit[0]
value = 1 / float(value_unit[2:])
else:
# e.g. 1A
if "m" in value_unit:
# e.g. 1mA
unit = value_unit[-2:]
value = float(value_unit[:-2])
else:
# e.g. 1A
unit = value_unit[-1]
value = float(value_unit[:-1])
# Read instruction
if instruction.lower() in ["discharge", "hold"]:
sign = 1
elif instruction.lower() == "charge":
sign = -1
else:
raise ValueError(
"""Instruction must be 'discharge', 'charge', 'rest', 'hold' or 'Run'.
For example: {}""".format(
examples
)
)
elif len(electric) == 2:
# e.g. 3 A, 4.1 V
value, unit = electric
sign = 1
elif len(electric) == 1:
# e.g. C/2, 1A
value_unit = electric[0]
if value_unit[0] == "C":
# e.g. C/2
unit = value_unit[0]
value = 1 / float(value_unit[2:])
else:
if "m" in value_unit:
# e.g. 1mA
unit = value_unit[-2:]
value = float(value_unit[:-2])
else:
# e.g. 1A
unit = value_unit[-1]
value = float(value_unit[:-1])
sign = 1
else:
raise ValueError(
"""Instruction '{}' not recognized. Some acceptable examples are: {}
""".format(
" ".join(electric), examples
)
)
# Read value and units
if unit == "C":
return (sign * float(value), "C")
elif unit == "A":
return (sign * float(value), "A")
elif unit == "mA":
return (sign * float(value) / 1000, "A")
elif unit == "V":
return (float(value), "V")
elif unit == "W":
return (sign * float(value), "W")
elif unit == "mW":
return (sign * float(value) / 1000, "W")
else:
raise ValueError(
"""units must be 'C', 'A', 'mA', 'V', 'W' or 'mW', not '{}'.
For example: {}
""".format(
unit, examples
)
)
def convert_time_to_seconds(self, time_and_units):
"""Convert a time in seconds, minutes or hours to a time in seconds"""
time, units = time_and_units
if units in ["second", "seconds", "s", "sec"]:
time_in_seconds = float(time)
elif units in ["minute", "minutes", "m", "min"]:
time_in_seconds = float(time) * 60
elif units in ["hour", "hours", "h", "hr"]:
time_in_seconds = float(time) * 3600
else:
raise ValueError(
"""time units must be 'seconds', 'minutes' or 'hours'. For example: {}
""".format(
examples
)
)
return time_in_seconds
def read_termination(self, termination):
"""
Read the termination reason. If this condition is hit, the experiment will stop.
"""
if termination is None:
return {}
elif isinstance(termination, str):
termination = [termination]
termination_dict = {}
for term in termination:
term_list = term.split()
if term_list[-1] == "capacity":
end_discharge = "".join(term_list[:-1])
if end_discharge.endswith("%"):
end_discharge_percent = end_discharge.split("%")[0]
termination_dict["capacity"] = (float(end_discharge_percent), "%")
elif end_discharge.endswith("Ah"):
end_discharge_Ah = end_discharge.split("Ah")[0]
termination_dict["capacity"] = (float(end_discharge_Ah), "Ah")
elif end_discharge.endswith("A.h"):
end_discharge_Ah = end_discharge.split("A.h")[0]
termination_dict["capacity"] = (float(end_discharge_Ah), "Ah")
else:
raise ValueError(
"Capacity termination must be given in the form "
"'80%', '4Ah', or '4A.h'"
)
else:
raise ValueError(
"Only capacity can be provided as a termination reason, "
"e.g. '80% capacity' or '4 Ah capacity'"
)
return termination_dict
def is_cccv(self, step, next_step):
"""
Check whether a step and the next step indicate a CCCV charge
"""
if self.cccv_handling == "two-step" or next_step is None:
return False
# e.g. step="Charge at 2.0 A until 4.2V"
# next_step="Hold at 4.2V until C/50"
if (
step.startswith("Charge")
and "until" in step
and "V" in step
and "Hold at " in next_step
and "V until" in next_step
):
_, events = self.read_string(step, None)
next_op, _ = self.read_string(next_step, None)
# Check that the event conditions are the same as the hold conditions
if events == next_op["electric"]:
return True
return False
| [
"numpy.append",
"numpy.tile",
"numpy.diff",
"numpy.column_stack"
] | [((12237, 12266), 'numpy.tile', 'np.tile', (['drive_cycle[:, 1]', 'i'], {}), '(drive_cycle[:, 1], i)\n', (12244, 12266), True, 'import numpy as np\n'), ((12341, 12376), 'numpy.column_stack', 'np.column_stack', (['(time, drive_data)'], {}), '((time, drive_data))\n', (12356, 12376), True, 'import numpy as np\n'), ((12040, 12108), 'numpy.append', 'np.append', (['temp_time[i - 1]', '(temp_time[0] + temp_time[i - 1][-1] + 1)'], {}), '(temp_time[i - 1], temp_time[0] + temp_time[i - 1][-1] + 1)\n', (12049, 12108), True, 'import numpy as np\n'), ((9461, 9491), 'numpy.diff', 'np.diff', (['ext_drive_cycle[:, 0]'], {}), '(ext_drive_cycle[:, 0])\n', (9468, 9491), True, 'import numpy as np\n'), ((10052, 10093), 'numpy.diff', 'np.diff', (['drive_cycles[cond_list[1]][:, 0]'], {}), '(drive_cycles[cond_list[1]][:, 0])\n', (10059, 10093), True, 'import numpy as np\n')] |
"""
This is is a part of the DeepLearning.AI TensorFlow Developer Professional Certificate offered on Coursera.
All copyrights belong to them. I am sharing this work here to showcase the projects I have worked on
Course: Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning
Week 1: A New Programming Paradigm
Aim: Predicting the y-axis values for the given x-axis values on a straight line:
"""
import tensorflow as tf
import numpy as np
from tensorflow import keras
import matplotlib as plt
"""
xs = np.array([1, 2, 3, 4, 5, 6])
ys = np.array([1, 1.5, 2, 2.5, 3, 3.5])
model=tf.keras.Sequential([keras.layers.Dense(1, input_shape=[1])])
model.compile(optimizer="sgd", loss= "mean_squared_error")
model.fit(xs, ys, epochs=500)
print(model.predict([7]))
"""
def house_model(y_new):
xs = np.array([1, 2, 3, 4, 5, 6])
ys = np.array([1, 1.5, 2, 2.5, 3, 3.5])
model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss= 'mean_squared_error')
model.fit(xs, ys, epochs=5000)
return model.predict(y_new)[0]
prediction = house_model([7.0])
print(prediction)
| [
"numpy.array",
"tensorflow.keras.layers.Dense"
] | [((871, 899), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6]'], {}), '([1, 2, 3, 4, 5, 6])\n', (879, 899), True, 'import numpy as np\n'), ((910, 944), 'numpy.array', 'np.array', (['[1, 1.5, 2, 2.5, 3, 3.5]'], {}), '([1, 1.5, 2, 2.5, 3, 3.5])\n', (918, 944), True, 'import numpy as np\n'), ((979, 1023), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', ([], {'units': '(1)', 'input_shape': '[1]'}), '(units=1, input_shape=[1])\n', (997, 1023), False, 'from tensorflow import keras\n')] |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 30 12:26:38 2012
Author: <NAME>
"""
'''
function jc = c_sja(n,p)
% PURPOSE: find critical values for Johansen maximum eigenvalue statistic
% ------------------------------------------------------------
% USAGE: jc = c_sja(n,p)
% where: n = dimension of the VAR system
% p = order of time polynomial in the null-hypothesis
% p = -1, no deterministic part
% p = 0, for constant term
% p = 1, for constant plus time-trend
% p > 1 returns no critical values
% ------------------------------------------------------------
% RETURNS: a (3x1) vector of percentiles for the maximum eigenvalue
% statistic for: [90% 95% 99%]
% ------------------------------------------------------------
% NOTES: for n > 12, the function returns a (3x1) vector of zeros.
% The values returned by the function were generated using
% a method described in MacKinnon (1996), using his FORTRAN
% program johdist.f
% ------------------------------------------------------------
% SEE ALSO: johansen()
% ------------------------------------------------------------
% References: MacKinnon, Haug, Michelis (1996) 'Numerical distribution
% functions of likelihood ratio tests for cointegration',
% Queen's University Institute for Economic Research Discussion paper.
% -------------------------------------------------------
% written by:
% <NAME>, Dept of Economics
% University of Toledo
% 2801 W. Bancroft St,
% Toledo, OH 43606
% <EMAIL>
'''
import numpy as np
ss_ejcp0 = '''\
2.9762 4.1296 6.9406
9.4748 11.2246 15.0923
15.7175 17.7961 22.2519
21.8370 24.1592 29.0609
27.9160 30.4428 35.7359
33.9271 36.6301 42.2333
39.9085 42.7679 48.6606
45.8930 48.8795 55.0335
51.8528 54.9629 61.3449
57.7954 61.0404 67.6415
63.7248 67.0756 73.8856
69.6513 73.0946 80.0937'''
ss_ejcp1 = '''\
2.7055 3.8415 6.6349
12.2971 14.2639 18.5200
18.8928 21.1314 25.8650
25.1236 27.5858 32.7172
31.2379 33.8777 39.3693
37.2786 40.0763 45.8662
43.2947 46.2299 52.3069
49.2855 52.3622 58.6634
55.2412 58.4332 64.9960
61.2041 64.5040 71.2525
67.1307 70.5392 77.4877
73.0563 76.5734 83.7105'''
ss_ejcp2 = '''\
2.7055 3.8415 6.6349
15.0006 17.1481 21.7465
21.8731 24.2522 29.2631
28.2398 30.8151 36.1930
34.4202 37.1646 42.8612
40.5244 43.4183 49.4095
46.5583 49.5875 55.8171
52.5858 55.7302 62.1741
58.5316 61.8051 68.5030
64.5292 67.9040 74.7434
70.4630 73.9355 81.0678
76.4081 79.9878 87.2395'''
ejcp0 = np.array(ss_ejcp0.split(),float).reshape(-1,3)
ejcp1 = np.array(ss_ejcp1.split(),float).reshape(-1,3)
ejcp2 = np.array(ss_ejcp2.split(),float).reshape(-1,3)
def c_sja(n, p):
if ((p > 1) or (p < -1)):
jc = np.full(3, np.nan)
elif ((n > 12) or (n < 1)):
jc = np.full(3, np.nan)
elif p == -1:
jc = ejcp0[n-1,:]
elif p == 0:
jc = ejcp1[n-1,:]
elif p == 1:
jc = ejcp2[n-1,:]
return jc
'''
function jc = c_sjt(n,p)
% PURPOSE: find critical values for Johansen trace statistic
% ------------------------------------------------------------
% USAGE: jc = c_sjt(n,p)
% where: n = dimension of the VAR system
% NOTE: routine doesn't work for n > 12
% p = order of time polynomial in the null-hypothesis
% p = -1, no deterministic part
% p = 0, for constant term
% p = 1, for constant plus time-trend
% p > 1 returns no critical values
% ------------------------------------------------------------
% RETURNS: a (3x1) vector of percentiles for the trace
% statistic for [90% 95% 99%]
% ------------------------------------------------------------
% NOTES: for n > 12, the function returns a (3x1) vector of zeros.
% The values returned by the function were generated using
% a method described in MacKinnon (1996), using his FORTRAN
% program johdist.f
% ------------------------------------------------------------
% SEE ALSO: johansen()
% ------------------------------------------------------------
% % References: MacKinnon, Haug, Michelis (1996) 'Numerical distribution
% functions of likelihood ratio tests for cointegration',
% Queen's University Institute for Economic Research Discussion paper.
% -------------------------------------------------------
% written by:
% <NAME>, Dept of Economics
% University of Toledo
% 2801 <NAME> St,
% Toledo, OH 43606
% <EMAIL>
% these are the values from Johansen's 1995 book
% for comparison to the MacKinnon values
%jcp0 = [ 2.98 4.14 7.02
% 10.35 12.21 16.16
% 21.58 24.08 29.19
% 36.58 39.71 46.00
% 55.54 59.24 66.71
% 78.30 86.36 91.12
% 104.93 109.93 119.58
% 135.16 140.74 151.70
% 169.30 175.47 187.82
% 207.21 214.07 226.95
% 248.77 256.23 270.47
% 293.83 301.95 318.14];
%
'''
ss_tjcp0 = '''\
2.9762 4.1296 6.9406
10.4741 12.3212 16.3640
21.7781 24.2761 29.5147
37.0339 40.1749 46.5716
56.2839 60.0627 67.6367
79.5329 83.9383 92.7136
106.7351 111.7797 121.7375
137.9954 143.6691 154.7977
173.2292 179.5199 191.8122
212.4721 219.4051 232.8291
255.6732 263.2603 277.9962
302.9054 311.1288 326.9716'''
ss_tjcp1 = '''\
2.7055 3.8415 6.6349
13.4294 15.4943 19.9349
27.0669 29.7961 35.4628
44.4929 47.8545 54.6815
65.8202 69.8189 77.8202
91.1090 95.7542 104.9637
120.3673 125.6185 135.9825
153.6341 159.5290 171.0905
190.8714 197.3772 210.0366
232.1030 239.2468 253.2526
277.3740 285.1402 300.2821
326.5354 334.9795 351.2150'''
ss_tjcp2 = '''\
2.7055 3.8415 6.6349
16.1619 18.3985 23.1485
32.0645 35.0116 41.0815
51.6492 55.2459 62.5202
75.1027 79.3422 87.7748
102.4674 107.3429 116.9829
133.7852 139.2780 150.0778
169.0618 175.1584 187.1891
208.3582 215.1268 228.2226
251.6293 259.0267 273.3838
298.8836 306.8988 322.4264
350.1125 358.7190 375.3203'''
tjcp0 = np.array(ss_tjcp0.split(),float).reshape(-1,3)
tjcp1 = np.array(ss_tjcp1.split(),float).reshape(-1,3)
tjcp2 = np.array(ss_tjcp2.split(),float).reshape(-1,3)
def c_sjt(n, p):
if ((p > 1) or (p < -1)):
jc = np.full(3, np.nan)
elif ((n > 12) or (n < 1)):
jc = np.full(3, np.nan)
elif p == -1:
jc = tjcp0[n-1,:]
elif p == 0:
jc = tjcp1[n-1,:]
elif p == 1:
jc = tjcp2[n-1,:]
else:
raise ValueError('invalid p')
return jc
if __name__ == '__main__':
for p in range(-2, 3, 1):
for n in range(12):
print(n, p)
print(c_sja(n, p))
print(c_sjt(n, p))
| [
"numpy.full"
] | [((3080, 3098), 'numpy.full', 'np.full', (['(3)', 'np.nan'], {}), '(3, np.nan)\n', (3087, 3098), True, 'import numpy as np\n'), ((6813, 6831), 'numpy.full', 'np.full', (['(3)', 'np.nan'], {}), '(3, np.nan)\n', (6820, 6831), True, 'import numpy as np\n'), ((3144, 3162), 'numpy.full', 'np.full', (['(3)', 'np.nan'], {}), '(3, np.nan)\n', (3151, 3162), True, 'import numpy as np\n'), ((6877, 6895), 'numpy.full', 'np.full', (['(3)', 'np.nan'], {}), '(3, np.nan)\n', (6884, 6895), True, 'import numpy as np\n')] |
from multiml.storegate import StoreGate
import numpy as np
def get_storegate(data_path='/tmp/onlyDiTau/', max_events=50000):
# Index for signal/background shuffle
cur_seed = np.random.get_state()
np.random.seed(1)
permute = np.random.permutation(2 * max_events)
np.random.set_state(cur_seed)
storegate = StoreGate(
backend='numpy',
data_id=''
)
for path, var_names in [
("jet.npy", (
'1stRecoJetPt', '1stRecoJetEta', '1stRecoJetPhi', '1stRecoJetMass',
'2ndRecoJetPt', '2ndRecoJetEta', '2ndRecoJetPhi', '2ndRecoJetMass'
)),
("tau.npy", (
'1stTruthTauJetPt', '1stTruthTauJetEta', '1stTruthTauJetPhi',
'1stTruthTauJetMass', '2ndTruthTauJetPt', '2ndTruthTauJetEta',
'2ndTruthTauJetPhi', '2ndTruthTauJetMass'
)),
("istau.npy", ('tauFlag1stJet', 'tauFlag2ndJet')),
("energy.npy", ('1stRecoJetEnergyMap', '2ndRecoJetEnergyMap')),
]:
data_list = []
for label in ['Htautau', 'Zpure_tau']:
data_loaded = np.load(data_path + f"{label}_{path}")
data_loaded = data_loaded[:max_events]
data_list.append(data_loaded)
data_loaded = np.concatenate(data_list)
data_loaded = data_loaded[permute]
if path == "energy.npy":
# for Pytorch image axis
data_loaded = np.transpose(data_loaded, (0, 1, 4, 2, 3))
storegate.update_data(
data=data_loaded,
var_names=var_names,
phase=(0.6, 0.2, 0.2)
)
# Setting labels
labels = np.concatenate([
np.ones(max_events),
np.zeros(max_events),
])[permute]
storegate.update_data(
data=labels,
var_names='label',
phase=(0.6, 0.2, 0.2)
)
storegate.compile()
# storegate.show_info()
return storegate
| [
"numpy.random.get_state",
"numpy.transpose",
"numpy.random.set_state",
"multiml.storegate.StoreGate",
"numpy.ones",
"numpy.zeros",
"numpy.random.seed",
"numpy.concatenate",
"numpy.load",
"numpy.random.permutation"
] | [((195, 216), 'numpy.random.get_state', 'np.random.get_state', ([], {}), '()\n', (214, 216), True, 'import numpy as np\n'), ((221, 238), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (235, 238), True, 'import numpy as np\n'), ((253, 290), 'numpy.random.permutation', 'np.random.permutation', (['(2 * max_events)'], {}), '(2 * max_events)\n', (274, 290), True, 'import numpy as np\n'), ((295, 324), 'numpy.random.set_state', 'np.random.set_state', (['cur_seed'], {}), '(cur_seed)\n', (314, 324), True, 'import numpy as np\n'), ((342, 380), 'multiml.storegate.StoreGate', 'StoreGate', ([], {'backend': '"""numpy"""', 'data_id': '""""""'}), "(backend='numpy', data_id='')\n", (351, 380), False, 'from multiml.storegate import StoreGate\n'), ((1251, 1276), 'numpy.concatenate', 'np.concatenate', (['data_list'], {}), '(data_list)\n', (1265, 1276), True, 'import numpy as np\n'), ((1097, 1135), 'numpy.load', 'np.load', (["(data_path + f'{label}_{path}')"], {}), "(data_path + f'{label}_{path}')\n", (1104, 1135), True, 'import numpy as np\n'), ((1417, 1459), 'numpy.transpose', 'np.transpose', (['data_loaded', '(0, 1, 4, 2, 3)'], {}), '(data_loaded, (0, 1, 4, 2, 3))\n', (1429, 1459), True, 'import numpy as np\n'), ((1665, 1684), 'numpy.ones', 'np.ones', (['max_events'], {}), '(max_events)\n', (1672, 1684), True, 'import numpy as np\n'), ((1694, 1714), 'numpy.zeros', 'np.zeros', (['max_events'], {}), '(max_events)\n', (1702, 1714), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
import numpy as np
import torch
from utils import utils_image as util
import re
import glob
import os
'''
# --------------------------------------------
# Model
# --------------------------------------------
# <NAME> (github: https://github.com/cszn)
# 03/Mar/2019
# --------------------------------------------
'''
def find_last_checkpoint(save_dir, net_type='G'):
"""
# ---------------------------------------
# <NAME> (github: https://github.com/cszn)
# 03/Mar/2019
# ---------------------------------------
Args:
save_dir: model folder
net_type: 'G' or 'D'
Return:
init_iter: iteration number
init_path: model path
# ---------------------------------------
"""
file_list = glob.glob(os.path.join(save_dir, '*_{}.pth'.format(net_type)))
if file_list:
iter_exist = []
for file_ in file_list:
iter_current = re.findall(r"(\d+)_{}.pth".format(net_type), file_)
iter_exist.append(int(iter_current[0]))
init_iter = max(iter_exist)
init_path = os.path.join(save_dir, '{}_{}.pth'.format(init_iter, net_type))
else:
init_iter = 0
init_path = None
return init_iter, init_path
def test_mode(model, L, mode=0, refield=32, min_size=256, sf=1, modulo=1):
'''
# ---------------------------------------
# <NAME> (github: https://github.com/cszn)
# 03/Mar/2019
# ---------------------------------------
Args:
model: trained model
L: input Low-quality image
mode:
(0) normal: test(model, L)
(1) pad: test_pad(model, L, modulo=16)
(2) split: test_split(model, L, refield=32, min_size=256, sf=1, modulo=1)
(3) x8: test_x8(model, L, modulo=1) ^_^
(4) split and x8: test_split_x8(model, L, refield=32, min_size=256, sf=1, modulo=1)
refield: effective receptive filed of the network, 32 is enough
useful when split, i.e., mode=2, 4
min_size: min_sizeXmin_size image, e.g., 256X256 image
useful when split, i.e., mode=2, 4
sf: scale factor for super-resolution, otherwise 1
modulo: 1 if split
useful when pad, i.e., mode=1
Returns:
E: estimated image
# ---------------------------------------
'''
if mode == 0:
E = test(model, L)
elif mode == 1:
E = test_pad(model, L, modulo, sf)
elif mode == 2:
E = test_split(model, L, refield, min_size, sf, modulo)
elif mode == 3:
E = test_x8(model, L, modulo, sf)
elif mode == 4:
E = test_split_x8(model, L, refield, min_size, sf, modulo)
return E
'''
# --------------------------------------------
# normal (0)
# --------------------------------------------
'''
def test(model, L):
E = model(L)
return E
'''
# --------------------------------------------
# pad (1)
# --------------------------------------------
'''
def test_pad(model, L, modulo=16, sf=1):
h, w = L.size()[-2:]
paddingBottom = int(np.ceil(h/modulo)*modulo-h)
paddingRight = int(np.ceil(w/modulo)*modulo-w)
L = torch.nn.ReplicationPad2d((0, paddingRight, 0, paddingBottom))(L)
E = model(L)
E = E[..., :h*sf, :w*sf]
return E
'''
# --------------------------------------------
# split (function)
# --------------------------------------------
'''
def test_split_fn(model, L, refield=32, min_size=256, sf=1, modulo=1):
"""
Args:
model: trained model
L: input Low-quality image
refield: effective receptive filed of the network, 32 is enough
min_size: min_sizeXmin_size image, e.g., 256X256 image
sf: scale factor for super-resolution, otherwise 1
modulo: 1 if split
Returns:
E: estimated result
"""
h, w = L.size()[-2:]
if h*w <= min_size**2:
L = torch.nn.ReplicationPad2d((0, int(np.ceil(w/modulo)*modulo-w), 0, int(np.ceil(h/modulo)*modulo-h)))(L)
E = model(L)
E = E[..., :h*sf, :w*sf]
else:
top = slice(0, (h//2//refield+1)*refield)
bottom = slice(h - (h//2//refield+1)*refield, h)
left = slice(0, (w//2//refield+1)*refield)
right = slice(w - (w//2//refield+1)*refield, w)
Ls = [L[..., top, left], L[..., top, right], L[..., bottom, left], L[..., bottom, right]]
if h * w <= 4*(min_size**2):
Es = [model(Ls[i]) for i in range(4)]
else:
Es = [test_split_fn(model, Ls[i], refield=refield, min_size=min_size, sf=sf, modulo=modulo) for i in range(4)]
b, c = Es[0].size()[:2]
E = torch.zeros(b, c, sf * h, sf * w).type_as(L)
E[..., :h//2*sf, :w//2*sf] = Es[0][..., :h//2*sf, :w//2*sf]
E[..., :h//2*sf, w//2*sf:w*sf] = Es[1][..., :h//2*sf, (-w + w//2)*sf:]
E[..., h//2*sf:h*sf, :w//2*sf] = Es[2][..., (-h + h//2)*sf:, :w//2*sf]
E[..., h//2*sf:h*sf, w//2*sf:w*sf] = Es[3][..., (-h + h//2)*sf:, (-w + w//2)*sf:]
return E
'''
# --------------------------------------------
# split (2)
# --------------------------------------------
'''
def test_split(model, L, refield=32, min_size=256, sf=1, modulo=1):
E = test_split_fn(model, L, refield=refield, min_size=min_size, sf=sf, modulo=modulo)
return E
'''
# --------------------------------------------
# x8 (3)
# --------------------------------------------
'''
def test_x8(model, L, modulo=1, sf=1):
E_list = [test_pad(model, util.augment_img_tensor4(L, mode=i), modulo=modulo, sf=sf) for i in range(8)]
for i in range(len(E_list)):
if i == 3 or i == 5:
E_list[i] = util.augment_img_tensor4(E_list[i], mode=8 - i)
else:
E_list[i] = util.augment_img_tensor4(E_list[i], mode=i)
output_cat = torch.stack(E_list, dim=0)
E = output_cat.mean(dim=0, keepdim=False)
return E
'''
# --------------------------------------------
# split and x8 (4)
# --------------------------------------------
'''
def test_split_x8(model, L, refield=32, min_size=256, sf=1, modulo=1):
E_list = [test_split_fn(model, util.augment_img_tensor4(L, mode=i), refield=refield, min_size=min_size, sf=sf, modulo=modulo) for i in range(8)]
for k, i in enumerate(range(len(E_list))):
if i==3 or i==5:
E_list[k] = util.augment_img_tensor4(E_list[k], mode=8-i)
else:
E_list[k] = util.augment_img_tensor4(E_list[k], mode=i)
output_cat = torch.stack(E_list, dim=0)
E = output_cat.mean(dim=0, keepdim=False)
return E
'''
# ^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-
# _^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^
# ^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-
'''
'''
# --------------------------------------------
# print
# --------------------------------------------
'''
# --------------------------------------------
# print model
# --------------------------------------------
def print_model(model):
msg = describe_model(model)
print(msg)
# --------------------------------------------
# print params
# --------------------------------------------
def print_params(model):
msg = describe_params(model)
print(msg)
'''
# --------------------------------------------
# information
# --------------------------------------------
'''
# --------------------------------------------
# model inforation
# --------------------------------------------
def info_model(model):
msg = describe_model(model)
return msg
# --------------------------------------------
# params inforation
# --------------------------------------------
def info_params(model):
msg = describe_params(model)
return msg
'''
# --------------------------------------------
# description
# --------------------------------------------
'''
# --------------------------------------------
# model name and total number of parameters
# --------------------------------------------
def describe_model(model):
if isinstance(model, torch.nn.DataParallel):
model = model.module
msg = '\n'
msg += 'models name: {}'.format(model.__class__.__name__) + '\n'
msg += 'Params number: {}'.format(sum(map(lambda x: x.numel(), model.parameters()))) + '\n'
msg += 'Net structure:\n{}'.format(str(model)) + '\n'
return msg
# --------------------------------------------
# parameters description
# --------------------------------------------
def describe_params(model):
if isinstance(model, torch.nn.DataParallel):
model = model.module
msg = '\n'
msg += ' | {:^6s} | {:^6s} | {:^6s} | {:^6s} || {:<20s}'.format('mean', 'min', 'max', 'std', 'param_name') + '\n'
for name, param in model.state_dict().items():
if not 'num_batches_tracked' in name:
v = param.data.clone().float()
msg += ' | {:>6.3f} | {:>6.3f} | {:>6.3f} | {:>6.3f} || {:s}'.format(v.mean(), v.min(), v.max(), v.std(), name) + '\n'
return msg
if __name__ == '__main__':
class Net(torch.nn.Module):
def __init__(self, in_channels=3, out_channels=3):
super(Net, self).__init__()
self.conv = torch.nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, padding=1)
def forward(self, x):
x = self.conv(x)
return x
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
model = Net()
model = model.eval()
print_model(model)
print_params(model)
x = torch.randn((2,3,401,401))
torch.cuda.empty_cache()
with torch.no_grad():
for mode in range(5):
y = test_mode(model, x, mode, refield=32, min_size=256, sf=1, modulo=1)
print(y.shape)
# run utils/utils_model.py | [
"torch.cuda.Event",
"numpy.ceil",
"torch.stack",
"utils.utils_image.augment_img_tensor4",
"torch.nn.Conv2d",
"torch.zeros",
"torch.no_grad",
"torch.nn.ReplicationPad2d",
"torch.cuda.empty_cache",
"torch.randn"
] | [((6013, 6039), 'torch.stack', 'torch.stack', (['E_list'], {'dim': '(0)'}), '(E_list, dim=0)\n', (6024, 6039), False, 'import torch\n'), ((6704, 6730), 'torch.stack', 'torch.stack', (['E_list'], {'dim': '(0)'}), '(E_list, dim=0)\n', (6715, 6730), False, 'import torch\n'), ((9648, 9684), 'torch.cuda.Event', 'torch.cuda.Event', ([], {'enable_timing': '(True)'}), '(enable_timing=True)\n', (9664, 9684), False, 'import torch\n'), ((9696, 9732), 'torch.cuda.Event', 'torch.cuda.Event', ([], {'enable_timing': '(True)'}), '(enable_timing=True)\n', (9712, 9732), False, 'import torch\n'), ((9838, 9867), 'torch.randn', 'torch.randn', (['(2, 3, 401, 401)'], {}), '((2, 3, 401, 401))\n', (9849, 9867), False, 'import torch\n'), ((9870, 9894), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (9892, 9894), False, 'import torch\n'), ((3288, 3350), 'torch.nn.ReplicationPad2d', 'torch.nn.ReplicationPad2d', (['(0, paddingRight, 0, paddingBottom)'], {}), '((0, paddingRight, 0, paddingBottom))\n', (3313, 3350), False, 'import torch\n'), ((9905, 9920), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (9918, 9920), False, 'import torch\n'), ((5696, 5731), 'utils.utils_image.augment_img_tensor4', 'util.augment_img_tensor4', (['L'], {'mode': 'i'}), '(L, mode=i)\n', (5720, 5731), True, 'from utils import utils_image as util\n'), ((5863, 5910), 'utils.utils_image.augment_img_tensor4', 'util.augment_img_tensor4', (['E_list[i]'], {'mode': '(8 - i)'}), '(E_list[i], mode=8 - i)\n', (5887, 5910), True, 'from utils import utils_image as util\n'), ((5951, 5994), 'utils.utils_image.augment_img_tensor4', 'util.augment_img_tensor4', (['E_list[i]'], {'mode': 'i'}), '(E_list[i], mode=i)\n', (5975, 5994), True, 'from utils import utils_image as util\n'), ((6343, 6378), 'utils.utils_image.augment_img_tensor4', 'util.augment_img_tensor4', (['L'], {'mode': 'i'}), '(L, mode=i)\n', (6367, 6378), True, 'from utils import utils_image as util\n'), ((6556, 6603), 'utils.utils_image.augment_img_tensor4', 'util.augment_img_tensor4', (['E_list[k]'], {'mode': '(8 - i)'}), '(E_list[k], mode=8 - i)\n', (6580, 6603), True, 'from utils import utils_image as util\n'), ((6642, 6685), 'utils.utils_image.augment_img_tensor4', 'util.augment_img_tensor4', (['E_list[k]'], {'mode': 'i'}), '(E_list[k], mode=i)\n', (6666, 6685), True, 'from utils import utils_image as util\n'), ((9454, 9551), 'torch.nn.Conv2d', 'torch.nn.Conv2d', ([], {'in_channels': 'in_channels', 'out_channels': 'out_channels', 'kernel_size': '(3)', 'padding': '(1)'}), '(in_channels=in_channels, out_channels=out_channels,\n kernel_size=3, padding=1)\n', (9469, 9551), False, 'import torch\n'), ((3199, 3218), 'numpy.ceil', 'np.ceil', (['(h / modulo)'], {}), '(h / modulo)\n', (3206, 3218), True, 'import numpy as np\n'), ((3251, 3270), 'numpy.ceil', 'np.ceil', (['(w / modulo)'], {}), '(w / modulo)\n', (3258, 3270), True, 'import numpy as np\n'), ((4819, 4852), 'torch.zeros', 'torch.zeros', (['b', 'c', '(sf * h)', '(sf * w)'], {}), '(b, c, sf * h, sf * w)\n', (4830, 4852), False, 'import torch\n'), ((4088, 4107), 'numpy.ceil', 'np.ceil', (['(w / modulo)'], {}), '(w / modulo)\n', (4095, 4107), True, 'import numpy as np\n'), ((4124, 4143), 'numpy.ceil', 'np.ceil', (['(h / modulo)'], {}), '(h / modulo)\n', (4131, 4143), True, 'import numpy as np\n')] |
import unittest
import shutil
import tempfile
import numpy as np
import pandas as pd
import pymc3 as pm
from pymc3 import summary
from sklearn.gaussian_process import GaussianProcessRegressor as skGaussianProcessRegressor
from sklearn.model_selection import train_test_split
from pymc3_models.exc import PyMC3ModelsError
from pymc3_models.models.GaussianProcessRegression import GaussianProcessRegression
class GaussianProcessRegressionTestCase(unittest.TestCase):
def setUp(self):
self.num_training_samples = 150
self.num_pred = 1
self.length_scale = 1.0
self.noise_variance = 2.0
self.signal_variance = 3.0
X = np.linspace(start=0, stop=10, num=self.num_training_samples)[:, None]
cov_func = self.signal_variance**2 * pm.gp.cov.ExpQuad(self.num_pred,
self.length_scale)
mean_func = pm.gp.mean.Zero()
f_ = np.random.multivariate_normal(mean_func(X).eval(),
cov_func(X).eval() + 1e-8 * np.eye(self.num_training_samples),
self.num_pred
).flatten()
y = f_ + self.noise_variance * np.random.randn(self.num_training_samples)
self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(
X, y, test_size=0.3
)
self.test_GPR = GaussianProcessRegression()
# self.test_nuts_GPR = GaussianProcessRegression()
self.test_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.test_dir)
class GaussianProcessRegressionFitTestCase(GaussianProcessRegressionTestCase):
def test_advi_fit_returns_correct_model(self):
# This print statement ensures PyMC3 output won't overwrite the test name
print('')
self.test_GPR.fit(self.X_train, self.y_train)
self.assertEqual(self.num_pred, self.test_GPR.num_pred)
self.assertAlmostEqual(self.signal_variance,
int(self.test_GPR.summary['mean']['signal_variance__0']),
0)
self.assertAlmostEqual(self.length_scale,
int(self.test_GPR.summary['mean']['length_scale__0_0']),
0)
self.assertAlmostEqual(self.noise_variance,
int(self.test_GPR.summary['mean']['noise_variance__0']),
0)
# def test_nuts_fit_returns_correct_model(self):
# # This print statement ensures PyMC3 output won't overwrite the test name
# print('')
# self.test_nuts_GPR.fit(self.X_train, self.y_train, inference_type='nuts')
#
# self.assertEqual(self.num_pred, self.test_nuts_GPR.num_pred)
# self.assertAlmostEqual(self.signal_variance,
# int(self.test_nuts_GPR.summary['mean']['signal_variance__0']),
# 0)
# self.assertAlmostEqual(self.length_scale,
# int(self.test_nuts_GPR.summary['mean']['length_scale__0_0']),
# 0)
# self.assertAlmostEqual(self.noise_variance,
# int(self.test_nuts_GPR.summary['mean']['noise_variance__0']),
# 0)
class GaussianProcessRegressionPredictTestCase(GaussianProcessRegressionTestCase):
def test_predict_returns_predictions(self):
print('')
self.test_GPR.fit(self.X_train, self.y_train)
preds = self.test_GPR.predict(self.X_test)
self.assertEqual(self.y_test.shape, preds.shape)
def test_predict_returns_mean_predictions_and_std(self):
print('')
self.test_GPR.fit(self.X_train, self.y_train)
preds, stds = self.test_GPR.predict(self.X_test, return_std=True)
self.assertEqual(self.y_test.shape, preds.shape)
self.assertEqual(self.y_test.shape, stds.shape)
def test_predict_raises_error_if_not_fit(self):
print('')
with self.assertRaises(PyMC3ModelsError) as no_fit_error:
test_GPR = GaussianProcessRegression()
test_GPR.predict(self.X_train)
expected = 'Run fit on the model before predict.'
self.assertEqual(str(no_fit_error.exception), expected)
class GaussianProcessRegressionScoreTestCase(GaussianProcessRegressionTestCase):
def test_score_matches_sklearn_performance(self):
print('')
skGPR = skGaussianProcessRegressor()
skGPR.fit(self.X_train, self.y_train)
skGPR_score = skGPR.score(self.X_test, self.y_test)
self.test_GPR.fit(self.X_train, self.y_train)
test_GPR_score = self.test_GPR.score(self.X_test, self.y_test)
self.assertAlmostEqual(skGPR_score, test_GPR_score, 1)
class GaussianProcessRegressionSaveAndLoadTestCase(GaussianProcessRegressionTestCase):
def test_save_and_load_work_correctly(self):
print('')
self.test_GPR.fit(self.X_train, self.y_train)
score1 = self.test_GPR.score(self.X_test, self.y_test)
self.test_GPR.save(self.test_dir)
GPR2 = GaussianProcessRegression()
GPR2.load(self.test_dir)
self.assertEqual(self.test_GPR.inference_type, GPR2.inference_type)
self.assertEqual(self.test_GPR.num_pred, GPR2.num_pred)
self.assertEqual(self.test_GPR.num_training_samples, GPR2.num_training_samples)
pd.testing.assert_frame_equal(summary(self.test_GPR.trace),
summary(GPR2.trace))
score2 = GPR2.score(self.X_test, self.y_test)
self.assertAlmostEqual(score1, score2, 1)
| [
"sklearn.gaussian_process.GaussianProcessRegressor",
"pymc3_models.models.GaussianProcessRegression.GaussianProcessRegression",
"pymc3.gp.cov.ExpQuad",
"numpy.eye",
"sklearn.model_selection.train_test_split",
"pymc3.summary",
"pymc3.gp.mean.Zero",
"numpy.linspace",
"tempfile.mkdtemp",
"shutil.rmtr... | [((924, 941), 'pymc3.gp.mean.Zero', 'pm.gp.mean.Zero', ([], {}), '()\n', (939, 941), True, 'import pymc3 as pm\n'), ((1370, 1407), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.3)'}), '(X, y, test_size=0.3)\n', (1386, 1407), False, 'from sklearn.model_selection import train_test_split\n'), ((1455, 1482), 'pymc3_models.models.GaussianProcessRegression.GaussianProcessRegression', 'GaussianProcessRegression', ([], {}), '()\n', (1480, 1482), False, 'from pymc3_models.models.GaussianProcessRegression import GaussianProcessRegression\n'), ((1566, 1584), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (1582, 1584), False, 'import tempfile\n'), ((1618, 1646), 'shutil.rmtree', 'shutil.rmtree', (['self.test_dir'], {}), '(self.test_dir)\n', (1631, 1646), False, 'import shutil\n'), ((4553, 4581), 'sklearn.gaussian_process.GaussianProcessRegressor', 'skGaussianProcessRegressor', ([], {}), '()\n', (4579, 4581), True, 'from sklearn.gaussian_process import GaussianProcessRegressor as skGaussianProcessRegressor\n'), ((5209, 5236), 'pymc3_models.models.GaussianProcessRegression.GaussianProcessRegression', 'GaussianProcessRegression', ([], {}), '()\n', (5234, 5236), False, 'from pymc3_models.models.GaussianProcessRegression import GaussianProcessRegression\n'), ((673, 733), 'numpy.linspace', 'np.linspace', ([], {'start': '(0)', 'stop': '(10)', 'num': 'self.num_training_samples'}), '(start=0, stop=10, num=self.num_training_samples)\n', (684, 733), True, 'import numpy as np\n'), ((788, 839), 'pymc3.gp.cov.ExpQuad', 'pm.gp.cov.ExpQuad', (['self.num_pred', 'self.length_scale'], {}), '(self.num_pred, self.length_scale)\n', (805, 839), True, 'import pymc3 as pm\n'), ((4188, 4215), 'pymc3_models.models.GaussianProcessRegression.GaussianProcessRegression', 'GaussianProcessRegression', ([], {}), '()\n', (4213, 4215), False, 'from pymc3_models.models.GaussianProcessRegression import GaussianProcessRegression\n'), ((5537, 5565), 'pymc3.summary', 'summary', (['self.test_GPR.trace'], {}), '(self.test_GPR.trace)\n', (5544, 5565), False, 'from pymc3 import summary\n'), ((5605, 5624), 'pymc3.summary', 'summary', (['GPR2.trace'], {}), '(GPR2.trace)\n', (5612, 5624), False, 'from pymc3 import summary\n'), ((1264, 1306), 'numpy.random.randn', 'np.random.randn', (['self.num_training_samples'], {}), '(self.num_training_samples)\n', (1279, 1306), True, 'import numpy as np\n'), ((1077, 1110), 'numpy.eye', 'np.eye', (['self.num_training_samples'], {}), '(self.num_training_samples)\n', (1083, 1110), True, 'import numpy as np\n')] |
from collections import defaultdict
import numpy as np
# Grafted from
# https://github.com/maartenbreddels/ipyvolume/blob/d13828dfd8b57739004d5daf7a1d93ad0839ed0f/ipyvolume/serialize.py#L219
def array_to_binary(ar, obj=None, force_contiguous=True):
if ar is None:
return None
if ar.dtype.kind not in ["u", "i", "f"]: # ints and floats
raise ValueError("unsupported dtype: %s" % (ar.dtype))
# WebGL does not support float64, case it here
if ar.dtype == np.float64:
ar = ar.astype(np.float32)
# JS does not support int64
if ar.dtype == np.int64:
ar = ar.astype(np.int32)
# make sure it's contiguous
if force_contiguous and not ar.flags["C_CONTIGUOUS"]:
ar = np.ascontiguousarray(ar)
return {
# binary data representation of a numpy matrix
"value": memoryview(ar),
# dtype convertible to a typed array
"dtype": str(ar.dtype),
# height of np matrix
"length": ar.shape[0],
# width of np matrix
"size": 1 if len(ar.shape) == 1 else ar.shape[1],
}
def serialize_columns(data_set_cols, obj=None):
if data_set_cols is None:
return None
layers = defaultdict(dict)
# Number of records in data set
length = {}
for col in data_set_cols:
accessor_attribute = array_to_binary(col["np_data"])
if length.get(col["layer_id"]):
length[col["layer_id"]] = max(length[col["layer_id"]], accessor_attribute["length"])
else:
length[col["layer_id"]] = accessor_attribute["length"]
# attributes is deck.gl's expected argument name for
# binary data transfer
if not layers[col["layer_id"]].get("attributes"):
layers[col["layer_id"]]["attributes"] = {}
# Add new accessor
layers[col["layer_id"]]["attributes"][col["accessor"]] = {
"value": accessor_attribute["value"],
"dtype": accessor_attribute["dtype"],
"size": accessor_attribute["size"],
}
for layer_key, _ in layers.items():
layers[layer_key]["length"] = length[layer_key]
return layers
data_buffer_serialization = dict(to_json=serialize_columns, from_json=None)
| [
"collections.defaultdict",
"numpy.ascontiguousarray"
] | [((1202, 1219), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (1213, 1219), False, 'from collections import defaultdict\n'), ((732, 756), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['ar'], {}), '(ar)\n', (752, 756), True, 'import numpy as np\n')] |
import random
import numpy as np
from MAIN.Basics import Processor, Space
from operator import itemgetter
class StateSpace(Processor, Space):
def __init__(self, agent):
self.agent = agent
super().__init__(agent.config['StateSpaceState'])
def process(self):
self.agent.data['NETWORK_STATE'] = self._get_network_input()
self.agent.data['ENGINE_STATE' ] = self._get_engine_input()
def _get_network_input(self):
method = self.agent.config['StateSpaceNetworkSampleType']
state = self.get_random_sample(method)
return state
def _get_engine_input(self):
method = self.agent.config['StateSpaceEngineSampleConversion']
state = self.agent.data['NETWORK_STATE']
state = self.convert(state, method)
return state
class ActionSpace(Processor, Space):
def __init__(self, agent):
self.agent = agent
super().__init__(agent.config['ActionSpaceAction'])
def process(self):
self.agent.data['NETWORK_ACTION'] = self._get_network_input()
self.agent.data['ENGINE_ACTION' ] = self._get_engine_input()
def _get_network_input(self):
method = self.agent.config['ActionSpaceNetworkSampleType']
if method == 'exploration':
self.agent.exploration.process()
action = self.agent.data['EXPLORATION_ACTION']
else:
action = self.get_random_sample(method)
return action
def _get_engine_input(self):
method = self.agent.config['ActionSpaceEngineSampleConversion']
index = self.agent.data['EXPLORATION_ACTION']
action = self.convert(index, method)
return action
class RewardEngine(Processor):
def __init__(self, agent, engine):
self.engine = engine
self.agent = agent
def process(self):
reward, record = self._get_reward()
self.agent.data['ENGINE_REWARD'] = reward
self.agent.data['ENGINE_RECORD'] = record
def _get_reward(self):
state = self.agent.data['ENGINE_STATE']
action = self.agent.data['ENGINE_ACTION']
self.engine.process(**state, **action)
return self.engine.reward, self.engine.record
class Exploration(Processor):
def __init__(self, agent):
self.agent = agent
self.method = agent.config['ExplorationMethod']
self.counter = agent.counters[agent.config['ExplorationCounter']]
self.func = self.get_func(self.method)
if self.method == 'boltzmann':
self.target_attr = getattr(self.agent, self.agent.config['ExplorationBoltzmannProbAttribute'])
def process(self):
self.agent.data['EXPLORATION_ACTION'] = self.func()
def get_func(self, method):
method = '_' + method
return getattr(self, method)
def _random(self):
n_action = self.agent.action_space.n_combination
action_idx = random.randrange(n_action)
return action_idx
def _greedy(self):
self.agent.feed_dict[self.agent.input_layer] = [self.agent.data['NETWORK_STATE']]
q_value = self.agent.session.run(self.agent.output_layer, feed_dict=self.agent.feed_dict)
q_value = q_value.reshape(-1,)
action_idx = np.argmax(q_value)
return action_idx
def _e_greedy(self):
e = self.counter.value
action_idx = self._random() if random.random() < e else self._greedy()
self.counter.step()
return action_idx
def _boltzmann(self):
self.agent.data['BOLTZMANN_TEMP'] = self.counter.value
self.agent.feed_dict[self.agent.input_layer] = [self.agent.data['NETWORK_STATE']]
self.agent.feed_dict[self.agent.temp ] = [self.agent.data['BOLTZMANN_TEMP']]
prob = self.agent.session.run(self.target_attr, feed_dict=self.agent.feed_dict)
action_idx = np.random.choice(self.agent.action_space.n_combination, p=prob)
self.counter.step()
return action_idx
class ExperienceBuffer(Processor):
def __init__(self, agent):
buffer_size = int(agent.config['ExperienceBufferBufferSize'])
self.agent = agent
self.buffer = []
self.buffer_size = buffer_size
def process(self, method):
if method == 'add':
self._add_sample(self.agent.data['SAMPLE'])
elif method == 'get':
self.agent.data['EXPERIENCE_BUFFER_SAMPLE'] = self._get_sample()
else:
raise ValueError("Error: method name should be add/get.")
def _add_sample(self, sample):
sample_length = len(sample)
buffer_length = len(self.buffer)
is_single_sample = True if sample_length == 1 else False
if is_single_sample is True:
total_length = buffer_length
elif is_single_sample is False:
total_length = buffer_length + sample_length
else:
raise ValueError("Error: Boolean value required for input is_single_sample.")
if total_length > buffer_length:
idx_start = total_length - buffer_length
self.buffer = self.buffer[idx_start:]
self.buffer.extend(sample)
else:
self.buffer.extend(sample)
def _get_sample(self):
size = int(self.agent.config['ExperienceBufferSamplingSize'])
sample = itemgetter(*np.random.randint(len(self.buffer), size=size))(self.buffer)
return sample
class Recorder(Processor):
def __init__(self, agent):
self.data_field = agent.config['RecorderDataField']
self.record_freq = agent.config['RecorderRecordFreq']
self.agent = agent
if self.data_field is not None:
self.record = {key: [] for key in self.data_field}
def process(self):
if self.data_field is not None:
if (self.agent.epoch_counter.n_step % self.record_freq) == 0:
for key in self.record.keys():
self.record[key].append(self.agent.data[key])
| [
"numpy.random.choice",
"random.random",
"numpy.argmax",
"random.randrange"
] | [((3017, 3043), 'random.randrange', 'random.randrange', (['n_action'], {}), '(n_action)\n', (3033, 3043), False, 'import random\n'), ((3349, 3367), 'numpy.argmax', 'np.argmax', (['q_value'], {}), '(q_value)\n', (3358, 3367), True, 'import numpy as np\n'), ((3978, 4041), 'numpy.random.choice', 'np.random.choice', (['self.agent.action_space.n_combination'], {'p': 'prob'}), '(self.agent.action_space.n_combination, p=prob)\n', (3994, 4041), True, 'import numpy as np\n'), ((3495, 3510), 'random.random', 'random.random', ([], {}), '()\n', (3508, 3510), False, 'import random\n')] |
#!/usr/bin/env python3
#
# Pocket SDR Python AP - GNSS Signal Tracking Log Plot
#
# Author:
# T.TAKASU
#
# History:
# 2022-02-11 1.0 new
#
import sys, re
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import sdr_rtk
mpl.rcParams['toolbar'] = 'None';
mpl.rcParams['font.size'] = 9
# show usage -------------------------------------------------------------------
def show_usage():
print('Usage: pocket_plot.py [-sig sig] [-prn prn] [-type type] [-atype type]')
print(' [-ts time] [-te time] [-nav file] [-pos lat,lon,hgt] file')
exit()
# time string to time ----------------------------------------------------------
def str2time(str):
return sdr_rtk.epoch2time([float(s) for s in re.split('[/:-_ ]', str)])
# satellite elevations ---------------------------------------------------------
def sat_els(ts, te, sat, pos, nav):
rr = sdr_rtk.pos2ecef(pos)
els = []
span = sdr_rtk.timediff(te, ts)
for t in np.arange(0.0, span + 30.0, 30.0):
time = sdr_rtk.timeadd(ts, t)
rs, dts, var, svh = sdr_rtk.satpos(time, time, sat, nav)
r, e = sdr_rtk.geodist(rs, rr)
az, el = sdr_rtk.satazel(pos, e)
els.append([time.time, el * sdr_rtk.R2D])
return np.array(els)
# read tracking log -----------------------------------------------------------
def read_log(ts, te, sig, prn, type, file):
time = sdr_rtk.GTIME()
log = []
fp = open(file)
for line in fp.readlines():
s = line.split(',')
if len(s) < 1:
continue
elif s[0] == '$TIME':
utc = sdr_rtk.epoch2time([float(s) for s in s[1:]])
time = sdr_rtk.utc2gpst(utc)
continue
if ((ts.time != 0 and sdr_rtk.timediff(time, ts) < 0.0) or
(te.time != 0 and sdr_rtk.timediff(time, te) >= 0.0)):
continue
if s[0] == '$CH':
if s[2] != sig or int(s[3]) != prn:
continue
elif type == 'LOCK':
log.append([time.time, float(s[4])])
elif type == 'C/N0':
log.append([time.time, float(s[5])])
elif type == 'COFF':
log.append([time.time, float(s[6])])
elif type == 'DOP':
log.append([time.time, float(s[7])])
elif type == 'ADR':
log.append([time.time, float(s[8])])
elif s[0] == '$L6FRM' and type == 'L6FRM':
if s[2] == sig and int(s[3]) == prn:
log.append([time.time, 1])
fp.close()
return np.array(log)
# plot log --------------------------------------------------------------------
def plot_log(fig, rect, type, log, els, msg):
color = ('darkblue', 'dimgray', 'blue')
ax = fig.add_axes(rect)
t0 = np.floor(log.T[0][0] / 86400) * 86400
time = (log.T[0] - t0) / 3600
ax.plot(time, log.T[1], '.', color=color[0], ms=0.1)
ax.grid(True, lw=0.4)
ax.set_xticks(np.arange(0, 24 * 7, 2))
ax.set_xlim(time[0], time[-1])
ax.set_xlabel('Hour (GPST)')
if type == 'LOCK':
ax.set_ylabel('LOCK TIME (s)')
elif type == 'C/N0':
ax.set_ylabel('C/N0 (dB-Hz)')
ax.set_ylim(20.0, 65.0)
elif type == 'COFF':
ax.set_ylabel('Code Offset (ms)')
ax.set_ylim(0.0, 10.0)
elif type == 'DOP':
ax.set_ylabel('Doppler Frequency (Hz)')
ax.set_ylim(-3000.0, 3000.0)
elif type == 'ADR':
ax.set_ylabel('Accumlated Delta Range (cyc)')
if len(els) > 0:
ax3 = ax.twinx()
time = (els.T[0] - t0) / 3600
ax3.plot(time, els.T[1], '.', color=color[1], ms=0.1)
ax3.set_ylim(0, 90.0)
ax3.set_ylabel('Elevation Angle (deg)', color=color[1])
plt.setp(ax3.get_yticklabels(), color=color[1])
if len(msg) > 0:
ax2 = ax.twinx()
ax2.axis('off')
time = (msg.T[0] - t0) / 3600
ax2.plot(time, msg.T[1], 'o', color=color[2], ms=2)
ax2.set_ylim(0, 20)
n = len(time)
N = (time[-1] - time[0]) * 3600 + 1
rate = n * 100.0 / N
ax2.text(0.97, 0.96, '# L6FRM = %d / %d (%.1f %%)' % (n, N, rate),
ha='right', va='top', c=color[2], transform=ax2.transAxes)
#-------------------------------------------------------------------------------
#
# Synopsis
#
# pocket_plot.py [-sig sig] [-prn prn] [-type type] [-atype type]
# [-ts time] [-te time] [-nav file] [-pos lat,lon,hgt] file
#
# Description
#
# Plot GNSS signal tracking log written by pocket_trk.py.
#
# Options ([]: default)
#
# -sig sig
# GNSS signal type ID (L1CA, L2CM, ...). [L6D]
#
# -prn prn
# PRN numbers of the GNSS signal. [194]
#
# -type type
# Log type to be plotted as follows. [C/N0]
#
# LOCK : signal lock time
# C/N0 : signal C/N0
# COFF : code offset
# DOP : Doppler frequency
# ADR : accumlated delta range
#
# -atype type
# Additional log type to be plotted as follows. []
#
# L6FRM : Valid L6 Frame decoded.
#
# -ts time
# Start time in GPST as format as YYYYMMDDHHmmss. [all]
#
# -te time
# End time in GPST as format as YYYYMMDDHHmmss. [all]
#
# -nav file
# RINEX NAV file path to plot satellite elevation angle. []
#
# -pos lat,lon,hgt
# Receiver latitude (deg), longitude (deg) and height (m)
#
# file
# GNSS signal tracking log written by pocket_trk.py.
#
if __name__ == '__main__':
window = 'Pocket SDR - GNSS SIGNAL TRACKING LOG'
ts = sdr_rtk.GTIME()
te = sdr_rtk.GTIME()
sig, prn, type, atype = 'L6D', 194, 'C/N0', ''
pos = [35.6 * sdr_rtk.D2R, 139.6 * sdr_rtk.D2R, 0.0]
size = (9, 6)
rect0 = [0.08, 0.090, 0.84, 0.85]
rect1 = [0.08, 0.089, 0.84, 0.85]
file, nfile = '', ''
i = 1
while i < len(sys.argv):
if sys.argv[i] == '-sig':
i += 1
sig = sys.argv[i]
elif sys.argv[i] == '-prn':
i += 1
prn = int(sys.argv[i])
elif sys.argv[i] == '-type':
i += 1
type = sys.argv[i]
elif sys.argv[i] == '-atype':
i += 1
atype = sys.argv[i]
elif sys.argv[i] == '-ts':
i += 1
ts = str2time(sys.argv[i])
elif sys.argv[i] == '-te':
i += 1
te = str2time(sys.argv[i])
elif sys.argv[i] == '-nav':
i += 1
nfile = sys.argv[i]
elif sys.argv[i] == '-pos':
i += 1
pos = [float(s) for s in sys.argv[i].split(',')]
pos[0] *= sdr_rtk.D2R
pos[1] *= sdr_rtk.D2R
elif sys.argv[i][0] == '-':
show_usage()
else:
file = sys.argv[i]
i += 1
if file == '':
print('Specify input file.')
exit()
if nfile:
sat = sdr_rtk.satno(sdr_rtk.SYS_QZS, prn)
obs, nav = sdr_rtk.readrnx(nfile)
els = sat_els(ts, te, sat, pos, nav)
sdr_rtk.navfree(nav)
else:
els = []
log = read_log(ts, te, sig, prn, type, file)
msg = read_log(ts, te, sig, prn, atype, file)
fig = plt.figure(window, figsize=size)
ax0 = fig.add_axes(rect0)
ax0.axis('off')
ax0.set_title('SIG = %s, PRN = %d, TYPE = %s, FILE = %s' %
(sig, prn, type, file), fontsize=10)
plot_log(fig, rect1, type, log, els, msg)
plt.show()
| [
"sdr_rtk.satpos",
"re.split",
"sdr_rtk.readrnx",
"sdr_rtk.GTIME",
"sdr_rtk.timediff",
"sdr_rtk.geodist",
"sdr_rtk.satazel",
"numpy.floor",
"sdr_rtk.pos2ecef",
"numpy.array",
"matplotlib.pyplot.figure",
"sdr_rtk.utc2gpst",
"sdr_rtk.satno",
"sdr_rtk.timeadd",
"sdr_rtk.navfree",
"numpy.ar... | [((894, 915), 'sdr_rtk.pos2ecef', 'sdr_rtk.pos2ecef', (['pos'], {}), '(pos)\n', (910, 915), False, 'import sdr_rtk\n'), ((940, 964), 'sdr_rtk.timediff', 'sdr_rtk.timediff', (['te', 'ts'], {}), '(te, ts)\n', (956, 964), False, 'import sdr_rtk\n'), ((978, 1011), 'numpy.arange', 'np.arange', (['(0.0)', '(span + 30.0)', '(30.0)'], {}), '(0.0, span + 30.0, 30.0)\n', (987, 1011), True, 'import numpy as np\n'), ((1257, 1270), 'numpy.array', 'np.array', (['els'], {}), '(els)\n', (1265, 1270), True, 'import numpy as np\n'), ((1407, 1422), 'sdr_rtk.GTIME', 'sdr_rtk.GTIME', ([], {}), '()\n', (1420, 1422), False, 'import sdr_rtk\n'), ((2586, 2599), 'numpy.array', 'np.array', (['log'], {}), '(log)\n', (2594, 2599), True, 'import numpy as np\n'), ((5629, 5644), 'sdr_rtk.GTIME', 'sdr_rtk.GTIME', ([], {}), '()\n', (5642, 5644), False, 'import sdr_rtk\n'), ((5654, 5669), 'sdr_rtk.GTIME', 'sdr_rtk.GTIME', ([], {}), '()\n', (5667, 5669), False, 'import sdr_rtk\n'), ((7275, 7307), 'matplotlib.pyplot.figure', 'plt.figure', (['window'], {'figsize': 'size'}), '(window, figsize=size)\n', (7285, 7307), True, 'import matplotlib.pyplot as plt\n'), ((7521, 7531), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7529, 7531), True, 'import matplotlib.pyplot as plt\n'), ((1028, 1050), 'sdr_rtk.timeadd', 'sdr_rtk.timeadd', (['ts', 't'], {}), '(ts, t)\n', (1043, 1050), False, 'import sdr_rtk\n'), ((1079, 1115), 'sdr_rtk.satpos', 'sdr_rtk.satpos', (['time', 'time', 'sat', 'nav'], {}), '(time, time, sat, nav)\n', (1093, 1115), False, 'import sdr_rtk\n'), ((1131, 1154), 'sdr_rtk.geodist', 'sdr_rtk.geodist', (['rs', 'rr'], {}), '(rs, rr)\n', (1146, 1154), False, 'import sdr_rtk\n'), ((1172, 1195), 'sdr_rtk.satazel', 'sdr_rtk.satazel', (['pos', 'e'], {}), '(pos, e)\n', (1187, 1195), False, 'import sdr_rtk\n'), ((2808, 2837), 'numpy.floor', 'np.floor', (['(log.T[0][0] / 86400)'], {}), '(log.T[0][0] / 86400)\n', (2816, 2837), True, 'import numpy as np\n'), ((2981, 3004), 'numpy.arange', 'np.arange', (['(0)', '(24 * 7)', '(2)'], {}), '(0, 24 * 7, 2)\n', (2990, 3004), True, 'import numpy as np\n'), ((6977, 7012), 'sdr_rtk.satno', 'sdr_rtk.satno', (['sdr_rtk.SYS_QZS', 'prn'], {}), '(sdr_rtk.SYS_QZS, prn)\n', (6990, 7012), False, 'import sdr_rtk\n'), ((7032, 7054), 'sdr_rtk.readrnx', 'sdr_rtk.readrnx', (['nfile'], {}), '(nfile)\n', (7047, 7054), False, 'import sdr_rtk\n'), ((7108, 7128), 'sdr_rtk.navfree', 'sdr_rtk.navfree', (['nav'], {}), '(nav)\n', (7123, 7128), False, 'import sdr_rtk\n'), ((740, 764), 're.split', 're.split', (['"""[/:-_ ]"""', 'str'], {}), "('[/:-_ ]', str)\n", (748, 764), False, 'import sys, re\n'), ((1673, 1694), 'sdr_rtk.utc2gpst', 'sdr_rtk.utc2gpst', (['utc'], {}), '(utc)\n', (1689, 1694), False, 'import sdr_rtk\n'), ((1755, 1781), 'sdr_rtk.timediff', 'sdr_rtk.timediff', (['time', 'ts'], {}), '(time, ts)\n', (1771, 1781), False, 'import sdr_rtk\n'), ((1823, 1849), 'sdr_rtk.timediff', 'sdr_rtk.timediff', (['time', 'te'], {}), '(time, te)\n', (1839, 1849), False, 'import sdr_rtk\n')] |
# -*- coding: utf-8 -*-
"""
201901, Dr. <NAME>, Beijing & Xinglong, NAOC
202101-? Dr. <NAME> & Dr./Prof. <NAME>
Light_Curve_Pipeline
v3 (2021A) Upgrade from former version, remove unused code
Qx_xxxx_ is the working part of the step, while Qx_xxxx is the shell
"""
import numpy as np
import astropy.io.fits as fits
from .JZ_utils import loadlist, datestr, logfile, conf
def _flatcomb_(ini, lst, bias_fits, out_flat_fits, lf):
nf = len(lst)
# get size of images
hdr = fits.getheader(lst[0])
nx = hdr['NAXIS1']
ny = hdr['NAXIS2']
lf.show("{:02d} flat files, image sizes {:4d}x{:4d}".format(nf, nx, ny), logfile.DEBUG)
# load bias
lf.show("Loading Bias: {}".format(bias_fits), logfile.DEBUG)
data_bias = fits.getdata(bias_fits)
# load images
data_cube = np.empty((nf, ny, nx), dtype=np.float32)
for f in range(nf):
data_tmp = fits.getdata(lst[f]) - data_bias
data_tmp_med = np.median(data_tmp)
if ini["flat_limit_low"] < data_tmp_med < ini["flat_limit_high"]:
data_cube[f, :, :] = data_tmp / data_tmp_med
lf.show("Loading {:02d}/{:02d}: {:40s} / Scaled by {:7.1f}".format(
f + 1, nf, lst[f], data_tmp_med), logfile.DEBUG)
else:
data_cube[f, :, :] = np.nan
lf.show("Ignore {:02d}/{:02d}: {:40s} / XXX MED = {:7.1f}".format(
f + 1, nf, lst[f], data_tmp_med), logfile.DEBUG)
# get median
data_med = np.nanmedian(data_cube, axis=0)
# add process time to header
hdr.append(('COMBTIME', datestr()))
s = hdr.tostring() # force check the header
# save new fits
new_fits = fits.HDUList([
fits.PrimaryHDU(header=hdr, data=data_med),
])
new_fits.writeto(out_flat_fits, overwrite=True)
lf.show("Writing to: {}".format(out_flat_fits), logfile.INFO)
| [
"numpy.median",
"astropy.io.fits.getheader",
"numpy.nanmedian",
"astropy.io.fits.PrimaryHDU",
"astropy.io.fits.getdata",
"numpy.empty"
] | [((504, 526), 'astropy.io.fits.getheader', 'fits.getheader', (['lst[0]'], {}), '(lst[0])\n', (518, 526), True, 'import astropy.io.fits as fits\n'), ((763, 786), 'astropy.io.fits.getdata', 'fits.getdata', (['bias_fits'], {}), '(bias_fits)\n', (775, 786), True, 'import astropy.io.fits as fits\n'), ((822, 862), 'numpy.empty', 'np.empty', (['(nf, ny, nx)'], {'dtype': 'np.float32'}), '((nf, ny, nx), dtype=np.float32)\n', (830, 862), True, 'import numpy as np\n'), ((1490, 1521), 'numpy.nanmedian', 'np.nanmedian', (['data_cube'], {'axis': '(0)'}), '(data_cube, axis=0)\n', (1502, 1521), True, 'import numpy as np\n'), ((962, 981), 'numpy.median', 'np.median', (['data_tmp'], {}), '(data_tmp)\n', (971, 981), True, 'import numpy as np\n'), ((906, 926), 'astropy.io.fits.getdata', 'fits.getdata', (['lst[f]'], {}), '(lst[f])\n', (918, 926), True, 'import astropy.io.fits as fits\n'), ((1704, 1746), 'astropy.io.fits.PrimaryHDU', 'fits.PrimaryHDU', ([], {'header': 'hdr', 'data': 'data_med'}), '(header=hdr, data=data_med)\n', (1719, 1746), True, 'import astropy.io.fits as fits\n')] |
import os
import time
import numpy as np
import tensorflow as tf
from config_api.config_utils import Config as Config
from data_apis.corpus import ConvAI2DialogCorpus
from data_apis.data_utils import ConvAI2DataLoader
from models.model import perCVAE
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-data", default="data/", help="ConvAI2 persona dialogue data directory.")
parser.add_argument("-vocab_file", default="convai2_vocab.txt", help="ConvAI2 persona dialogue vocabulary.")
parser.add_argument("-idf_file", default="convai2_voacb_idf.txt", help="ConvAI2 persona dialogue words' IDF.")
parser.add_argument("-embedding", default=None, help="The path to word2vec. Can be None.")
parser.add_argument("-save_to", default="saved_models", help="Experiment results directory.")
parser.add_argument("-train", action='store_true', help="Training model otherwise testing")
parser.add_argument("-test", action='store_true', help="Testing model")
parser.add_argument("-model", default=None, help="Trained model used in testing")
parser.add_argument("-config", default="without_labeled_data.yaml", help="Config for basic parameter setting")
args = parser.parse_args()
word2vec_path = args.embedding
data_dir = args.data
work_dir = args.save_to
test_path = args.model
vocab_file = args.vocab_file
idf_file = args.idf_file
para_config = args.config
forward_only = None
if args.train:
forward_only = False
elif args.test:
forward_only = True
if forward_only is None:
print("Please specify training or testing by -train or -test")
raise NameError
tf.app.flags.DEFINE_string("word2vec_path", word2vec_path, "The path to word2vec. Can be None.")
tf.app.flags.DEFINE_string("data_dir", data_dir, "ConvAI2 persona dialogue data directory.")
tf.app.flags.DEFINE_string("work_dir", work_dir, "Experiment results directory.")
tf.app.flags.DEFINE_string("test_path", test_path, "the dir to load checkpoint for forward only")
tf.app.flags.DEFINE_string("vocab_file", vocab_file, "the dir to load pre-processed vocabulary")
tf.app.flags.DEFINE_string("idf_file", idf_file, "the dir to load pre-processed words' IDF")
tf.app.flags.DEFINE_string("para_config", para_config, "the config name for para setting")
tf.app.flags.DEFINE_bool("forward_only", forward_only, "Only do decoding")
tf.app.flags.DEFINE_bool("equal_batch", True, "Make each batch has similar length.")
tf.app.flags.DEFINE_bool("resume", False, "Resume from previous")
tf.app.flags.DEFINE_bool("save_model", True, "Create checkpoints")
FLAGS = tf.app.flags.FLAGS
def main():
config = Config(FLAGS.para_config)
valid_config = Config(FLAGS.para_config)
valid_config.keep_prob = 1.0
valid_config.dec_keep_prob = 1.0
valid_config.batch_size = 32
test_config = Config(FLAGS.para_config)
test_config.keep_prob = 1.0
test_config.dec_keep_prob = 1.0
test_config.batch_size = config.test_batchsize
corpus = ConvAI2DialogCorpus(FLAGS.data_dir, max_vocab_cnt=config.vocab_size, word2vec=FLAGS.word2vec_path,
word2vec_dim=config.embed_size, vocab_files=FLAGS.vocab_file, idf_files=FLAGS.idf_file)
dial_corpus = corpus.get_dialog_corpus()
meta_corpus = corpus.get_meta_corpus()
persona_corpus = corpus.get_persona_corpus()
persona_word_corpus = corpus.get_persona_word_corpus()
vocab_size = corpus.gen_vocab_size
vocab_idf = corpus.index2idf
train_meta, valid_meta, test_meta = meta_corpus.get("train"), meta_corpus.get("valid"), meta_corpus.get("test")
train_dial, valid_dial, test_dial = dial_corpus.get("train"), dial_corpus.get("valid"), dial_corpus.get("test")
train_persona, valid_persona, test_persona = persona_corpus.get("train"), persona_corpus.get(
"valid"), persona_corpus.get("test")
train_persona_word, valid_persona_word, test_persona_word = persona_word_corpus.get(
"train"), persona_word_corpus.get("valid"), persona_word_corpus.get("test")
train_feed = ConvAI2DataLoader("Train", train_dial, train_meta, train_persona, train_persona_word, config,
vocab_size, vocab_idf)
valid_feed = ConvAI2DataLoader("Valid", valid_dial, valid_meta, valid_persona, valid_persona_word, config,
vocab_size, vocab_idf)
test_feed = ConvAI2DataLoader("Test", test_dial, test_meta, test_persona, test_persona_word, config, vocab_size,
vocab_idf)
if FLAGS.forward_only or FLAGS.resume:
log_dir = os.path.join(FLAGS.test_path)
else:
log_dir = os.path.join(FLAGS.work_dir, "model" + time.strftime("_%Y_%m_%d_%H_%M_%S"))
with tf.Session() as sess:
initializer = tf.random_uniform_initializer(-1.0 * config.init_w, config.init_w)
scope = "model"
with tf.variable_scope(scope, reuse=None, initializer=initializer):
model = perCVAE(sess, config, corpus, log_dir=None if FLAGS.forward_only else log_dir, forward=False,
scope=scope, name="Train")
with tf.variable_scope(scope, reuse=True, initializer=initializer):
valid_model = perCVAE(sess, valid_config, corpus, log_dir=None, forward=False, scope=scope, name="Valid")
with tf.variable_scope(scope, reuse=True, initializer=initializer):
test_model = perCVAE(sess, test_config, corpus, log_dir=None, forward=True, scope=scope, name="Test")
print("Created computation graphs")
if corpus.word2vec is not None and not FLAGS.forward_only:
print("Loaded word2vec")
sess.run(model.embedding.assign(np.array(corpus.word2vec)))
ckp_dir = os.path.join(log_dir, "checkpoints")
if not os.path.exists(ckp_dir):
os.mkdir(ckp_dir)
ckpt = tf.train.get_checkpoint_state(ckp_dir)
if ckpt:
print("Reading dm models parameters from %s" % ckpt.model_checkpoint_path)
model.saver.restore(sess, ckpt.model_checkpoint_path)
else:
print("Created models with fresh parameters.")
sess.run(tf.global_variables_initializer())
if not FLAGS.forward_only:
dm_checkpoint_path = os.path.join(ckp_dir, model.__class__.__name__ + ".ckpt")
global_t = 1
patience = 10
dev_loss_threshold = np.inf
best_dev_loss = np.inf
for epoch in range(config.max_epoch):
print(">> Epoch %d with lr %f" % (epoch, model.learning_rate.eval()))
if train_feed.num_batch is None or train_feed.ptr >= train_feed.num_batch:
train_feed.epoch_init(config.batch_size, config.context_window,
config.step_size, shuffle=True)
global_t, train_loss = model.train(global_t, sess, train_feed, update_limit=config.update_limit)
valid_feed.epoch_init(valid_config.batch_size, valid_config.context_window,
valid_config.step_size, shuffle=False, intra_shuffle=False)
valid_loss = valid_model.valid("ELBO_VALID", sess, valid_feed)
test_feed.epoch_init(test_config.batch_size, test_config.context_window,
test_config.step_size, shuffle=True, intra_shuffle=False)
test_model.test(sess, test_feed, num_batch=5)
done_epoch = epoch + 1
if config.op == "sgd" and done_epoch > config.lr_hold:
sess.run(model.learning_rate_decay_op)
if valid_loss < best_dev_loss:
if valid_loss <= dev_loss_threshold * config.improve_threshold:
patience = max(patience, done_epoch * config.patient_increase)
dev_loss_threshold = valid_loss
best_dev_loss = valid_loss
if FLAGS.save_model:
print("Save model!!")
model.saver.save(sess, dm_checkpoint_path, global_step=epoch)
if config.early_stop and patience <= done_epoch:
print("!!Early stop due to run out of patience!!")
break
print("Best validation loss %f" % best_dev_loss)
print("Done training")
else:
test_feed.epoch_init(test_config.batch_size, test_config.context_window,
test_config.step_size, shuffle=False, intra_shuffle=False)
test_model.test(sess, test_feed, num_batch=None, repeat=config.test_samples)
if __name__ == "__main__":
if FLAGS.forward_only:
if FLAGS.test_path is None:
print("Set test_path before forward only")
exit(1)
main()
| [
"os.path.exists",
"config_api.config_utils.Config",
"tensorflow.variable_scope",
"argparse.ArgumentParser",
"models.model.perCVAE",
"tensorflow.Session",
"time.strftime",
"os.path.join",
"tensorflow.app.flags.DEFINE_string",
"tensorflow.train.get_checkpoint_state",
"tensorflow.global_variables_i... | [((277, 302), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (300, 302), False, 'import argparse\n'), ((1581, 1681), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""word2vec_path"""', 'word2vec_path', '"""The path to word2vec. Can be None."""'], {}), "('word2vec_path', word2vec_path,\n 'The path to word2vec. Can be None.')\n", (1607, 1681), True, 'import tensorflow as tf\n'), ((1678, 1774), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""data_dir"""', 'data_dir', '"""ConvAI2 persona dialogue data directory."""'], {}), "('data_dir', data_dir,\n 'ConvAI2 persona dialogue data directory.')\n", (1704, 1774), True, 'import tensorflow as tf\n'), ((1771, 1856), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""work_dir"""', 'work_dir', '"""Experiment results directory."""'], {}), "('work_dir', work_dir,\n 'Experiment results directory.')\n", (1797, 1856), True, 'import tensorflow as tf\n'), ((1853, 1954), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""test_path"""', 'test_path', '"""the dir to load checkpoint for forward only"""'], {}), "('test_path', test_path,\n 'the dir to load checkpoint for forward only')\n", (1879, 1954), True, 'import tensorflow as tf\n'), ((1951, 2051), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""vocab_file"""', 'vocab_file', '"""the dir to load pre-processed vocabulary"""'], {}), "('vocab_file', vocab_file,\n 'the dir to load pre-processed vocabulary')\n", (1977, 2051), True, 'import tensorflow as tf\n'), ((2048, 2144), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""idf_file"""', 'idf_file', '"""the dir to load pre-processed words\' IDF"""'], {}), '(\'idf_file\', idf_file,\n "the dir to load pre-processed words\' IDF")\n', (2074, 2144), True, 'import tensorflow as tf\n'), ((2141, 2235), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""para_config"""', 'para_config', '"""the config name for para setting"""'], {}), "('para_config', para_config,\n 'the config name for para setting')\n", (2167, 2235), True, 'import tensorflow as tf\n'), ((2232, 2306), 'tensorflow.app.flags.DEFINE_bool', 'tf.app.flags.DEFINE_bool', (['"""forward_only"""', 'forward_only', '"""Only do decoding"""'], {}), "('forward_only', forward_only, 'Only do decoding')\n", (2256, 2306), True, 'import tensorflow as tf\n'), ((2307, 2395), 'tensorflow.app.flags.DEFINE_bool', 'tf.app.flags.DEFINE_bool', (['"""equal_batch"""', '(True)', '"""Make each batch has similar length."""'], {}), "('equal_batch', True,\n 'Make each batch has similar length.')\n", (2331, 2395), True, 'import tensorflow as tf\n'), ((2392, 2457), 'tensorflow.app.flags.DEFINE_bool', 'tf.app.flags.DEFINE_bool', (['"""resume"""', '(False)', '"""Resume from previous"""'], {}), "('resume', False, 'Resume from previous')\n", (2416, 2457), True, 'import tensorflow as tf\n'), ((2458, 2524), 'tensorflow.app.flags.DEFINE_bool', 'tf.app.flags.DEFINE_bool', (['"""save_model"""', '(True)', '"""Create checkpoints"""'], {}), "('save_model', True, 'Create checkpoints')\n", (2482, 2524), True, 'import tensorflow as tf\n'), ((2579, 2604), 'config_api.config_utils.Config', 'Config', (['FLAGS.para_config'], {}), '(FLAGS.para_config)\n', (2585, 2604), True, 'from config_api.config_utils import Config as Config\n'), ((2625, 2650), 'config_api.config_utils.Config', 'Config', (['FLAGS.para_config'], {}), '(FLAGS.para_config)\n', (2631, 2650), True, 'from config_api.config_utils import Config as Config\n'), ((2773, 2798), 'config_api.config_utils.Config', 'Config', (['FLAGS.para_config'], {}), '(FLAGS.para_config)\n', (2779, 2798), True, 'from config_api.config_utils import Config as Config\n'), ((2932, 3126), 'data_apis.corpus.ConvAI2DialogCorpus', 'ConvAI2DialogCorpus', (['FLAGS.data_dir'], {'max_vocab_cnt': 'config.vocab_size', 'word2vec': 'FLAGS.word2vec_path', 'word2vec_dim': 'config.embed_size', 'vocab_files': 'FLAGS.vocab_file', 'idf_files': 'FLAGS.idf_file'}), '(FLAGS.data_dir, max_vocab_cnt=config.vocab_size,\n word2vec=FLAGS.word2vec_path, word2vec_dim=config.embed_size,\n vocab_files=FLAGS.vocab_file, idf_files=FLAGS.idf_file)\n', (2951, 3126), False, 'from data_apis.corpus import ConvAI2DialogCorpus\n'), ((3987, 4107), 'data_apis.data_utils.ConvAI2DataLoader', 'ConvAI2DataLoader', (['"""Train"""', 'train_dial', 'train_meta', 'train_persona', 'train_persona_word', 'config', 'vocab_size', 'vocab_idf'], {}), "('Train', train_dial, train_meta, train_persona,\n train_persona_word, config, vocab_size, vocab_idf)\n", (4004, 4107), False, 'from data_apis.data_utils import ConvAI2DataLoader\n'), ((4156, 4276), 'data_apis.data_utils.ConvAI2DataLoader', 'ConvAI2DataLoader', (['"""Valid"""', 'valid_dial', 'valid_meta', 'valid_persona', 'valid_persona_word', 'config', 'vocab_size', 'vocab_idf'], {}), "('Valid', valid_dial, valid_meta, valid_persona,\n valid_persona_word, config, vocab_size, vocab_idf)\n", (4173, 4276), False, 'from data_apis.data_utils import ConvAI2DataLoader\n'), ((4324, 4439), 'data_apis.data_utils.ConvAI2DataLoader', 'ConvAI2DataLoader', (['"""Test"""', 'test_dial', 'test_meta', 'test_persona', 'test_persona_word', 'config', 'vocab_size', 'vocab_idf'], {}), "('Test', test_dial, test_meta, test_persona,\n test_persona_word, config, vocab_size, vocab_idf)\n", (4341, 4439), False, 'from data_apis.data_utils import ConvAI2DataLoader\n'), ((4532, 4561), 'os.path.join', 'os.path.join', (['FLAGS.test_path'], {}), '(FLAGS.test_path)\n', (4544, 4561), False, 'import os\n'), ((4676, 4688), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (4686, 4688), True, 'import tensorflow as tf\n'), ((4720, 4786), 'tensorflow.random_uniform_initializer', 'tf.random_uniform_initializer', (['(-1.0 * config.init_w)', 'config.init_w'], {}), '(-1.0 * config.init_w, config.init_w)\n', (4749, 4786), True, 'import tensorflow as tf\n'), ((5679, 5715), 'os.path.join', 'os.path.join', (['log_dir', '"""checkpoints"""'], {}), "(log_dir, 'checkpoints')\n", (5691, 5715), False, 'import os\n'), ((5802, 5840), 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['ckp_dir'], {}), '(ckp_dir)\n', (5831, 5840), True, 'import tensorflow as tf\n'), ((4824, 4885), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {'reuse': 'None', 'initializer': 'initializer'}), '(scope, reuse=None, initializer=initializer)\n', (4841, 4885), True, 'import tensorflow as tf\n'), ((4907, 5031), 'models.model.perCVAE', 'perCVAE', (['sess', 'config', 'corpus'], {'log_dir': '(None if FLAGS.forward_only else log_dir)', 'forward': '(False)', 'scope': 'scope', 'name': '"""Train"""'}), "(sess, config, corpus, log_dir=None if FLAGS.forward_only else\n log_dir, forward=False, scope=scope, name='Train')\n", (4914, 5031), False, 'from models.model import perCVAE\n'), ((5069, 5130), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {'reuse': '(True)', 'initializer': 'initializer'}), '(scope, reuse=True, initializer=initializer)\n', (5086, 5130), True, 'import tensorflow as tf\n'), ((5158, 5254), 'models.model.perCVAE', 'perCVAE', (['sess', 'valid_config', 'corpus'], {'log_dir': 'None', 'forward': '(False)', 'scope': 'scope', 'name': '"""Valid"""'}), "(sess, valid_config, corpus, log_dir=None, forward=False, scope=\n scope, name='Valid')\n", (5165, 5254), False, 'from models.model import perCVAE\n'), ((5263, 5324), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {'reuse': '(True)', 'initializer': 'initializer'}), '(scope, reuse=True, initializer=initializer)\n', (5280, 5324), True, 'import tensorflow as tf\n'), ((5351, 5443), 'models.model.perCVAE', 'perCVAE', (['sess', 'test_config', 'corpus'], {'log_dir': 'None', 'forward': '(True)', 'scope': 'scope', 'name': '"""Test"""'}), "(sess, test_config, corpus, log_dir=None, forward=True, scope=scope,\n name='Test')\n", (5358, 5443), False, 'from models.model import perCVAE\n'), ((5731, 5754), 'os.path.exists', 'os.path.exists', (['ckp_dir'], {}), '(ckp_dir)\n', (5745, 5754), False, 'import os\n'), ((5768, 5785), 'os.mkdir', 'os.mkdir', (['ckp_dir'], {}), '(ckp_dir)\n', (5776, 5785), False, 'import os\n'), ((6210, 6267), 'os.path.join', 'os.path.join', (['ckp_dir', "(model.__class__.__name__ + '.ckpt')"], {}), "(ckp_dir, model.__class__.__name__ + '.ckpt')\n", (6222, 6267), False, 'import os\n'), ((4629, 4664), 'time.strftime', 'time.strftime', (['"""_%Y_%m_%d_%H_%M_%S"""'], {}), "('_%Y_%m_%d_%H_%M_%S')\n", (4642, 4664), False, 'import time\n'), ((6106, 6139), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (6137, 6139), True, 'import tensorflow as tf\n'), ((5633, 5658), 'numpy.array', 'np.array', (['corpus.word2vec'], {}), '(corpus.word2vec)\n', (5641, 5658), True, 'import numpy as np\n')] |
#from planenet code is adapted for planercnn code
import cv2
import numpy as np
WIDTH = 256
HEIGHT = 192
ALL_TITLES = ['PlaneNet']
ALL_METHODS = [('sample_np10_hybrid3_bl0_dl0_ds0_crfrnn5_sm0', '', 0, 2)]
def predict3D(folder, index, image, depth, segmentation, planes, info):
writePLYFile(folder, index, image, depth, segmentation, planes, info)
#writePLYFile(options.test_dir, image_index + options.startIndex, segmentationImageBlended, pred_dict['depth'][image_index], segmentation, pred_dict['plane'][image_index], pred_dict['info'][image_index])
print("done")
def getCameraFromInfo(info):
camera = {}
camera['fx'] = info[0]
camera['fy'] = info[5]
camera['cx'] = info[2]
camera['cy'] = info[6]
camera['width'] = info[16]
camera['height'] = info[17]
camera['depth_shift'] = info[18]
return camera
def writePLYFile(folder, index, image, depth, segmentation, planes, info):
imageFilename = str(index) + '_model_texture.png'
cv2.imwrite(folder + '/' + imageFilename, image)
width = image.shape[1]
height = image.shape[0]
numPlanes = planes.shape[0]
camera = getCameraFromInfo(info)
#camera = getNYURGBDCamera()
#camera = getSUNCGCamera()
urange = (np.arange(width, dtype=np.float32) / width * camera['width'] - camera['cx']) / camera['fx']
urange = urange.reshape(1, -1).repeat(height, 0)
vrange = (np.arange(height, dtype=np.float32) / height * camera['height'] - camera['cy']) / camera['fy']
vrange = vrange.reshape(-1, 1).repeat(width, 1)
X = depth * urange
Y = depth
Z = -depth * vrange
XYZ = np.stack([X, Y, Z], axis=2)
#focalLength = 517.97
faces = []
#minDepthDiff = 0.15
#maxDepthDiff = 0.3
#occlusionBoundary = boundaries[:, :, 1]
betweenRegionThreshold = 0.1
nonPlanarRegionThreshold = 0.02
planesD = np.linalg.norm(planes, axis=1, keepdims=True)
planeNormals = -planes / np.maximum(planesD, 1e-4)
croppingRatio = -0.05
dotThreshold = np.cos(np.deg2rad(30))
for y in range(height - 1):
for x in range(width - 1):
if y < height * croppingRatio or y > height * (1 - croppingRatio) or x < width * croppingRatio or x > width * (1 - croppingRatio):
continue
segmentIndex = segmentation[y][x]
if segmentIndex == -1:
continue
point = XYZ[y][x]
#neighborPixels = []
validNeighborPixels = []
for neighborPixel in [(x, y + 1), (x + 1, y), (x + 1, y + 1)]:
neighborSegmentIndex = segmentation[neighborPixel[1]][neighborPixel[0]]
if neighborSegmentIndex == segmentIndex:
if segmentIndex < numPlanes:
validNeighborPixels.append(neighborPixel)
else:
neighborPoint = XYZ[neighborPixel[1]][neighborPixel[0]]
if np.linalg.norm(neighborPoint - point) < nonPlanarRegionThreshold:
validNeighborPixels.append(neighborPixel)
pass
pass
else:
neighborPoint = XYZ[neighborPixel[1]][neighborPixel[0]]
if segmentIndex < numPlanes and neighborSegmentIndex < numPlanes:
if (abs(np.dot(planeNormals[segmentIndex], neighborPoint) + planesD[segmentIndex]) < betweenRegionThreshold or abs(np.dot(planeNormals[neighborSegmentIndex], point) + planesD[neighborSegmentIndex]) < betweenRegionThreshold) and np.abs(np.dot(planeNormals[segmentIndex], planeNormals[neighborSegmentIndex])) < dotThreshold:
validNeighborPixels.append(neighborPixel)
pass
else:
if np.linalg.norm(neighborPoint - point) < betweenRegionThreshold:
validNeighborPixels.append(neighborPixel)
pass
pass
pass
continue
if len(validNeighborPixels) == 3:
faces.append((x, y, x + 1, y + 1, x + 1, y))
faces.append((x, y, x, y + 1, x + 1, y + 1))
elif len(validNeighborPixels) == 2 and segmentIndex < numPlanes:
faces.append((x, y, validNeighborPixels[0][0], validNeighborPixels[0][1], validNeighborPixels[1][0], validNeighborPixels[1][1]))
pass
continue
continue
with open(folder + '/' + str(index) + '_model.ply', 'w') as f:
header = """ply
format ascii 1.0
comment VCGLIB generated
comment TextureFile """
header += imageFilename
header += """
element vertex """
header += str(width * height)
header += """
property float x
property float y
property float z
element face """
header += str(len(faces))
header += """
property list uchar int vertex_indices
property list uchar float texcoord
end_header
"""
f.write(header)
for y in range(height):
for x in range(width):
segmentIndex = segmentation[y][x]
if segmentIndex == -1:
f.write("0.0 0.0 0.0\n")
continue
point = XYZ[y][x]
X = point[0]
Y = point[1]
Z = point[2]
#Y = depth[y][x]
#X = Y / focalLength * (x - width / 2) / width * 640
#Z = -Y / focalLength * (y - height / 2) / height * 480
f.write(str(X) + ' ' + str(Z) + ' ' + str(-Y) + '\n')
continue
continue
for face in faces:
f.write('3 ')
for c in range(3):
f.write(str(face[c * 2 + 1] * width + face[c * 2]) + ' ')
continue
f.write('6 ')
for c in range(3):
f.write(str(float(face[c * 2]) / width) + ' ' + str(1 - float(face[c * 2 + 1]) / height) + ' ')
continue
f.write('\n')
continue
f.close()
pass
return
def evaluatePlanes(options):
for image_index in range(options.visualizeImages):
if options.applicationType == 'grids':
cv2.imwrite(options.test_dir + '/' + str(image_index + options.startIndex) + '_image.png', pred_dict['image'][image_index])
segmentation = predictions[0]['segmentation'][image_index]
#segmentation = np.argmax(np.concatenate([segmentation, pred_dict['np_mask'][image_index]], axis=2), -1)
segmentationImage = drawSegmentationImage(segmentation, blackIndex=options.numOutputPlanes)
#cv2.imwrite(options.test_dir + '/' + str(image_index + options.startIndex) + '_segmentation_pred_' + str(0) + '.png', segmentationImage)
segmentationImageBlended = (segmentationImage * 0.7 + pred_dict['image'][image_index] * 0.3).astype(np.uint8)
cv2.imwrite(options.test_dir + '/' + str(image_index + options.startIndex) + '_segmentation_pred_blended_' + str(0) + '.png', segmentationImageBlended)
continue
cv2.imwrite(options.test_dir + '/' + str(image_index + options.startIndex) + '_image.png', pred_dict['image'][image_index])
info = pred_dict['info'][image_index]
for method_index, pred_dict in enumerate(predictions):
cv2.imwrite(options.test_dir + '/' + str(image_index + options.startIndex) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_dict['depth'][image_index]))
if 'pixelwise' in options.methods[method_index][1]:
continue
allSegmentations = pred_dict['segmentation'][image_index]
segmentation = np.argmax(allSegmentations, axis=-1)
#segmentation = np.argmax(np.concatenate([segmentation, pred_dict['np_mask'][image_index]], axis=2), -1)
segmentationImage = drawSegmentationImage(segmentation, blackIndex=options.numOutputPlanes)
cv2.imwrite(options.test_dir + '/' + str(image_index + options.startIndex) + '_segmentation_pred_' + str(method_index) + '.png', segmentationImage)
segmentationImageBlended = (segmentationImage * 0.7 + pred_dict['image'][image_index] * 0.3).astype(np.uint8)
cv2.imwrite(options.test_dir + '/' + str(image_index + options.startIndex) + '_segmentation_pred_blended_' + str(method_index) + '.png', segmentationImageBlended)
segmentationImageBlended = np.minimum(segmentationImage * 0.3 + pred_dict['image'][image_index] * 0.7, 255).astype(np.uint8)
if options.imageIndex >= 0:
for planeIndex in range(options.numOutputPlanes):
cv2.imwrite(options.test_dir + '/mask_' + str(planeIndex) + '.png', drawMaskImage(segmentation == planeIndex))
continue
if options.applicationType == 'logo_video':
copyLogoVideo(options.textureImageFilename, options.test_dir, image_index + options.startIndex, pred_dict['image'][image_index], pred_dict['depth'][image_index], pred_dict['plane'][image_index], segmentation, pred_dict['info'][image_index], textureType='logo')
elif options.applicationType == 'wall_video':
if options.wallIndices == '':
print('please specify wall indices')
exit(1)
pass
wallIndices = [int(value) for value in options.wallIndices.split(',')]
copyLogoVideo(options.textureImageFilename, options.test_dir, image_index + options.startIndex, pred_dict['image'][image_index], pred_dict['depth'][image_index], pred_dict['plane'][image_index], segmentation, pred_dict['info'][image_index], textureType='wall', wallInds=wallIndices)
elif options.applicationType == 'ruler':
if options.startPixel == '' or options.endPixel == '':
print('please specify start pixel and end pixel')
exit(1)
pass
startPixel = tuple([int(value) for value in options.startPixel.split(',')])
endPixel = tuple([int(value) for value in options.endPixel.split(',')])
addRulerComplete(options.textureImageFilename, options.test_dir, image_index + options.startIndex, pred_dict['image'][image_index], pred_dict['depth'][image_index], pred_dict['plane'][image_index], segmentation, pred_dict['info'][image_index], startPixel=startPixel, endPixel=endPixel, fixedEndPoint=True, numFrames=1000)
elif options.applicationType == 'logo_texture':
resultImage = copyLogo(options.textureImageFilename, options.test_dir, image_index + options.startIndex, pred_dict['image'][image_index], pred_dict['depth'][image_index], pred_dict['plane'][image_index], segmentation, pred_dict['info'][image_index])
cv2.imwrite(options.test_dir + '/' + str(image_index + options.startIndex) + '_result.png', resultImage)
elif options.applicationType == 'wall_texture':
if options.wallIndices == '':
print('please specify wall indices')
exit(1)
pass
wallIndices = [int(value) for value in options.wallIndices.split(',')]
resultImage = copyWallTexture(options.textureImageFilename, options.test_dir, image_index + options.startIndex, pred_dict['image'][image_index], pred_dict['depth'][image_index], pred_dict['plane'][image_index], segmentation, pred_dict['info'][image_index], wallPlanes=wallIndices)
cv2.imwrite(options.test_dir + '/' + str(image_index + options.startIndex) + '_result.png', resultImage)
elif options.applicationType == 'TV':
if options.wallIndices == '':
print('please specify wall indices')
exit(1)
pass
wallIndices = [int(value) for value in options.wallIndices.split(',')]
copyLogoVideo(options.textureImageFilename, options.test_dir, image_index + options.startIndex, pred_dict['image'][image_index], pred_dict['depth'][image_index], pred_dict['plane'][image_index], segmentation, pred_dict['info'][image_index], textureType='TV', wallInds=wallIndices)
elif options.applicationType == 'pool':
print('dump')
newPlanes = []
newSegmentation = np.full(segmentation.shape, -1)
newPlaneIndex = 0
planes = pred_dict['plane'][image_index]
for planeIndex in range(options.numOutputPlanes):
mask = segmentation == planeIndex
if mask.sum() > 0:
newPlanes.append(planes[planeIndex])
newSegmentation[mask] = newPlaneIndex
newPlaneIndex += 1
pass
continue
np.save('pool/dump/' + str(image_index + options.startIndex) + '_planes.npy', np.stack(newPlanes, axis=0))
#print(global_gt['non_plane_mask'].shape)
np.save('pool/dump/' + str(image_index + options.startIndex) + '_segmentation.npy', newSegmentation)
cv2.imwrite('pool/dump/' + str(image_index + options.startIndex) + '_image.png', pred_dict['image'][image_index])
depth = pred_dict['depth'][image_index]
np.save('pool/dump/' + str(image_index + options.startIndex) + '_depth.npy', depth)
info = pred_dict['info'][image_index]
#normal = calcNormal(depth, info)
#np.save('test/' + str(image_index + options.startIndex) + '_normal.npy', normal)
np.save('pool/dump/' + str(image_index + options.startIndex) + '_info.npy', info)
exit(1)
else:
print('please specify application type')
np_mask = (segmentation == options.numOutputPlanes).astype(np.float32)
np_depth = pred_dict['np_depth'][image_index].squeeze()
np_depth = cv2.resize(np_depth, (np_mask.shape[1], np_mask.shape[0]))
cv2.imwrite(options.test_dir + '/' + str(image_index + options.startIndex) + '_np_depth_pred_' + str(method_index) + '.png', drawDepthImage(np_depth * np_mask))
# folder, \ - directory - done
# index, \ - idx number of image - done
# image, \ - segmentationImageBlended
# depth, \ - pred_dict['depth'][image_index] - done
# segmentation, \ - segmentation
# planes, \ - pred_dict['plane'][image_index]
# info - pred_dict['info'][image_index] - done
writePLYFile(options.test_dir, image_index + options.startIndex, segmentationImageBlended, pred_dict['depth'][image_index], segmentation, pred_dict['plane'][image_index], pred_dict['info'][image_index])
pass
exit(1)
pass
continue
continue
writeHTML(options)
return
def getResults(options):
checkpoint_prefix = 'checkpoint/'
methods = options.methods
predictions = []
if os.path.exists(options.result_filename) and options.useCache == 1:
predictions = np.load(options.result_filename)
return predictions
for method_index, method in enumerate(methods):
if len(method) < 4 or method[3] < 2:
continue
if method[0] == '':
continue
if 'ds0' not in method[0]:
options.deepSupervisionLayers = ['res4b22_relu', ]
else:
options.deepSupervisionLayers = []
pass
options.predictConfidence = 0
options.predictLocal = 0
options.predictPixelwise = 1
options.predictBoundary = int('pb' in method[0])
options.anchorPlanes = 0
if 'ps' in method[0]:
options.predictSemantics = 1
else:
options.predictSemantics = 0
pass
if 'crfrnn' in method[0]:
options.crfrnn = 10
else:
options.crfrnn = 0
pass
if 'ap1' in method[0]:
options.anchorPlanes = 1
pass
options.checkpoint_dir = checkpoint_prefix + method[0]
print(options.checkpoint_dir)
options.suffix = method[1]
method_names = [previous_method[0] for previous_method in methods[:method_index]]
if options.customImageFolder != '':
print('make predictions on custom images')
pred_dict = getPredictionCustom(options)
elif options.dataFolder != '':
print('make predictions on ScanNet images')
pred_dict = getPredictionScanNet(options)
else:
print('please specify customImageFolder or dataFolder')
exit(1)
pass
predictions.append(pred_dict)
continue
#np.save(options.test_dir + '/curves.npy', curves)
results = predictions
#print(results)
if options.useCache != -1:
np.save(options.result_filename, results)
pass
pass
return results
def getPredictionCustom(options):
tf.reset_default_graph()
options.batchSize = 1
img_inp = tf.placeholder(tf.float32, shape=[1, HEIGHT, WIDTH, 3], name='image')
training_flag = tf.constant(False, tf.bool)
options.gpu_id = 0
global_pred_dict, local_pred_dict, deep_pred_dicts = build_graph(img_inp, img_inp, training_flag, options)
var_to_restore = tf.global_variables()
config=tf.ConfigProto()
config.gpu_options.allow_growth=True
config.allow_soft_placement=True
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
width_high_res = 640
height_high_res = 480
#image_list = glob.glob('../my_images/*.jpg') + glob.glob('../my_images/*.png') + glob.glob('../my_images/*.JPG')
#image_list = glob.glob('../my_images/TV/*.jpg') + glob.glob('../my_images/TV/*.png') + glob.glob('../my_images/TV/*.JPG')
#image_list = glob.glob('../my_images/TV/*.jpg') + glob.glob('../my_images/TV/*.png') + glob.glob('../my_images/TV/*.JPG')
image_list = glob.glob(options.customImageFolder + '/*.jpg') + glob.glob(options.customImageFolder + '/*.png') + glob.glob(options.customImageFolder + '/*.JPG')
options.visualizeImages = min(options.visualizeImages, len(image_list))
pred_dict = {}
with tf.Session(config=config) as sess:
sess.run(init_op)
#var_to_restore = [v for v in var_to_restore if 'res4b22_relu_non_plane' not in v.name]
loader = tf.train.Saver(var_to_restore)
loader.restore(sess, "%s/checkpoint.ckpt"%(options.checkpoint_dir))
#loader.restore(sess, options.fineTuningCheckpoint)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
try:
predDepths = []
predPlanes = []
predSegmentations = []
predSemantics = []
predNonPlaneDepths = []
predNonPlaneNormals = []
predNonPlaneMasks = []
predBoundaries = []
images = []
infos = []
for index in range(min(options.startIndex + options.numImages, len(image_list))):
if index % 10 == 0:
print(('image', index))
pass
t0=time.time()
print(('image', index))
img_ori = cv2.imread(image_list[index])
images.append(img_ori)
img = cv2.resize(img_ori, (WIDTH, HEIGHT))
img = img.astype(np.float32) / 255 - 0.5
img = np.expand_dims(img, 0)
global_pred = sess.run(global_pred_dict, feed_dict={img_inp: img})
if index < options.startIndex:
continue
pred_p = global_pred['plane'][0]
pred_s = global_pred['segmentation'][0]
pred_np_m = global_pred['non_plane_mask'][0]
pred_np_d = global_pred['non_plane_depth'][0]
pred_np_n = global_pred['non_plane_normal'][0]
#if global_gt['info'][0][19] > 1 and global_gt['info'][0][19] < 4 and False:
#pred_np_n = calcNormal(pred_np_d.squeeze(), global_gt['info'][0])
#pass
#pred_b = global_pred['boundary'][0]
predNonPlaneMasks.append(pred_np_m)
predNonPlaneDepths.append(pred_np_d)
predNonPlaneNormals.append(pred_np_n)
#predBoundaries.append(pred_b)
all_segmentations = np.concatenate([pred_s, pred_np_m], axis=2)
info = np.zeros(20)
if options.estimateFocalLength:
focalLength = estimateFocalLength(img_ori)
info[0] = focalLength
info[5] = focalLength
info[2] = img_ori.shape[1] / 2
info[6] = img_ori.shape[0] / 2
info[16] = img_ori.shape[1]
info[17] = img_ori.shape[0]
info[10] = 1
info[15] = 1
info[18] = 1000
info[19] = 5
else:
info[0] = 2800.71
info[2] = 1634.45
info[5] = 2814.01
info[6] = 1224.18
info[16] = img_ori.shape[1]
info[17] = img_ori.shape[0]
info[10] = 1
info[15] = 1
info[18] = 1000
info[19] = 5
pass
# print(focalLength)
# cv2.imwrite('test/image.png', ((img[0] + 0.5) * 255).astype(np.uint8))
# cv2.imwrite('test/segmentation.png', drawSegmentationImage(pred_s, blackIndex=options.numOutputPlanes))
# exit(1)
infos.append(info)
width_high_res = img_ori.shape[1]
height_high_res = img_ori.shape[0]
plane_depths = calcPlaneDepths(pred_p, width_high_res, height_high_res, info)
pred_np_d = np.expand_dims(cv2.resize(pred_np_d.squeeze(), (width_high_res, height_high_res)), -1)
all_depths = np.concatenate([plane_depths, pred_np_d], axis=2)
all_segmentations = np.stack([cv2.resize(all_segmentations[:, :, planeIndex], (width_high_res, height_high_res)) for planeIndex in range(all_segmentations.shape[-1])], axis=2)
segmentation = np.argmax(all_segmentations, 2)
pred_d = all_depths.reshape(-1, options.numOutputPlanes + 1)[np.arange(height_high_res * width_high_res), segmentation.reshape(-1)].reshape(height_high_res, width_high_res)
if 'semantics' in global_pred:
#cv2.imwrite('test/semantics.png', drawSegmentationImage(np.argmax(global_pred['semantics'][0], axis=-1)))
#exit(1)
predSemantics.append(np.argmax(global_pred['semantics'][0], axis=-1))
else:
predSemantics.append(np.zeros((HEIGHT, WIDTH)))
pass
predDepths.append(pred_d)
predPlanes.append(pred_p)
predSegmentations.append(all_segmentations)
continue
pred_dict['plane'] = np.array(predPlanes)
pred_dict['segmentation'] = np.array(predSegmentations)
pred_dict['depth'] = np.array(predDepths)
#pred_dict['semantics'] = np.array(predSemantics)
pred_dict['np_depth'] = np.array(predNonPlaneDepths)
#pred_dict['np_normal'] = np.array(predNonPlaneNormals)
pred_dict['np_mask'] = np.array(predNonPlaneMasks)
pred_dict['image'] = np.array(images)
pred_dict['info'] = np.array(infos)
#pred_dict['boundary'] = np.array(predBoundaries)
pass
except tf.errors.OutOfRangeError:
print('Done training -- epoch limit reached')
finally:
# When done, ask the threads to stop.
coord.request_stop()
pass
# Wait for threads to finish.
coord.join(threads)
sess.close()
pass
return pred_dict
if __name__=='__main__':
info = np.array([1.82e+03, 0.00e+00, 1.63e+03, 0.00e+00,\
0.00e+00, 1.82e+03, 1.22e+03, 0.00e+00, 0.00e+00, 0.00e+00, \
1.00e+00, 0.00e+00, 0.00e+00, 0.00e+00, 0.00e+00, 1.00e+00, 3.26e+03, 2.45e+03,\
1.00e+03,5.00e+00])
image = cv2.imread("single_rgb_sample/12/12_segmentation_0_final.png") #x,x,3
depth = cv2.imread("single_rgb_sample/12/12_depth_0_final_ori.png",0) #x,x
segmentation = cv2.imread("single_rgb_sample/12/12_segmentation_0_final.png",0) #change it
planes = np.load("single_rgb_sample/12/12_plane_masks_0.npy") #change if its not working
folder = "predict3fol"
index = 12
predict3D(folder, index, image, depth, segmentation, planes, info)
#todo
# try to add focal length
# try to do with rgb based one | [
"cv2.imwrite",
"cv2.resize",
"numpy.minimum",
"numpy.arange",
"numpy.argmax",
"numpy.array",
"numpy.stack",
"numpy.deg2rad",
"numpy.zeros",
"numpy.dot",
"numpy.expand_dims",
"numpy.linalg.norm",
"numpy.concatenate",
"numpy.full",
"numpy.maximum",
"numpy.load",
"cv2.imread",
"numpy.... | [((995, 1043), 'cv2.imwrite', 'cv2.imwrite', (["(folder + '/' + imageFilename)", 'image'], {}), "(folder + '/' + imageFilename, image)\n", (1006, 1043), False, 'import cv2\n'), ((1637, 1664), 'numpy.stack', 'np.stack', (['[X, Y, Z]'], {'axis': '(2)'}), '([X, Y, Z], axis=2)\n', (1645, 1664), True, 'import numpy as np\n'), ((1903, 1948), 'numpy.linalg.norm', 'np.linalg.norm', (['planes'], {'axis': '(1)', 'keepdims': '(True)'}), '(planes, axis=1, keepdims=True)\n', (1917, 1948), True, 'import numpy as np\n'), ((25595, 25730), 'numpy.array', 'np.array', (['[1820.0, 0.0, 1630.0, 0.0, 0.0, 1820.0, 1220.0, 0.0, 0.0, 0.0, 1.0, 0.0, \n 0.0, 0.0, 0.0, 1.0, 3260.0, 2450.0, 1000.0, 5.0]'], {}), '([1820.0, 0.0, 1630.0, 0.0, 0.0, 1820.0, 1220.0, 0.0, 0.0, 0.0, 1.0,\n 0.0, 0.0, 0.0, 0.0, 1.0, 3260.0, 2450.0, 1000.0, 5.0])\n', (25603, 25730), True, 'import numpy as np\n'), ((25837, 25899), 'cv2.imread', 'cv2.imread', (['"""single_rgb_sample/12/12_segmentation_0_final.png"""'], {}), "('single_rgb_sample/12/12_segmentation_0_final.png')\n", (25847, 25899), False, 'import cv2\n'), ((25919, 25981), 'cv2.imread', 'cv2.imread', (['"""single_rgb_sample/12/12_depth_0_final_ori.png"""', '(0)'], {}), "('single_rgb_sample/12/12_depth_0_final_ori.png', 0)\n", (25929, 25981), False, 'import cv2\n'), ((26005, 26070), 'cv2.imread', 'cv2.imread', (['"""single_rgb_sample/12/12_segmentation_0_final.png"""', '(0)'], {}), "('single_rgb_sample/12/12_segmentation_0_final.png', 0)\n", (26015, 26070), False, 'import cv2\n'), ((26095, 26147), 'numpy.load', 'np.load', (['"""single_rgb_sample/12/12_plane_masks_0.npy"""'], {}), "('single_rgb_sample/12/12_plane_masks_0.npy')\n", (26102, 26147), True, 'import numpy as np\n'), ((1978, 2005), 'numpy.maximum', 'np.maximum', (['planesD', '(0.0001)'], {}), '(planesD, 0.0001)\n', (1988, 2005), True, 'import numpy as np\n'), ((2061, 2075), 'numpy.deg2rad', 'np.deg2rad', (['(30)'], {}), '(30)\n', (2071, 2075), True, 'import numpy as np\n'), ((15990, 16022), 'numpy.load', 'np.load', (['options.result_filename'], {}), '(options.result_filename)\n', (15997, 16022), True, 'import numpy as np\n'), ((17875, 17916), 'numpy.save', 'np.save', (['options.result_filename', 'results'], {}), '(options.result_filename, results)\n', (17882, 17916), True, 'import numpy as np\n'), ((7957, 7993), 'numpy.argmax', 'np.argmax', (['allSegmentations'], {'axis': '(-1)'}), '(allSegmentations, axis=-1)\n', (7966, 7993), True, 'import numpy as np\n'), ((24607, 24627), 'numpy.array', 'np.array', (['predPlanes'], {}), '(predPlanes)\n', (24615, 24627), True, 'import numpy as np\n'), ((24668, 24695), 'numpy.array', 'np.array', (['predSegmentations'], {}), '(predSegmentations)\n', (24676, 24695), True, 'import numpy as np\n'), ((24729, 24749), 'numpy.array', 'np.array', (['predDepths'], {}), '(predDepths)\n', (24737, 24749), True, 'import numpy as np\n'), ((24872, 24900), 'numpy.array', 'np.array', (['predNonPlaneDepths'], {}), '(predNonPlaneDepths)\n', (24880, 24900), True, 'import numpy as np\n'), ((25004, 25031), 'numpy.array', 'np.array', (['predNonPlaneMasks'], {}), '(predNonPlaneMasks)\n', (25012, 25031), True, 'import numpy as np\n'), ((25065, 25081), 'numpy.array', 'np.array', (['images'], {}), '(images)\n', (25073, 25081), True, 'import numpy as np\n'), ((25114, 25129), 'numpy.array', 'np.array', (['infos'], {}), '(infos)\n', (25122, 25129), True, 'import numpy as np\n'), ((20467, 20496), 'cv2.imread', 'cv2.imread', (['image_list[index]'], {}), '(image_list[index])\n', (20477, 20496), False, 'import cv2\n'), ((20558, 20594), 'cv2.resize', 'cv2.resize', (['img_ori', '(WIDTH, HEIGHT)'], {}), '(img_ori, (WIDTH, HEIGHT))\n', (20568, 20594), False, 'import cv2\n'), ((20674, 20696), 'numpy.expand_dims', 'np.expand_dims', (['img', '(0)'], {}), '(img, 0)\n', (20688, 20696), True, 'import numpy as np\n'), ((21736, 21779), 'numpy.concatenate', 'np.concatenate', (['[pred_s, pred_np_m]'], {'axis': '(2)'}), '([pred_s, pred_np_m], axis=2)\n', (21750, 21779), True, 'import numpy as np\n'), ((21804, 21816), 'numpy.zeros', 'np.zeros', (['(20)'], {}), '(20)\n', (21812, 21816), True, 'import numpy as np\n'), ((23442, 23491), 'numpy.concatenate', 'np.concatenate', (['[plane_depths, pred_np_d]'], {'axis': '(2)'}), '([plane_depths, pred_np_d], axis=2)\n', (23456, 23491), True, 'import numpy as np\n'), ((23733, 23764), 'numpy.argmax', 'np.argmax', (['all_segmentations', '(2)'], {}), '(all_segmentations, 2)\n', (23742, 23764), True, 'import numpy as np\n'), ((1259, 1293), 'numpy.arange', 'np.arange', (['width'], {'dtype': 'np.float32'}), '(width, dtype=np.float32)\n', (1268, 1293), True, 'import numpy as np\n'), ((1418, 1453), 'numpy.arange', 'np.arange', (['height'], {'dtype': 'np.float32'}), '(height, dtype=np.float32)\n', (1427, 1453), True, 'import numpy as np\n'), ((8712, 8797), 'numpy.minimum', 'np.minimum', (["(segmentationImage * 0.3 + pred_dict['image'][image_index] * 0.7)", '(255)'], {}), "(segmentationImage * 0.3 + pred_dict['image'][image_index] * 0.7, 255\n )\n", (8722, 8797), True, 'import numpy as np\n'), ((23539, 23625), 'cv2.resize', 'cv2.resize', (['all_segmentations[:, :, planeIndex]', '(width_high_res, height_high_res)'], {}), '(all_segmentations[:, :, planeIndex], (width_high_res,\n height_high_res))\n', (23549, 23625), False, 'import cv2\n'), ((24199, 24246), 'numpy.argmax', 'np.argmax', (["global_pred['semantics'][0]"], {'axis': '(-1)'}), "(global_pred['semantics'][0], axis=-1)\n", (24208, 24246), True, 'import numpy as np\n'), ((24311, 24336), 'numpy.zeros', 'np.zeros', (['(HEIGHT, WIDTH)'], {}), '((HEIGHT, WIDTH))\n', (24319, 24336), True, 'import numpy as np\n'), ((3009, 3046), 'numpy.linalg.norm', 'np.linalg.norm', (['(neighborPoint - point)'], {}), '(neighborPoint - point)\n', (3023, 3046), True, 'import numpy as np\n'), ((3894, 3931), 'numpy.linalg.norm', 'np.linalg.norm', (['(neighborPoint - point)'], {}), '(neighborPoint - point)\n', (3908, 3931), True, 'import numpy as np\n'), ((23842, 23885), 'numpy.arange', 'np.arange', (['(height_high_res * width_high_res)'], {}), '(height_high_res * width_high_res)\n', (23851, 23885), True, 'import numpy as np\n'), ((3650, 3720), 'numpy.dot', 'np.dot', (['planeNormals[segmentIndex]', 'planeNormals[neighborSegmentIndex]'], {}), '(planeNormals[segmentIndex], planeNormals[neighborSegmentIndex])\n', (3656, 3720), True, 'import numpy as np\n'), ((3423, 3472), 'numpy.dot', 'np.dot', (['planeNormals[segmentIndex]', 'neighborPoint'], {}), '(planeNormals[segmentIndex], neighborPoint)\n', (3429, 3472), True, 'import numpy as np\n'), ((3530, 3579), 'numpy.dot', 'np.dot', (['planeNormals[neighborSegmentIndex]', 'point'], {}), '(planeNormals[neighborSegmentIndex], point)\n', (3536, 3579), True, 'import numpy as np\n'), ((12933, 12964), 'numpy.full', 'np.full', (['segmentation.shape', '(-1)'], {}), '(segmentation.shape, -1)\n', (12940, 12964), True, 'import numpy as np\n'), ((14713, 14771), 'cv2.resize', 'cv2.resize', (['np_depth', '(np_mask.shape[1], np_mask.shape[0])'], {}), '(np_depth, (np_mask.shape[1], np_mask.shape[0]))\n', (14723, 14771), False, 'import cv2\n'), ((13578, 13605), 'numpy.stack', 'np.stack', (['newPlanes'], {'axis': '(0)'}), '(newPlanes, axis=0)\n', (13586, 13605), True, 'import numpy as np\n')] |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import time
import numpy as np
import argparse
import functools
import shutil
import math
import multiprocessing
def set_paddle_flags(**kwargs):
for key, value in kwargs.items():
if os.environ.get(key, None) is None:
os.environ[key] = str(value)
# NOTE(paddle-dev): All of these flags should be
# set before `import paddle`. Otherwise, it would
# not take any effect.
set_paddle_flags(
FLAGS_eager_delete_tensor_gb=0, # enable GC to save memory
)
import paddle
import paddle.fluid as fluid
import reader
from mobilenet_ssd import build_mobilenet_ssd
from utility import add_arguments, print_arguments, check_cuda
parser = argparse.ArgumentParser(description=__doc__)
add_arg = functools.partial(add_arguments, argparser=parser)
# yapf: disable
add_arg('learning_rate', float, 0.001, "Learning rate.")
add_arg('batch_size', int, 64, "Minibatch size of all devices.")
add_arg('epoc_num', int, 120, "Epoch number.")
add_arg('use_gpu', bool, True, "Whether use GPU.")
add_arg('parallel', bool, True, "Whether train in parallel on multi-devices.")
add_arg('dataset', str, 'pascalvoc', "dataset can be coco2014, coco2017, and pascalvoc.")
add_arg('model_save_dir', str, 'model', "The path to save model.")
add_arg('pretrained_model', str, 'pretrained/ssd_mobilenet_v1_coco/', "The init model path.")
add_arg('ap_version', str, '11point', "mAP version can be integral or 11point.")
add_arg('image_shape', str, '3,300,300', "Input image shape.")
add_arg('mean_BGR', str, '127.5,127.5,127.5', "Mean value for B,G,R channel which will be subtracted.")
add_arg('data_dir', str, 'data/pascalvoc', "Data directory.")
add_arg('use_multiprocess', bool, True, "Whether use multi-process for data preprocessing.")
add_arg('enable_ce', bool, False, "Whether use CE to evaluate the model.")
#yapf: enable
train_parameters = {
"pascalvoc": {
"train_images": 16551,
"image_shape": [3, 300, 300],
"class_num": 21,
"batch_size": 64,
"lr": 0.001,
"lr_epochs": [40, 60, 80, 100],
"lr_decay": [1, 0.5, 0.25, 0.1, 0.01],
"ap_version": '11point',
},
"coco2014": {
"train_images": 82783,
"image_shape": [3, 300, 300],
"class_num": 91,
"batch_size": 64,
"lr": 0.001,
"lr_epochs": [12, 19],
"lr_decay": [1, 0.5, 0.25],
"ap_version": 'integral', # should use eval_coco_map.py to test model
},
"coco2017": {
"train_images": 118287,
"image_shape": [3, 300, 300],
"class_num": 91,
"batch_size": 64,
"lr": 0.001,
"lr_epochs": [12, 19],
"lr_decay": [1, 0.5, 0.25],
"ap_version": 'integral', # should use eval_coco_map.py to test model
}
}
def optimizer_setting(train_params):
batch_size = train_params["batch_size"]
iters = train_params["train_images"] // batch_size
lr = train_params["lr"]
boundaries = [i * iters for i in train_params["lr_epochs"]]
values = [ i * lr for i in train_params["lr_decay"]]
optimizer = fluid.optimizer.RMSProp(
learning_rate=fluid.layers.piecewise_decay(boundaries, values),
regularization=fluid.regularizer.L2Decay(0.00005), )
return optimizer
def build_program(main_prog, startup_prog, train_params, is_train):
image_shape = train_params['image_shape']
class_num = train_params['class_num']
ap_version = train_params['ap_version']
outs = []
with fluid.program_guard(main_prog, startup_prog):
py_reader = fluid.layers.py_reader(
capacity=64,
shapes=[[-1] + image_shape, [-1, 4], [-1, 1], [-1, 1]],
lod_levels=[0, 1, 1, 1],
dtypes=["float32", "float32", "int32", "int32"],
use_double_buffer=True)
with fluid.unique_name.guard():
image, gt_box, gt_label, difficult = fluid.layers.read_file(py_reader)
locs, confs, box, box_var = build_mobilenet_ssd(image, class_num, image_shape)
if is_train:
with fluid.unique_name.guard("train"):
loss = fluid.layers.ssd_loss(locs, confs, gt_box, gt_label, box,
box_var)
loss = fluid.layers.reduce_sum(loss)
optimizer = optimizer_setting(train_params)
optimizer.minimize(loss)
outs = [py_reader, loss]
else:
with fluid.unique_name.guard("inference"):
nmsed_out = fluid.layers.detection_output(
locs, confs, box, box_var, nms_threshold=0.45)
map_eval = fluid.metrics.DetectionMAP(
nmsed_out,
gt_label,
gt_box,
difficult,
class_num,
overlap_threshold=0.5,
evaluate_difficult=False,
ap_version=ap_version)
# nmsed_out and image is used to save mode for inference
outs = [py_reader, map_eval, nmsed_out, image]
return outs
def train(args,
data_args,
train_params,
train_file_list,
val_file_list):
model_save_dir = args.model_save_dir
pretrained_model = args.pretrained_model
use_gpu = args.use_gpu
parallel = args.parallel
enable_ce = args.enable_ce
is_shuffle = True
if not use_gpu:
devices_num = int(os.environ.get('CPU_NUM',
multiprocessing.cpu_count()))
else:
devices_num = fluid.core.get_cuda_device_count()
batch_size = train_params['batch_size']
epoc_num = train_params['epoc_num']
batch_size_per_device = batch_size // devices_num
num_workers = 8
startup_prog = fluid.Program()
train_prog = fluid.Program()
test_prog = fluid.Program()
if enable_ce:
import random
random.seed(0)
np.random.seed(0)
is_shuffle = False
startup_prog.random_seed = 111
train_prog.random_seed = 111
test_prog.random_seed = 111
train_py_reader, loss = build_program(
main_prog=train_prog,
startup_prog=startup_prog,
train_params=train_params,
is_train=True)
test_py_reader, map_eval, _, _ = build_program(
main_prog=test_prog,
startup_prog=startup_prog,
train_params=train_params,
is_train=False)
test_prog = test_prog.clone(for_test=True)
place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(startup_prog)
if pretrained_model:
def if_exist(var):
return os.path.exists(os.path.join(pretrained_model, var.name))
fluid.io.load_vars(exe, pretrained_model, main_program=train_prog,
predicate=if_exist)
if parallel:
loss.persistable = True
build_strategy = fluid.BuildStrategy()
build_strategy.enable_inplace = True
build_strategy.memory_optimize = True
train_exe = fluid.ParallelExecutor(main_program=train_prog,
use_cuda=use_gpu, loss_name=loss.name, build_strategy=build_strategy)
test_reader = reader.test(data_args, val_file_list, batch_size)
test_py_reader.decorate_paddle_reader(test_reader)
def save_model(postfix, main_prog):
model_path = os.path.join(model_save_dir, postfix)
if os.path.isdir(model_path):
shutil.rmtree(model_path)
print('save models to %s' % (model_path))
fluid.io.save_persistables(exe, model_path, main_program=main_prog)
best_map = 0.
test_map = None
def test(epoc_id, best_map):
_, accum_map = map_eval.get_map_var()
map_eval.reset(exe)
every_epoc_map=[] # for CE
test_py_reader.start()
try:
batch_id = 0
while True:
test_map, = exe.run(test_prog, fetch_list=[accum_map])
if batch_id % 10 == 0:
every_epoc_map.append(test_map)
print("Batch {0}, map {1}".format(batch_id, test_map))
batch_id += 1
except fluid.core.EOFException:
test_py_reader.reset()
mean_map = np.mean(every_epoc_map)
print("Epoc {0}, test map {1}".format(epoc_id, test_map[0]))
if test_map[0] > best_map:
best_map = test_map[0]
save_model('best_model', test_prog)
return best_map, mean_map
total_time = 0.0
for epoc_id in range(epoc_num):
train_reader = reader.train(data_args,
train_file_list,
batch_size_per_device,
shuffle=is_shuffle,
use_multiprocess=args.use_multiprocess,
num_workers=num_workers,
enable_ce=enable_ce)
train_py_reader.decorate_paddle_reader(train_reader)
epoch_idx = epoc_id + 1
start_time = time.time()
prev_start_time = start_time
every_epoc_loss = []
batch_id = 0
train_py_reader.start()
while True:
try:
prev_start_time = start_time
start_time = time.time()
if parallel:
loss_v, = train_exe.run(fetch_list=[loss.name])
else:
loss_v, = exe.run(train_prog, fetch_list=[loss])
loss_v = np.mean(np.array(loss_v))
every_epoc_loss.append(loss_v)
if batch_id % 10 == 0:
print("Epoc {:d}, batch {:d}, loss {:.6f}, time {:.5f}".format(
epoc_id, batch_id, loss_v, start_time - prev_start_time))
batch_id += 1
except (fluid.core.EOFException, StopIteration):
train_reader().close()
train_py_reader.reset()
break
end_time = time.time()
total_time += end_time - start_time
if epoc_id % 10 == 0 or epoc_id == epoc_num - 1:
best_map, mean_map = test(epoc_id, best_map)
print("Best test map {0}".format(best_map))
# save model
save_model(str(epoc_id), train_prog)
if enable_ce:
train_avg_loss = np.mean(every_epoc_loss)
if devices_num == 1:
print("kpis train_cost %s" % train_avg_loss)
print("kpis test_acc %s" % mean_map)
print("kpis train_speed %s" % (total_time / epoch_idx))
else:
print("kpis train_cost_card%s %s" %
(devices_num, train_avg_loss))
print("kpis test_acc_card%s %s" %
(devices_num, mean_map))
print("kpis train_speed_card%s %f" %
(devices_num, total_time / epoch_idx))
def main():
args = parser.parse_args()
print_arguments(args)
check_cuda(args.use_gpu)
data_dir = args.data_dir
dataset = args.dataset
assert dataset in ['pascalvoc', 'coco2014', 'coco2017']
# for pascalvoc
label_file = 'label_list'
train_file_list = 'trainval.txt'
val_file_list = 'test.txt'
if dataset == 'coco2014':
train_file_list = 'annotations/instances_train2014.json'
val_file_list = 'annotations/instances_val2014.json'
elif dataset == 'coco2017':
train_file_list = 'annotations/instances_train2017.json'
val_file_list = 'annotations/instances_val2017.json'
mean_BGR = [float(m) for m in args.mean_BGR.split(",")]
image_shape = [int(m) for m in args.image_shape.split(",")]
train_parameters[dataset]['image_shape'] = image_shape
train_parameters[dataset]['batch_size'] = args.batch_size
train_parameters[dataset]['lr'] = args.learning_rate
train_parameters[dataset]['epoc_num'] = args.epoc_num
train_parameters[dataset]['ap_version'] = args.ap_version
data_args = reader.Settings(
dataset=args.dataset,
data_dir=data_dir,
label_file=label_file,
resize_h=image_shape[1],
resize_w=image_shape[2],
mean_value=mean_BGR,
apply_distort=True,
apply_expand=True,
ap_version = args.ap_version)
train(args,
data_args,
train_parameters[dataset],
train_file_list=train_file_list,
val_file_list=val_file_list)
if __name__ == '__main__':
main()
| [
"reader.Settings",
"paddle.fluid.metrics.DetectionMAP",
"paddle.fluid.layers.py_reader",
"utility.check_cuda",
"multiprocessing.cpu_count",
"numpy.array",
"paddle.fluid.Executor",
"paddle.fluid.layers.ssd_loss",
"paddle.fluid.layers.piecewise_decay",
"reader.train",
"numpy.mean",
"paddle.fluid... | [((1280, 1324), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (1303, 1324), False, 'import argparse\n'), ((1335, 1385), 'functools.partial', 'functools.partial', (['add_arguments'], {'argparser': 'parser'}), '(add_arguments, argparser=parser)\n', (1352, 1385), False, 'import functools\n'), ((6597, 6612), 'paddle.fluid.Program', 'fluid.Program', ([], {}), '()\n', (6610, 6612), True, 'import paddle.fluid as fluid\n'), ((6630, 6645), 'paddle.fluid.Program', 'fluid.Program', ([], {}), '()\n', (6643, 6645), True, 'import paddle.fluid as fluid\n'), ((6662, 6677), 'paddle.fluid.Program', 'fluid.Program', ([], {}), '()\n', (6675, 6677), True, 'import paddle.fluid as fluid\n'), ((7371, 7392), 'paddle.fluid.Executor', 'fluid.Executor', (['place'], {}), '(place)\n', (7385, 7392), True, 'import paddle.fluid as fluid\n'), ((8027, 8076), 'reader.test', 'reader.test', (['data_args', 'val_file_list', 'batch_size'], {}), '(data_args, val_file_list, batch_size)\n', (8038, 8076), False, 'import reader\n'), ((11759, 11780), 'utility.print_arguments', 'print_arguments', (['args'], {}), '(args)\n', (11774, 11780), False, 'from utility import add_arguments, print_arguments, check_cuda\n'), ((11786, 11810), 'utility.check_cuda', 'check_cuda', (['args.use_gpu'], {}), '(args.use_gpu)\n', (11796, 11810), False, 'from utility import add_arguments, print_arguments, check_cuda\n'), ((12802, 13033), 'reader.Settings', 'reader.Settings', ([], {'dataset': 'args.dataset', 'data_dir': 'data_dir', 'label_file': 'label_file', 'resize_h': 'image_shape[1]', 'resize_w': 'image_shape[2]', 'mean_value': 'mean_BGR', 'apply_distort': '(True)', 'apply_expand': '(True)', 'ap_version': 'args.ap_version'}), '(dataset=args.dataset, data_dir=data_dir, label_file=\n label_file, resize_h=image_shape[1], resize_w=image_shape[2],\n mean_value=mean_BGR, apply_distort=True, apply_expand=True, ap_version=\n args.ap_version)\n', (12817, 13033), False, 'import reader\n'), ((4237, 4281), 'paddle.fluid.program_guard', 'fluid.program_guard', (['main_prog', 'startup_prog'], {}), '(main_prog, startup_prog)\n', (4256, 4281), True, 'import paddle.fluid as fluid\n'), ((4303, 4501), 'paddle.fluid.layers.py_reader', 'fluid.layers.py_reader', ([], {'capacity': '(64)', 'shapes': '[[-1] + image_shape, [-1, 4], [-1, 1], [-1, 1]]', 'lod_levels': '[0, 1, 1, 1]', 'dtypes': "['float32', 'float32', 'int32', 'int32']", 'use_double_buffer': '(True)'}), "(capacity=64, shapes=[[-1] + image_shape, [-1, 4], [-\n 1, 1], [-1, 1]], lod_levels=[0, 1, 1, 1], dtypes=['float32', 'float32',\n 'int32', 'int32'], use_double_buffer=True)\n", (4325, 4501), True, 'import paddle.fluid as fluid\n'), ((6383, 6417), 'paddle.fluid.core.get_cuda_device_count', 'fluid.core.get_cuda_device_count', ([], {}), '()\n', (6415, 6417), True, 'import paddle.fluid as fluid\n'), ((6727, 6741), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (6738, 6741), False, 'import random\n'), ((6750, 6767), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (6764, 6767), True, 'import numpy as np\n'), ((7309, 7327), 'paddle.fluid.CUDAPlace', 'fluid.CUDAPlace', (['(0)'], {}), '(0)\n', (7324, 7327), True, 'import paddle.fluid as fluid\n'), ((7344, 7360), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (7358, 7360), True, 'import paddle.fluid as fluid\n'), ((7556, 7646), 'paddle.fluid.io.load_vars', 'fluid.io.load_vars', (['exe', 'pretrained_model'], {'main_program': 'train_prog', 'predicate': 'if_exist'}), '(exe, pretrained_model, main_program=train_prog,\n predicate=if_exist)\n', (7574, 7646), True, 'import paddle.fluid as fluid\n'), ((7745, 7766), 'paddle.fluid.BuildStrategy', 'fluid.BuildStrategy', ([], {}), '()\n', (7764, 7766), True, 'import paddle.fluid as fluid\n'), ((7878, 8000), 'paddle.fluid.ParallelExecutor', 'fluid.ParallelExecutor', ([], {'main_program': 'train_prog', 'use_cuda': 'use_gpu', 'loss_name': 'loss.name', 'build_strategy': 'build_strategy'}), '(main_program=train_prog, use_cuda=use_gpu, loss_name\n =loss.name, build_strategy=build_strategy)\n', (7900, 8000), True, 'import paddle.fluid as fluid\n'), ((8194, 8231), 'os.path.join', 'os.path.join', (['model_save_dir', 'postfix'], {}), '(model_save_dir, postfix)\n', (8206, 8231), False, 'import os\n'), ((8243, 8268), 'os.path.isdir', 'os.path.isdir', (['model_path'], {}), '(model_path)\n', (8256, 8268), False, 'import os\n'), ((8366, 8433), 'paddle.fluid.io.save_persistables', 'fluid.io.save_persistables', (['exe', 'model_path'], {'main_program': 'main_prog'}), '(exe, model_path, main_program=main_prog)\n', (8392, 8433), True, 'import paddle.fluid as fluid\n'), ((9069, 9092), 'numpy.mean', 'np.mean', (['every_epoc_map'], {}), '(every_epoc_map)\n', (9076, 9092), True, 'import numpy as np\n'), ((9396, 9575), 'reader.train', 'reader.train', (['data_args', 'train_file_list', 'batch_size_per_device'], {'shuffle': 'is_shuffle', 'use_multiprocess': 'args.use_multiprocess', 'num_workers': 'num_workers', 'enable_ce': 'enable_ce'}), '(data_args, train_file_list, batch_size_per_device, shuffle=\n is_shuffle, use_multiprocess=args.use_multiprocess, num_workers=\n num_workers, enable_ce=enable_ce)\n', (9408, 9575), False, 'import reader\n'), ((9872, 9883), 'time.time', 'time.time', ([], {}), '()\n', (9881, 9883), False, 'import time\n'), ((10829, 10840), 'time.time', 'time.time', ([], {}), '()\n', (10838, 10840), False, 'import time\n'), ((11173, 11197), 'numpy.mean', 'np.mean', (['every_epoc_loss'], {}), '(every_epoc_loss)\n', (11180, 11197), True, 'import numpy as np\n'), ((818, 843), 'os.environ.get', 'os.environ.get', (['key', 'None'], {}), '(key, None)\n', (832, 843), False, 'import os\n'), ((3879, 3927), 'paddle.fluid.layers.piecewise_decay', 'fluid.layers.piecewise_decay', (['boundaries', 'values'], {}), '(boundaries, values)\n', (3907, 3927), True, 'import paddle.fluid as fluid\n'), ((3952, 3984), 'paddle.fluid.regularizer.L2Decay', 'fluid.regularizer.L2Decay', (['(5e-05)'], {}), '(5e-05)\n', (3977, 3984), True, 'import paddle.fluid as fluid\n'), ((4567, 4592), 'paddle.fluid.unique_name.guard', 'fluid.unique_name.guard', ([], {}), '()\n', (4590, 4592), True, 'import paddle.fluid as fluid\n'), ((4643, 4676), 'paddle.fluid.layers.read_file', 'fluid.layers.read_file', (['py_reader'], {}), '(py_reader)\n', (4665, 4676), True, 'import paddle.fluid as fluid\n'), ((4717, 4767), 'mobilenet_ssd.build_mobilenet_ssd', 'build_mobilenet_ssd', (['image', 'class_num', 'image_shape'], {}), '(image, class_num, image_shape)\n', (4736, 4767), False, 'from mobilenet_ssd import build_mobilenet_ssd\n'), ((8282, 8307), 'shutil.rmtree', 'shutil.rmtree', (['model_path'], {}), '(model_path)\n', (8295, 8307), False, 'import shutil\n'), ((6321, 6348), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (6346, 6348), False, 'import multiprocessing\n'), ((7506, 7546), 'os.path.join', 'os.path.join', (['pretrained_model', 'var.name'], {}), '(pretrained_model, var.name)\n', (7518, 7546), False, 'import os\n'), ((10114, 10125), 'time.time', 'time.time', ([], {}), '()\n', (10123, 10125), False, 'import time\n'), ((4814, 4846), 'paddle.fluid.unique_name.guard', 'fluid.unique_name.guard', (['"""train"""'], {}), "('train')\n", (4837, 4846), True, 'import paddle.fluid as fluid\n'), ((4875, 4941), 'paddle.fluid.layers.ssd_loss', 'fluid.layers.ssd_loss', (['locs', 'confs', 'gt_box', 'gt_label', 'box', 'box_var'], {}), '(locs, confs, gt_box, gt_label, box, box_var)\n', (4896, 4941), True, 'import paddle.fluid as fluid\n'), ((4993, 5022), 'paddle.fluid.layers.reduce_sum', 'fluid.layers.reduce_sum', (['loss'], {}), '(loss)\n', (5016, 5022), True, 'import paddle.fluid as fluid\n'), ((5212, 5248), 'paddle.fluid.unique_name.guard', 'fluid.unique_name.guard', (['"""inference"""'], {}), "('inference')\n", (5235, 5248), True, 'import paddle.fluid as fluid\n'), ((5282, 5358), 'paddle.fluid.layers.detection_output', 'fluid.layers.detection_output', (['locs', 'confs', 'box', 'box_var'], {'nms_threshold': '(0.45)'}), '(locs, confs, box, box_var, nms_threshold=0.45)\n', (5311, 5358), True, 'import paddle.fluid as fluid\n'), ((5415, 5573), 'paddle.fluid.metrics.DetectionMAP', 'fluid.metrics.DetectionMAP', (['nmsed_out', 'gt_label', 'gt_box', 'difficult', 'class_num'], {'overlap_threshold': '(0.5)', 'evaluate_difficult': '(False)', 'ap_version': 'ap_version'}), '(nmsed_out, gt_label, gt_box, difficult,\n class_num, overlap_threshold=0.5, evaluate_difficult=False, ap_version=\n ap_version)\n', (5441, 5573), True, 'import paddle.fluid as fluid\n'), ((10347, 10363), 'numpy.array', 'np.array', (['loss_v'], {}), '(loss_v)\n', (10355, 10363), True, 'import numpy as np\n')] |
"""
This module contains all functions that are used the load the data.
Todo:
* Clean the code.
.. _Google Python Style Guide:
http://google.github.io/styleguide/pyguide.html
Format for data loaders:
p, x, h, n_full, cate_name
"""
import numpy as np
import scipy as sp
import pickle
from scipy import stats
from scipy.stats import ttest_ind
import matplotlib.pyplot as plt
import adafdr
from adafdr.util import *
from matplotlib import mlab
from adafdr.method import *
import logging
# External datasets
def data_airway():
file_path = adafdr.__path__[0]
file_name = file_path + '/data/airway'
X = np.loadtxt(file_name,skiprows=0,delimiter=',')
x=X[:,2].reshape([-1,1])
p=X[:,0]
return p, x
def data_bottomly():
file_path = adafdr.__path__[0]
file_name = file_path + '/data/bottomly'
X = np.loadtxt(file_name,skiprows=0,delimiter=',')
x=X[:,2].reshape([-1,1])
p=X[:,0]
return p, x
def data_pasilla():
file_path = adafdr.__path__[0]
file_name = file_path + '/data/pasilla'
X = np.loadtxt(file_name,skiprows=0,delimiter=',')
x=X[:,2].reshape([-1,1])
p=X[:,0]
return p, x
def data_small_gtex():
# Hard-coded information of the GTEx dataset.
cate_name = {3: {1: 'TssA', 2: 'TssAFlnk', 3: 'TxFlnk', 4: 'Tx',
5: 'TxWk', 6: 'EnhG', 7: 'Enh', 8: 'ZNF/Rpts',
9: 'Het', 10: 'TssBiv', 11: 'BivFlnk', 12: 'EnhBiv',
13: 'ReprPC', 14: 'ReprPCWk', 15: 'Quies'}}
n_full = 172353475
fname = 'GTEx_small.pickle'
file_path = adafdr.__path__[0]
fname = file_path + '/data/' + fname
with open(fname, 'rb') as handle:
p = pickle.load(handle)
x = pickle.load(handle)
cis_name = pickle.load(handle)
return p, x, n_full, cate_name, cis_name
def data_small_gtex_chr21(opt='Adipose_Subcutaneous'):
np.random.seed(0)
# Hard-coded information of the GTEx dataset.
cate_name = {3: {1: 'TssA', 2: 'TssAFlnk', 3: 'TxFlnk', 4: 'Tx',
5: 'TxWk', 6: 'EnhG', 7: 'Enh', 8: 'ZNF/Rpts',
9: 'Het', 10: 'TssBiv', 11: 'BivFlnk', 12: 'EnhBiv',
13: 'ReprPC', 14: 'ReprPCWk', 15: 'Quies'}}
file_path = adafdr.__path__[0]
file_name = file_path + '/data/%s_chr21_300k'%opt
temp_data = np.loadtxt(file_name, dtype=str, delimiter=',')
p = temp_data[:, 0].astype(float)
cis_name = temp_data[:, 1]
x = temp_data[:, 2:].astype(float)
x[:, 0] = np.log10(x[:, 0]+0.5) + np.random.rand(x.shape[0])*1e-8
return p, x, cate_name, cis_name
## generating the 1d toy example
def toy_data_1d(job_id=0,n_sample=10000,vis=0):
def pi1_gen(x): # need to be fixed
pi1=0.03*sp.stats.norm.pdf(x,loc=0.2,scale=0.05)+0.04*sp.stats.norm.pdf(x,loc=0.8,scale=0.05)
pi1+=0.15*x
return pi1
def plot_pi1_1d(pi1_gen):
x_grid = np.linspace(0,1,100)
pi1_grid = pi1_gen(x_grid)
plt.plot(x_grid,pi1_grid)
plt.xlabel('covariate')
plt.ylabel('alt distribution')
plt.title('the alternative distribution')
np.random.seed(42)
if job_id == 0: # Gaussian mixtures
x = np.random.uniform(0,1,size=n_sample)
pi1 = pi1_gen(x)
p = np.zeros(n_sample)
# generating the hypothesis
h = np.array((np.random.uniform(size=n_sample)<pi1),dtype=int)
n0 = np.sum(h==0)
n1 = np.sum(h==1)
# generating the p-values
p[h==0] = np.random.uniform(size=n0)
p[h==1] = np.random.beta(a=0.4,b=4,size=n1)
#plt.figure()
#plt.hist(p[h==1],bins=100)
#plt.show()
#print(np.mean(p[h==1]))
if vis == 1:
print('### Summary ###')
print('# null: %s, # alt: %s:, null proportion: %s'%(str(np.sum(h==0)),str(np.sum(h==1)),str(np.sum(h==0)/h.shape[0])))
plt.figure(figsize=[16,5])
plt.subplot(121)
plot_pi1_1d(pi1_gen)
plt.subplot(122)
plot_data_1d(p,x,h)
plt.legend()
plt.show()
return p,x,h
def write_simulation_data(p, x, h, filename):
"""Write the simulation data with format:
p, h, x0, x1, x2, ... for the columns
Args:
p ((n,) ndarray): The p-value.
x ((n,d) ndarray): The covaraites.
h ((n,) boolean ndarray): The ground truth. True indicates the
hypothesis is alternative.
filename (str): path of the file.
Returns:
"""
temp_data = np.zeros([x.shape[0], x.shape[1]+2], dtype=float)
temp_data[:, 0] = p
temp_data[:, 1] = h
temp_data[:, 2:] = x
np.savetxt(filename, temp_data, delimiter=",")
return
def load_simulation_data(filename):
"""Load the simulation data with format:
p, h, x0, x1, x2, ... for the columns
Args:
filename (str): path of the file.
Returns:
p ((n,) ndarray): The p-value.
x ((n,d) ndarray): The covaraites.
h ((n,) boolean ndarray): The ground truth. True indicates the
hypothesis is alternative.
"""
temp_data = np.loadtxt(filename, delimiter=',')
p = temp_data[:, 0].astype(float)
h = temp_data[:, 1].astype(bool)
x = temp_data[:, 2:].astype(float)
return p, x, h
def load_x_mixture(opt=0):
"""Generate a mixture data (of x) to test mixture_fit.
Args:
opt (int): 0: 2d slope.
1: 2d bump.
2: 2d slope+bump.
3: 10d data with slope+bump in the first 2d.
Returns:
x ((n,d) ndarray): The mixture data
param (list): Parameters that are used to generate the data.
"""
n_sample = 10000
if opt==0:
a = np.array([2,0],dtype=float)
x_grid = get_grid_2d(101)
n_grid = x_grid.shape[0]
p = f_slope(x_grid,a)
p /= p.sum()
x = np.random.choice(np.arange(n_grid),size=n_sample,p=p)
x = x_grid[x,:]
param = a
elif opt==1:
mu = np.array([0.5,0.05],dtype=float)
sigma = np.array([0.1,0.1],dtype=float)
x_grid = get_grid_2d(101)
n_grid = x_grid.shape[0]
p = f_bump(x_grid,mu,sigma)
p /= p.sum()
x = np.random.choice(np.arange(n_grid),size=n_sample,p=p)
x = x_grid[x,:]
param = (mu,sigma)
elif opt==2:
w = np.array([0.4,0.3,0.3],dtype=float)
a = np.array([2,0],dtype=float)
mu = np.array([[0.2,0.2],[0.7,0.7]],dtype=float)
sigma = np.array([[0.1,0.2],[0.1,0.1]],dtype=float)
x_grid = get_grid_2d(101)
n_grid = x_grid.shape[0]
p = f_all(x_grid,a,mu,sigma,w)
p /= p.sum()
x = np.random.choice(np.arange(n_grid),size=n_sample,p=p)
x = x_grid[x,:]
param = (a,mu,sigma,w)
elif opt==3:
w = np.array([0.4,0.3,0.3],dtype=float)
a = np.array([2,0],dtype=float)
mu = np.array([[0.2,0.2],[0.7,0.7]],dtype=float)
sigma = np.array([[0.1,0.2],[0.1,0.1]],dtype=float)
x_grid = get_grid_2d(101)
n_grid = x_grid.shape[0]
p = f_all(x_grid,a,mu,sigma,w)
p /= p.sum()
x = np.random.choice(np.arange(n_grid),size=n_sample,p=p)
x = x_grid[x,:]
a_ = np.zeros(10)
a_[0:2] = a
mu_ = np.zeros([2,10],dtype=float)+0.5
mu_[:,0:2] = mu
sigma_ = np.ones([2,10],dtype=float)
sigma_[:,0:2] = sigma
param = (a_,mu_,sigma_,w)
x_noise = np.random.uniform(high=1,low=0,size = (n_sample,8))
x = np.concatenate([x,x_noise],1)
else:
pass
return x,param
def load_1d_bump_slope(n_sample=20000, n_dim=2, random_state=0):
"""Generate a 1d simulated data.
Args:
n_sample (int): The number of hypotheses.
n_dim (int): The number of dimensions. If n_dim>2, the rest of dimensions
contains uninformative features.
random_state (int): The random seed
Returns:
p ((n,) ndarray): The p-value.
x ((n,d) ndarray): The covaraites.
h ((n,) boolean ndarray): The ground truth. True indicates the
hypothesis is alternative.
n_full (int): The number of hypotheses before filtering. Same as
n if no filtering is applied.
cate_name (dic of dics): (key,val) gives the (feature index, cate_name_dic) for
discrete features. For each discrete feature, the (key,val) of the sub dic
gives the (val,name) for all categories.
"""
np.random.seed(random_state)
# Generate pi1
x_grid = get_grid_1d(101)
x = np.random.choice(np.arange(x_grid.shape[0]), size=n_sample)
x = x_grid[x,:]
w = np.array([0.5,0.25,0.25],dtype=float)
a = np.array([0.5],dtype=float)
mu = np.array([[0.25], [0.75]],dtype=float)
sigma = np.array([[0.05], [0.05]],dtype=float)
pi1 = (0.1*f_all(x,a,mu,sigma,w)).clip(max=1)
# Generate data
p = np.zeros(n_sample)
h = np.zeros(n_sample, dtype=bool)
rnd = np.random.uniform(size=n_sample)
p[rnd>=pi1] = np.random.uniform(size=np.sum(rnd>=pi1))
p[rnd<pi1] = np.random.beta(a=0.3, b=4, size=np.sum(rnd<pi1))
h[rnd<pi1] = True
# Add non-informative dimensions.
if n_dim>1:
x_noise = np.random.uniform(size=(n_sample, n_dim-2))
x = np.concatenate([x,x_noise],1)
return p,x,h,p.shape[0],{}
def load_2d_bump_slope(n_sample=20000, n_dim=2, random_state=0):
"""Generate a simulated data.
Args:
n_sample (int): The number of hypotheses.
n_dim (int): The number of dimensions. If n_dim>2, the rest of dimensions
contains uninformative features.
random_state (int): The random seed
Returns:
p ((n,) ndarray): The p-value.
x ((n,d) ndarray): The covaraites.
h ((n,) boolean ndarray): The ground truth. True indicates the
hypothesis is alternative.
n_full (int): The number of hypotheses before filtering. Same as
n if no filtering is applied.
cate_name (dic of dics): (key,val) gives the (feature index, cate_name_dic) for
discrete features. For each discrete feature, the (key,val) of the sub dic
gives the (val,name) for all categories.
"""
np.random.seed(random_state)
# Generate pi1
x_grid = get_grid_2d(101)
x = np.random.choice(np.arange(x_grid.shape[0]),size=n_sample)
x = x_grid[x,:]
w = np.array([0.5,0.25,0.25],dtype=float)
a = np.array([0.5,0.5],dtype=float)
mu = np.array([[0.25,0.25],[0.75,0.75]],dtype=float)
sigma = np.array([[0.1,0.1],[0.1,0.1]],dtype=float)
pi1 = (0.1*f_all(x,a,mu,sigma,w)).clip(max=1)
# Generate data
p = np.zeros(n_sample)
h = np.zeros(n_sample, dtype=bool)
rnd = np.random.uniform(size=n_sample)
p[rnd>=pi1] = np.random.uniform(size=np.sum(rnd>=pi1))
p[rnd<pi1] = np.random.beta(a=0.3, b=4, size=np.sum(rnd<pi1))
h[rnd<pi1] = True
# Add non-informative dimensions.
if n_dim>2:
x_noise = np.random.uniform(size=(n_sample, n_dim-2))
x = np.concatenate([x,x_noise],1)
return p,x,h,p.shape[0],{}
def load_data_ihw(random_state=0):
"""data from ihw supp 4.2.2
"""
np.random.seed(random_state)
n_sample = 20000
n_alt = int(20000*0.1)
h = np.zeros([n_sample], dtype=int)
h[0:n_alt] = 1
data_case = np.random.randn(5, n_sample) + h*2
data_control = np.random.randn(5, n_sample)
p = ttest_ind(data_case, data_control)[1]
data_pool = np.concatenate([data_case, data_control], axis=0)
x = np.var(data_pool, axis=0)
x = x.reshape([-1,1])
return p, x, h
def load_data_wd(n_sample=20000, random_state=0):
"""Weakly dependent dataset following the receipe of Sec. 3.2,
from the paper "Strong control, conservative point estimation
and simultaneous conservative consistency of false discovery rates:
a unified approach"
"""
np.random.seed(random_state)
# Weakly-dependent covariance matrix.
cov_mat = np.zeros([10, 10], dtype=float)
for j in range(10):
for k in range(j,10):
if j == k:
cov_mat[j, k] = 1
elif j < k and k <= 4:
cov_mat[j, k] = 0.25
elif j <= 4 and k > 4:
cov_mat[j, k] = -0.25
for j in range(10):
for k in range(j):
cov_mat[j, k] = cov_mat[k, j]
# Generate pi1
x_grid = get_grid_1d(101)
x = np.random.choice(np.arange(x_grid.shape[0]), size=n_sample)
x = x_grid[x,:]
w = np.array([0.5,0.25,0.25],dtype=float)
a = np.array([0.5],dtype=float)
mu = np.array([[0.25], [0.75]],dtype=float)
sigma = np.array([[0.05], [0.05]],dtype=float)
pi1 = (0.1*f_all(x,a,mu,sigma,w)).clip(max=1)
# Generate p-values
null_z = np.random.multivariate_normal(np.zeros([10]), cov_mat, int(n_sample/10)).flatten()
alt_z = np.random.multivariate_normal(np.zeros([10])+2, cov_mat, int(n_sample/10)).flatten()
null_p = 1 - stats.norm.cdf(null_z)
alt_p = 1 - stats.norm.cdf(alt_z)
rnd = np.random.uniform(size=n_sample)
p = np.zeros([n_sample], dtype=float)
p[rnd>=pi1] = null_p[0:np.sum(rnd>=pi1)]
p[rnd<pi1] = alt_p[0:np.sum(rnd<pi1)]
h = np.zeros(n_sample, dtype=bool)
h[rnd<pi1] = True
return p, x, h
def load_data_sd(n_sample=20000, random_state=0):
"""Strong dependent dataset modelling LD: every 5 hypotheses
are completely dependent
"""
np.random.seed(random_state)
# Strongly-dependent covariance matrix.
cov_mat = np.ones([5, 5], dtype=float)
# Generate pi1
x_grid = get_grid_1d(101)
x = np.random.choice(np.arange(x_grid.shape[0]), size=n_sample)
x = x_grid[x,:]
w = np.array([0.5,0.25,0.25],dtype=float)
a = np.array([0.5],dtype=float)
mu = np.array([[0.25], [0.75]],dtype=float)
sigma = np.array([[0.05], [0.05]],dtype=float)
pi1 = (0.1*f_all(x,a,mu,sigma,w)).clip(max=1)
# Generate p-values
null_z = np.random.multivariate_normal(np.zeros([5]), cov_mat, int(n_sample/5)).flatten()
alt_z = np.random.multivariate_normal(np.zeros([5])+2, cov_mat, int(n_sample/5)).flatten()
null_p = 1 - stats.norm.cdf(null_z)
alt_p = 1 - stats.norm.cdf(alt_z)
rnd = np.random.uniform(size=n_sample)
p = np.zeros([n_sample], dtype=float)
p[rnd>=pi1] = null_p[0:np.sum(rnd>=pi1)]
p[rnd<pi1] = alt_p[0:np.sum(rnd<pi1)]
h = np.zeros(n_sample, dtype=bool)
h[rnd<pi1] = True
return p, x, h
## neuralFDR simulated examples
def neuralfdr_generate_data_1D(job=0, n_samples=10000,data_vis=0, num_case=4):
if job == 0: # discrete case
pi1=np.random.uniform(0,0.3,size=num_case)
X=np.random.randint(0, num_case, n_samples)
p = np.zeros(n_samples)
h = np.zeros(n_samples)
for i in range(n_samples):
rnd = np.random.uniform()
if rnd > pi1[X[i]]:
p[i] = np.random.uniform()
h[i] = 0
else:
p[i] = np.random.beta(a = np.random.uniform(0.2,0.4), b = 4)
h[i] = 1
return p,h,X
def neuralfdr_generate_data_2D(job=0, n_samples=100000,data_vis=0):
np.random.seed(42)
if job == 0: # Gaussian mixtures
x1 = np.random.uniform(-1,1,size = n_samples)
x2 = np.random.uniform(-1,1,size = n_samples)
pi1 = ((mlab.bivariate_normal(x1, x2, 0.25, 0.25, -0.5, -0.2)+
mlab.bivariate_normal(x1, x2, 0.25, 0.25, 0.7, 0.5))/2).clip(max=1)
p = np.zeros(n_samples)
h = np.zeros(n_samples)
for i in range(n_samples):
rnd = np.random.uniform()
if rnd > pi1[i]:
p[i] = np.random.uniform()
h[i] = 0
else:
p[i] = np.random.beta(a = 0.3, b = 4)
h[i] = 1
X = np.concatenate([[x1],[x2]]).T
X = (X+1)/2
if data_vis == 1:
fig = plt.figure()
ax1 = fig.add_subplot(121)
x_grid = np.arange(-1, 1, 1/100.0)
y_grid = np.arange(-1, 1, 1/100.0)
X_grid, Y_grid = np.meshgrid(x_grid, y_grid)
pi1_grid = ((mlab.bivariate_normal(X_grid, Y_grid, 0.25, 0.25, -0.5, -0.2)+
mlab.bivariate_normal(X_grid, Y_grid, 0.25, 0.25, 0.7, 0.5))/2).clip(max=1)
ax1.pcolor(X_grid, Y_grid, pi1_grid)
ax2 = fig.add_subplot(122)
alt=ax2.scatter(x1[h==1][1:50], x2[h==1][1:50],color='r')
nul=ax2.scatter(x1[h==0][1:50], x2[h==0][1:50],color='b')
ax2.legend((alt,nul),('50 alternatives', '50 nulls'))
return p, h, X
if job == 1: # Linear trend
x1 = np.random.uniform(-1,1,size = n_samples)
x2 = np.random.uniform(-1,1,size = n_samples)
pi1 = 0.1 * (x1 + 1) /2 + 0.3 *(1-x2) / 2
p = np.zeros(n_samples)
h = np.zeros(n_samples)
for i in range(n_samples):
rnd = np.random.uniform()
if rnd > pi1[i]:
p[i] = np.random.uniform()
h[i] = 0
else:
p[i] = np.random.beta(a = 0.3, b = 4)
h[i] = 1
X = np.concatenate([[x1],[x2]]).T
X = (X+1)/2
if data_vis == 1:
fig = plt.figure()
ax1 = fig.add_subplot(121)
x_grid = np.arange(-1, 1, 1/100.0)
y_grid = np.arange(-1, 1, 1/100.0)
X_grid, Y_grid = np.meshgrid(x_grid, y_grid)
pi1_grid = 0.1 * (X_grid + 1) /2 + 0.3 *(1-Y_grid) / 2
ax1.pcolor(X_grid, Y_grid, pi1_grid)
ax2 = fig.add_subplot(122)
alt=ax2.scatter(x1[h==1][1:50], x2[h==1][1:50],color='r')
nul=ax2.scatter(x1[h==0][1:50], x2[h==0][1:50],color='b')
ax2.legend((alt,nul),('50 alternatives', '50 nulls'))
return p, h, X
if job == 2: # Gaussian mixture + linear trend
x1 = np.random.uniform(-1,1,size = n_samples)
x2 = np.random.uniform(-1,1,size = n_samples)
pi1 = ((mlab.bivariate_normal(x1, x2, 0.25, 0.25, -0.5, -0.2)+
mlab.bivariate_normal(x1, x2, 0.25, 0.25, 0.7, 0.5))/2).clip(max=1)
pi1 = pi1 * 0.5 + 0.5*(0.5 * (x1 + 1) /2 + 0.3 *(1-x2) / 2)
p = np.zeros(n_samples)
h = np.zeros(n_samples)
for i in range(n_samples):
rnd = np.random.uniform()
if rnd > pi1[i]:
p[i] = np.random.uniform()
h[i] = 0
else:
p[i] = np.random.beta(a = 0.3, b = 4)
h[i] = 1
X = np.concatenate([[x1],[x2]]).T
X = (X+1)/2
if data_vis == 1:
fig = plt.figure()
ax1 = fig.add_subplot(121)
x_grid = np.arange(-1, 1, 1/100.0)
y_grid = np.arange(-1, 1, 1/100.0)
X_grid, Y_grid = np.meshgrid(x_grid, y_grid)
pi1_grid = ((mlab.bivariate_normal(X_grid, Y_grid, 0.25, 0.25, -0.5, -0.2)+
mlab.bivariate_normal(X_grid, Y_grid, 0.25, 0.25, 0.7, 0.5))/2).clip(max=1) * 0.5 + (0.5 * (0.5 * (X_grid + 1) /2 + 0.3 *(1-Y_grid) / 2))
ax1.pcolor(X_grid, Y_grid, pi1_grid)
ax2 = fig.add_subplot(122)
alt=ax2.scatter(x1[h==1][1:50], x2[h==1][1:50],color='r')
nul=ax2.scatter(x1[h==0][1:50], x2[h==0][1:50],color='b')
ax2.legend((alt,nul),('50 alternatives', '50 nulls'))
return p, h, X
def load_2DGM(n_samples=100000,verbose=False):
np.random.seed(42)
x1 = np.random.uniform(-1,1,size = n_samples)
x2 = np.random.uniform(-1,1,size = n_samples)
pi1 = ((mlab.bivariate_normal(x1, x2, 0.25, 0.25, -0.5, -0.2)+
mlab.bivariate_normal(x1, x2, 0.25, 0.25, 0.7, 0.5))/2).clip(max=1)
p = np.zeros(n_samples)
h = np.zeros(n_samples)
for i in range(n_samples):
rnd = np.random.uniform()
if rnd > pi1[i]:
p[i] = np.random.uniform()
h[i] = 0
else:
p[i] = np.random.beta(a = 0.3, b = 4)
h[i] = 1
X = np.concatenate([[x1],[x2]]).T
X = (X+1)/2
if verbose:
fig = plt.figure()
ax1 = fig.add_subplot(121)
x_grid = np.arange(-1, 1, 1/100.0)
y_grid = np.arange(-1, 1, 1/100.0)
X_grid, Y_grid = np.meshgrid(x_grid, y_grid)
pi1_grid = ((mlab.bivariate_normal(X_grid, Y_grid, 0.25, 0.25, -0.5, -0.2)+
mlab.bivariate_normal(X_grid, Y_grid, 0.25, 0.25, 0.7, 0.5))/2).clip(max=1)
ax1.pcolor(X_grid, Y_grid, pi1_grid)
ax2 = fig.add_subplot(122)
alt=ax2.scatter(x1[h==1][1:50], x2[h==1][1:50],color='r')
nul=ax2.scatter(x1[h==0][1:50], x2[h==0][1:50],color='b')
ax2.legend((alt,nul),('50 alternatives', '50 nulls'))
return p,h,X
def load_2Dslope(n_samples=100000,verbose=False):
x1 = np.random.uniform(-1,1,size = n_samples)
x2 = np.random.uniform(-1,1,size = n_samples)
pi1 = 0.1 * (x1 + 1) /2 + 0.3 *(1-x2) / 2
p = np.zeros(n_samples)
h = np.zeros(n_samples)
for i in range(n_samples):
rnd = np.random.uniform()
if rnd > pi1[i]:
p[i] = np.random.uniform()
h[i] = 0
else:
p[i] = np.random.beta(a = 0.3, b = 4)
h[i] = 1
X = np.concatenate([[x1],[x2]]).T
X = (X+1)/2
if verbose:
fig = plt.figure()
ax1 = fig.add_subplot(121)
x_grid = np.arange(-1, 1, 1/100.0)
y_grid = np.arange(-1, 1, 1/100.0)
X_grid, Y_grid = np.meshgrid(x_grid, y_grid)
pi1_grid = 0.1 * (X_grid + 1) /2 + 0.3 *(1-Y_grid) / 2
ax1.pcolor(X_grid, Y_grid, pi1_grid)
ax2 = fig.add_subplot(122)
alt=ax2.scatter(x1[h==1][1:50], x2[h==1][1:50],color='r')
nul=ax2.scatter(x1[h==0][1:50], x2[h==0][1:50],color='b')
ax2.legend((alt,nul),('50 alternatives', '50 nulls'))
return p,h,X
def load_2DGM_slope(n_samples=100000,verbose=False):
x1 = np.random.uniform(-1,1,size = n_samples)
x2 = np.random.uniform(-1,1,size = n_samples)
pi1 = ((mlab.bivariate_normal(x1, x2, 0.25, 0.25, -0.5, -0.2)+
mlab.bivariate_normal(x1, x2, 0.25, 0.25, 0.7, 0.5))/2).clip(max=1)
pi1 = pi1 * 0.5 + 0.5*(0.5 * (x1 + 1) /2 + 0.3 *(1-x2) / 2)
p = np.zeros(n_samples)
h = np.zeros(n_samples)
for i in range(n_samples):
rnd = np.random.uniform()
if rnd > pi1[i]:
p[i] = np.random.uniform()
h[i] = 0
else:
p[i] = np.random.beta(a = 0.3, b = 4)
h[i] = 1
X = np.concatenate([[x1],[x2]]).T
X = (X+1)/2
if verbose:
fig = plt.figure()
ax1 = fig.add_subplot(121)
x_grid = np.arange(-1, 1, 1/100.0)
y_grid = np.arange(-1, 1, 1/100.0)
X_grid, Y_grid = np.meshgrid(x_grid, y_grid)
pi1_grid = ((mlab.bivariate_normal(X_grid, Y_grid, 0.25, 0.25, -0.5, -0.2)+
mlab.bivariate_normal(X_grid, Y_grid, 0.25, 0.25, 0.7, 0.5))/2).clip(max=1) * 0.5 + (0.5 * (0.5 * (X_grid + 1) /2 + 0.3 *(1-Y_grid) / 2))
ax1.pcolor(X_grid, Y_grid, pi1_grid)
ax2 = fig.add_subplot(122)
alt=ax2.scatter(x1[h==1][1:50], x2[h==1][1:50],color='r')
nul=ax2.scatter(x1[h==0][1:50], x2[h==0][1:50],color='b')
ax2.legend((alt,nul),('50 alternatives', '50 nulls'))
return p,h,X
def load_5DGM(n_sample=100000,verbose=False):
p,h,x = load_2DGM(n_samples=n_sample,verbose=verbose)
x_noise = np.random.uniform(high=1,low=-1,size = (n_sample,3))
x = np.concatenate([x,x_noise],1)
return p,h,x
def load_100D(n_sample=100000,verbose=False):
def generate_data_1D_cont(pi1,X):
n_samples = len(X)
p = np.zeros(n_samples)
h = np.zeros(n_samples)
for i in range(n_samples):
rnd = np.random.uniform()
if rnd > pi1[i]:
p[i] = np.random.uniform()
h[i] = 0
else:
p[i] = np.random.beta(a = np.random.uniform(0.2,0.4), b = 4)
h[i] = 1
return p, h, X
X = np.random.uniform(high = 5, size = (n_sample,))
pi1 = (5-X) / 10.0
p, h, x = generate_data_1D_cont(pi1, X)
x_noise = np.random.uniform(high = 5, size = (n_sample,99))
x = np.concatenate([np.expand_dims(x,1), x_noise], 1)
return p,h,x
def load_airway(verbose=False):
file_name='/data3/martin/nfdr2_simulation_data/RNA_seq/airway'
X = np.loadtxt(file_name,skiprows=0,delimiter=',')
x=X[:,2].reshape([-1,1])
p=X[:,0]
return p, None, x
def load_bottomly(verbose=False):
file_name='/data3/martin/nfdr2_simulation_data/RNA_seq/bottomly'
X = np.loadtxt(file_name,skiprows=0,delimiter=',')
x=X[:,2].reshape([-1,1])
p=X[:,0]
return p, None, x
def load_pasilla(verbose=False):
file_name='/data3/martin/nfdr2_simulation_data/RNA_seq/pasilla'
X = np.loadtxt(file_name,skiprows=0,delimiter=',')
x=X[:,2].reshape([-1,1])
p=X[:,0]
return p, None, x
def load_proteomics(verbose=False):
file_name='/data/martin/NeuralFDR/NeuralFDR_data/proteomics.csv'
X = np.loadtxt(file_name,skiprows=0,delimiter=',')
x=X[:,0]
p=X[:,1]
if verbose:
print('## proteomics.csv ##')
print('# hypothesis: %s'%str(x.shape[0]))
for i in range(5):
print('p=%s, x=%s'%(str(p[i]),str(x[i])))
print('\n')
return p,x
def load_GTEx_1d(verbose=False):
file_name='/data/martin/NeuralFDR/NeuralFDR_data/data_gtex.csv'
X = np.loadtxt(file_name,skiprows=1,delimiter=',')
x=X[:,0]
p=X[:,1]
if verbose:
print('## airway data ##')
print('# hypothesis: %s'%str(x.shape[0]))
for i in range(5):
print('p=%s, x=%s'%(str(p[i]),str(x[i])))
print('\n')
return p,x
"""
Load the GTEx full data.
Data are only kept for those with p-values >0.995 or <0.005.
The full data size is 10623893
"""
def load_GTEx_full(verbose=False):
file_name='/data/martin/NeuralFDR/NeuralFDR_data/gtex_new_filtered.csv'
X = np.loadtxt(file_name,skiprows=1,delimiter=',')
x,p,n_full = X[:,0:4],X[:,4],10623893
#x[:,0],x[:,1] = np.log(x[:,0]+1), np.log(x[:,1]+1)
if verbose:
print('## Load GTEx full data ##')
print('# all hypothesis: %d'%n_full)
print('# filtered hypothesis: %d'%x.shape[0])
for i in range(5):
print('# p=%s, x=%s'%(str(p[i]),str(x[i])))
print('\n')
cate_name = {'Art': 0, 'Ctcf': 1, 'CtcfO': 2, 'DnaseD': 3, 'DnaseU': 4, 'Elon': 5, 'ElonW': 6, 'Enh': 7, 'EnhF': 8, 'EnhW': 9, 'EnhWF': 10, 'FaireW': 11, "Gen3'": 12, "Gen5'": 13, 'H4K20': 14, 'Low': 15, 'Pol2': 16, 'PromF': 17, 'PromP': 18, 'Quies': 19, 'Repr': 20, 'ReprD': 21, 'ReprW': 22, 'Tss': 23, 'TssF': 24}
cate_name = {v: k for k, v in cate_name.items()}
cate_name_dic = {}
cate_name_dic[3] = cate_name
#cate_name = [None,None,None,cate_name]
return p,x,n_full,cate_name_dic
def load_GTEx_small():
n_full = 172353475
fpath = '/data3/martin/gtex_data/GTEx_Analysis_v7_eQTL_all_associations'
fname = 'GTEx_small.pickle'
fname = fpath + '/' + fname
with open(fname, 'rb') as handle:
p = pickle.load(handle)
x = pickle.load(handle)
n_full = pickle.load(handle)
return p, x, n_full, {}
def load_GTEx_Adipose_Subcutaneous():
""" Load data for Adipose_Subcutaneous
"""
n_full = 172353475
fpath = '/data3/martin/gtex_data/GTEx_Analysis_v7_eQTL_all_associations'
fname = 'Adipose_Subcutaneous.allpairs.txt.processed.filtered'
fname = fpath + '/' + fname
data = np.loadtxt(fname, dtype=str, delimiter=', ')
hypothesis_name = data[:, 0]
p = data[:, -1].astype(dtype = float)
x = data[:, 1:5].astype(dtype = float)
ind_nan = np.isnan(x[:, 1])
x[ind_nan, 1] = np.mean(x[~ind_nan, 1])
x = x[p<1, :]
p = p[p<1]
return p, x, n_full, {}
def load_GTEx_Colon_Sigmoid():
""" Load data for Colon_Sigmoid
"""
n_full = 170481049
fpath = '/data3/martin/gtex_data/GTEx_Analysis_v7_eQTL_all_associations'
fname = 'Colon_Sigmoid.allpairs.txt.processed.filtered'
fname = fpath + '/' + fname
data = np.loadtxt(fname, dtype=str, delimiter=', ')
hypothesis_name = data[:, 0]
p = data[:, -1].astype(dtype = float)
x = data[:, 1:5].astype(dtype = float)
ind_nan = np.isnan(x[:, 1])
x[ind_nan, 1] = np.mean(x[~ind_nan, 1])
x = x[p<1, :]
p = p[p<1]
return p, x, n_full, {}
def load_GTEx_Artery_Aorta():
""" Load data for Artery_Aorta
"""
n_full = 166456366
fpath = '/data3/martin/gtex_data/GTEx_Analysis_v7_eQTL_all_associations'
fname = 'Artery_Aorta.allpairs.txt.processed.filtered'
fname = fpath + '/' + fname
data = np.loadtxt(fname, dtype=str, delimiter=', ')
hypothesis_name = data[:, 0]
p = data[:, -1].astype(dtype = float)
x = data[:, 1:5].astype(dtype = float)
ind_nan = np.isnan(x[:, 1])
x[ind_nan, 1] = np.mean(x[~ind_nan, 1])
x = x[p<1, :]
p = p[p<1]
return p, x, n_full, {}
def load_GTEx(data_name='GTEx_small', if_impute=True):
""" Load data for the GTEx data
Data information:
fixit: add the data information here.
"""
print('load %s'%data_name)
n_trunc = 300000
# Hard-coded information of the GTEx dataset.
cate_name = {3: {1: 'TssA', 2: 'TssAFlnk', 3: 'TxFlnk', 4: 'Tx',
5: 'TxWk', 6: 'EnhG', 7: 'Enh', 8: 'ZNF/Rpts',
9: 'Het', 10: 'TssBiv', 11: 'BivFlnk', 12: 'EnhBiv',
13: 'ReprPC', 14: 'ReprPCWk', 15: 'Quies'}}
dic_n_full = {'GTEx_test': 1,\
'test-aug': 1,\
'GTEx_small': 172353475,\
'Adipose_Subcutaneous': 172353475,\
'Adipose_Subcutaneous-aug': 172353475,\
'Adipose_Subcutaneous-a_ur': 172353475,\
'Adipose_Visceral_Omentum': 172595476,\
'Adipose_Visceral_Omentum-aug': 172595476,\
'Adipose_Visceral_Omentum-a_ur': 172595476,\
'Artery_Aorta': 166456366,\
'Breast_Mammary_Tissue': 179856829,\
'Cells_EBV-transformed_lymphocytes': 159717963,\
'Colon_Sigmoid': 170481049,\
'Colon_Sigmoid-aug': 170481049,\
'Colon_Sigmoid-a_ur': 170481049,\
'Colon_Transverse': 176504796,\
'Colon_Transverse-aug': 176504796,\
'Colon_Transverse-a_ur': 176504796,\
'Esophagus_Gastroesophageal_Junction': 167240321,\
'Esophagus_Mucosa': 167425246,\
'Esophagus_Muscularis': 165726398,\
'Heart_Atrial_Appendage': 161328107,\
'Heart_Left_Ventricle': 149705855,\
'Lung': 182309377,\
'Muscle_Skeletal': 147337341,\
'Pancreas': 158693140,\
'Stomach': 168679055,\
'Whole_Blood': 144733342,\
'Adipose_Subcutaneous-chr21': n_trunc,\
'Adipose_Visceral_Omentum-chr21': n_trunc}
data_name_list = dic_n_full.keys()
fpath = '/data3/martin/gtex_data/GTEx_Analysis_v7_eQTL_all_associations'
# Load the information
n_full = dic_n_full[data_name]
if data_name == 'GTEx_small':
fname = 'GTEx_small.pickle'
fname = fpath + '/' + fname
with open(fname, 'rb') as handle:
p = pickle.load(handle)
x = pickle.load(handle)
cis_name = pickle.load(handle)
else:
suffix = ''
if 'chr21' in data_name:
data_name, suffix = data_name.split('-')
fname = data_name + '.allpairs.txt.processed.chr21.txt'
elif 'aug' in data_name:
data_name, suffix = data_name.split('-')
fname = data_name + '.allpairs.txt.processed.filtered.augmented.txt'
elif 'a_ur' in data_name:
data_name, suffix = data_name.split('-')
fname = data_name + '.allpairs.txt.processed.filtered.augmented_not_related.txt'
else:
fname = data_name + '.allpairs.txt.processed.filtered'
fname = fpath + '/' + fname
data = np.loadtxt(fname, dtype=str, delimiter=', ')
hypothesis_name = data[:, 0]
if (suffix == 'aug') or (suffix == 'a_ur'):
x = data[:, [1,2,3,4,7]].astype(dtype = float)
x[:, 4] = -np.log10(x[:, 4])
p = data[:, -2].astype(dtype = float)
cis_name = data[:, 0]
elif suffix == 'chr21':
x = data[:n_trunc, [1,2,3,4]].astype(dtype = float)
p = data[:n_trunc, -1].astype(dtype = float)
cis_name = data[:n_trunc, 0]
else:
x = data[:, [1,2,3,4]].astype(dtype = float)
p = data[:, -1].astype(dtype = float)
cis_name = data[:, 0]
# nan values.
if if_impute:
for i in range(x.shape[1]):
ind_nan = np.isnan(x[:, i])
x[ind_nan, i] = np.mean(x[~ind_nan, i])
else:
# remove the nan values
ind_nan = np.zeros([x.shape[0]], dtype=bool)
for i in range(x.shape[1]):
ind_nan[np.isnan(x[:, i])] = True
x = x[~ind_nan, :]
p = p[~ind_nan]
cis_name = cis_name[~ind_nan]
# Expression level.
x[:, 0] = np.log10(x[:, 0]+0.5)
if suffix == 'chr21':
np.random.seed(0)
x[:, 0] = x[:, 0] + np.random.rand(x.shape[0])*1e-8
x = x[p<1, :]
cis_name = cis_name[p<1]
p = p[p<1]
return p, x, n_full, cate_name, cis_name
"""
load ukbb breast cancer
"""
def load_ukbb_breast_cancer(verbose=False, use_other=False):
file_name='/data/ukbb_process/breast_cancer_filtered.csv'
file_name='/data/martin/breast_cancer_filtered.csv'
X = np.loadtxt(file_name,skiprows=1,delimiter=',')
if not use_other:
x,p,n_full = X[:,0:2],X[:,-2],847800
else:
x,p,n_full = X[:,0:6],X[:,-2],847800
#x[:,0],x[:,1] = np.log(x[:,0]+1), np.log(x[:,1]+1)
if verbose:
print('## Load ukbb breast cancer data ##')
print('# all hypothesis: %d'%n_full)
print('# filtered hypothesis: %d'%x.shape[0])
for i in range(5):
print('# p=%s, x=%s'%(str(p[i]),str(x[i])))
print('')
cate_name = {'Art': 0, 'Ctcf': 1, 'CtcfO': 2, 'DnaseD': 3, 'DnaseU': 4, 'Elon': 5, 'ElonW': 6, 'Enh': 7, 'EnhF': 8, 'EnhW': 9, 'EnhWF': 10, 'FaireW': 11, "Gen3'": 12, "Gen5'": 13, 'H4K20': 14, 'Low': 15, 'Pol2': 16, 'PromF': 17, 'PromP': 18, 'Quies': 19, 'Repr': 20, 'ReprD': 21, 'ReprW': 22, 'Tss': 23, 'TssF': 24}
cate_name = {v: k for k, v in cate_name.items()}
cate_name_dic = {}
cate_name_dic[3] = cate_name
#if not use_other:
# cate_name = [cate_name,None]
#else:
# cate_name = [cate_name,None, None, None, None, None]
return p,x,n_full,cate_name_dic
def load_common_dataset(filename,n,verbose=True):
X = np.loadtxt(filename, skiprows=1, delimiter=',')
x,p,n_full = X[:, 0:-2], X[:, -2], n
#cat_name = [None] * (x.shape[1])
cat_name = {}
if verbose:
print('## Load ukbb %s ##'%filename)
print('# all hypothesis: %d'%n_full)
print('# filtered hypothesis: %d'%x.shape[0])
for i in range(5):
print('# p=%s, x=%s'%(str(p[i]),str(x[i])))
print('')
return p, x, n_full, cat_name | [
"numpy.log10",
"numpy.random.rand",
"matplotlib.pyplot.ylabel",
"numpy.array",
"scipy.stats.ttest_ind",
"scipy.stats.norm.cdf",
"numpy.arange",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.linspace",
"numpy.random.seed",
"numpy.concatenate",
"numpy.meshgrid",
... | [((629, 677), 'numpy.loadtxt', 'np.loadtxt', (['file_name'], {'skiprows': '(0)', 'delimiter': '""","""'}), "(file_name, skiprows=0, delimiter=',')\n", (639, 677), True, 'import numpy as np\n'), ((844, 892), 'numpy.loadtxt', 'np.loadtxt', (['file_name'], {'skiprows': '(0)', 'delimiter': '""","""'}), "(file_name, skiprows=0, delimiter=',')\n", (854, 892), True, 'import numpy as np\n'), ((1057, 1105), 'numpy.loadtxt', 'np.loadtxt', (['file_name'], {'skiprows': '(0)', 'delimiter': '""","""'}), "(file_name, skiprows=0, delimiter=',')\n", (1067, 1105), True, 'import numpy as np\n'), ((1891, 1908), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (1905, 1908), True, 'import numpy as np\n'), ((2340, 2387), 'numpy.loadtxt', 'np.loadtxt', (['file_name'], {'dtype': 'str', 'delimiter': '""","""'}), "(file_name, dtype=str, delimiter=',')\n", (2350, 2387), True, 'import numpy as np\n'), ((3146, 3164), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (3160, 3164), True, 'import numpy as np\n'), ((4619, 4670), 'numpy.zeros', 'np.zeros', (['[x.shape[0], x.shape[1] + 2]'], {'dtype': 'float'}), '([x.shape[0], x.shape[1] + 2], dtype=float)\n', (4627, 4670), True, 'import numpy as np\n'), ((4746, 4792), 'numpy.savetxt', 'np.savetxt', (['filename', 'temp_data'], {'delimiter': '""","""'}), "(filename, temp_data, delimiter=',')\n", (4756, 4792), True, 'import numpy as np\n'), ((5222, 5257), 'numpy.loadtxt', 'np.loadtxt', (['filename'], {'delimiter': '""","""'}), "(filename, delimiter=',')\n", (5232, 5257), True, 'import numpy as np\n'), ((8696, 8724), 'numpy.random.seed', 'np.random.seed', (['random_state'], {}), '(random_state)\n', (8710, 8724), True, 'import numpy as np\n'), ((8877, 8917), 'numpy.array', 'np.array', (['[0.5, 0.25, 0.25]'], {'dtype': 'float'}), '([0.5, 0.25, 0.25], dtype=float)\n', (8885, 8917), True, 'import numpy as np\n'), ((8923, 8951), 'numpy.array', 'np.array', (['[0.5]'], {'dtype': 'float'}), '([0.5], dtype=float)\n', (8931, 8951), True, 'import numpy as np\n'), ((8960, 8999), 'numpy.array', 'np.array', (['[[0.25], [0.75]]'], {'dtype': 'float'}), '([[0.25], [0.75]], dtype=float)\n', (8968, 8999), True, 'import numpy as np\n'), ((9011, 9050), 'numpy.array', 'np.array', (['[[0.05], [0.05]]'], {'dtype': 'float'}), '([[0.05], [0.05]], dtype=float)\n', (9019, 9050), True, 'import numpy as np\n'), ((9131, 9149), 'numpy.zeros', 'np.zeros', (['n_sample'], {}), '(n_sample)\n', (9139, 9149), True, 'import numpy as np\n'), ((9158, 9188), 'numpy.zeros', 'np.zeros', (['n_sample'], {'dtype': 'bool'}), '(n_sample, dtype=bool)\n', (9166, 9188), True, 'import numpy as np\n'), ((9199, 9231), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'n_sample'}), '(size=n_sample)\n', (9216, 9231), True, 'import numpy as np\n'), ((10469, 10497), 'numpy.random.seed', 'np.random.seed', (['random_state'], {}), '(random_state)\n', (10483, 10497), True, 'import numpy as np\n'), ((10649, 10689), 'numpy.array', 'np.array', (['[0.5, 0.25, 0.25]'], {'dtype': 'float'}), '([0.5, 0.25, 0.25], dtype=float)\n', (10657, 10689), True, 'import numpy as np\n'), ((10695, 10728), 'numpy.array', 'np.array', (['[0.5, 0.5]'], {'dtype': 'float'}), '([0.5, 0.5], dtype=float)\n', (10703, 10728), True, 'import numpy as np\n'), ((10736, 10787), 'numpy.array', 'np.array', (['[[0.25, 0.25], [0.75, 0.75]]'], {'dtype': 'float'}), '([[0.25, 0.25], [0.75, 0.75]], dtype=float)\n', (10744, 10787), True, 'import numpy as np\n'), ((10796, 10843), 'numpy.array', 'np.array', (['[[0.1, 0.1], [0.1, 0.1]]'], {'dtype': 'float'}), '([[0.1, 0.1], [0.1, 0.1]], dtype=float)\n', (10804, 10843), True, 'import numpy as np\n'), ((10921, 10939), 'numpy.zeros', 'np.zeros', (['n_sample'], {}), '(n_sample)\n', (10929, 10939), True, 'import numpy as np\n'), ((10948, 10978), 'numpy.zeros', 'np.zeros', (['n_sample'], {'dtype': 'bool'}), '(n_sample, dtype=bool)\n', (10956, 10978), True, 'import numpy as np\n'), ((10989, 11021), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'n_sample'}), '(size=n_sample)\n', (11006, 11021), True, 'import numpy as np\n'), ((11442, 11470), 'numpy.random.seed', 'np.random.seed', (['random_state'], {}), '(random_state)\n', (11456, 11470), True, 'import numpy as np\n'), ((11527, 11558), 'numpy.zeros', 'np.zeros', (['[n_sample]'], {'dtype': 'int'}), '([n_sample], dtype=int)\n', (11535, 11558), True, 'import numpy as np\n'), ((11648, 11676), 'numpy.random.randn', 'np.random.randn', (['(5)', 'n_sample'], {}), '(5, n_sample)\n', (11663, 11676), True, 'import numpy as np\n'), ((11739, 11788), 'numpy.concatenate', 'np.concatenate', (['[data_case, data_control]'], {'axis': '(0)'}), '([data_case, data_control], axis=0)\n', (11753, 11788), True, 'import numpy as np\n'), ((11797, 11822), 'numpy.var', 'np.var', (['data_pool'], {'axis': '(0)'}), '(data_pool, axis=0)\n', (11803, 11822), True, 'import numpy as np\n'), ((12166, 12194), 'numpy.random.seed', 'np.random.seed', (['random_state'], {}), '(random_state)\n', (12180, 12194), True, 'import numpy as np\n'), ((12251, 12282), 'numpy.zeros', 'np.zeros', (['[10, 10]'], {'dtype': 'float'}), '([10, 10], dtype=float)\n', (12259, 12282), True, 'import numpy as np\n'), ((12792, 12832), 'numpy.array', 'np.array', (['[0.5, 0.25, 0.25]'], {'dtype': 'float'}), '([0.5, 0.25, 0.25], dtype=float)\n', (12800, 12832), True, 'import numpy as np\n'), ((12838, 12866), 'numpy.array', 'np.array', (['[0.5]'], {'dtype': 'float'}), '([0.5], dtype=float)\n', (12846, 12866), True, 'import numpy as np\n'), ((12875, 12914), 'numpy.array', 'np.array', (['[[0.25], [0.75]]'], {'dtype': 'float'}), '([[0.25], [0.75]], dtype=float)\n', (12883, 12914), True, 'import numpy as np\n'), ((12926, 12965), 'numpy.array', 'np.array', (['[[0.05], [0.05]]'], {'dtype': 'float'}), '([[0.05], [0.05]], dtype=float)\n', (12934, 12965), True, 'import numpy as np\n'), ((13323, 13355), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'n_sample'}), '(size=n_sample)\n', (13340, 13355), True, 'import numpy as np\n'), ((13367, 13400), 'numpy.zeros', 'np.zeros', (['[n_sample]'], {'dtype': 'float'}), '([n_sample], dtype=float)\n', (13375, 13400), True, 'import numpy as np\n'), ((13496, 13526), 'numpy.zeros', 'np.zeros', (['n_sample'], {'dtype': 'bool'}), '(n_sample, dtype=bool)\n', (13504, 13526), True, 'import numpy as np\n'), ((13731, 13759), 'numpy.random.seed', 'np.random.seed', (['random_state'], {}), '(random_state)\n', (13745, 13759), True, 'import numpy as np\n'), ((13818, 13846), 'numpy.ones', 'np.ones', (['[5, 5]'], {'dtype': 'float'}), '([5, 5], dtype=float)\n', (13825, 13846), True, 'import numpy as np\n'), ((13999, 14039), 'numpy.array', 'np.array', (['[0.5, 0.25, 0.25]'], {'dtype': 'float'}), '([0.5, 0.25, 0.25], dtype=float)\n', (14007, 14039), True, 'import numpy as np\n'), ((14045, 14073), 'numpy.array', 'np.array', (['[0.5]'], {'dtype': 'float'}), '([0.5], dtype=float)\n', (14053, 14073), True, 'import numpy as np\n'), ((14082, 14121), 'numpy.array', 'np.array', (['[[0.25], [0.75]]'], {'dtype': 'float'}), '([[0.25], [0.75]], dtype=float)\n', (14090, 14121), True, 'import numpy as np\n'), ((14133, 14172), 'numpy.array', 'np.array', (['[[0.05], [0.05]]'], {'dtype': 'float'}), '([[0.05], [0.05]], dtype=float)\n', (14141, 14172), True, 'import numpy as np\n'), ((14526, 14558), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'n_sample'}), '(size=n_sample)\n', (14543, 14558), True, 'import numpy as np\n'), ((14570, 14603), 'numpy.zeros', 'np.zeros', (['[n_sample]'], {'dtype': 'float'}), '([n_sample], dtype=float)\n', (14578, 14603), True, 'import numpy as np\n'), ((14699, 14729), 'numpy.zeros', 'np.zeros', (['n_sample'], {'dtype': 'bool'}), '(n_sample, dtype=bool)\n', (14707, 14729), True, 'import numpy as np\n'), ((15491, 15509), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (15505, 15509), True, 'import numpy as np\n'), ((20008, 20026), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (20022, 20026), True, 'import numpy as np\n'), ((20036, 20076), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n_samples'}), '(-1, 1, size=n_samples)\n', (20053, 20076), True, 'import numpy as np\n'), ((20086, 20126), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n_samples'}), '(-1, 1, size=n_samples)\n', (20103, 20126), True, 'import numpy as np\n'), ((20293, 20312), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (20301, 20312), True, 'import numpy as np\n'), ((20321, 20340), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (20329, 20340), True, 'import numpy as np\n'), ((21414, 21454), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n_samples'}), '(-1, 1, size=n_samples)\n', (21431, 21454), True, 'import numpy as np\n'), ((21464, 21504), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n_samples'}), '(-1, 1, size=n_samples)\n', (21481, 21504), True, 'import numpy as np\n'), ((21565, 21584), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (21573, 21584), True, 'import numpy as np\n'), ((21593, 21612), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (21601, 21612), True, 'import numpy as np\n'), ((22574, 22614), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n_samples'}), '(-1, 1, size=n_samples)\n', (22591, 22614), True, 'import numpy as np\n'), ((22624, 22664), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n_samples'}), '(-1, 1, size=n_samples)\n', (22641, 22664), True, 'import numpy as np\n'), ((22897, 22916), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (22905, 22916), True, 'import numpy as np\n'), ((22925, 22944), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (22933, 22944), True, 'import numpy as np\n'), ((24123, 24176), 'numpy.random.uniform', 'np.random.uniform', ([], {'high': '(1)', 'low': '(-1)', 'size': '(n_sample, 3)'}), '(high=1, low=-1, size=(n_sample, 3))\n', (24140, 24176), True, 'import numpy as np\n'), ((24184, 24215), 'numpy.concatenate', 'np.concatenate', (['[x, x_noise]', '(1)'], {}), '([x, x_noise], 1)\n', (24198, 24215), True, 'import numpy as np\n'), ((24742, 24785), 'numpy.random.uniform', 'np.random.uniform', ([], {'high': '(5)', 'size': '(n_sample,)'}), '(high=5, size=(n_sample,))\n', (24759, 24785), True, 'import numpy as np\n'), ((24871, 24917), 'numpy.random.uniform', 'np.random.uniform', ([], {'high': '(5)', 'size': '(n_sample, 99)'}), '(high=5, size=(n_sample, 99))\n', (24888, 24917), True, 'import numpy as np\n'), ((25104, 25152), 'numpy.loadtxt', 'np.loadtxt', (['file_name'], {'skiprows': '(0)', 'delimiter': '""","""'}), "(file_name, skiprows=0, delimiter=',')\n", (25114, 25152), True, 'import numpy as np\n'), ((25327, 25375), 'numpy.loadtxt', 'np.loadtxt', (['file_name'], {'skiprows': '(0)', 'delimiter': '""","""'}), "(file_name, skiprows=0, delimiter=',')\n", (25337, 25375), True, 'import numpy as np\n'), ((25548, 25596), 'numpy.loadtxt', 'np.loadtxt', (['file_name'], {'skiprows': '(0)', 'delimiter': '""","""'}), "(file_name, skiprows=0, delimiter=',')\n", (25558, 25596), True, 'import numpy as np\n'), ((25773, 25821), 'numpy.loadtxt', 'np.loadtxt', (['file_name'], {'skiprows': '(0)', 'delimiter': '""","""'}), "(file_name, skiprows=0, delimiter=',')\n", (25783, 25821), True, 'import numpy as np\n'), ((26180, 26228), 'numpy.loadtxt', 'np.loadtxt', (['file_name'], {'skiprows': '(1)', 'delimiter': '""","""'}), "(file_name, skiprows=1, delimiter=',')\n", (26190, 26228), True, 'import numpy as np\n'), ((26733, 26781), 'numpy.loadtxt', 'np.loadtxt', (['file_name'], {'skiprows': '(1)', 'delimiter': '""","""'}), "(file_name, skiprows=1, delimiter=',')\n", (26743, 26781), True, 'import numpy as np\n'), ((28319, 28363), 'numpy.loadtxt', 'np.loadtxt', (['fname'], {'dtype': 'str', 'delimiter': '""", """'}), "(fname, dtype=str, delimiter=', ')\n", (28329, 28363), True, 'import numpy as np\n'), ((28496, 28513), 'numpy.isnan', 'np.isnan', (['x[:, 1]'], {}), '(x[:, 1])\n', (28504, 28513), True, 'import numpy as np\n'), ((28534, 28557), 'numpy.mean', 'np.mean', (['x[~ind_nan, 1]'], {}), '(x[~ind_nan, 1])\n', (28541, 28557), True, 'import numpy as np\n'), ((28898, 28942), 'numpy.loadtxt', 'np.loadtxt', (['fname'], {'dtype': 'str', 'delimiter': '""", """'}), "(fname, dtype=str, delimiter=', ')\n", (28908, 28942), True, 'import numpy as np\n'), ((29075, 29092), 'numpy.isnan', 'np.isnan', (['x[:, 1]'], {}), '(x[:, 1])\n', (29083, 29092), True, 'import numpy as np\n'), ((29113, 29136), 'numpy.mean', 'np.mean', (['x[~ind_nan, 1]'], {}), '(x[~ind_nan, 1])\n', (29120, 29136), True, 'import numpy as np\n'), ((29478, 29522), 'numpy.loadtxt', 'np.loadtxt', (['fname'], {'dtype': 'str', 'delimiter': '""", """'}), "(fname, dtype=str, delimiter=', ')\n", (29488, 29522), True, 'import numpy as np\n'), ((29655, 29672), 'numpy.isnan', 'np.isnan', (['x[:, 1]'], {}), '(x[:, 1])\n', (29663, 29672), True, 'import numpy as np\n'), ((29693, 29716), 'numpy.mean', 'np.mean', (['x[~ind_nan, 1]'], {}), '(x[~ind_nan, 1])\n', (29700, 29716), True, 'import numpy as np\n'), ((34712, 34760), 'numpy.loadtxt', 'np.loadtxt', (['file_name'], {'skiprows': '(1)', 'delimiter': '""","""'}), "(file_name, skiprows=1, delimiter=',')\n", (34722, 34760), True, 'import numpy as np\n'), ((35891, 35938), 'numpy.loadtxt', 'np.loadtxt', (['filename'], {'skiprows': '(1)', 'delimiter': '""","""'}), "(filename, skiprows=1, delimiter=',')\n", (35901, 35938), True, 'import numpy as np\n'), ((1695, 1714), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (1706, 1714), False, 'import pickle\n'), ((1727, 1746), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (1738, 1746), False, 'import pickle\n'), ((1766, 1785), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (1777, 1785), False, 'import pickle\n'), ((2510, 2533), 'numpy.log10', 'np.log10', (['(x[:, 0] + 0.5)'], {}), '(x[:, 0] + 0.5)\n', (2518, 2533), True, 'import numpy as np\n'), ((2924, 2946), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(100)'], {}), '(0, 1, 100)\n', (2935, 2946), True, 'import numpy as np\n'), ((2990, 3016), 'matplotlib.pyplot.plot', 'plt.plot', (['x_grid', 'pi1_grid'], {}), '(x_grid, pi1_grid)\n', (2998, 3016), True, 'import matplotlib.pyplot as plt\n'), ((3024, 3047), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""covariate"""'], {}), "('covariate')\n", (3034, 3047), True, 'import matplotlib.pyplot as plt\n'), ((3056, 3086), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""alt distribution"""'], {}), "('alt distribution')\n", (3066, 3086), True, 'import matplotlib.pyplot as plt\n'), ((3095, 3136), 'matplotlib.pyplot.title', 'plt.title', (['"""the alternative distribution"""'], {}), "('the alternative distribution')\n", (3104, 3136), True, 'import matplotlib.pyplot as plt\n'), ((3224, 3262), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {'size': 'n_sample'}), '(0, 1, size=n_sample)\n', (3241, 3262), True, 'import numpy as np\n'), ((3300, 3318), 'numpy.zeros', 'np.zeros', (['n_sample'], {}), '(n_sample)\n', (3308, 3318), True, 'import numpy as np\n'), ((3456, 3470), 'numpy.sum', 'np.sum', (['(h == 0)'], {}), '(h == 0)\n', (3462, 3470), True, 'import numpy as np\n'), ((3482, 3496), 'numpy.sum', 'np.sum', (['(h == 1)'], {}), '(h == 1)\n', (3488, 3496), True, 'import numpy as np\n'), ((3557, 3583), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'n0'}), '(size=n0)\n', (3574, 3583), True, 'import numpy as np\n'), ((3602, 3637), 'numpy.random.beta', 'np.random.beta', ([], {'a': '(0.4)', 'b': '(4)', 'size': 'n1'}), '(a=0.4, b=4, size=n1)\n', (3616, 3637), True, 'import numpy as np\n'), ((5826, 5855), 'numpy.array', 'np.array', (['[2, 0]'], {'dtype': 'float'}), '([2, 0], dtype=float)\n', (5834, 5855), True, 'import numpy as np\n'), ((8799, 8825), 'numpy.arange', 'np.arange', (['x_grid.shape[0]'], {}), '(x_grid.shape[0])\n', (8808, 8825), True, 'import numpy as np\n'), ((9455, 9500), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(n_sample, n_dim - 2)'}), '(size=(n_sample, n_dim - 2))\n', (9472, 9500), True, 'import numpy as np\n'), ((9511, 9542), 'numpy.concatenate', 'np.concatenate', (['[x, x_noise]', '(1)'], {}), '([x, x_noise], 1)\n', (9525, 9542), True, 'import numpy as np\n'), ((10572, 10598), 'numpy.arange', 'np.arange', (['x_grid.shape[0]'], {}), '(x_grid.shape[0])\n', (10581, 10598), True, 'import numpy as np\n'), ((11245, 11290), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(n_sample, n_dim - 2)'}), '(size=(n_sample, n_dim - 2))\n', (11262, 11290), True, 'import numpy as np\n'), ((11301, 11332), 'numpy.concatenate', 'np.concatenate', (['[x, x_noise]', '(1)'], {}), '([x, x_noise], 1)\n', (11315, 11332), True, 'import numpy as np\n'), ((11594, 11622), 'numpy.random.randn', 'np.random.randn', (['(5)', 'n_sample'], {}), '(5, n_sample)\n', (11609, 11622), True, 'import numpy as np\n'), ((11685, 11719), 'scipy.stats.ttest_ind', 'ttest_ind', (['data_case', 'data_control'], {}), '(data_case, data_control)\n', (11694, 11719), False, 'from scipy.stats import ttest_ind\n'), ((12714, 12740), 'numpy.arange', 'np.arange', (['x_grid.shape[0]'], {}), '(x_grid.shape[0])\n', (12723, 12740), True, 'import numpy as np\n'), ((13252, 13274), 'scipy.stats.norm.cdf', 'stats.norm.cdf', (['null_z'], {}), '(null_z)\n', (13266, 13274), False, 'from scipy import stats\n'), ((13291, 13312), 'scipy.stats.norm.cdf', 'stats.norm.cdf', (['alt_z'], {}), '(alt_z)\n', (13305, 13312), False, 'from scipy import stats\n'), ((13921, 13947), 'numpy.arange', 'np.arange', (['x_grid.shape[0]'], {}), '(x_grid.shape[0])\n', (13930, 13947), True, 'import numpy as np\n'), ((14455, 14477), 'scipy.stats.norm.cdf', 'stats.norm.cdf', (['null_z'], {}), '(null_z)\n', (14469, 14477), False, 'from scipy import stats\n'), ((14494, 14515), 'scipy.stats.norm.cdf', 'stats.norm.cdf', (['alt_z'], {}), '(alt_z)\n', (14508, 14515), False, 'from scipy import stats\n'), ((14928, 14968), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(0.3)'], {'size': 'num_case'}), '(0, 0.3, size=num_case)\n', (14945, 14968), True, 'import numpy as np\n'), ((14977, 15018), 'numpy.random.randint', 'np.random.randint', (['(0)', 'num_case', 'n_samples'], {}), '(0, num_case, n_samples)\n', (14994, 15018), True, 'import numpy as np\n'), ((15040, 15059), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (15048, 15059), True, 'import numpy as np\n'), ((15072, 15091), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (15080, 15091), True, 'import numpy as np\n'), ((15561, 15601), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n_samples'}), '(-1, 1, size=n_samples)\n', (15578, 15601), True, 'import numpy as np\n'), ((15615, 15655), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n_samples'}), '(-1, 1, size=n_samples)\n', (15632, 15655), True, 'import numpy as np\n'), ((15830, 15849), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (15838, 15849), True, 'import numpy as np\n'), ((15862, 15881), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (15870, 15881), True, 'import numpy as np\n'), ((17059, 17099), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n_samples'}), '(-1, 1, size=n_samples)\n', (17076, 17099), True, 'import numpy as np\n'), ((17113, 17153), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n_samples'}), '(-1, 1, size=n_samples)\n', (17130, 17153), True, 'import numpy as np\n'), ((17226, 17245), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (17234, 17245), True, 'import numpy as np\n'), ((17258, 17277), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (17266, 17277), True, 'import numpy as np\n'), ((18370, 18410), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n_samples'}), '(-1, 1, size=n_samples)\n', (18387, 18410), True, 'import numpy as np\n'), ((18424, 18464), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n_samples'}), '(-1, 1, size=n_samples)\n', (18441, 18464), True, 'import numpy as np\n'), ((18717, 18736), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (18725, 18736), True, 'import numpy as np\n'), ((18749, 18768), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (18757, 18768), True, 'import numpy as np\n'), ((20402, 20421), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (20419, 20421), True, 'import numpy as np\n'), ((20600, 20628), 'numpy.concatenate', 'np.concatenate', (['[[x1], [x2]]'], {}), '([[x1], [x2]])\n', (20614, 20628), True, 'import numpy as np\n'), ((20683, 20695), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (20693, 20695), True, 'import matplotlib.pyplot as plt\n'), ((20748, 20775), 'numpy.arange', 'np.arange', (['(-1)', '(1)', '(1 / 100.0)'], {}), '(-1, 1, 1 / 100.0)\n', (20757, 20775), True, 'import numpy as np\n'), ((20791, 20818), 'numpy.arange', 'np.arange', (['(-1)', '(1)', '(1 / 100.0)'], {}), '(-1, 1, 1 / 100.0)\n', (20800, 20818), True, 'import numpy as np\n'), ((20842, 20869), 'numpy.meshgrid', 'np.meshgrid', (['x_grid', 'y_grid'], {}), '(x_grid, y_grid)\n', (20853, 20869), True, 'import numpy as np\n'), ((21664, 21683), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (21681, 21683), True, 'import numpy as np\n'), ((21862, 21890), 'numpy.concatenate', 'np.concatenate', (['[[x1], [x2]]'], {}), '([[x1], [x2]])\n', (21876, 21890), True, 'import numpy as np\n'), ((21943, 21955), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (21953, 21955), True, 'import matplotlib.pyplot as plt\n'), ((22008, 22035), 'numpy.arange', 'np.arange', (['(-1)', '(1)', '(1 / 100.0)'], {}), '(-1, 1, 1 / 100.0)\n', (22017, 22035), True, 'import numpy as np\n'), ((22051, 22078), 'numpy.arange', 'np.arange', (['(-1)', '(1)', '(1 / 100.0)'], {}), '(-1, 1, 1 / 100.0)\n', (22060, 22078), True, 'import numpy as np\n'), ((22102, 22129), 'numpy.meshgrid', 'np.meshgrid', (['x_grid', 'y_grid'], {}), '(x_grid, y_grid)\n', (22113, 22129), True, 'import numpy as np\n'), ((23002, 23021), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (23019, 23021), True, 'import numpy as np\n'), ((23200, 23228), 'numpy.concatenate', 'np.concatenate', (['[[x1], [x2]]'], {}), '([[x1], [x2]])\n', (23214, 23228), True, 'import numpy as np\n'), ((23281, 23293), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (23291, 23293), True, 'import matplotlib.pyplot as plt\n'), ((23346, 23373), 'numpy.arange', 'np.arange', (['(-1)', '(1)', '(1 / 100.0)'], {}), '(-1, 1, 1 / 100.0)\n', (23355, 23373), True, 'import numpy as np\n'), ((23389, 23416), 'numpy.arange', 'np.arange', (['(-1)', '(1)', '(1 / 100.0)'], {}), '(-1, 1, 1 / 100.0)\n', (23398, 23416), True, 'import numpy as np\n'), ((23440, 23467), 'numpy.meshgrid', 'np.meshgrid', (['x_grid', 'y_grid'], {}), '(x_grid, y_grid)\n', (23451, 23467), True, 'import numpy as np\n'), ((24355, 24374), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (24363, 24374), True, 'import numpy as np\n'), ((24387, 24406), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (24395, 24406), True, 'import numpy as np\n'), ((27902, 27921), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (27913, 27921), False, 'import pickle\n'), ((27934, 27953), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (27945, 27953), False, 'import pickle\n'), ((27971, 27990), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (27982, 27990), False, 'import pickle\n'), ((33011, 33055), 'numpy.loadtxt', 'np.loadtxt', (['fname'], {'dtype': 'str', 'delimiter': '""", """'}), "(fname, dtype=str, delimiter=', ')\n", (33021, 33055), True, 'import numpy as np\n'), ((34214, 34237), 'numpy.log10', 'np.log10', (['(x[:, 0] + 0.5)'], {}), '(x[:, 0] + 0.5)\n', (34222, 34237), True, 'import numpy as np\n'), ((2534, 2560), 'numpy.random.rand', 'np.random.rand', (['x.shape[0]'], {}), '(x.shape[0])\n', (2548, 2560), True, 'import numpy as np\n'), ((3967, 3994), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[16, 5]'}), '(figsize=[16, 5])\n', (3977, 3994), True, 'import matplotlib.pyplot as plt\n'), ((4006, 4022), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (4017, 4022), True, 'import matplotlib.pyplot as plt\n'), ((4068, 4084), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(122)'], {}), '(122)\n', (4079, 4084), True, 'import matplotlib.pyplot as plt\n'), ((4129, 4141), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4139, 4141), True, 'import matplotlib.pyplot as plt\n'), ((4154, 4164), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4162, 4164), True, 'import matplotlib.pyplot as plt\n'), ((6006, 6023), 'numpy.arange', 'np.arange', (['n_grid'], {}), '(n_grid)\n', (6015, 6023), True, 'import numpy as np\n'), ((6125, 6159), 'numpy.array', 'np.array', (['[0.5, 0.05]'], {'dtype': 'float'}), '([0.5, 0.05], dtype=float)\n', (6133, 6159), True, 'import numpy as np\n'), ((6174, 6207), 'numpy.array', 'np.array', (['[0.1, 0.1]'], {'dtype': 'float'}), '([0.1, 0.1], dtype=float)\n', (6182, 6207), True, 'import numpy as np\n'), ((9277, 9295), 'numpy.sum', 'np.sum', (['(rnd >= pi1)'], {}), '(rnd >= pi1)\n', (9283, 9295), True, 'import numpy as np\n'), ((9344, 9361), 'numpy.sum', 'np.sum', (['(rnd < pi1)'], {}), '(rnd < pi1)\n', (9350, 9361), True, 'import numpy as np\n'), ((11067, 11085), 'numpy.sum', 'np.sum', (['(rnd >= pi1)'], {}), '(rnd >= pi1)\n', (11073, 11085), True, 'import numpy as np\n'), ((11134, 11151), 'numpy.sum', 'np.sum', (['(rnd < pi1)'], {}), '(rnd < pi1)\n', (11140, 11151), True, 'import numpy as np\n'), ((13428, 13446), 'numpy.sum', 'np.sum', (['(rnd >= pi1)'], {}), '(rnd >= pi1)\n', (13434, 13446), True, 'import numpy as np\n'), ((13471, 13488), 'numpy.sum', 'np.sum', (['(rnd < pi1)'], {}), '(rnd < pi1)\n', (13477, 13488), True, 'import numpy as np\n'), ((14631, 14649), 'numpy.sum', 'np.sum', (['(rnd >= pi1)'], {}), '(rnd >= pi1)\n', (14637, 14649), True, 'import numpy as np\n'), ((14674, 14691), 'numpy.sum', 'np.sum', (['(rnd < pi1)'], {}), '(rnd < pi1)\n', (14680, 14691), True, 'import numpy as np\n'), ((15154, 15173), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (15171, 15173), True, 'import numpy as np\n'), ((15951, 15970), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (15968, 15970), True, 'import numpy as np\n'), ((16177, 16205), 'numpy.concatenate', 'np.concatenate', (['[[x1], [x2]]'], {}), '([[x1], [x2]])\n', (16191, 16205), True, 'import numpy as np\n'), ((16278, 16290), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (16288, 16290), True, 'import matplotlib.pyplot as plt\n'), ((16351, 16378), 'numpy.arange', 'np.arange', (['(-1)', '(1)', '(1 / 100.0)'], {}), '(-1, 1, 1 / 100.0)\n', (16360, 16378), True, 'import numpy as np\n'), ((16398, 16425), 'numpy.arange', 'np.arange', (['(-1)', '(1)', '(1 / 100.0)'], {}), '(-1, 1, 1 / 100.0)\n', (16407, 16425), True, 'import numpy as np\n'), ((16453, 16480), 'numpy.meshgrid', 'np.meshgrid', (['x_grid', 'y_grid'], {}), '(x_grid, y_grid)\n', (16464, 16480), True, 'import numpy as np\n'), ((17341, 17360), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (17358, 17360), True, 'import numpy as np\n'), ((17567, 17595), 'numpy.concatenate', 'np.concatenate', (['[[x1], [x2]]'], {}), '([[x1], [x2]])\n', (17581, 17595), True, 'import numpy as np\n'), ((17670, 17682), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (17680, 17682), True, 'import matplotlib.pyplot as plt\n'), ((17743, 17770), 'numpy.arange', 'np.arange', (['(-1)', '(1)', '(1 / 100.0)'], {}), '(-1, 1, 1 / 100.0)\n', (17752, 17770), True, 'import numpy as np\n'), ((17790, 17817), 'numpy.arange', 'np.arange', (['(-1)', '(1)', '(1 / 100.0)'], {}), '(-1, 1, 1 / 100.0)\n', (17799, 17817), True, 'import numpy as np\n'), ((17845, 17872), 'numpy.meshgrid', 'np.meshgrid', (['x_grid', 'y_grid'], {}), '(x_grid, y_grid)\n', (17856, 17872), True, 'import numpy as np\n'), ((18838, 18857), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (18855, 18857), True, 'import numpy as np\n'), ((19064, 19092), 'numpy.concatenate', 'np.concatenate', (['[[x1], [x2]]'], {}), '([[x1], [x2]])\n', (19078, 19092), True, 'import numpy as np\n'), ((19167, 19179), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (19177, 19179), True, 'import matplotlib.pyplot as plt\n'), ((19240, 19267), 'numpy.arange', 'np.arange', (['(-1)', '(1)', '(1 / 100.0)'], {}), '(-1, 1, 1 / 100.0)\n', (19249, 19267), True, 'import numpy as np\n'), ((19287, 19314), 'numpy.arange', 'np.arange', (['(-1)', '(1)', '(1 / 100.0)'], {}), '(-1, 1, 1 / 100.0)\n', (19296, 19314), True, 'import numpy as np\n'), ((19342, 19369), 'numpy.meshgrid', 'np.meshgrid', (['x_grid', 'y_grid'], {}), '(x_grid, y_grid)\n', (19353, 19369), True, 'import numpy as np\n'), ((20466, 20485), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (20483, 20485), True, 'import numpy as np\n'), ((20540, 20566), 'numpy.random.beta', 'np.random.beta', ([], {'a': '(0.3)', 'b': '(4)'}), '(a=0.3, b=4)\n', (20554, 20566), True, 'import numpy as np\n'), ((21728, 21747), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (21745, 21747), True, 'import numpy as np\n'), ((21802, 21828), 'numpy.random.beta', 'np.random.beta', ([], {'a': '(0.3)', 'b': '(4)'}), '(a=0.3, b=4)\n', (21816, 21828), True, 'import numpy as np\n'), ((23066, 23085), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (23083, 23085), True, 'import numpy as np\n'), ((23140, 23166), 'numpy.random.beta', 'np.random.beta', ([], {'a': '(0.3)', 'b': '(4)'}), '(a=0.3, b=4)\n', (23154, 23166), True, 'import numpy as np\n'), ((24469, 24488), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (24486, 24488), True, 'import numpy as np\n'), ((24945, 24965), 'numpy.expand_dims', 'np.expand_dims', (['x', '(1)'], {}), '(x, 1)\n', (24959, 24965), True, 'import numpy as np\n'), ((32237, 32256), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (32248, 32256), False, 'import pickle\n'), ((32273, 32292), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (32284, 32292), False, 'import pickle\n'), ((32316, 32335), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (32327, 32335), False, 'import pickle\n'), ((33942, 33976), 'numpy.zeros', 'np.zeros', (['[x.shape[0]]'], {'dtype': 'bool'}), '([x.shape[0]], dtype=bool)\n', (33950, 33976), True, 'import numpy as np\n'), ((34278, 34295), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (34292, 34295), True, 'import numpy as np\n'), ((2749, 2790), 'scipy.stats.norm.pdf', 'sp.stats.norm.pdf', (['x'], {'loc': '(0.2)', 'scale': '(0.05)'}), '(x, loc=0.2, scale=0.05)\n', (2766, 2790), True, 'import scipy as sp\n'), ((2794, 2835), 'scipy.stats.norm.pdf', 'sp.stats.norm.pdf', (['x'], {'loc': '(0.8)', 'scale': '(0.05)'}), '(x, loc=0.8, scale=0.05)\n', (2811, 2835), True, 'import scipy as sp\n'), ((3394, 3426), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'n_sample'}), '(size=n_sample)\n', (3411, 3426), True, 'import numpy as np\n'), ((6364, 6381), 'numpy.arange', 'np.arange', (['n_grid'], {}), '(n_grid)\n', (6373, 6381), True, 'import numpy as np\n'), ((6481, 6519), 'numpy.array', 'np.array', (['[0.4, 0.3, 0.3]'], {'dtype': 'float'}), '([0.4, 0.3, 0.3], dtype=float)\n', (6489, 6519), True, 'import numpy as np\n'), ((6529, 6558), 'numpy.array', 'np.array', (['[2, 0]'], {'dtype': 'float'}), '([2, 0], dtype=float)\n', (6537, 6558), True, 'import numpy as np\n'), ((6570, 6617), 'numpy.array', 'np.array', (['[[0.2, 0.2], [0.7, 0.7]]'], {'dtype': 'float'}), '([[0.2, 0.2], [0.7, 0.7]], dtype=float)\n', (6578, 6617), True, 'import numpy as np\n'), ((6630, 6677), 'numpy.array', 'np.array', (['[[0.1, 0.2], [0.1, 0.1]]'], {'dtype': 'float'}), '([[0.1, 0.2], [0.1, 0.1]], dtype=float)\n', (6638, 6677), True, 'import numpy as np\n'), ((13085, 13099), 'numpy.zeros', 'np.zeros', (['[10]'], {}), '([10])\n', (13093, 13099), True, 'import numpy as np\n'), ((14292, 14305), 'numpy.zeros', 'np.zeros', (['[5]'], {}), '([5])\n', (14300, 14305), True, 'import numpy as np\n'), ((15229, 15248), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (15246, 15248), True, 'import numpy as np\n'), ((16023, 16042), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (16040, 16042), True, 'import numpy as np\n'), ((16109, 16135), 'numpy.random.beta', 'np.random.beta', ([], {'a': '(0.3)', 'b': '(4)'}), '(a=0.3, b=4)\n', (16123, 16135), True, 'import numpy as np\n'), ((17413, 17432), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (17430, 17432), True, 'import numpy as np\n'), ((17499, 17525), 'numpy.random.beta', 'np.random.beta', ([], {'a': '(0.3)', 'b': '(4)'}), '(a=0.3, b=4)\n', (17513, 17525), True, 'import numpy as np\n'), ((18910, 18929), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (18927, 18929), True, 'import numpy as np\n'), ((18996, 19022), 'numpy.random.beta', 'np.random.beta', ([], {'a': '(0.3)', 'b': '(4)'}), '(a=0.3, b=4)\n', (19010, 19022), True, 'import numpy as np\n'), ((24541, 24560), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (24558, 24560), True, 'import numpy as np\n'), ((33235, 33252), 'numpy.log10', 'np.log10', (['x[:, 4]'], {}), '(x[:, 4])\n', (33243, 33252), True, 'import numpy as np\n'), ((33796, 33813), 'numpy.isnan', 'np.isnan', (['x[:, i]'], {}), '(x[:, i])\n', (33804, 33813), True, 'import numpy as np\n'), ((33846, 33869), 'numpy.mean', 'np.mean', (['x[~ind_nan, i]'], {}), '(x[~ind_nan, i])\n', (33853, 33869), True, 'import numpy as np\n'), ((6841, 6858), 'numpy.arange', 'np.arange', (['n_grid'], {}), '(n_grid)\n', (6850, 6858), True, 'import numpy as np\n'), ((6974, 7012), 'numpy.array', 'np.array', (['[0.4, 0.3, 0.3]'], {'dtype': 'float'}), '([0.4, 0.3, 0.3], dtype=float)\n', (6982, 7012), True, 'import numpy as np\n'), ((7022, 7051), 'numpy.array', 'np.array', (['[2, 0]'], {'dtype': 'float'}), '([2, 0], dtype=float)\n', (7030, 7051), True, 'import numpy as np\n'), ((7063, 7110), 'numpy.array', 'np.array', (['[[0.2, 0.2], [0.7, 0.7]]'], {'dtype': 'float'}), '([[0.2, 0.2], [0.7, 0.7]], dtype=float)\n', (7071, 7110), True, 'import numpy as np\n'), ((7123, 7170), 'numpy.array', 'np.array', (['[[0.1, 0.2], [0.1, 0.1]]'], {'dtype': 'float'}), '([[0.1, 0.2], [0.1, 0.1]], dtype=float)\n', (7131, 7170), True, 'import numpy as np\n'), ((7417, 7429), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (7425, 7429), True, 'import numpy as np\n'), ((7538, 7567), 'numpy.ones', 'np.ones', (['[2, 10]'], {'dtype': 'float'}), '([2, 10], dtype=float)\n', (7545, 7567), True, 'import numpy as np\n'), ((7656, 7708), 'numpy.random.uniform', 'np.random.uniform', ([], {'high': '(1)', 'low': '(0)', 'size': '(n_sample, 8)'}), '(high=1, low=0, size=(n_sample, 8))\n', (7673, 7708), True, 'import numpy as np\n'), ((7720, 7751), 'numpy.concatenate', 'np.concatenate', (['[x, x_noise]', '(1)'], {}), '([x, x_noise], 1)\n', (7734, 7751), True, 'import numpy as np\n'), ((13180, 13194), 'numpy.zeros', 'np.zeros', (['[10]'], {}), '([10])\n', (13188, 13194), True, 'import numpy as np\n'), ((14385, 14398), 'numpy.zeros', 'np.zeros', (['[5]'], {}), '([5])\n', (14393, 14398), True, 'import numpy as np\n'), ((20139, 20192), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['x1', 'x2', '(0.25)', '(0.25)', '(-0.5)', '(-0.2)'], {}), '(x1, x2, 0.25, 0.25, -0.5, -0.2)\n', (20160, 20192), False, 'from matplotlib import mlab\n'), ((20209, 20260), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['x1', 'x2', '(0.25)', '(0.25)', '(0.7)', '(0.5)'], {}), '(x1, x2, 0.25, 0.25, 0.7, 0.5)\n', (20230, 20260), False, 'from matplotlib import mlab\n'), ((22677, 22730), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['x1', 'x2', '(0.25)', '(0.25)', '(-0.5)', '(-0.2)'], {}), '(x1, x2, 0.25, 0.25, -0.5, -0.2)\n', (22698, 22730), False, 'from matplotlib import mlab\n'), ((22743, 22794), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['x1', 'x2', '(0.25)', '(0.25)', '(0.7)', '(0.5)'], {}), '(x1, x2, 0.25, 0.25, 0.7, 0.5)\n', (22764, 22794), False, 'from matplotlib import mlab\n'), ((34041, 34058), 'numpy.isnan', 'np.isnan', (['x[:, i]'], {}), '(x[:, i])\n', (34049, 34058), True, 'import numpy as np\n'), ((34328, 34354), 'numpy.random.rand', 'np.random.rand', (['x.shape[0]'], {}), '(x.shape[0])\n', (34342, 34354), True, 'import numpy as np\n'), ((7334, 7351), 'numpy.arange', 'np.arange', (['n_grid'], {}), '(n_grid)\n', (7343, 7351), True, 'import numpy as np\n'), ((7464, 7494), 'numpy.zeros', 'np.zeros', (['[2, 10]'], {'dtype': 'float'}), '([2, 10], dtype=float)\n', (7472, 7494), True, 'import numpy as np\n'), ((15334, 15361), 'numpy.random.uniform', 'np.random.uniform', (['(0.2)', '(0.4)'], {}), '(0.2, 0.4)\n', (15351, 15361), True, 'import numpy as np\n'), ((15672, 15725), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['x1', 'x2', '(0.25)', '(0.25)', '(-0.5)', '(-0.2)'], {}), '(x1, x2, 0.25, 0.25, -0.5, -0.2)\n', (15693, 15725), False, 'from matplotlib import mlab\n'), ((15742, 15793), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['x1', 'x2', '(0.25)', '(0.25)', '(0.7)', '(0.5)'], {}), '(x1, x2, 0.25, 0.25, 0.7, 0.5)\n', (15763, 15793), False, 'from matplotlib import mlab\n'), ((18481, 18534), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['x1', 'x2', '(0.25)', '(0.25)', '(-0.5)', '(-0.2)'], {}), '(x1, x2, 0.25, 0.25, -0.5, -0.2)\n', (18502, 18534), False, 'from matplotlib import mlab\n'), ((18551, 18602), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['x1', 'x2', '(0.25)', '(0.25)', '(0.7)', '(0.5)'], {}), '(x1, x2, 0.25, 0.25, 0.7, 0.5)\n', (18572, 18602), False, 'from matplotlib import mlab\n'), ((20891, 20952), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['X_grid', 'Y_grid', '(0.25)', '(0.25)', '(-0.5)', '(-0.2)'], {}), '(X_grid, Y_grid, 0.25, 0.25, -0.5, -0.2)\n', (20912, 20952), False, 'from matplotlib import mlab\n'), ((20965, 21024), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['X_grid', 'Y_grid', '(0.25)', '(0.25)', '(0.7)', '(0.5)'], {}), '(X_grid, Y_grid, 0.25, 0.25, 0.7, 0.5)\n', (20986, 21024), False, 'from matplotlib import mlab\n'), ((24646, 24673), 'numpy.random.uniform', 'np.random.uniform', (['(0.2)', '(0.4)'], {}), '(0.2, 0.4)\n', (24663, 24673), True, 'import numpy as np\n'), ((3892, 3906), 'numpy.sum', 'np.sum', (['(h == 0)'], {}), '(h == 0)\n', (3898, 3906), True, 'import numpy as np\n'), ((3910, 3924), 'numpy.sum', 'np.sum', (['(h == 1)'], {}), '(h == 1)\n', (3916, 3924), True, 'import numpy as np\n'), ((16506, 16567), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['X_grid', 'Y_grid', '(0.25)', '(0.25)', '(-0.5)', '(-0.2)'], {}), '(X_grid, Y_grid, 0.25, 0.25, -0.5, -0.2)\n', (16527, 16567), False, 'from matplotlib import mlab\n'), ((16584, 16643), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['X_grid', 'Y_grid', '(0.25)', '(0.25)', '(0.7)', '(0.5)'], {}), '(X_grid, Y_grid, 0.25, 0.25, 0.7, 0.5)\n', (16605, 16643), False, 'from matplotlib import mlab\n'), ((3928, 3942), 'numpy.sum', 'np.sum', (['(h == 0)'], {}), '(h == 0)\n', (3934, 3942), True, 'import numpy as np\n'), ((23489, 23550), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['X_grid', 'Y_grid', '(0.25)', '(0.25)', '(-0.5)', '(-0.2)'], {}), '(X_grid, Y_grid, 0.25, 0.25, -0.5, -0.2)\n', (23510, 23550), False, 'from matplotlib import mlab\n'), ((23563, 23622), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['X_grid', 'Y_grid', '(0.25)', '(0.25)', '(0.7)', '(0.5)'], {}), '(X_grid, Y_grid, 0.25, 0.25, 0.7, 0.5)\n', (23584, 23622), False, 'from matplotlib import mlab\n'), ((19395, 19456), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['X_grid', 'Y_grid', '(0.25)', '(0.25)', '(-0.5)', '(-0.2)'], {}), '(X_grid, Y_grid, 0.25, 0.25, -0.5, -0.2)\n', (19416, 19456), False, 'from matplotlib import mlab\n'), ((19473, 19532), 'matplotlib.mlab.bivariate_normal', 'mlab.bivariate_normal', (['X_grid', 'Y_grid', '(0.25)', '(0.25)', '(0.7)', '(0.5)'], {}), '(X_grid, Y_grid, 0.25, 0.25, 0.7, 0.5)\n', (19494, 19532), False, 'from matplotlib import mlab\n')] |
import numpy as np
#pythran export _Aij(float[:,:], int, int)
#pythran export _Aij(int[:,:], int, int)
def _Aij(A, i, j):
"""Sum of upper-left and lower right blocks of contingency table."""
# See `somersd` References [2] bottom of page 309
return A[:i, :j].sum() + A[i+1:, j+1:].sum()
#pythran export _Dij(float[:,:], int, int)
#pythran export _Dij(int[:,:], int, int)
def _Dij(A, i, j):
"""Sum of lower-left and upper-right blocks of contingency table."""
# See `somersd` References [2] bottom of page 309
return A[i+1:, :j].sum() + A[:i, j+1:].sum()
# pythran export _concordant_pairs(float[:,:])
# pythran export _concordant_pairs(int[:,:])
def _concordant_pairs(A):
"""Twice the number of concordant pairs, excluding ties."""
# See `somersd` References [2] bottom of page 309
m, n = A.shape
count = 0
for i in range(m):
for j in range(n):
count += A[i, j]*_Aij(A, i, j)
return count
# pythran export _discordant_pairs(float[:,:])
# pythran export _discordant_pairs(int[:,:])
def _discordant_pairs(A):
"""Twice the number of discordant pairs, excluding ties."""
# See `somersd` References [2] bottom of page 309
m, n = A.shape
count = 0
for i in range(m):
for j in range(n):
count += A[i, j]*_Dij(A, i, j)
return count
#pythran export _a_ij_Aij_Dij2(float[:,:])
#pythran export _a_ij_Aij_Dij2(int[:,:])
def _a_ij_Aij_Dij2(A):
"""A term that appears in the ASE of Kendall's tau and Somers' D."""
# See `somersd` References [2] section 4: Modified ASEs to test the null hypothesis...
m, n = A.shape
count = 0
for i in range(m):
for j in range(n):
count += A[i, j]*(_Aij(A, i, j) - _Dij(A, i, j))**2
return count
#pythran export _compute_outer_prob_inside_method(int64, int64, int64, int64)
def _compute_outer_prob_inside_method(m, n, g, h):
"""
Count the proportion of paths that do not stay strictly inside two
diagonal lines.
Parameters
----------
m : integer
m > 0
n : integer
n > 0
g : integer
g is greatest common divisor of m and n
h : integer
0 <= h <= lcm(m,n)
Returns
-------
p : float
The proportion of paths that do not stay inside the two lines.
The classical algorithm counts the integer lattice paths from (0, 0)
to (m, n) which satisfy |x/m - y/n| < h / lcm(m, n).
The paths make steps of size +1 in either positive x or positive y
directions.
We are, however, interested in 1 - proportion to computes p-values,
so we change the recursion to compute 1 - p directly while staying
within the "inside method" a described by Hodges.
We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk.
<NAME>.,
"The Significance Probability of the Smirnov Two-Sample Test,"
Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.
For the recursion for 1-p see
<NAME>.: "Numerically more stable computation of the p-values
for the two-sample Kolmogorov-Smirnov test," arXiv: 2102.08037
"""
# Probability is symmetrical in m, n. Computation below uses m >= n.
if m < n:
m, n = n, m
mg = m // g
ng = n // g
# Count the integer lattice paths from (0, 0) to (m, n) which satisfy
# |nx/g - my/g| < h.
# Compute matrix A such that:
# A(x, 0) = A(0, y) = 1
# A(x, y) = A(x, y-1) + A(x-1, y), for x,y>=1, except that
# A(x, y) = 0 if |x/m - y/n|>= h
# Probability is A(m, n)/binom(m+n, n)
# Optimizations exist for m==n, m==n*p.
# Only need to preserve a single column of A, and only a
# sliding window of it.
# minj keeps track of the slide.
minj, maxj = 0, min(int(np.ceil(h / mg)), n + 1)
curlen = maxj - minj
# Make a vector long enough to hold maximum window needed.
lenA = min(2 * maxj + 2, n + 1)
# This is an integer calculation, but the entries are essentially
# binomial coefficients, hence grow quickly.
# Scaling after each column is computed avoids dividing by a
# large binomial coefficient at the end, but is not sufficient to avoid
# the large dyanamic range which appears during the calculation.
# Instead we rescale based on the magnitude of the right most term in
# the column and keep track of an exponent separately and apply
# it at the end of the calculation. Similarly when multiplying by
# the binomial coefficient
dtype = np.float64
A = np.ones(lenA, dtype=dtype)
# Initialize the first column
A[minj:maxj] = 0.0
for i in range(1, m + 1):
# Generate the next column.
# First calculate the sliding window
lastminj, lastlen = minj, curlen
minj = max(int(np.floor((ng * i - h) / mg)) + 1, 0)
minj = min(minj, n)
maxj = min(int(np.ceil((ng * i + h) / mg)), n + 1)
if maxj <= minj:
return 1.0
# Now fill in the values. We cannot use cumsum, unfortunately.
val = 0.0 if minj == 0 else 1.0
for jj in range(maxj - minj):
j = jj + minj
val = (A[jj + minj - lastminj] * i + val * j) / (i + j)
A[jj] = val
curlen = maxj - minj
if lastlen > curlen:
# Set some carried-over elements to 1
A[maxj - minj:maxj - minj + (lastlen - curlen)] = 1
return A[maxj - minj - 1]
| [
"numpy.ceil",
"numpy.floor",
"numpy.ones"
] | [((4510, 4536), 'numpy.ones', 'np.ones', (['lenA'], {'dtype': 'dtype'}), '(lenA, dtype=dtype)\n', (4517, 4536), True, 'import numpy as np\n'), ((3757, 3772), 'numpy.ceil', 'np.ceil', (['(h / mg)'], {}), '(h / mg)\n', (3764, 3772), True, 'import numpy as np\n'), ((4857, 4883), 'numpy.ceil', 'np.ceil', (['((ng * i + h) / mg)'], {}), '((ng * i + h) / mg)\n', (4864, 4883), True, 'import numpy as np\n'), ((4769, 4796), 'numpy.floor', 'np.floor', (['((ng * i - h) / mg)'], {}), '((ng * i - h) / mg)\n', (4777, 4796), True, 'import numpy as np\n')] |
import random
import torch
import os
import numpy as np
def seed_everything(seed=1234):
"""
Sets a random seed for OS, NumPy, PyTorch and CUDA.
:dwi_params seed: random seed to apply
:return: None
"""
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
torch.backends.cudnn.deterministic = True
| [
"torch.cuda.manual_seed_all",
"torch.manual_seed",
"numpy.random.seed",
"random.seed"
] | [((227, 244), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (238, 244), False, 'import random\n'), ((249, 272), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (266, 272), False, 'import torch\n'), ((277, 309), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (303, 309), False, 'import torch\n'), ((314, 334), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (328, 334), True, 'import numpy as np\n')] |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
QDrift Class
"""
from typing import cast
import numpy as np
from qiskit.aqua import aqua_globals
from .trotterization_base import TrotterizationBase
from ...operator_base import OperatorBase
from ...list_ops.summed_op import SummedOp
from ...list_ops.composed_op import ComposedOp
from ...primitive_ops.pauli_sum_op import PauliSumOp
# pylint: disable=invalid-name
class QDrift(TrotterizationBase):
""" The QDrift Trotterization method, which selects each each term in the
Trotterization randomly, with a probability proportional to its weight. Based on the work
of <NAME> in https://arxiv.org/abs/1811.08017.
"""
def __init__(self, reps: int = 1) -> None:
r"""
Args:
reps: The number of times to repeat the Trotterization circuit.
"""
super().__init__(reps=reps)
def convert(self, operator: OperatorBase) -> OperatorBase:
# TODO: implement direct way
if isinstance(operator, PauliSumOp):
operator = operator.to_pauli_op()
if not isinstance(operator, SummedOp):
raise TypeError('Trotterization converters can only convert SummedOps.')
summed_op = cast(SummedOp, operator)
# We artificially make the weights positive, TODO check approximation performance
weights = np.abs([op.coeff for op in summed_op.oplist]) # type: ignore
lambd = sum(weights)
N = 2 * (lambd ** 2) * (summed_op.coeff ** 2)
factor = lambd * summed_op.coeff / (N * self.reps)
# The protocol calls for the removal of the individual coefficients,
# and multiplication by a constant factor.
scaled_ops = \
[(op * (factor / op.coeff)).exp_i() for op in summed_op.oplist] # type: ignore
sampled_ops = aqua_globals.random.choice(scaled_ops,
size=(int(N * self.reps),), # type: ignore
p=weights / lambd)
return ComposedOp(sampled_ops).reduce()
| [
"numpy.abs",
"typing.cast"
] | [((1663, 1687), 'typing.cast', 'cast', (['SummedOp', 'operator'], {}), '(SummedOp, operator)\n', (1667, 1687), False, 'from typing import cast\n'), ((1796, 1841), 'numpy.abs', 'np.abs', (['[op.coeff for op in summed_op.oplist]'], {}), '([op.coeff for op in summed_op.oplist])\n', (1802, 1841), True, 'import numpy as np\n')] |
import utils
import torch
import numpy as np
from torch import nn
import torchgeometry
from kornia import color
import torch.nn.functional as F
from time import time
from torchvision.transforms import RandomResizedCrop
class Dense(nn.Module):
def __init__(self, in_features, out_features, activation='relu'):
super(Dense, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.activation = activation
self.linear = nn.Linear(in_features, out_features)
self.IN = nn.InstanceNorm1d(self.out_features)
nn.init.kaiming_normal_(self.linear.weight)
def forward(self, inputs):
outputs = self.linear(inputs)
outputs = outputs.unsqueeze(1)
outputs = self.IN(outputs)
outputs = outputs.squeeze(1)
if self.activation is not None:
if self.activation == 'relu':
outputs = nn.ReLU(inplace=True)(outputs)
elif self.activation == 'tanh':
outputs = nn.Tanh()(outputs)
elif self.activation == 'sigmoid':
outputs = nn.Sigmoid()(outputs)
else:
raise NotImplementedError
return outputs
class Conv2D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, activation='relu', strides=1, pad=None):
super(Conv2D, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.activation = activation
self.strides = strides
if pad is None:
self.pad = int((kernel_size - 1) / 2)
else:
self.pad = pad
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, strides, self.pad)
self.IN = nn.InstanceNorm2d(self.out_channels)
# default: using he_normal as the kernel initializer
nn.init.kaiming_normal_(self.conv.weight)
def forward(self, inputs):
outputs = self.conv(inputs)
outputs = self.IN(outputs)
if self.activation is not None:
if self.activation == 'relu':
outputs = nn.ReLU(inplace=True)(outputs)
elif self.activation == 'tanh':
outputs = nn.Tanh()(outputs)
elif self.activation == 'sigmoid':
outputs = nn.Sigmoid()(outputs)
else:
raise NotImplementedError
return outputs
class Flatten(nn.Module):
def __init__(self):
super(Flatten, self).__init__()
def forward(self, input):
return input.view(input.size(0), -1)
class StegaStampEncoder(nn.Module):
def __init__(self):
super(StegaStampEncoder, self).__init__()
self.secret_dense = Dense(100, 7500, activation='relu')
self.conv1 = Conv2D(6, 32, 3, activation='relu')
self.conv2 = Conv2D(32, 32, 3, activation='relu', strides=2)
self.conv3 = Conv2D(32, 64, 3, activation='relu', strides=2)
self.conv4 = Conv2D(64, 128, 3, activation='relu', strides=2)
self.conv5 = Conv2D(128, 256, 3, activation='relu', strides=2)
self.up6 = Conv2D(256, 128, 3, activation='relu')
self.conv6 = Conv2D(256, 128, 3, activation='relu')
self.up7 = Conv2D(128, 64, 3, activation='relu')
self.conv7 = Conv2D(128, 64, 3, activation='relu')
self.up8 = Conv2D(64, 32, 3, activation='relu')
self.conv8 = Conv2D(64, 32, 3, activation='relu')
self.up9 = Conv2D(32, 32, 3, activation='relu')
self.conv9 = Conv2D(70, 32, 3, activation='relu')
self.residual = Conv2D(32, 3, 1, activation=None)
def forward(self, inputs):
secret, image = inputs
secret = secret - .5
image = image - .5
secret = self.secret_dense(secret)
secret = secret.reshape(-1, 3, 50, 50)
secret_enlarged = nn.Upsample(scale_factor=(8, 8))(secret)
inputs = torch.cat([secret_enlarged, image], dim=1)
conv1 = self.conv1(inputs)
conv2 = self.conv2(conv1)
conv3 = self.conv3(conv2)
conv4 = self.conv4(conv3)
conv5 = self.conv5(conv4)
up6 = self.up6(nn.Upsample(scale_factor=(2, 2))(conv5))
merge6 = torch.cat([conv4, up6], dim=1)
conv6 = self.conv6(merge6)
up7 = self.up7(nn.Upsample(scale_factor=(2, 2))(conv6))
merge7 = torch.cat([conv3, up7], dim=1)
conv7 = self.conv7(merge7)
up8 = self.up8(nn.Upsample(scale_factor=(2, 2))(conv7))
merge8 = torch.cat([conv2, up8], dim=1)
conv8 = self.conv8(merge8)
up9 = self.up9(nn.Upsample(scale_factor=(2, 2))(conv8))
merge9 = torch.cat([conv1, up9, inputs], dim=1)
conv9 = self.conv9(merge9)
residual = self.residual(conv9)
return residual
class SpatialTransformerNetwork(nn.Module):
def __init__(self):
super(SpatialTransformerNetwork, self).__init__()
self.localization = nn.Sequential(
Conv2D(3, 32, 3, strides=2, activation='relu'),
Conv2D(32, 64, 3, strides=2, activation='relu'),
Conv2D(64, 128, 3, strides=2, activation='relu'),
Flatten(),
Dense(320000, 128, activation='relu'),
nn.Linear(128, 6)
)
self.localization[-1].weight.data.fill_(0)
self.localization[-1].bias.data = torch.FloatTensor([1, 0, 0, 0, 1, 0])
def forward(self, image):
theta = self.localization(image)
theta = theta.view(-1, 2, 3)
grid = F.affine_grid(theta, image.size(), align_corners=False)
transformed_image = F.grid_sample(image, grid, align_corners=False)
return transformed_image
class StegaStampDecoder(nn.Module):
def __init__(self, secret_size=100):
super(StegaStampDecoder, self).__init__()
self.secret_size = secret_size
self.stn = SpatialTransformerNetwork()
self.decoder = nn.Sequential(
Conv2D(3, 32, 3, strides=2, activation='relu'),
Conv2D(32, 32, 3, activation='relu'),
Conv2D(32, 64, 3, strides=2, activation='relu'),
Conv2D(64, 64, 3, activation='relu'),
Conv2D(64, 64, 3, strides=2, activation='relu'),
Conv2D(64, 128, 3, strides=2, activation='relu'),
Conv2D(128, 128, 3, strides=2, activation='relu'),
Flatten(),
Dense(21632, 512, activation='relu'),
Dense(512, secret_size, activation='sigmoid'))
def forward(self, image):
image = image - .5
transformed_image = self.stn(image)
return self.decoder(transformed_image)
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.model = nn.Sequential(
Conv2D(3, 8, 3, strides=2, activation='relu'),
Conv2D(8, 16, 3, strides=2, activation='relu'),
Conv2D(16, 32, 3, strides=2, activation='relu'),
Conv2D(32, 64, 3, strides=2, activation='relu'),
Conv2D(64, 1, 3, activation=None))
def forward(self, image):
x = image - .5
x = self.model(x)
output = torch.mean(x)
return output, x
def transform_net(encoded_image, args, global_step):
sh = encoded_image.size()
ramp_fn = lambda ramp: np.min([global_step / ramp, 1.])
rnd_bri = ramp_fn(args.rnd_bri_ramp) * args.rnd_bri
rnd_hue = ramp_fn(args.rnd_hue_ramp) * args.rnd_hue
rnd_brightness = utils.get_rnd_brightness_torch(rnd_bri, rnd_hue, args.batch_size) # [batch_size, 3, 1, 1]
jpeg_quality = 100. - torch.rand(1)[0] * ramp_fn(args.jpeg_quality_ramp) * (100. - args.jpeg_quality)
rnd_noise = torch.rand(1)[0] * ramp_fn(args.rnd_noise_ramp) * args.rnd_noise
contrast_low = 1. - (1. - args.contrast_low) * ramp_fn(args.contrast_ramp)
contrast_high = 1. + (args.contrast_high - 1.) * ramp_fn(args.contrast_ramp)
contrast_params = [contrast_low, contrast_high]
rnd_sat = torch.rand(1)[0] * ramp_fn(args.rnd_sat_ramp) * args.rnd_sat
# blur
N_blur = 7
f = utils.random_blur_kernel(probs=[.25, .25], N_blur=N_blur, sigrange_gauss=[1., 3.], sigrange_line=[.25, 1.],
wmin_line=3)
if args.cuda:
f = f.cuda()
encoded_image = F.conv2d(encoded_image, f, bias=None, padding=int((N_blur - 1) / 2))
# noise
noise = torch.normal(mean=0, std=rnd_noise, size=encoded_image.size(), dtype=torch.float32)
if args.cuda:
noise = noise.cuda()
encoded_image = encoded_image + noise
encoded_image = torch.clamp(encoded_image, 0, 1)
# contrast & brightness
contrast_scale = torch.Tensor(encoded_image.size()[0]).uniform_(contrast_params[0], contrast_params[1])
contrast_scale = contrast_scale.reshape(encoded_image.size()[0], 1, 1, 1)
if args.cuda:
contrast_scale = contrast_scale.cuda()
rnd_brightness = rnd_brightness.cuda()
encoded_image = encoded_image * contrast_scale
encoded_image = encoded_image + rnd_brightness
encoded_image = torch.clamp(encoded_image, 0, 1)
# saturation
sat_weight = torch.FloatTensor([.3, .6, .1]).reshape(1, 3, 1, 1)
if args.cuda:
sat_weight = sat_weight.cuda()
encoded_image_lum = torch.mean(encoded_image * sat_weight, dim=1).unsqueeze_(1)
encoded_image = (1 - rnd_sat) * encoded_image + rnd_sat * encoded_image_lum
# jpeg
encoded_image = encoded_image.reshape([-1, 3, 400, 400])
if not args.no_jpeg:
encoded_image = utils.jpeg_compress_decompress(encoded_image, rounding=utils.round_only_at_0,
quality=jpeg_quality)
crop_scale = 1 - 0.4 * ramp_fn(2e4)
cropper = RandomResizedCrop((400, 400), (crop_scale, 1.))
encoded_image = cropper(encoded_image)
return encoded_image
def get_secret_acc(secret_true, secret_pred):
if 'cuda' in str(secret_pred.device):
secret_pred = secret_pred.cpu()
secret_true = secret_true.cpu()
secret_pred = torch.round(secret_pred)
correct_pred = torch.sum((secret_pred - secret_true) == 0, dim=1)
str_acc = 1.0 - torch.sum((correct_pred - secret_pred.size()[1]) != 0).numpy() / correct_pred.size()[0]
bit_acc = torch.sum(correct_pred).numpy() / secret_pred.numel()
return bit_acc, str_acc
class LossCombine(nn.Module):
def __init__(self, initial):
super(LossCombine, self).__init__()
self.weight = nn.Parameter(torch.tensor(initial, dtype=torch.float32), requires_grad=True)
def forward(self, losses):
positive_weight = F.relu(self.weight)
num = self.weight.shape[-1]
loss_combine = torch.log(positive_weight + 1e-6).sum()
for i in range(num):
loss_combine += losses[i] / positive_weight[i]
return loss_combine
def build_model(encoder, decoder, discriminator, loss_combine, lpips_fn, secret_input, image_input, l2_edge_gain,
M, loss_scales, yuv_scales, args, global_step, writer):
input_warped = torchgeometry.warp_perspective(image_input, M[:, 1, :, :], dsize=(400, 400), flags='bilinear')
mask_warped = torchgeometry.warp_perspective(torch.ones_like(input_warped), M[:, 1, :, :], dsize=(400, 400),
flags='bilinear')
input_warped += (1 - mask_warped) * image_input
residual_warped = encoder((secret_input, input_warped))
image_rate = 5 * np.min([global_step / 2e4, 1.])
encoded_warped = residual_warped + (input_warped - 0.5)
encoded_warped = nn.Sigmoid()(encoded_warped)
mask = torchgeometry.warp_perspective(torch.ones_like(encoded_warped), M[:, 0, :, :], dsize=(400, 400),
flags='bilinear')
encoded_image = torchgeometry.warp_perspective(encoded_warped, M[:, 0, :, :], dsize=(400, 400),
flags='bilinear')
encoded_image += (1 - mask) * image_input
borders = args.borders
if borders == 'no_edge':
D_output_real, _ = discriminator(image_input)
D_output_fake, D_heatmap = discriminator(encoded_image)
else:
D_output_real, _ = discriminator(input_warped)
D_output_fake, D_heatmap = discriminator(encoded_warped)
transformed_image = transform_net(encoded_image, args, global_step)
decoded_secret = decoder(transformed_image)
bit_acc, str_acc = get_secret_acc(secret_input, decoded_secret)
normalized_input = image_input * 2 - 1
normalized_encoded = encoded_image * 2 - 1
lpips_loss = torch.mean(lpips_fn(normalized_input, normalized_encoded))
cross_entropy = nn.BCELoss()
if args.cuda:
cross_entropy = cross_entropy.cuda()
secret_loss = cross_entropy(decoded_secret, secret_input)
'''
size = (int(image_input.shape[2]), int(image_input.shape[3]))
gain = 10
falloff_speed = 4
falloff_im = np.ones(size)
for i in range(int(falloff_im.shape[0] / falloff_speed)): # for i in range 100
falloff_im[-i, :] *= (np.cos(4 * np.pi * i / size[0] + np.pi) + 1) / 2 # [cos[(4*pi*i/400)+pi] + 1]/2
falloff_im[i, :] *= (np.cos(4 * np.pi * i / size[0] + np.pi) + 1) / 2 # [cos[(4*pi*i/400)+pi] + 1]/2
for j in range(int(falloff_im.shape[1] / falloff_speed)):
falloff_im[:, -j] *= (np.cos(4 * np.pi * j / size[0] + np.pi) + 1) / 2
falloff_im[:, j] *= (np.cos(4 * np.pi * j / size[0] + np.pi) + 1) / 2
falloff_im = 1 - falloff_im
falloff_im = torch.from_numpy(falloff_im).float()
if args.cuda:
falloff_im = falloff_im.cuda()
falloff_im *= l2_edge_gain
'''
encoded_image_yuv = color.rgb_to_yuv(encoded_image)
image_input_yuv = color.rgb_to_yuv(image_input)
im_diff = encoded_image_yuv - image_input_yuv
# im_diff += im_diff * falloff_im.unsqueeze_(0)
yuv_loss = torch.mean((im_diff) ** 2, axis=[0, 2, 3])
yuv_scales = torch.Tensor(yuv_scales)
if args.cuda:
yuv_scales = yuv_scales.cuda()
image_loss = torch.dot(yuv_loss, yuv_scales)
D_loss = D_output_real - D_output_fake
G_loss = D_output_fake
if args.no_gan:
loss = loss_combine([secret_loss, image_loss, lpips_loss])
else:
loss = loss_combine([secret_loss, image_loss, lpips_loss, G_loss])
writer.add_scalar('loss/image_loss', image_loss, global_step)
writer.add_scalar('loss/lpips_loss', lpips_loss, global_step)
writer.add_scalar('loss/secret_loss', secret_loss, global_step)
writer.add_scalar('loss/G_loss', G_loss, global_step)
writer.add_scalar('loss/secret_weight', loss_combine.weight[0], global_step)
writer.add_scalar('loss/image_weight', loss_combine.weight[1], global_step)
writer.add_scalar('loss/lpips_weight', loss_combine.weight[2], global_step)
writer.add_scalar('residual/max', residual_warped.max(), global_step)
writer.add_scalar('residual/min', residual_warped.min(), global_step)
writer.add_scalar('metric/bit_acc', bit_acc, global_step)
writer.add_scalar('metric/str_acc', str_acc, global_step)
if global_step % 100 == 0:
'''
writer.add_image('input/image_input', image_input[0], global_step)
writer.add_image('input/image_warped', input_warped[0], global_step)
writer.add_image('encoded/encoded_warped', encoded_warped[0], global_step)
writer.add_image('encoded/encoded_image', encoded_image[0], global_step)
writer.add_image('transformed/transformed_image', transformed_image[0], global_step)
'''
return loss, secret_loss, D_loss, bit_acc, str_acc
if __name__ == "__main__":
decoder = StegaStampDecoder()
input = torch.zeros((1, 3, 400, 400))
output = decoder(input)
print(output.shape)
| [
"torch.nn.ReLU",
"torch.nn.Tanh",
"torch.nn.InstanceNorm1d",
"torch.nn.InstanceNorm2d",
"torch.sum",
"utils.random_blur_kernel",
"kornia.color.rgb_to_yuv",
"torch.nn.functional.grid_sample",
"torch.nn.Sigmoid",
"torch.mean",
"torch.nn.init.kaiming_normal_",
"torchgeometry.warp_perspective",
... | [((7505, 7570), 'utils.get_rnd_brightness_torch', 'utils.get_rnd_brightness_torch', (['rnd_bri', 'rnd_hue', 'args.batch_size'], {}), '(rnd_bri, rnd_hue, args.batch_size)\n', (7535, 7570), False, 'import utils\n'), ((8109, 8240), 'utils.random_blur_kernel', 'utils.random_blur_kernel', ([], {'probs': '[0.25, 0.25]', 'N_blur': 'N_blur', 'sigrange_gauss': '[1.0, 3.0]', 'sigrange_line': '[0.25, 1.0]', 'wmin_line': '(3)'}), '(probs=[0.25, 0.25], N_blur=N_blur, sigrange_gauss=\n [1.0, 3.0], sigrange_line=[0.25, 1.0], wmin_line=3)\n', (8133, 8240), False, 'import utils\n'), ((8609, 8641), 'torch.clamp', 'torch.clamp', (['encoded_image', '(0)', '(1)'], {}), '(encoded_image, 0, 1)\n', (8620, 8641), False, 'import torch\n'), ((9091, 9123), 'torch.clamp', 'torch.clamp', (['encoded_image', '(0)', '(1)'], {}), '(encoded_image, 0, 1)\n', (9102, 9123), False, 'import torch\n'), ((9764, 9812), 'torchvision.transforms.RandomResizedCrop', 'RandomResizedCrop', (['(400, 400)', '(crop_scale, 1.0)'], {}), '((400, 400), (crop_scale, 1.0))\n', (9781, 9812), False, 'from torchvision.transforms import RandomResizedCrop\n'), ((10069, 10093), 'torch.round', 'torch.round', (['secret_pred'], {}), '(secret_pred)\n', (10080, 10093), False, 'import torch\n'), ((10113, 10161), 'torch.sum', 'torch.sum', (['(secret_pred - secret_true == 0)'], {'dim': '(1)'}), '(secret_pred - secret_true == 0, dim=1)\n', (10122, 10161), False, 'import torch\n'), ((11077, 11175), 'torchgeometry.warp_perspective', 'torchgeometry.warp_perspective', (['image_input', 'M[:, 1, :, :]'], {'dsize': '(400, 400)', 'flags': '"""bilinear"""'}), "(image_input, M[:, 1, :, :], dsize=(400, 400),\n flags='bilinear')\n", (11107, 11175), False, 'import torchgeometry\n'), ((11818, 11920), 'torchgeometry.warp_perspective', 'torchgeometry.warp_perspective', (['encoded_warped', 'M[:, 0, :, :]'], {'dsize': '(400, 400)', 'flags': '"""bilinear"""'}), "(encoded_warped, M[:, 0, :, :], dsize=(400, \n 400), flags='bilinear')\n", (11848, 11920), False, 'import torchgeometry\n'), ((12697, 12709), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (12707, 12709), False, 'from torch import nn\n'), ((13708, 13739), 'kornia.color.rgb_to_yuv', 'color.rgb_to_yuv', (['encoded_image'], {}), '(encoded_image)\n', (13724, 13739), False, 'from kornia import color\n'), ((13762, 13791), 'kornia.color.rgb_to_yuv', 'color.rgb_to_yuv', (['image_input'], {}), '(image_input)\n', (13778, 13791), False, 'from kornia import color\n'), ((13909, 13949), 'torch.mean', 'torch.mean', (['(im_diff ** 2)'], {'axis': '[0, 2, 3]'}), '(im_diff ** 2, axis=[0, 2, 3])\n', (13919, 13949), False, 'import torch\n'), ((13969, 13993), 'torch.Tensor', 'torch.Tensor', (['yuv_scales'], {}), '(yuv_scales)\n', (13981, 13993), False, 'import torch\n'), ((14068, 14099), 'torch.dot', 'torch.dot', (['yuv_loss', 'yuv_scales'], {}), '(yuv_loss, yuv_scales)\n', (14077, 14099), False, 'import torch\n'), ((15713, 15742), 'torch.zeros', 'torch.zeros', (['(1, 3, 400, 400)'], {}), '((1, 3, 400, 400))\n', (15724, 15742), False, 'import torch\n'), ((493, 529), 'torch.nn.Linear', 'nn.Linear', (['in_features', 'out_features'], {}), '(in_features, out_features)\n', (502, 529), False, 'from torch import nn\n'), ((548, 584), 'torch.nn.InstanceNorm1d', 'nn.InstanceNorm1d', (['self.out_features'], {}), '(self.out_features)\n', (565, 584), False, 'from torch import nn\n'), ((593, 636), 'torch.nn.init.kaiming_normal_', 'nn.init.kaiming_normal_', (['self.linear.weight'], {}), '(self.linear.weight)\n', (616, 636), False, 'from torch import nn\n'), ((1719, 1787), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'out_channels', 'kernel_size', 'strides', 'self.pad'], {}), '(in_channels, out_channels, kernel_size, strides, self.pad)\n', (1728, 1787), False, 'from torch import nn\n'), ((1806, 1842), 'torch.nn.InstanceNorm2d', 'nn.InstanceNorm2d', (['self.out_channels'], {}), '(self.out_channels)\n', (1823, 1842), False, 'from torch import nn\n'), ((1912, 1953), 'torch.nn.init.kaiming_normal_', 'nn.init.kaiming_normal_', (['self.conv.weight'], {}), '(self.conv.weight)\n', (1935, 1953), False, 'from torch import nn\n'), ((3959, 4001), 'torch.cat', 'torch.cat', (['[secret_enlarged, image]'], {'dim': '(1)'}), '([secret_enlarged, image], dim=1)\n', (3968, 4001), False, 'import torch\n'), ((4254, 4284), 'torch.cat', 'torch.cat', (['[conv4, up6]'], {'dim': '(1)'}), '([conv4, up6], dim=1)\n', (4263, 4284), False, 'import torch\n'), ((4401, 4431), 'torch.cat', 'torch.cat', (['[conv3, up7]'], {'dim': '(1)'}), '([conv3, up7], dim=1)\n', (4410, 4431), False, 'import torch\n'), ((4548, 4578), 'torch.cat', 'torch.cat', (['[conv2, up8]'], {'dim': '(1)'}), '([conv2, up8], dim=1)\n', (4557, 4578), False, 'import torch\n'), ((4695, 4733), 'torch.cat', 'torch.cat', (['[conv1, up9, inputs]'], {'dim': '(1)'}), '([conv1, up9, inputs], dim=1)\n', (4704, 4733), False, 'import torch\n'), ((5394, 5431), 'torch.FloatTensor', 'torch.FloatTensor', (['[1, 0, 0, 0, 1, 0]'], {}), '([1, 0, 0, 0, 1, 0])\n', (5411, 5431), False, 'import torch\n'), ((5640, 5687), 'torch.nn.functional.grid_sample', 'F.grid_sample', (['image', 'grid'], {'align_corners': '(False)'}), '(image, grid, align_corners=False)\n', (5653, 5687), True, 'import torch.nn.functional as F\n'), ((7187, 7200), 'torch.mean', 'torch.mean', (['x'], {}), '(x)\n', (7197, 7200), False, 'import torch\n'), ((7338, 7371), 'numpy.min', 'np.min', (['[global_step / ramp, 1.0]'], {}), '([global_step / ramp, 1.0])\n', (7344, 7371), True, 'import numpy as np\n'), ((9554, 9658), 'utils.jpeg_compress_decompress', 'utils.jpeg_compress_decompress', (['encoded_image'], {'rounding': 'utils.round_only_at_0', 'quality': 'jpeg_quality'}), '(encoded_image, rounding=utils.\n round_only_at_0, quality=jpeg_quality)\n', (9584, 9658), False, 'import utils\n'), ((10634, 10653), 'torch.nn.functional.relu', 'F.relu', (['self.weight'], {}), '(self.weight)\n', (10640, 10653), True, 'import torch.nn.functional as F\n'), ((11221, 11250), 'torch.ones_like', 'torch.ones_like', (['input_warped'], {}), '(input_warped)\n', (11236, 11250), False, 'import torch\n'), ((11487, 11523), 'numpy.min', 'np.min', (['[global_step / 20000.0, 1.0]'], {}), '([global_step / 20000.0, 1.0])\n', (11493, 11523), True, 'import numpy as np\n'), ((11600, 11612), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (11610, 11612), False, 'from torch import nn\n'), ((11672, 11703), 'torch.ones_like', 'torch.ones_like', (['encoded_warped'], {}), '(encoded_warped)\n', (11687, 11703), False, 'import torch\n'), ((3900, 3932), 'torch.nn.Upsample', 'nn.Upsample', ([], {'scale_factor': '(8, 8)'}), '(scale_factor=(8, 8))\n', (3911, 3932), False, 'from torch import nn\n'), ((5273, 5290), 'torch.nn.Linear', 'nn.Linear', (['(128)', '(6)'], {}), '(128, 6)\n', (5282, 5290), False, 'from torch import nn\n'), ((9159, 9193), 'torch.FloatTensor', 'torch.FloatTensor', (['[0.3, 0.6, 0.1]'], {}), '([0.3, 0.6, 0.1])\n', (9176, 9193), False, 'import torch\n'), ((9292, 9337), 'torch.mean', 'torch.mean', (['(encoded_image * sat_weight)'], {'dim': '(1)'}), '(encoded_image * sat_weight, dim=1)\n', (9302, 9337), False, 'import torch\n'), ((10512, 10554), 'torch.tensor', 'torch.tensor', (['initial'], {'dtype': 'torch.float32'}), '(initial, dtype=torch.float32)\n', (10524, 10554), False, 'import torch\n'), ((4196, 4228), 'torch.nn.Upsample', 'nn.Upsample', ([], {'scale_factor': '(2, 2)'}), '(scale_factor=(2, 2))\n', (4207, 4228), False, 'from torch import nn\n'), ((4343, 4375), 'torch.nn.Upsample', 'nn.Upsample', ([], {'scale_factor': '(2, 2)'}), '(scale_factor=(2, 2))\n', (4354, 4375), False, 'from torch import nn\n'), ((4490, 4522), 'torch.nn.Upsample', 'nn.Upsample', ([], {'scale_factor': '(2, 2)'}), '(scale_factor=(2, 2))\n', (4501, 4522), False, 'from torch import nn\n'), ((4637, 4669), 'torch.nn.Upsample', 'nn.Upsample', ([], {'scale_factor': '(2, 2)'}), '(scale_factor=(2, 2))\n', (4648, 4669), False, 'from torch import nn\n'), ((7720, 7733), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (7730, 7733), False, 'import torch\n'), ((8013, 8026), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (8023, 8026), False, 'import torch\n'), ((10286, 10309), 'torch.sum', 'torch.sum', (['correct_pred'], {}), '(correct_pred)\n', (10295, 10309), False, 'import torch\n'), ((10714, 10748), 'torch.log', 'torch.log', (['(positive_weight + 1e-06)'], {}), '(positive_weight + 1e-06)\n', (10723, 10748), False, 'import torch\n'), ((926, 947), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (933, 947), False, 'from torch import nn\n'), ((2165, 2186), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (2172, 2186), False, 'from torch import nn\n'), ((7623, 7636), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (7633, 7636), False, 'import torch\n'), ((1027, 1036), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (1034, 1036), False, 'from torch import nn\n'), ((2266, 2275), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (2273, 2275), False, 'from torch import nn\n'), ((1119, 1131), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (1129, 1131), False, 'from torch import nn\n'), ((2358, 2370), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (2368, 2370), False, 'from torch import nn\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 25 21:23:38 2011
Author: <NAME> and Scipy developers
License : BSD-3
"""
import numpy as np
from scipy import stats
from statsmodels.tools.validation import array_like, bool_like, int_like
def anderson_statistic(x, dist='norm', fit=True, params=(), axis=0):
"""
Calculate the Anderson-Darling a2 statistic.
Parameters
----------
x : array_like
The data to test.
dist : {'norm', callable}
The assumed distribution under the null of test statistic.
fit : bool
If True, then the distribution parameters are estimated.
Currently only for 1d data x, except in case dist='norm'.
params : tuple
The optional distribution parameters if fit is False.
axis : int
If dist is 'norm' or fit is False, then data can be an n-dimensional
and axis specifies the axis of a variable.
Returns
-------
{float, ndarray}
The Anderson-Darling statistic.
"""
x = array_like(x, 'x', ndim=None)
fit = bool_like(fit, 'fit')
axis = int_like(axis, 'axis')
y = np.sort(x, axis=axis)
nobs = y.shape[axis]
if fit:
if dist == 'norm':
xbar = np.expand_dims(np.mean(x, axis=axis), axis)
s = np.expand_dims(np.std(x, ddof=1, axis=axis), axis)
w = (y - xbar) / s
z = stats.norm.cdf(w)
# print z
elif callable(dist):
params = dist.fit(x)
# print params
z = dist.cdf(y, *params)
print(z)
else:
raise ValueError("dist must be 'norm' or a Callable")
else:
if callable(dist):
z = dist.cdf(y, *params)
else:
raise ValueError('if fit is false, then dist must be callable')
i = np.arange(1, nobs + 1)
sl1 = [None] * x.ndim
sl1[axis] = slice(None)
sl1 = tuple(sl1)
sl2 = [slice(None)] * x.ndim
sl2[axis] = slice(None, None, -1)
sl2 = tuple(sl2)
s = np.sum((2 * i[sl1] - 1.0) / nobs * (np.log(z) + np.log1p(-z[sl2])),
axis=axis)
a2 = -nobs - s
return a2
def normal_ad(x, axis=0):
"""
Anderson-Darling test for normal distribution unknown mean and variance.
Parameters
----------
x : array_like
The data array.
axis : int
The axis to perform the test along.
Returns
-------
ad2 : float
Anderson Darling test statistic.
pval : float
The pvalue for hypothesis that the data comes from a normal
distribution with unknown mean and variance.
See Also
--------
statsmodels.stats.diagnostic.anderson_statistic
The Anderson-Darling a2 statistic.
statsmodels.stats.diagnostic.kstest_fit
Kolmogorov-Smirnov test with estimated parameters for Normal or
Exponential distributions.
"""
ad2 = anderson_statistic(x, dist='norm', fit=True, axis=axis)
n = x.shape[axis]
ad2a = ad2 * (1 + 0.75 / n + 2.25 / n ** 2)
if np.size(ad2a) == 1:
if (ad2a >= 0.00 and ad2a < 0.200):
pval = 1 - np.exp(-13.436 + 101.14 * ad2a - 223.73 * ad2a ** 2)
elif ad2a < 0.340:
pval = 1 - np.exp(-8.318 + 42.796 * ad2a - 59.938 * ad2a ** 2)
elif ad2a < 0.600:
pval = np.exp(0.9177 - 4.279 * ad2a - 1.38 * ad2a ** 2)
elif ad2a <= 13:
pval = np.exp(1.2937 - 5.709 * ad2a + 0.0186 * ad2a ** 2)
else:
pval = 0.0 # is < 4.9542108058458799e-31
else:
bounds = np.array([0.0, 0.200, 0.340, 0.600])
pval0 = lambda ad2a: np.nan * np.ones_like(ad2a)
pval1 = lambda ad2a: 1 - np.exp(
-13.436 + 101.14 * ad2a - 223.73 * ad2a ** 2)
pval2 = lambda ad2a: 1 - np.exp(
-8.318 + 42.796 * ad2a - 59.938 * ad2a ** 2)
pval3 = lambda ad2a: np.exp(0.9177 - 4.279 * ad2a - 1.38 * ad2a ** 2)
pval4 = lambda ad2a: np.exp(1.2937 - 5.709 * ad2a + 0.0186 * ad2a ** 2)
pvalli = [pval0, pval1, pval2, pval3, pval4]
idx = np.searchsorted(bounds, ad2a, side='right')
pval = np.nan * np.ones_like(ad2a)
for i in range(5):
mask = (idx == i)
pval[mask] = pvalli[i](ad2a[mask])
return ad2, pval
if __name__ == '__main__':
x = np.array([-0.1184, -1.3403, 0.0063, -0.612, -0.3869, -0.2313,
-2.8485, -0.2167, 0.4153, 1.8492, -0.3706, 0.9726,
-0.1501, -0.0337, -1.4423, 1.2489, 0.9182, -0.2331,
-0.6182, 0.1830])
r_res = np.array([0.58672353588821502, 0.1115380760041617])
ad2, pval = normal_ad(x)
print(ad2, pval)
print(r_res - [ad2, pval])
print(anderson_statistic((x - x.mean()) / x.std(), dist=stats.norm,
fit=False))
print(anderson_statistic(x, dist=stats.norm, fit=True))
| [
"numpy.ones_like",
"numpy.mean",
"statsmodels.tools.validation.int_like",
"statsmodels.tools.validation.bool_like",
"numpy.searchsorted",
"numpy.sort",
"numpy.size",
"numpy.log",
"statsmodels.tools.validation.array_like",
"numpy.array",
"numpy.exp",
"numpy.std",
"scipy.stats.norm.cdf",
"nu... | [((1011, 1040), 'statsmodels.tools.validation.array_like', 'array_like', (['x', '"""x"""'], {'ndim': 'None'}), "(x, 'x', ndim=None)\n", (1021, 1040), False, 'from statsmodels.tools.validation import array_like, bool_like, int_like\n'), ((1051, 1072), 'statsmodels.tools.validation.bool_like', 'bool_like', (['fit', '"""fit"""'], {}), "(fit, 'fit')\n", (1060, 1072), False, 'from statsmodels.tools.validation import array_like, bool_like, int_like\n'), ((1084, 1106), 'statsmodels.tools.validation.int_like', 'int_like', (['axis', '"""axis"""'], {}), "(axis, 'axis')\n", (1092, 1106), False, 'from statsmodels.tools.validation import array_like, bool_like, int_like\n'), ((1115, 1136), 'numpy.sort', 'np.sort', (['x'], {'axis': 'axis'}), '(x, axis=axis)\n', (1122, 1136), True, 'import numpy as np\n'), ((1818, 1840), 'numpy.arange', 'np.arange', (['(1)', '(nobs + 1)'], {}), '(1, nobs + 1)\n', (1827, 1840), True, 'import numpy as np\n'), ((4332, 4523), 'numpy.array', 'np.array', (['[-0.1184, -1.3403, 0.0063, -0.612, -0.3869, -0.2313, -2.8485, -0.2167, \n 0.4153, 1.8492, -0.3706, 0.9726, -0.1501, -0.0337, -1.4423, 1.2489, \n 0.9182, -0.2331, -0.6182, 0.183]'], {}), '([-0.1184, -1.3403, 0.0063, -0.612, -0.3869, -0.2313, -2.8485, -\n 0.2167, 0.4153, 1.8492, -0.3706, 0.9726, -0.1501, -0.0337, -1.4423, \n 1.2489, 0.9182, -0.2331, -0.6182, 0.183])\n', (4340, 4523), True, 'import numpy as np\n'), ((4581, 4630), 'numpy.array', 'np.array', (['[0.586723535888215, 0.1115380760041617]'], {}), '([0.586723535888215, 0.1115380760041617])\n', (4589, 4630), True, 'import numpy as np\n'), ((3035, 3048), 'numpy.size', 'np.size', (['ad2a'], {}), '(ad2a)\n', (3042, 3048), True, 'import numpy as np\n'), ((3563, 3594), 'numpy.array', 'np.array', (['[0.0, 0.2, 0.34, 0.6]'], {}), '([0.0, 0.2, 0.34, 0.6])\n', (3571, 3594), True, 'import numpy as np\n'), ((4082, 4125), 'numpy.searchsorted', 'np.searchsorted', (['bounds', 'ad2a'], {'side': '"""right"""'}), "(bounds, ad2a, side='right')\n", (4097, 4125), True, 'import numpy as np\n'), ((1378, 1395), 'scipy.stats.norm.cdf', 'stats.norm.cdf', (['w'], {}), '(w)\n', (1392, 1395), False, 'from scipy import stats\n'), ((3884, 3932), 'numpy.exp', 'np.exp', (['(0.9177 - 4.279 * ad2a - 1.38 * ad2a ** 2)'], {}), '(0.9177 - 4.279 * ad2a - 1.38 * ad2a ** 2)\n', (3890, 3932), True, 'import numpy as np\n'), ((3962, 4012), 'numpy.exp', 'np.exp', (['(1.2937 - 5.709 * ad2a + 0.0186 * ad2a ** 2)'], {}), '(1.2937 - 5.709 * ad2a + 0.0186 * ad2a ** 2)\n', (3968, 4012), True, 'import numpy as np\n'), ((4150, 4168), 'numpy.ones_like', 'np.ones_like', (['ad2a'], {}), '(ad2a)\n', (4162, 4168), True, 'import numpy as np\n'), ((1235, 1256), 'numpy.mean', 'np.mean', (['x'], {'axis': 'axis'}), '(x, axis=axis)\n', (1242, 1256), True, 'import numpy as np\n'), ((1295, 1323), 'numpy.std', 'np.std', (['x'], {'ddof': '(1)', 'axis': 'axis'}), '(x, ddof=1, axis=axis)\n', (1301, 1323), True, 'import numpy as np\n'), ((2052, 2061), 'numpy.log', 'np.log', (['z'], {}), '(z)\n', (2058, 2061), True, 'import numpy as np\n'), ((2064, 2081), 'numpy.log1p', 'np.log1p', (['(-z[sl2])'], {}), '(-z[sl2])\n', (2072, 2081), True, 'import numpy as np\n'), ((3122, 3174), 'numpy.exp', 'np.exp', (['(-13.436 + 101.14 * ad2a - 223.73 * ad2a ** 2)'], {}), '(-13.436 + 101.14 * ad2a - 223.73 * ad2a ** 2)\n', (3128, 3174), True, 'import numpy as np\n'), ((3639, 3657), 'numpy.ones_like', 'np.ones_like', (['ad2a'], {}), '(ad2a)\n', (3651, 3657), True, 'import numpy as np\n'), ((3691, 3743), 'numpy.exp', 'np.exp', (['(-13.436 + 101.14 * ad2a - 223.73 * ad2a ** 2)'], {}), '(-13.436 + 101.14 * ad2a - 223.73 * ad2a ** 2)\n', (3697, 3743), True, 'import numpy as np\n'), ((3790, 3841), 'numpy.exp', 'np.exp', (['(-8.318 + 42.796 * ad2a - 59.938 * ad2a ** 2)'], {}), '(-8.318 + 42.796 * ad2a - 59.938 * ad2a ** 2)\n', (3796, 3841), True, 'import numpy as np\n'), ((3225, 3276), 'numpy.exp', 'np.exp', (['(-8.318 + 42.796 * ad2a - 59.938 * ad2a ** 2)'], {}), '(-8.318 + 42.796 * ad2a - 59.938 * ad2a ** 2)\n', (3231, 3276), True, 'import numpy as np\n'), ((3323, 3371), 'numpy.exp', 'np.exp', (['(0.9177 - 4.279 * ad2a - 1.38 * ad2a ** 2)'], {}), '(0.9177 - 4.279 * ad2a - 1.38 * ad2a ** 2)\n', (3329, 3371), True, 'import numpy as np\n'), ((3416, 3466), 'numpy.exp', 'np.exp', (['(1.2937 - 5.709 * ad2a + 0.0186 * ad2a ** 2)'], {}), '(1.2937 - 5.709 * ad2a + 0.0186 * ad2a ** 2)\n', (3422, 3466), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# coding=utf-8
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# parameters
learning_rate = 0.01
trainint_epochs = 2000
display_step = 50
# Training Data
train_X = np.array([3.3, 4.4, 5.5, 6.7, 7.0, 4.2, 9.8, 6.2, 7.6, 2.2, 7.0, 10.8, 5.3, 8.0, 5.7, 9.3, 3.1])
train_Y = np.array([1.7, 2.8, 2.1, 3.2, 1.7, 1.6, 3.4, 2.6, 2.5, 1.2, 2.8, 3.4, 1.6, 2.9, 2.4, 2.9, 1.3])
n_samples = train_X.shape[0]
# tf Graph Input
X = tf.placeholder('float')
Y = tf.placeholder('float')
# Create Model
# Set model weights
W = tf.Variable(np.random.randn(), name = 'weights')
b = tf.Variable(np.random.randn(), name = 'b')
# Construct a linear Model
activation = tf.add(tf.multiply(X, W), b)
# Minimize the squared errors
cost = tf.reduce_sum(tf.pow(activation - Y, 2))/(2*n_samples)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# Initializating the variables
init = tf.global_variables_initializer()
# Launch the Graph
with tf.Session() as sess:
sess.run(init)
# Fit all training Data
for epoch in range(trainint_epochs):
for (x, y) in zip(train_X, train_Y):
sess.run(optimizer, feed_dict={X: x, Y: y})
# Display logs per epoch step
if epoch % display_step == 0:
print('Epoch: {}'.format(epoch+1))
print('Cost={:.9f}'.format(sess.run(cost, feed_dict={X:train_X, Y:train_Y})))
print('W={}'.format(sess.run(W)))
print('b={}'.format(sess.run(b)))
print('Optimization finished!')
print('cost = {}'.format(cost, feed_dict={X:train_X, Y:train_Y}))
print('W = {}'.format(sess.run(W)))
print('b = {}'.format(sess.run(b)))
# Graphic display
plt.plot(train_X, train_Y, 'ro', label = 'Original data')
plt.plot(train_X, sess.run(W)*train_X + sess.run(b), label = 'Fitted line')
plt.legend()
plt.show()
| [
"tensorflow.pow",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.multiply",
"matplotlib.pyplot.plot",
"tensorflow.global_variables_initializer",
"numpy.array",
"tensorflow.train.GradientDescentOptimizer",
"numpy.random.randn",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((216, 316), 'numpy.array', 'np.array', (['[3.3, 4.4, 5.5, 6.7, 7.0, 4.2, 9.8, 6.2, 7.6, 2.2, 7.0, 10.8, 5.3, 8.0, 5.7,\n 9.3, 3.1]'], {}), '([3.3, 4.4, 5.5, 6.7, 7.0, 4.2, 9.8, 6.2, 7.6, 2.2, 7.0, 10.8, 5.3,\n 8.0, 5.7, 9.3, 3.1])\n', (224, 316), True, 'import numpy as np\n'), ((323, 423), 'numpy.array', 'np.array', (['[1.7, 2.8, 2.1, 3.2, 1.7, 1.6, 3.4, 2.6, 2.5, 1.2, 2.8, 3.4, 1.6, 2.9, 2.4,\n 2.9, 1.3]'], {}), '([1.7, 2.8, 2.1, 3.2, 1.7, 1.6, 3.4, 2.6, 2.5, 1.2, 2.8, 3.4, 1.6, \n 2.9, 2.4, 2.9, 1.3])\n', (331, 423), True, 'import numpy as np\n'), ((470, 493), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""'], {}), "('float')\n", (484, 493), True, 'import tensorflow as tf\n'), ((498, 521), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""'], {}), "('float')\n", (512, 521), True, 'import tensorflow as tf\n'), ((937, 970), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (968, 970), True, 'import tensorflow as tf\n'), ((575, 592), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (590, 592), True, 'import numpy as np\n'), ((628, 645), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (643, 645), True, 'import numpy as np\n'), ((707, 724), 'tensorflow.multiply', 'tf.multiply', (['X', 'W'], {}), '(X, W)\n', (718, 724), True, 'import tensorflow as tf\n'), ((996, 1008), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1006, 1008), True, 'import tensorflow as tf\n'), ((1728, 1783), 'matplotlib.pyplot.plot', 'plt.plot', (['train_X', 'train_Y', '"""ro"""'], {'label': '"""Original data"""'}), "(train_X, train_Y, 'ro', label='Original data')\n", (1736, 1783), True, 'import matplotlib.pyplot as plt\n'), ((1870, 1882), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1880, 1882), True, 'import matplotlib.pyplot as plt\n'), ((1887, 1897), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1895, 1897), True, 'import matplotlib.pyplot as plt\n'), ((781, 806), 'tensorflow.pow', 'tf.pow', (['(activation - Y)', '(2)'], {}), '(activation - Y, 2)\n', (787, 806), True, 'import tensorflow as tf\n'), ((834, 882), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['learning_rate'], {}), '(learning_rate)\n', (867, 882), True, 'import tensorflow as tf\n')] |
import numpy as np
def normalize(x: np.ndarray) -> np.ndarray:
assert x.ndim == 1, 'x must be a vector (ndim: 1)'
return x / np.linalg.norm(x)
def look_at(
eye,
target,
up,
) -> np.ndarray:
"""Returns transformation matrix with eye, at and up.
Parameters
----------
eye: (3,) float
Camera position.
target: (3,) float
Camera look_at position.
up: (3,) float
Vector that defines y-axis of camera (z-axis is vector from eye to at).
Returns
-------
T_cam2world: (4, 4) float (if return_homography is True)
Homography transformation matrix from camera to world.
Points are transformed like below:
# x: camera coordinate, y: world coordinate
y = trimesh.transforms.transform_points(x, T_cam2world)
x = trimesh.transforms.transform_points(
y, np.linalg.inv(T_cam2world)
)
"""
eye = np.asarray(eye, dtype=float)
if target is None:
target = np.array([0, 0, 0], dtype=float)
else:
target = np.asarray(target, dtype=float)
if up is None:
up = np.array([0, 0, -1], dtype=float)
else:
up = np.asarray(up, dtype=float)
assert eye.shape == (3,), 'eye must be (3,) float'
assert target.shape == (3,), 'target must be (3,) float'
assert up.shape == (3,), 'up must be (3,) float'
# create new axes
z_axis = normalize(target - eye)
x_axis = normalize(np.cross(up, z_axis))
y_axis = normalize(np.cross(z_axis, x_axis))
# create rotation matrix: [bs, 3, 3]
R = np.vstack((x_axis, y_axis, z_axis))
t = eye
T_cam2world = np.zeros([4,4])
T_cam2world[:3,:3] = R.T
T_cam2world[:3, 3] = t
T_cam2world[3,3] = 1.
return T_cam2world
| [
"numpy.cross",
"numpy.asarray",
"numpy.array",
"numpy.zeros",
"numpy.vstack",
"numpy.linalg.norm"
] | [((948, 976), 'numpy.asarray', 'np.asarray', (['eye'], {'dtype': 'float'}), '(eye, dtype=float)\n', (958, 976), True, 'import numpy as np\n'), ((1602, 1637), 'numpy.vstack', 'np.vstack', (['(x_axis, y_axis, z_axis)'], {}), '((x_axis, y_axis, z_axis))\n', (1611, 1637), True, 'import numpy as np\n'), ((1669, 1685), 'numpy.zeros', 'np.zeros', (['[4, 4]'], {}), '([4, 4])\n', (1677, 1685), True, 'import numpy as np\n'), ((135, 152), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {}), '(x)\n', (149, 152), True, 'import numpy as np\n'), ((1018, 1050), 'numpy.array', 'np.array', (['[0, 0, 0]'], {'dtype': 'float'}), '([0, 0, 0], dtype=float)\n', (1026, 1050), True, 'import numpy as np\n'), ((1078, 1109), 'numpy.asarray', 'np.asarray', (['target'], {'dtype': 'float'}), '(target, dtype=float)\n', (1088, 1109), True, 'import numpy as np\n'), ((1143, 1176), 'numpy.array', 'np.array', (['[0, 0, -1]'], {'dtype': 'float'}), '([0, 0, -1], dtype=float)\n', (1151, 1176), True, 'import numpy as np\n'), ((1200, 1227), 'numpy.asarray', 'np.asarray', (['up'], {'dtype': 'float'}), '(up, dtype=float)\n', (1210, 1227), True, 'import numpy as np\n'), ((1481, 1501), 'numpy.cross', 'np.cross', (['up', 'z_axis'], {}), '(up, z_axis)\n', (1489, 1501), True, 'import numpy as np\n'), ((1526, 1550), 'numpy.cross', 'np.cross', (['z_axis', 'x_axis'], {}), '(z_axis, x_axis)\n', (1534, 1550), True, 'import numpy as np\n')] |
"""Module containing python functions, which generate first order Pauli kernel."""
import numpy as np
import itertools
from ...wrappers.mytypes import doublenp
from ...specfunc.specfunc_elph import FuncPauliElPh
from ..aprclass import ApproachElPh
from ..base.pauli import ApproachPauli as ApproachPauliBase
# ---------------------------------------------------------------------------------------------------------
# Pauli master equation
# ---------------------------------------------------------------------------------------------------------
class ApproachPauli(ApproachElPh):
kerntype = 'pyPauli'
def get_kern_size(self):
return self.si.npauli
def prepare_arrays(self):
ApproachPauliBase.prepare_arrays(self)
nbaths, ndm0 = self.si_elph.nbaths, self.si_elph.ndm0
self.paulifct_elph = np.zeros((nbaths, ndm0), dtype=doublenp)
def clean_arrays(self):
ApproachPauliBase.clean_arrays(self)
self.paulifct_elph.fill(0.0)
def generate_fct(self):
ApproachPauliBase.generate_fct(self)
E, Vbbp = self.qd.Ea, self.baths.Vbbp
si, kh = self.si_elph, self.kernel_handler
ncharge, nbaths, statesdm = si.ncharge, si.nbaths, si.statesdm
func_pauli = FuncPauliElPh(self.baths.tlst_ph, self.baths.dlst_ph,
self.baths.bath_func, self.funcp.eps_elph)
paulifct = self.paulifct_elph
for charge in range(ncharge):
# The diagonal elements b=bp are excluded, because they do not contribute
for b, bp in itertools.permutations(statesdm[charge], 2):
bbp_bool = si.get_ind_dm0(b, bp, charge, maptype=2)
if not bbp_bool:
continue
bbp = si.get_ind_dm0(b, bp, charge)
Ebbp = E[b]-E[bp]
for l in range(nbaths):
xbbp = 0.5*(Vbbp[l, b, bp]*Vbbp[l, b, bp].conjugate() +
Vbbp[l, bp, b].conjugate()*Vbbp[l, bp, b]).real
func_pauli.eval(Ebbp, l)
paulifct[l, bbp] = xbbp*func_pauli.val
def generate_kern(self):
ApproachPauliBase.generate_kern(self)
def generate_coupling_terms(self, b, bp, bcharge):
ApproachPauliBase.generate_coupling_terms(self, b, bp, bcharge)
paulifct = self.paulifct_elph
si, si_elph, kh = self.si, self.si_elph, self.kernel_handler
nbaths, statesdm = si.nbaths, si.statesdm
acharge = bcharge
bb = si.get_ind_dm0(b, b, bcharge)
for a in statesdm[acharge]:
aa = si.get_ind_dm0(a, a, acharge)
ab = si_elph.get_ind_dm0(a, b, bcharge)
ba = si_elph.get_ind_dm0(b, a, acharge)
if aa == -1 or ba == -1:
continue
fctm, fctp = 0, 0
for l in range(nbaths):
fctm -= paulifct[l, ab]
fctp += paulifct[l, ba]
kh.set_matrix_element_pauli(fctm, fctp, bb, aa)
def generate_current(self):
ApproachPauliBase.generate_current(self)
| [
"itertools.permutations",
"numpy.zeros"
] | [((844, 884), 'numpy.zeros', 'np.zeros', (['(nbaths, ndm0)'], {'dtype': 'doublenp'}), '((nbaths, ndm0), dtype=doublenp)\n', (852, 884), True, 'import numpy as np\n'), ((1581, 1624), 'itertools.permutations', 'itertools.permutations', (['statesdm[charge]', '(2)'], {}), '(statesdm[charge], 2)\n', (1603, 1624), False, 'import itertools\n')] |
import numpy as np
from spinup.envs.pointbot_const import *
import pickle
class ReacherRewardBrex():
# Daniel's Suggested Reward
def __init__(self):
with open('brex_reacher.pickle', 'rb') as handle:
b = pickle.load(handle)
#print(b)
self.posterior = []
self.target_penalty = []
self.obstacle_penalty = []
self.weight_vectors = []
for w, prob in b.items():
self.posterior.append(prob)
self.target_penalty.append(w[0])
self.obstacle_penalty.append(w[1])
self.weight_vectors.append(np.asarray(w))
self.posterior = np.array(self.posterior)
self.obstacle_penalty = np.array(self.obstacle_penalty)
self.target_penalty = np.array(self.target_penalty)
self.weight_vectors = np.array(self.weight_vectors)
def get_posterior_weight_matrix(self):
#get the matrix of hypothesis weight vectors from the posterior one per row
return self.weight_vectors
def get_reward_distribution(self, env):
feats = env.get_features()
#print(feats)
dist_rew = feats[0]*self.target_penalty
obs_rew = feats[1]*self.obstacle_penalty
return dist_rew+obs_rew
| [
"numpy.array",
"numpy.asarray",
"pickle.load"
] | [((645, 669), 'numpy.array', 'np.array', (['self.posterior'], {}), '(self.posterior)\n', (653, 669), True, 'import numpy as np\n'), ((702, 733), 'numpy.array', 'np.array', (['self.obstacle_penalty'], {}), '(self.obstacle_penalty)\n', (710, 733), True, 'import numpy as np\n'), ((764, 793), 'numpy.array', 'np.array', (['self.target_penalty'], {}), '(self.target_penalty)\n', (772, 793), True, 'import numpy as np\n'), ((824, 853), 'numpy.array', 'np.array', (['self.weight_vectors'], {}), '(self.weight_vectors)\n', (832, 853), True, 'import numpy as np\n'), ((231, 250), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (242, 250), False, 'import pickle\n'), ((604, 617), 'numpy.asarray', 'np.asarray', (['w'], {}), '(w)\n', (614, 617), True, 'import numpy as np\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.