code stringlengths 17 6.64M |
|---|
def get_same_padding_maxPool2d(image_size=None):
'Chooses static padding if you have specified an image size, and dynamic padding otherwise.\n Static padding is necessary for ONNX exporting of models.\n Args:\n image_size (int or tuple): Size of the image.\n Returns:\n MaxPool2dDynamicSa... |
class MaxPool2dDynamicSamePadding(nn.MaxPool2d):
"2D MaxPooling like TensorFlow's 'SAME' mode, with a dynamic image size.\n The padding is operated in forward function by calculating dynamically.\n "
def __init__(self, kernel_size, stride, padding=0, dilation=1, return_indices=False, ceil_mode=False... |
class MaxPool2dStaticSamePadding(nn.MaxPool2d):
"2D MaxPooling like TensorFlow's 'SAME' mode, with the given input image size.\n The padding mudule is calculated in construction function, then used in forward.\n "
def __init__(self, kernel_size, stride, image_size=None, **kwargs):
super().__... |
class BlockDecoder(object):
'Block Decoder for readability,\n straight from the official TensorFlow repository.\n '
@staticmethod
def _decode_block_string(block_string):
"Get a block through a string notation of arguments.\n Args:\n block_string (str): A string notation... |
def efficientnet_params(model_name):
'Map EfficientNet model name to parameter coefficients.\n Args:\n model_name (str): Model name to be queried.\n Returns:\n params_dict[model_name]: A (width,depth,res,dropout) tuple.\n '
params_dict = {'efficientnet-b0': (1.0, 1.0, 224, 0.2), 'effici... |
def efficientnet(width_coefficient=None, depth_coefficient=None, image_size=None, dropout_rate=0.2, drop_connect_rate=0.2, num_classes=1000, include_top=True):
'Create BlockArgs and GlobalParams for efficientnet model.\n Args:\n width_coefficient (float)\n depth_coefficient (float)\n image... |
def get_model_params(model_name, override_params):
"Get the block args and global params for a given model name.\n Args:\n model_name (str): Model's name.\n override_params (dict): A dict to modify global_params.\n Returns:\n blocks_args, global_params\n "
if model_name.startswit... |
def load_pretrained_weights(model, model_name, weights_path=None, load_fc=True, advprop=False):
'Loads pretrained weights from weights path or download using url.\n Args:\n model (Module): The whole model of efficientnet.\n model_name (str): Model name of efficientnet.\n weights_path (None... |
def conv3x3(in_planes: int, out_planes: int, stride: int=1, groups: int=1, dilation: int=1) -> nn.Conv2d:
'3x3 convolution with padding'
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
|
def conv1x1(in_planes: int, out_planes: int, stride: int=1) -> nn.Conv2d:
'1x1 convolution'
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
|
class BasicBlock(nn.Module):
expansion: int = 1
def __init__(self, inplanes: int, planes: int, stride: int=1, downsample: Optional[nn.Module]=None, groups: int=1, base_width: int=64, dilation: int=1, norm_layer: Optional[Callable[(..., nn.Module)]]=None) -> None:
super(BasicBlock, self).__init__()
... |
class Bottleneck(nn.Module):
expansion: int = 4
def __init__(self, inplanes: int, planes: int, stride: int=1, downsample: Optional[nn.Module]=None, groups: int=1, base_width: int=64, dilation: int=1, norm_layer: Optional[Callable[(..., nn.Module)]]=None) -> None:
super(Bottleneck, self).__init__()
... |
class ResNet(nn.Module):
def __init__(self, block: Type[Union[(BasicBlock, Bottleneck)]], layers: List[int], num_classes: int=1000, in_channels: int=3, zero_init_residual: bool=False, groups: int=1, width_per_group: int=64, replace_stride_with_dilation: Optional[List[bool]]=None, norm_layer: Optional[Callable[(.... |
def _resnet(arch: str, block: Type[Union[(BasicBlock, Bottleneck)]], layers: List[int], pretrained: bool, progress: bool, **kwargs: Any) -> ResNet:
model = ResNet(block, layers, **kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
model.load_state... |
def resnet18(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNet:
'ResNet-18 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool):... |
def resnet34(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNet:
'ResNet-34 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool):... |
def resnet50(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNet:
'ResNet-50 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool):... |
def resnet101(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNet:
'ResNet-101 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool... |
def resnet152(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNet:
'ResNet-152 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool... |
def resnext50_32x4d(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNet:
'ResNeXt-50 32x4d model from\n `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_.\n Args:\n pretrained (bool): If True, returns a model pre-trained on Image... |
def resnext101_32x8d(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNet:
'ResNeXt-101 32x8d model from\n `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_.\n Args:\n pretrained (bool): If True, returns a model pre-trained on Ima... |
def wide_resnet50_2(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNet:
'Wide ResNet-50-2 model from\n `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_.\n The model is the same as ResNet except for the bottleneck number of channels\n which is twice larger in every blo... |
def wide_resnet101_2(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNet:
'Wide ResNet-101-2 model from\n `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_.\n The model is the same as ResNet except for the bottleneck number of channels\n which is twice larger in every b... |
class MultiLeNet(nn.Module):
def __init__(self, dim, **kwargs):
super().__init__()
self.shared = nn.Sequential(nn.Conv2d(dim[0], 10, kernel_size=5), nn.MaxPool2d(kernel_size=2), nn.ReLU(), nn.Conv2d(10, 20, kernel_size=5), nn.MaxPool2d(kernel_size=2), nn.ReLU(), nn.Flatten(), nn.Linear(720, 50), ... |
class FullyConnected(nn.Module):
def __init__(self, dim, **kwargs):
super().__init__()
self.f = nn.Sequential(nn.Linear(dim[0], 60), nn.ReLU(), nn.Linear(60, 25), nn.ReLU(), nn.Linear(25, 1))
def forward(self, batch):
x = batch['data']
return dict(logits=self.f(x))
|
def from_name(names, task_names):
objectives = {'CrossEntropyLoss': CrossEntropyLoss, 'BinaryCrossEntropyLoss': BinaryCrossEntropyLoss, 'L1Regularization': L1Regularization, 'L2Regularization': L2Regularization, 'ddp': DDPHyperbolicTangentRelaxation, 'deo': DEOHyperbolicTangentRelaxation}
if (task_names is no... |
class CrossEntropyLoss(torch.nn.CrossEntropyLoss):
def __init__(self, label_name='labels', logits_name='logits'):
super().__init__(reduction='mean')
self.label_name = label_name
self.logits_name = logits_name
def __call__(self, **kwargs):
logits = kwargs[self.logits_name]
... |
class BinaryCrossEntropyLoss(torch.nn.BCEWithLogitsLoss):
def __init__(self, label_name='labels', logits_name='logits', pos_weight=None):
super().__init__(reduction='mean', pos_weight=(torch.Tensor([pos_weight]).cuda() if pos_weight else None))
self.label_name = label_name
self.logits_nam... |
class MSELoss(torch.nn.MSELoss):
def __init__(self, label_name='labels'):
super().__init__()
self.label_name = label_name
def __call__(self, **kwargs):
logits = kwargs['logits']
labels = kwargs[self.label_name]
if (logits.ndim == 2):
logits = torch.squeeze... |
class L1Regularization():
def __call__(self, **kwargs):
model = kwargs['model']
return torch.linalg.norm(torch.cat([p.view((- 1)) for p in model.parameters()]), ord=1)
|
class L2Regularization():
def __call__(self, **kwargs):
model = kwargs['model']
return torch.linalg.norm(torch.cat([p.view((- 1)) for p in model.parameters()]), ord=2)
|
class DDPHyperbolicTangentRelaxation():
def __init__(self, label_name='labels', logits_name='logits', s_name='sensible_attribute', c=1):
self.label_name = label_name
self.logits_name = logits_name
self.s_name = s_name
self.c = c
def __call__(self, **kwargs):
logits = ... |
class DEOHyperbolicTangentRelaxation():
def __init__(self, label_name='labels', logits_name='logits', s_name='sensible_attribute', c=1):
self.label_name = label_name
self.logits_name = logits_name
self.s_name = s_name
self.c = c
def __call__(self, **kwargs):
logits = ... |
class Fonseca1():
def f1(theta):
d = len(theta)
sum1 = autograd.numpy.sum([((theta[i] - (1.0 / autograd.numpy.sqrt(d))) ** 2) for i in range(d)])
f1 = (1 - autograd.numpy.exp((- sum1)))
return f1
f1_dx = autograd.grad(f1)
def __call__(self, **kwargs):
return f1(kw... |
class Fonseca2():
def f2(theta):
d = len(theta)
sum1 = autograd.numpy.sum([((theta[i] + (1.0 / autograd.numpy.sqrt(d))) ** 2) for i in range(d)])
f1 = (1 - autograd.numpy.exp((- sum1)))
return f1
f2_dx = autograd.grad(f2)
def __call__(self, **kwargs):
return f2(kw... |
def from_objectives(objectives):
scores = {obj.CrossEntropyLoss: CrossEntropy, obj.BinaryCrossEntropyLoss: BinaryCrossEntropy, obj.DDPHyperbolicTangentRelaxation: DDP, obj.DEOHyperbolicTangentRelaxation: DEO, obj.MSELoss: L2Distance}
return [scores[o.__class__](o.label_name, o.logits_name) for o in objectives... |
class BaseScore():
def __init__(self, label_name='labels', logits_name='logits'):
super().__init__()
self.label_name = label_name
self.logits_name = logits_name
@abstractmethod
def __call__(self, **kwargs):
raise NotImplementedError()
|
class CrossEntropy(BaseScore):
def __call__(self, **kwargs):
logits = kwargs[self.logits_name]
labels = kwargs[self.label_name]
with torch.no_grad():
return torch.nn.functional.cross_entropy(logits, labels.long(), reduction='mean').item()
|
class BinaryCrossEntropy(BaseScore):
def __call__(self, **kwargs):
logits = kwargs[self.logits_name]
labels = kwargs[self.label_name]
if ((len(logits.shape) > 1) and (logits.shape[1] == 1)):
logits = torch.squeeze(logits)
with torch.no_grad():
return torch.... |
class L2Distance(BaseScore):
def __call__(self, **kwargs):
prediction = kwargs['logits']
labels = kwargs[self.label_name]
with torch.no_grad():
return torch.linalg.norm((prediction - labels), ord=2)
|
class mcr(BaseScore):
def __call__(self, **kwargs):
logits = kwargs[self.logits_name]
labels = kwargs[self.label_name]
with torch.no_grad():
if (len(logits.shape) == 1):
y_hat = torch.round(torch.sigmoid(logits))
elif (logits.shape[1] == 1):
... |
class DDP(BaseScore):
'Difference in Democratic Parity'
def __call__(self, **kwargs):
logits = kwargs[self.logits_name]
labels = kwargs[self.label_name]
sensible_attribute = kwargs['sensible_attribute']
with torch.no_grad():
n = logits.shape[0]
logits_s... |
class DEO(BaseScore):
'Difference in Equality of Opportunity'
def __call__(self, **kwargs):
logits = kwargs[self.logits_name]
labels = kwargs[self.label_name]
sensible_attribute = kwargs['sensible_attribute']
with torch.no_grad():
n = logits.shape[0]
lo... |
class MiniImageNet(Dataset):
def __init__(self, setname, args):
csv_path = osp.join(SPLIT_PATH, (setname + '.csv'))
lines = [x.strip() for x in open(csv_path, 'r').readlines()][1:]
data = []
label = []
lb = (- 1)
self.wnids = []
for l in lines:
... |
class CategoriesSamplerBak():
def __init__(self, label, n_batch, n_cls, n_per):
self.n_batch = n_batch
self.n_cls = n_cls
self.n_per = n_per
self.n_step = 0
self.mark = {}
self.r_clses = None
label = np.array(label)
self.m_ind = []
for i in ... |
class CategoriesSampler():
def __init__(self, label, n_batch, n_cls, n_per):
self.n_batch = n_batch
self.n_cls = n_cls
self.n_per = n_per
self.n_step = 0
label = np.array(label)
self.m_ind = []
for i in range((max(label) + 1)):
ind = np.argwhere... |
class ScaledDotProductAttention(nn.Module):
' Scaled Dot-Product Attention '
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature = temperature
self.dropout = nn.Dropout(attn_dropout)
self.softmax = nn.Softmax(dim=(- 1))
def forward(self,... |
class MultiHeadAttention(nn.Module):
' Multi-Head Attention module '
def __init__(self, args, n_head, d_model, d_k, d_v, dropout=0.1, do_activation=True):
super().__init__()
self.n_head = n_head
self.d_k = d_k
self.d_v = d_v
self.do_activation = do_activation
s... |
class SSL_boost(nn.Module):
def __init__(self, args, dropout=0.2):
super().__init__()
self.args = args
if (args.model_type == 'ConvNet'):
from SSL.networks.convnet import ConvNet
cnn_dim = args.embed_size
self.encoder = ConvNet(args, z_dim=cnn_dim)
... |
def conv_block(in_channels, out_channels):
return nn.Sequential(nn.Conv2d(in_channels, out_channels, 3, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(), nn.MaxPool2d(2))
|
class ConvNet(nn.Module):
def __init__(self, args, x_dim=3, hid_dim=64, z_dim=64):
super().__init__()
self.args = args
self.encoder = nn.Sequential(conv_block(x_dim, hid_dim), conv_block(hid_dim, hid_dim), conv_block(hid_dim, hid_dim), conv_block(hid_dim, z_dim))
def forward(self, x)... |
class WiderConvnet(nn.Module):
def __init__(self, args, emb_size=128):
super(WiderConvnet, self).__init__()
self.hidden = 64
self.last_hidden = (self.hidden * 25)
self.emb_size = emb_size
self.conv_1 = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=self.hidden, kernel... |
def set_gpu(x):
os.environ['CUDA_VISIBLE_DEVICES'] = x
print('using gpu:', x)
|
def ensure_path(path, remove=True):
if os.path.exists(path):
if remove:
if (input('{} exists, remove? ([y]/n)'.format(path)) != 'n'):
shutil.rmtree(path)
os.makedirs(path)
else:
os.makedirs(path)
|
class Averager():
def __init__(self):
self.n = 0
self.v = 0
def add(self, x):
self.v = (((self.v * self.n) + x) / (self.n + 1))
self.n += 1
def item(self):
return self.v
|
def count_acc(logits, label):
pred = torch.argmax(logits, dim=1)
if torch.cuda.is_available():
return (pred == label).type(torch.cuda.FloatTensor).mean().item()
else:
return (pred == label).type(torch.FloatTensor).mean().item()
|
def euclidean_metric(a, b):
n = a.shape[0]
m = b.shape[0]
a = a.unsqueeze(1).expand(n, m, (- 1))
b = b.unsqueeze(0).expand(n, m, (- 1))
logits = (- ((a - b) ** 2).sum(dim=(- 1)))
return logits
|
def cosine_metric(a, b):
n = a.shape[0]
m = b.shape[0]
a = a.unsqueeze(1).expand(n, m, (- 1))
b = b.unsqueeze(0).expand(n, m, (- 1))
|
class Timer():
def __init__(self):
self.o = time.time()
def measure(self, p=1):
x = ((time.time() - self.o) / p)
x = int(x)
if (x >= 3600):
return '{:.1f}h'.format((x / 3600))
if (x >= 60):
return '{}m'.format(round((x / 60)))
return '{... |
def pprint(x):
_utils_pp.pprint(x)
|
def compute_confidence_interval(data):
'\n Compute 95% confidence interval\n :param data: An array of mean accuracy (or mAP) across a number of sampled episodes.\n :return: the 95% confidence interval for this data.\n '
a = (1.0 * np.array(data))
m = np.mean(a)
std = np.std(a)
pm = (1.... |
def merge_new_config(config, new_config):
if ('_BASE_CONFIG_' in new_config):
with open(new_config['_BASE_CONFIG_'], 'r') as f:
try:
yaml_config = yaml.load(f, Loader=yaml.FullLoader)
except:
yaml_config = yaml.load(f)
config.update(EasyDict(... |
def cfg_from_yaml_file(cfg_file, config):
with open(cfg_file, 'r') as f:
try:
new_config = yaml.load(f, Loader=yaml.FullLoader)
except:
new_config = yaml.load(f)
merge_new_config(config=config, new_config=new_config)
return config
|
def set_gpu(x):
os.environ['CUDA_VISIBLE_DEVICES'] = x
print('using gpu:', x)
|
class BasicConvLSTMCell(object):
'Basic Conv LSTM recurrent network cell.\n '
def __init__(self, shape, filter_size, num_features, forget_bias=1.0, input_size=None, state_is_tuple=False, activation=tf.nn.tanh):
'Initialize the basic Conv LSTM cell.\n Args:\n shape: int tuple thats the height... |
def _conv_linear(args, filter_size, num_features, bias, bias_start=0.0, scope=None, reuse=False):
'convolution:\n Args:\n args: a 4D Tensor or a list of 4D, batch x n, Tensors.\n filter_size: int tuple of filter height and width.\n num_features: int, number of features.\n bias_start: starting value t... |
def batch_norm(inputs, name, train=True, reuse=False):
return tf.contrib.layers.batch_norm(inputs=inputs, is_training=train, reuse=reuse, scope=name, scale=True)
|
def conv2d(input_, output_dim, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, name='conv2d', reuse=False, padding='SAME'):
with tf.variable_scope(name, reuse=reuse):
w = tf.get_variable('w', [k_h, k_w, input_.get_shape()[(- 1)], output_dim], initializer=tf.contrib.layers.xavier_initializer())
conv = tf.... |
def deconv2d(input_, output_shape, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, name='deconv2d', reuse=False, with_w=False, padding='SAME'):
with tf.variable_scope(name, reuse=reuse):
w = tf.get_variable('w', [k_h, k_h, output_shape[(- 1)], input_.get_shape()[(- 1)]], initializer=tf.contrib.layers.xavier_init... |
def lrelu(x, leak=0.2, name='lrelu'):
with tf.variable_scope(name):
f1 = (0.5 * (1 + leak))
f2 = (0.5 * (1 - leak))
return ((f1 * x) + (f2 * abs(x)))
|
def relu(x):
return tf.nn.relu(x)
|
def tanh(x):
return tf.nn.tanh(x)
|
def shape2d(a):
'\n a: a int or tuple/list of length 2\n '
if (type(a) == int):
return [a, a]
if isinstance(a, (list, tuple)):
assert (len(a) == 2)
return list(a)
raise RuntimeError('Illegal shape: {}'.format(a))
|
def shape4d(a):
return (([1] + shape2d(a)) + [1])
|
def UnPooling2x2ZeroFilled(x):
out = tf.concat(axis=3, values=[x, tf.zeros_like(x)])
out = tf.concat(axis=2, values=[out, tf.zeros_like(out)])
sh = x.get_shape().as_list()
if (None not in sh[1:]):
out_size = [(- 1), (sh[1] * 2), (sh[2] * 2), sh[3]]
return tf.reshape(out, out_size)
... |
def MaxPooling(x, shape, stride=None, padding='VALID'):
"\n MaxPooling on images.\n :param input: NHWC tensor.\n :param shape: int or [h, w]\n :param stride: int or [h, w]. default to be shape.\n :param padding: 'valid' or 'same'. default to 'valid'\n :returns: NHWC tensor.\n "
padding = padding.upper(... |
def FixedUnPooling(x, shape):
'\n Unpool the input with a fixed mat to perform kronecker product with.\n :param input: NHWC tensor\n :param shape: int or [h, w]\n :returns: NHWC tensor\n '
shape = shape2d(shape)
return UnPooling2x2ZeroFilled(x)
|
def gdl(gen_frames, gt_frames, alpha):
'\n Calculates the sum of GDL losses between the predicted and gt frames.\n @param gen_frames: The predicted frames at each scale.\n @param gt_frames: The ground truth frames at each scale\n @param alpha: The power to which each gradient term is raised.\n @return: The G... |
def linear(input_, output_size, name, stddev=0.02, bias_start=0.0, reuse=False, with_w=False):
shape = input_.get_shape().as_list()
with tf.variable_scope(name, reuse=reuse):
matrix = tf.get_variable('Matrix', [shape[1], output_size], tf.float32, tf.random_normal_initializer(stddev=stddev))
bi... |
class Acq_Optimizer(object):
def __init__(self, model, acqu_func, bounds, batch_method='CL', batch_size=1, model_name='GP', nsubspace=1):
'\n Optimise the acquisition functions to recommend the next (batch) locations for evaluation\n\n :param model: BO surrogate model function\n :par... |
class BaseModel():
@abstractmethod
def _create_model(self, X, Y):
raise NotImplementedError('')
@abstractmethod
def _update_model(self, X_all, Y_all, itr=0):
'\n Updates the model with new observations.\n '
return
@abstractmethod
def predict(self, X):
... |
def generate_attack_data_set(data, num_sample, img_offset, model, attack_type='targeted', random_target_class=None, shift_index=False):
'\n Generate the data for conducting attack. Only select the data being classified correctly.\n '
orig_img = []
orig_labels = []
target_labels = []
orig_img... |
def model_prediction(model, inputs):
prob = model.model.predict(inputs)
predicted_class = np.argmax(prob)
prob_str = np.array2string(prob).replace('\n', '')
return (prob, predicted_class, prob_str)
|
class NodeLookup(object):
"Converts integer node ID's to human readable labels."
def __init__(self, model_path='./', label_lookup_path=None):
model_path_dir = os.path.join(model_path, FLAGS.model_dir)
if (not label_lookup_path):
label_lookup_path = os.path.join(model_path_dir, 'la... |
def create_graph(model_path='./'):
'Creates a graph from saved GraphDef file and returns a saver.'
sys.argv = [sys.argv[0]]
model_path_dir = os.path.join(model_path, FLAGS.model_dir)
with tf.gfile.FastGFile(os.path.join(model_path_dir, 'frozen_inception_v3.pb'), 'rb') as f:
graph_def = tf.Grap... |
def run_inference_on_image(image):
'Runs inference on an image. (Not updated, not working for inception v3 20160828)\n\n Args:\n image: Image file name.\n\n Returns:\n Nothing\n '
if (not tf.gfile.Exists(image)):
tf.logging.fatal('File does not exist %s', image)
image_data = tf.gfile.Fast... |
class InceptionModelPrediction():
def __init__(self, sess, model_path, use_softmax=False):
self.model_path = model_path
self.sess = sess
self.use_softmax = use_softmax
if self.use_softmax:
output_name = 'InceptionV3/Predictions/Softmax:0'
else:
outp... |
class InceptionModel():
image_size = 299
num_labels = 1001
num_channels = 3
def __init__(self, model_path, use_softmax=False):
with tf.Session() as sess:
global CREATED_GRAPH
self.sess = sess
self.use_softmax = use_softmax
if (not CREATED_GRAPH)... |
def maybe_download_and_extract():
'Download and extract model tar file.'
dest_directory = FLAGS.model_dir
if (not os.path.exists(dest_directory)):
os.makedirs(dest_directory)
filename = DATA_URL.split('/')[(- 1)]
filepath = os.path.join(dest_directory, filename)
if (not os.path.exists(... |
def main(_):
maybe_download_and_extract()
image = (FLAGS.image_file if FLAGS.image_file else os.path.join(FLAGS.model_dir, 'cropped_panda.jpg'))
create_graph()
with tf.Session() as sess:
dat = np.array(scipy.misc.imresize(scipy.misc.imread(image), (299, 299)), dtype=np.float32)
dat /= ... |
def readimg(f, force=False):
FILENAME_RE = re.compile('(\\d+).(\\d+).jpg')
img = scipy.misc.imread(f)
if ((img.shape[0] < 299) or (img.shape[1] < 299)):
return None
img = ((np.array(scipy.misc.imresize(img, (299, 299)), dtype=np.float32) / 255) - 0.5)
if (not force):
if (img.shape ... |
class ImageNet():
def __init__(self, data_path, targetFile=None, targetClass=None):
if (targetFile is None):
random.seed(5566)
from fnmatch import fnmatch
file_list = []
for (path, subdirs, files) in os.walk(data_path):
for name in files:
... |
class ImageNetDataGen():
def __init__(self, train_dir, validate_dir, batch_size=100, data_augmentation=True):
if data_augmentation:
print('Enable data augmentation')
train_datagen = ImageDataGenerator(preprocessing_function=(lambda x: ((x / 255) - 0.5)), shear_range=0.2, zoom_rang... |
class ImageNetDataNP():
def __init__(self, folder_path):
test_data = np.load(os.path.join(folder_path, 'imagenet_test_data.npy'))
test_labels = np.load(os.path.join(folder_path, 'imagenet_test_labels.npy'))
self.test_data = test_data
self.test_labels = test_labels
|
def read_file_list(filename, remove_bounds):
'\n Reads a trajectory from a text file. \n \n File format:\n The file format is "stamp d1 d2 d3 ...", where stamp denotes the time stamp (to be matched)\n and "d1 d2 d3.." is arbitary data (e.g., a 3D position and 3D orientation) associated to this time... |
def associate(first_list, second_list, offset, max_difference):
'\n Associate two dictionaries of (stamp,data). As the time stamps never match exactly, we aim \n to find the closest match for every input tuple.\n \n Input:\n first_list -- first dictionary of (stamp,data) tuples\n second_list -- ... |
def sqdist(X, Y):
assert (X.size()[1] == Y.size()[1]), 'dims do not match'
return ((X.reshape(X.size()[0], 1, X.size()[1]) - Y.reshape(1, Y.size()[0], Y.size()[1])) ** 2).sum(2)
|
class Constant(nn.Module):
def __init__(self, variance=1.0):
super(Constant, self).__init__()
self.variance = torch.nn.Parameter(transform_backward(torch.tensor([variance])))
def forward(self, X, X2=None):
if (X2 is None):
shape = [X.size()[0], X.size()[0]]
else:
... |
class RBF(nn.Module):
def __init__(self, dim, variance=1.0, lengthscale=None):
super(RBF, self).__init__()
self.dim = torch.tensor([dim], requires_grad=False)
if (lengthscale is None):
self.lengthscale = torch.nn.Parameter(transform_backward(torch.ones(1, dim)))
else:
... |
class Linear(nn.Module):
def __init__(self, dim, variance=1.0, lengthscale=None):
super(Linear, self).__init__()
self.dim = torch.tensor([dim], requires_grad=False)
if (lengthscale is None):
self.lengthscale = torch.nn.Parameter(transform_backward(torch.ones(1, dim)))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.