code stringlengths 17 6.64M |
|---|
def print_descriptor_similarity(image_description_similarity, index, label, label_name, label_type='provided'):
print(f'Total similarity to {label_name} ({label_type} label) descriptors:')
print(f'Average: {(100.0 * aggregate_similarity(image_description_similarity[label][index].unsqueeze(0)).item())}')
... |
def print_max_descriptor_similarity(image_description_similarity, index, label, label_name):
(max_similarity, argmax) = image_description_similarity[label][index].max(dim=0)
label_descriptors = gpt_descriptions[label_name]
print(f'I saw a {label_name} because I saw {unmodify_dict[label_name][label_descrip... |
def show_misclassified_images(images, labels, predictions, n=None, image_description_similarity=None, image_labels_similarity=None, true_label_to_consider: int=None, predicted_label_to_consider: int=None):
misclassified_indices = yield_misclassified_indices(images, labels=labels, predictions=predictions, true_lab... |
def yield_misclassified_indices(images, labels, predictions, true_label_to_consider=None, predicted_label_to_consider=None):
misclassified_indicators = (predictions.cpu() != labels.cpu())
if (true_label_to_consider is not None):
misclassified_indicators = (misclassified_indicators & (labels.cpu() == t... |
def predict_and_show_explanations(images, model, labels=None, description_encodings=None, label_encodings=None, device=None):
if (type(images) == Image):
images = tfms(images)
if (images.device != device):
images = images.to(device)
labels = labels.to(device)
image_encodings = mode... |
def load_json(filename):
if (not filename.endswith('.json')):
filename += '.json'
with open(filename, 'r') as fp:
return json.load(fp)
|
def wordify(string):
word = string.replace('_', ' ')
return word
|
def make_descriptor_sentence(descriptor):
if (descriptor.startswith('a') or descriptor.startswith('an')):
return f'which is {descriptor}'
elif (descriptor.startswith('has') or descriptor.startswith('often') or descriptor.startswith('typically') or descriptor.startswith('may') or descriptor.startswith(... |
def modify_descriptor(descriptor, apply_changes):
if apply_changes:
return make_descriptor_sentence(descriptor)
return descriptor
|
def load_gpt_descriptions(hparams, classes_to_load=None):
gpt_descriptions_unordered = load_json(hparams['descriptor_fname'])
unmodify_dict = {}
if (classes_to_load is not None):
gpt_descriptions = {c: gpt_descriptions_unordered[c] for c in classes_to_load}
else:
gpt_descriptions = gpt... |
def seed_everything(seed: int):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = True
|
def denormalize(images, means=(0.485, 0.456, 0.406), stds=(0.229, 0.224, 0.225)):
means = torch.tensor(means).reshape(1, 3, 1, 1)
stds = torch.tensor(stds).reshape(1, 3, 1, 1)
return ((images * stds) + means)
|
def show_single_image(image):
(fig, ax) = plt.subplots(figsize=(12, 12))
ax.set_xticks([])
ax.set_yticks([])
denorm_image = denormalize(image.unsqueeze(0).cpu(), *stats)
ax.imshow(denorm_image.squeeze().permute(1, 2, 0).clamp(0, 1))
plt.show()
|
class Agent():
def __init__(self, state_size, is_eval=False, model_name=''):
self.state_size = state_size
self.action_size = 5
self.memory = deque(maxlen=2000)
self.inventory1 = []
self.inventory2 = []
self.model_name = model_name
self.is_eval = is_eval
... |
def formatPrice(n):
return (('-$' if (n < 0) else '$') + '{0:.2f}'.format(abs(n)))
|
def getStockDataVec(key):
vec = []
lines = open((('data/' + key) + '.txt'), 'r').read().splitlines()
for line in lines[1:]:
vec.append(float(line.split(',')[4]))
return vec
|
def getStockVolVec(key):
vol = []
lines = open((('data/' + key) + '.txt'), 'r').read().splitlines()
for line in lines[1:]:
vol.append(float(line.split(',')[5]))
return vol
|
def sigmoid(x):
return (1 / (1 + math.exp((- x))))
|
class State():
def __init__(self, data1, data2, Bal_stock1, Bal_stock2, open_cash, timestep):
self.Stock1Price = data1[timestep]
self.Stock2Price = data2[timestep]
self.Stock1Blnc = Bal_stock1
self.Stock2Blnc = Bal_stock2
self.open_cash = open_cash
self.fiveday_sto... |
def get_available_gpus():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if (x.device_type == 'GPU')]
|
def get_available_gpus():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if (x.device_type == 'GPU')]
|
def adjust_multilabel(y, is_pred=False):
y_adjusted = []
for y_c in y:
y_test_curr = ([0] * 19)
if (is_pred == True):
y_c = target_vaiables_id2topic_dict[np.argmax(y_c)]
for tag in y_c.split(','):
topic_index = topics_list.index(tag)
y_test_curr[topi... |
def get_metrics(y_test, y_pred_tag, for_classifier=True):
y_test = adjust_multilabel(y_test)
y_test = np.array(y_test)
y_pred_tag = adjust_multilabel(y_pred_tag, is_pred=True)
y_pred_tag = np.array(y_pred_tag)
spl = random.randint(1, 1000)
print('y_test', y_test.shape)
print('y_test\n', y_... |
def get_count(topic):
return topic2count_dict[topic]
|
def is_manual(text):
if (text in manual_set):
return 'crowd_source'
else:
return 'semi_automative'
|
def round_val(val):
if (val < ROUND_THRESHOLD):
return 0
else:
return 1
|
def depersonalize(text):
text = str(text)
url_regex = '(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:\'\\".,<>?«»“”‘’]))'
text = re.sub(url_regex, 'url', text)
text... |
def adjust_multilabel(y, is_pred=False):
y_adjusted = []
for y_c in y:
y_test_curr = ([0] * 19)
index = str(int(np.argmax(y_c)))
y_c = target_vaiables_id2topic_dict[index]
return y_c
|
def get_labels(dataframe):
labels = []
for (i, el) in dataframe.iterrows():
current_sample_labels = []
any_class = False
for clm in necessary_columns:
if (el[clm] == 1):
any_class = True
current_sample_labels.append(clm)
if (any_class... |
class UnsafeData(Dataset):
def __init__(self, texts, targets, tokenizer, max_len):
super().__init__()
self.texts = texts
self.targets = targets
self.max_len = max_len
self.tokenizer = tokenizer
def __len__(self):
return len(self.texts)
def __getitem__(sel... |
def adjust_multilabel(y, is_pred=False):
y_adjusted = []
for y_c in y:
y_test_curr = ([0] * 19)
if (is_pred == True):
y_c = target_vaiables_id2topic_dict[np.argmax(y_c)]
else:
y_c = target_vaiables_id2topic_dict[y_c]
for tag in y_c.split(','):
... |
def compute_metrics(pred):
labels = pred.label_ids
labels = adjust_multilabel(labels, is_pred=False)
preds = pred.predictions
preds = adjust_multilabel(preds, is_pred=True)
(precision, recall, f1, _) = precision_recall_fscore_support(labels, preds, average='weighted', zero_division=0)
acc = ac... |
def cleanup():
gc.collect()
torch.cuda.empty_cache()
|
def is_manual(text):
if (text in manual_set):
return 'crowd_source'
else:
return 'semi_automative'
|
def round_val(val):
if (val < ROUND_THRESHOLD):
return 0
else:
return 1
|
class MyDataset(torch.utils.data.Dataset):
def __init__(self, imList, labelList, transform=None):
self.imList = imList
self.labelList = labelList
self.transform = transform
def __len__(self):
return len(self.imList)
def __getitem__(self, idx):
image_name = self.i... |
class iouEval():
def __init__(self, nClasses):
self.nClasses = nClasses
self.reset()
def reset(self):
self.overall_acc = 0
self.per_class_acc = np.zeros(self.nClasses, dtype=np.float32)
self.per_class_iu = np.zeros(self.nClasses, dtype=np.float32)
self.mIOU = ... |
class CBR(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1):
super().__init__()
padding = int(((kSize - 1) / 2))
self.conv = nn.Conv3d(nIn, nOut, kSize, stride=stride, padding=padding, bias=False)
self.bn = nn.BatchNorm3d(nOut, momentum=0.95, eps=0.001)
self.act =... |
class CB(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1):
super().__init__()
padding = int(((kSize - 1) / 2))
self.conv = nn.Conv3d(nIn, nOut, kSize, stride=stride, padding=padding, bias=False)
self.bn = nn.BatchNorm3d(nOut, momentum=0.95, eps=0.001)
def forward(se... |
class C(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1, groups=1):
super().__init__()
padding = int(((kSize - 1) / 2))
self.conv = nn.Conv3d(nIn, nOut, kSize, stride=stride, padding=padding, bias=False, groups=groups)
def forward(self, input):
output = self.conv(in... |
class DownSamplerA(nn.Module):
def __init__(self, nIn, nOut):
super().__init__()
self.conv = CBR(nIn, nOut, 3, 2)
def forward(self, input):
output = self.conv(input)
return output
|
class DownSamplerB(nn.Module):
def __init__(self, nIn, nOut):
super().__init__()
k = 4
n = int((nOut / k))
n1 = (nOut - ((k - 1) * n))
self.c1 = nn.Sequential(CBR(nIn, n, 1, 1), C(n, n, 3, 2))
self.d1 = CDilated(n, n1, 3, 1, 1)
self.d2 = CDilated(n, n, 3, 1... |
class BR(nn.Module):
def __init__(self, nOut):
super().__init__()
self.bn = nn.BatchNorm3d(nOut, momentum=0.95, eps=0.001)
self.act = nn.ReLU(inplace=True)
def forward(self, input):
output = self.bn(input)
output = self.act(output)
return output
|
class CDilated(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1, d=1, groups=1):
super().__init__()
padding = (int(((kSize - 1) / 2)) * d)
self.conv = nn.Conv3d(nIn, nOut, kSize, stride=stride, padding=padding, bias=False, dilation=d, groups=groups)
def forward(self, input):... |
class InputProjectionA(nn.Module):
'\n This class projects the input image to the same spatial dimensions as the feature map.\n For example, if the input image is 512 x512 x3 and spatial dimensions of feature map size are 56x56xF, then\n this class will generate an output of 56x56x3\n '
def __ini... |
class DilatedParllelResidualBlockB1(nn.Module):
def __init__(self, nIn, nOut, stride=1):
super().__init__()
k = 4
n = int((nOut / k))
n1 = (nOut - ((k - 1) * n))
self.c1 = CBR(nIn, n, 1, 1)
self.d1 = CDilated(n, n1, 3, stride, 1)
self.d2 = CDilated(n, n, 3,... |
class ASPBlock(nn.Module):
def __init__(self, nIn, nOut, stride=1):
super().__init__()
self.d1 = CB(nIn, nOut, 3, 1)
self.d2 = CB(nIn, nOut, 5, 1)
self.d4 = CB(nIn, nOut, 7, 1)
self.d8 = CB(nIn, nOut, 9, 1)
self.act = nn.ReLU(inplace=True)
def forward(self, in... |
class UpSampler(nn.Module):
'\n Up-sample the feature maps by 2\n '
def __init__(self, nIn, nOut):
super().__init__()
self.up = CBR(nIn, nOut, 3, 1)
def forward(self, inp):
return F.upsample(self.up(inp), mode='trilinear', scale_factor=2)
|
class PSPDec(nn.Module):
'\n Inspired or Adapted from Pyramid Scene Network paper\n '
def __init__(self, nIn, nOut, downSize):
super().__init__()
self.scale = downSize
self.features = CBR(nIn, nOut, 3, 1)
def forward(self, x):
assert (x.dim() == 5)
inp_size ... |
class ESPNet(nn.Module):
def __init__(self, classes=4, channels=1):
super().__init__()
self.input1 = InputProjectionA(1)
self.input2 = InputProjectionA(1)
initial = 16
config = [32, 128, 256, 256]
reps = [2, 2, 3]
self.level0 = CBR(channels, initial, 7, 2)
... |
class ScaleToFixed(object):
'\n All images after removing redundard black pixels are of different sizes.\n Fix their size, so that we can group them in batches\n '
def __init__(self, dimA, dimB, dimC):
self.dimA = dimA
self.dimB = dimB
self.dimC = dimC
def __call__(self,... |
class RandomFlip(object):
'Randomly flips (horizontally as well as vertically) the given PIL.Image with a probability of 0.5\n '
def __call__(self, image, imageA, imageB, imageC, label):
if (random.random() < 0.5):
flip_type = np.random.randint(0, 3)
image = np.flip(image, ... |
class MinMaxNormalize(object):
'Min-Max normalization\n '
def __call__(self, image, imageA, imageB, imageC, label):
def norm(im):
im = im.astype(np.float32)
min_v = np.min(im)
max_v = np.max(im)
im = ((im - min_v) / (max_v - min_v))
retu... |
class ToTensor(object):
def __init__(self, scale=1):
self.scale = scale
def __call__(self, image, imageA, imageB, imageC, label):
image = image.astype(np.float32)
imageA = imageA.astype(np.float32)
imageB = imageB.astype(np.float32)
imageC = imageC.astype(np.float32)
... |
class Compose(object):
'Composes several transforms together.\n '
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, *args):
for t in self.transforms:
args = t(*args)
return args
|
def make_dot(var, params=None):
' Produces Graphviz representation of PyTorch autograd graph\n Blue nodes are the Variables that require grad, orange are Tensors\n saved for backward in torch.autograd.Function\n Args:\n var: output Variable\n params: dict of (name, Variable) to add names to... |
class LoadData():
def __init__(self, data_dir, data_dir_val, classes, cached_data_file, normVal=1.1):
self.data_dir = data_dir
self.data_dir_val = data_dir_val
self.classes = classes
self.classWeights = np.ones(self.classes, dtype=np.float32)
self.normVal = normVal
... |
def val(args, val_loader, model, criterion):
model.eval()
iouEvalVal = iouEval(args.classes)
epoch_loss = []
total_batches = len(val_loader)
for (i, (inp, inputA, inputB, inputC, target)) in enumerate(val_loader):
start_time = time.time()
input = torch.cat([inp, inputA, inputB, inp... |
def train(args, train_loader, model, criterion, optimizer, epoch):
model.train()
iouEvalTrain = iouEval(args.classes)
epoch_loss = []
total_batches = len(train_loader)
for (i, (inp, inputA, inputB, inputC, target)) in enumerate(train_loader):
start_time = time.time()
input = torch.... |
def save_checkpoint(state, filenameCheckpoint='checkpoint.pth.tar'):
torch.save(state, filenameCheckpoint)
|
def trainValidateSegmentation(args):
print(('Data file: ' + str(args.cached_data_file)))
print(args)
if (not os.path.isfile(args.cached_data_file)):
dataLoader = ld.LoadData(args.data_dir, args.data_dir_val, args.classes, args.cached_data_file)
data = dataLoader.processData()
if (d... |
class CBR(nn.Module):
'\n This class defines the convolution layer with batch normalization and PReLU activation\n '
def __init__(self, nIn, nOut, kSize, stride=1):
'\n\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel si... |
class BR(nn.Module):
'\n This class groups the batch normalization and PReLU activation\n '
def __init__(self, nOut):
'\n :param nOut: output feature maps\n '
super().__init__()
self.bn = nn.BatchNorm2d(nOut, eps=0.001)
self.act = nn.PReLU(nOut)
de... |
class CB(nn.Module):
'\n This class groups the convolution and batch normalization\n '
def __init__(self, nIn, nOut, kSize, stride=1):
'\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel size\n :param stride: op... |
class C(nn.Module):
'\n This class is for a convolutional layer.\n '
def __init__(self, nIn, nOut, kSize, stride=1):
'\n\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel size\n :param stride: optional stride rate ... |
class CDilated(nn.Module):
'\n This class defines the dilated convolution.\n '
def __init__(self, nIn, nOut, kSize, stride=1, d=1):
'\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel size\n :param stride: optional... |
class DownSamplerB(nn.Module):
def __init__(self, nIn, nOut):
super().__init__()
n = int((nOut / 5))
n1 = (nOut - (4 * n))
self.c1 = C(nIn, n, 3, 2)
self.d1 = CDilated(n, n1, 3, 1, 1)
self.d2 = CDilated(n, n, 3, 1, 2)
self.d4 = CDilated(n, n, 3, 1, 4)
... |
class DilatedParllelResidualBlockB(nn.Module):
'\n This class defines the ESP block, which is based on the following principle\n Reduce ---> Split ---> Transform --> Merge\n '
def __init__(self, nIn, nOut, add=True):
'\n :param nIn: number of input channels\n :param nOut: n... |
class InputProjectionA(nn.Module):
'\n This class projects the input image to the same spatial dimensions as the feature map.\n For example, if the input image is 512 x512 x3 and spatial dimensions of feature map size are 56x56xF, then\n this class will generate an output of 56x56x3\n '
def __ini... |
class ESPNet_Encoder(nn.Module):
'\n This class defines the ESPNet-C network in the paper\n '
def __init__(self, classes=20, p=5, q=3):
'\n :param classes: number of classes in the dataset. Default is 20 for the cityscapes\n :param p: depth multiplier\n :param q: depth mult... |
class ESPNet(nn.Module):
'\n This class defines the ESPNet network\n '
def __init__(self, classes=20, p=2, q=3, encoderFile=None):
'\n :param classes: number of classes in the dataset. Default is 20 for the cityscapes\n :param p: depth multiplier\n :param q: depth multiplie... |
class CrossEntropyLoss2d(nn.Module):
'\n This file defines a cross entropy loss for 2D images\n '
def __init__(self, weight=None):
'\n :param weight: 1D weight vector to deal with the class-imbalance\n '
super().__init__()
self.loss = nn.NLLLoss2d(weight)
def ... |
class MyDataset(torch.utils.data.Dataset):
'\n Class to load the dataset\n '
def __init__(self, imList, labelList, transform=None):
'\n :param imList: image list (Note that these lists have been processed and pickled using the loadData.py)\n :param labelList: label list (Note that... |
class iouEval():
def __init__(self, nClasses):
self.nClasses = nClasses
self.reset()
def reset(self):
self.overall_acc = 0
self.per_class_acc = np.zeros(self.nClasses, dtype=np.float32)
self.per_class_iu = np.zeros(self.nClasses, dtype=np.float32)
self.mIOU = ... |
class CBR(nn.Module):
'\n This class defines the convolution layer with batch normalization and PReLU activation\n '
def __init__(self, nIn, nOut, kSize, stride=1):
'\n\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel si... |
class BR(nn.Module):
'\n This class groups the batch normalization and PReLU activation\n '
def __init__(self, nOut):
'\n :param nOut: output feature maps\n '
super().__init__()
self.bn = nn.BatchNorm2d(nOut, eps=0.001)
self.act = nn.PReLU(nOut)
de... |
class CB(nn.Module):
'\n This class groups the convolution and batch normalization\n '
def __init__(self, nIn, nOut, kSize, stride=1):
'\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel size\n :param stride: op... |
class C(nn.Module):
'\n This class is for a convolutional layer.\n '
def __init__(self, nIn, nOut, kSize, stride=1):
'\n\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel size\n :param stride: optional stride rate ... |
class CDilated(nn.Module):
'\n This class defines the dilated convolution.\n '
def __init__(self, nIn, nOut, kSize, stride=1, d=1):
'\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel size\n :param stride: optional... |
class DownSamplerB(nn.Module):
def __init__(self, nIn, nOut):
super().__init__()
n = int((nOut / 5))
n1 = (nOut - (4 * n))
self.c1 = C(nIn, n, 3, 2)
self.d1 = CDilated(n, n1, 3, 1, 1)
self.d2 = CDilated(n, n, 3, 1, 2)
self.d4 = CDilated(n, n, 3, 1, 4)
... |
class DilatedParllelResidualBlockB(nn.Module):
'\n This class defines the ESP block, which is based on the following principle\n Reduce ---> Split ---> Transform --> Merge\n '
def __init__(self, nIn, nOut, add=True):
'\n :param nIn: number of input channels\n :param nOut: n... |
class InputProjectionA(nn.Module):
'\n This class projects the input image to the same spatial dimensions as the feature map.\n For example, if the input image is 512 x512 x3 and spatial dimensions of feature map size are 56x56xF, then\n this class will generate an output of 56x56x3\n '
def __ini... |
class ESPNet_Encoder(nn.Module):
'\n This class defines the ESPNet-C network in the paper\n '
def __init__(self, classes=20, p=5, q=3):
'\n :param classes: number of classes in the dataset. Default is 20 for the cityscapes\n :param p: depth multiplier\n :param q: depth mult... |
class ESPNet(nn.Module):
'\n This class defines the ESPNet network\n '
def __init__(self, classes=20, p=2, q=3, encoderFile=None):
'\n :param classes: number of classes in the dataset. Default is 20 for the cityscapes\n :param p: depth multiplier\n :param q: depth multiplie... |
def make_dot(var, params=None):
' Produces Graphviz representation of PyTorch autograd graph\n Blue nodes are the Variables that require grad, orange are Tensors\n saved for backward in torch.autograd.Function\n Args:\n var: output Variable\n params: dict of (name, Variable) to add names to... |
def val(args, val_loader, model, criterion):
'\n :param args: general arguments\n :param val_loader: loaded for validation dataset\n :param model: model\n :param criterion: loss function\n :return: average epoch loss, overall pixel-wise accuracy, per class accuracy, per class iu, and mIOU\n '
... |
def train(args, train_loader, model, criterion, optimizer, epoch):
'\n :param args: general arguments\n :param train_loader: loaded for training dataset\n :param model: model\n :param criterion: loss function\n :param optimizer: optimization algo, such as ADAM or SGD\n :param epoch: epoch number... |
def save_checkpoint(state, filenameCheckpoint='checkpoint.pth.tar'):
'\n helper function to save the checkpoint\n :param state: model state\n :param filenameCheckpoint: where to save the checkpoint\n :return: nothing\n '
torch.save(state, filenameCheckpoint)
|
def netParams(model):
'\n helper function to see total network parameters\n :param model: model\n :return: total network parameters\n '
total_paramters = 0
for parameter in model.parameters():
i = len(parameter.size())
p = 1
for j in range(i):
p *= parameter... |
def trainValidateSegmentation(args):
'\n Main function for trainign and validation\n :param args: global arguments\n :return: None\n '
if (not os.path.isfile(args.cached_data_file)):
dataLoad = ld.LoadData(args.data_dir, args.classes, args.cached_data_file)
data = dataLoad.processD... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model', help='full path to the .h5 model (download from https://goo.gl/ciEYZi)', required=True)
parser.add_argument('--image', help='full path to the image', required=True)
parser.add_argument('--output', help='full path to the outp... |
def main():
input_file = 'image.jpg'
output_file = 'labels.png'
saved_model_path = 'crfrnn_keras_model.h5'
model = get_crfrnn_model_def()
model.load_weights(saved_model_path)
(img_data, img_h, img_w, size) = util.get_preprocessed_image(input_file)
probs = model.predict(img_data, verbose=Fa... |
def get_crfrnn_model_def():
' Returns Keras CRN-RNN model definition.\n\n Currently, only 500 x 500 images are supported. However, one can get this to\n work with different image sizes by adjusting the parameters of the Cropping2D layers\n below.\n '
(channels, height, width) = (3, 500, 500)
i... |
@ops.RegisterGradient('HighDimFilter')
def _high_dim_filter_grad(op, grad):
' Gradients for the HighDimFilter op. We only need to calculate the gradients\n w.r.t. the first input (unaries) as we never need to backprop errors to the\n second input (RGB values of the image).\n\n Args:\n op: The `high_di... |
class HighDimGradTest(tf.test.TestCase):
def test_high_dim_filter_grad(self):
x_shape = [5, 10, 10]
unary_np = np.random.randn(*x_shape).astype(np.float32)
rgb_np = np.random.randint(low=0, high=256, size=x_shape).astype(np.float32)
with self.test_session():
unary_tf =... |
def safe_readline(f):
pos = f.tell()
while True:
try:
return f.readline()
except UnicodeDecodeError:
pos -= 1
f.seek(pos)
|
class Binarizer():
@staticmethod
def binarize(filename, dict, consumer, tokenize=tokenize_line, append_eos=True, reverse_order=False, offset=0, end=(- 1), already_numberized=False):
(nseq, ntok) = (0, 0)
replaced = Counter()
def replaced_consumer(word, idx):
if ((idx == d... |
class BleuStat(ctypes.Structure):
_fields_ = [('reflen', ctypes.c_size_t), ('predlen', ctypes.c_size_t), ('match1', ctypes.c_size_t), ('count1', ctypes.c_size_t), ('match2', ctypes.c_size_t), ('count2', ctypes.c_size_t), ('match3', ctypes.c_size_t), ('count3', ctypes.c_size_t), ('match4', ctypes.c_size_t), ('coun... |
class SacrebleuScorer(object):
def __init__(self):
import sacrebleu
self.sacrebleu = sacrebleu
self.reset()
def reset(self, one_init=False):
if one_init:
raise NotImplementedError
self.ref = []
self.sys = []
def add_string(self, ref, pred):
... |
class Scorer(object):
def __init__(self, pad, eos, unk):
self.stat = BleuStat()
self.pad = pad
self.eos = eos
self.unk = unk
self.reset()
def reset(self, one_init=False):
if one_init:
C.bleu_one_init(ctypes.byref(self.stat))
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.