id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
33,523 | from collections import namedtuple
from functools import partial
from inspect import isfunction
import torch
import torch.nn.functional as F
from einops import rearrange, reduce, repeat
from torch import einsum, nn
def always(val):
def inner(*args, **kwargs):
return val
return inner | null |
33,524 | from collections import namedtuple
from functools import partial
from inspect import isfunction
import torch
import torch.nn.functional as F
from einops import rearrange, reduce, repeat
from torch import einsum, nn
def not_equals(val):
def inner(x):
return x != val
return inner | null |
33,525 | from collections import namedtuple
from functools import partial
from inspect import isfunction
import torch
import torch.nn.functional as F
from einops import rearrange, reduce, repeat
from torch import einsum, nn
def equals(val):
def inner(x):
return x == val
return inner | null |
33,526 | from collections import namedtuple
from functools import partial
from inspect import isfunction
import torch
import torch.nn.functional as F
from einops import rearrange, reduce, repeat
from torch import einsum, nn
def max_neg_value(tensor):
return -torch.finfo(tensor.dtype).max | null |
33,527 | from collections import namedtuple
from functools import partial
from inspect import isfunction
import torch
import torch.nn.functional as F
from einops import rearrange, reduce, repeat
from torch import einsum, nn
def pick_and_pop(keys, d):
values = list(map(lambda key: d.pop(key), keys))
return dict(zip(keys... | null |
33,528 | from collections import namedtuple
from functools import partial
from inspect import isfunction
import torch
import torch.nn.functional as F
from einops import rearrange, reduce, repeat
from torch import einsum, nn
def group_dict_by_key(cond, d):
return_val = [dict(), dict()]
for key in d.keys():
match ... | null |
33,529 | from collections import namedtuple
from functools import partial
from inspect import isfunction
import torch
import torch.nn.functional as F
from einops import rearrange, reduce, repeat
from torch import einsum, nn
def group_dict_by_key(cond, d):
return_val = [dict(), dict()]
for key in d.keys():
match ... | null |
33,531 | from functools import partial
import clip
import kornia
import numpy as np
import torch
import torch.nn as nn
from extern.ldm_zero123.modules.x_transformer import ( # TODO: can we directly rely on lucidrains code and simply add this as a reuirement? --> test
Encoder,
TransformerWrapper,
)
from extern.ldm_zero1... | Overwrite model.train with this function to make sure train/eval mode does not change anymore. |
33,532 | import importlib
import os
import time
from inspect import isfunction
import cv2
import matplotlib.pyplot as plt
import numpy as np
import PIL
import torch
import torchvision
from PIL import Image, ImageDraw, ImageFont
from torch import optim
def pil_rectangle_crop(im):
width, height = im.size # Get dimensions
... | null |
33,533 | import importlib
import os
import time
from inspect import isfunction
import cv2
import matplotlib.pyplot as plt
import numpy as np
import PIL
import torch
import torchvision
from PIL import Image, ImageDraw, ImageFont
from torch import optim
def log_txt_as_img(wh, xc, size=10):
# wh a tuple of (width, height)
... | null |
33,534 | import importlib
import os
import time
from inspect import isfunction
import cv2
import matplotlib.pyplot as plt
import numpy as np
import PIL
import torch
import torchvision
from PIL import Image, ImageDraw, ImageFont
from torch import optim
def ismap(x):
if not isinstance(x, torch.Tensor):
return False
... | null |
33,535 | import importlib
import os
import time
from inspect import isfunction
import cv2
import matplotlib.pyplot as plt
import numpy as np
import PIL
import torch
import torchvision
from PIL import Image, ImageDraw, ImageFont
from torch import optim
def isimage(x):
if not isinstance(x, torch.Tensor):
return False... | null |
33,536 | import importlib
import os
import time
from inspect import isfunction
import cv2
import matplotlib.pyplot as plt
import numpy as np
import PIL
import torch
import torchvision
from PIL import Image, ImageDraw, ImageFont
from torch import optim
def exists(x):
return x is not None
def default(val, d):
if exists(v... | null |
33,537 | import importlib
import os
import time
from inspect import isfunction
import cv2
import matplotlib.pyplot as plt
import numpy as np
import PIL
import torch
import torchvision
from PIL import Image, ImageDraw, ImageFont
from torch import optim
The provided code snippet includes necessary dependencies for implementing t... | https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86 Take the mean over all non-batch dimensions. |
33,538 | import importlib
import os
import time
from inspect import isfunction
import cv2
import matplotlib.pyplot as plt
import numpy as np
import PIL
import torch
import torchvision
from PIL import Image, ImageDraw, ImageFont
from torch import optim
def count_params(model, verbose=False):
total_params = sum(p.numel() for... | null |
33,539 | import logging
from contextlib import contextmanager
from pathlib import Path
import torch
from omegaconf import OmegaConf
from extern.ldm_zero123.util import instantiate_from_config
def load_model_from_config(config, ckpt, device="cpu", verbose=False):
"""Loads a model from config and a ckpt
if config is a pat... | Load a checkpoint and config from training directory |
33,540 | from collections import namedtuple
import torch
from torch.nn import (
AdaptiveAvgPool2d,
BatchNorm2d,
Conv2d,
MaxPool2d,
Module,
PReLU,
ReLU,
Sequential,
Sigmoid,
)
def l2_norm(input, axis=1):
norm = torch.norm(input, 2, axis, True)
output = torch.div(input, norm)
retur... | null |
33,541 | from collections import namedtuple
import torch
from torch.nn import (
AdaptiveAvgPool2d,
BatchNorm2d,
Conv2d,
MaxPool2d,
Module,
PReLU,
ReLU,
Sequential,
Sigmoid,
)
def get_block(in_channel, depth, num_units, stride=2):
def get_blocks(num_layers):
if num_layers == 50:
b... | null |
33,542 | from torch.nn import (
BatchNorm1d,
BatchNorm2d,
Conv2d,
Dropout,
Linear,
Module,
PReLU,
Sequential,
)
from extern.ldm_zero123.thirdp.psp.helpers import (
Flatten,
bottleneck_IR,
bottleneck_IR_SE,
get_blocks,
l2_norm,
)
class Backbone(Module):
def __init__(self, i... | Constructs a ir-50 model. |
33,543 | from torch.nn import (
BatchNorm1d,
BatchNorm2d,
Conv2d,
Dropout,
Linear,
Module,
PReLU,
Sequential,
)
from extern.ldm_zero123.thirdp.psp.helpers import (
Flatten,
bottleneck_IR,
bottleneck_IR_SE,
get_blocks,
l2_norm,
)
class Backbone(Module):
def __init__(self, i... | Constructs a ir-101 model. |
33,544 | from torch.nn import (
BatchNorm1d,
BatchNorm2d,
Conv2d,
Dropout,
Linear,
Module,
PReLU,
Sequential,
)
from extern.ldm_zero123.thirdp.psp.helpers import (
Flatten,
bottleneck_IR,
bottleneck_IR_SE,
get_blocks,
l2_norm,
)
class Backbone(Module):
def __init__(self, i... | Constructs a ir-152 model. |
33,545 | from torch.nn import (
BatchNorm1d,
BatchNorm2d,
Conv2d,
Dropout,
Linear,
Module,
PReLU,
Sequential,
)
from extern.ldm_zero123.thirdp.psp.helpers import (
Flatten,
bottleneck_IR,
bottleneck_IR_SE,
get_blocks,
l2_norm,
)
class Backbone(Module):
def __init__(self, i... | Constructs a ir_se-50 model. |
33,546 | from torch.nn import (
BatchNorm1d,
BatchNorm2d,
Conv2d,
Dropout,
Linear,
Module,
PReLU,
Sequential,
)
from extern.ldm_zero123.thirdp.psp.helpers import (
Flatten,
bottleneck_IR,
bottleneck_IR_SE,
get_blocks,
l2_norm,
)
class Backbone(Module):
def __init__(self, i... | Constructs a ir_se-101 model. |
33,547 | from torch.nn import (
BatchNorm1d,
BatchNorm2d,
Conv2d,
Dropout,
Linear,
Module,
PReLU,
Sequential,
)
from extern.ldm_zero123.thirdp.psp.helpers import (
Flatten,
bottleneck_IR,
bottleneck_IR_SE,
get_blocks,
l2_norm,
)
class Backbone(Module):
def __init__(self, i... | Constructs a ir_se-152 model. |
33,548 | import numpy as np
import torch
def renorm_thresholding(x0, value):
# renorm
pred_max = x0.max()
pred_min = x0.min()
pred_x0 = (x0 - pred_min) / (pred_max - pred_min) # 0 ... 1
pred_x0 = 2 * pred_x0 - 1.0 # -1 ... 1
s = torch.quantile(rearrange(pred_x0, "b ... -> b (...)").abs(), value, dim=... | null |
33,549 | import numpy as np
import torch
def append_dims(x, target_dims):
"""Appends dimensions to the end of a tensor until it has target_dims dimensions.
From https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/utils.py"""
dims_to_append = target_dims - x.ndim
if dims_to_append < 0:
raise ... | null |
33,550 | import numpy as np
import torch
def spatial_norm_thresholding(x0, value):
# b c h w
s = x0.pow(2).mean(1, keepdim=True).sqrt().clamp(min=value)
return x0 * (value / s) | null |
33,551 | import os
from copy import deepcopy
from glob import glob
import pytorch_lightning as pl
import torch
from einops import rearrange
from natsort import natsorted
from omegaconf import OmegaConf
from torch.nn import functional as F
from torch.optim import AdamW
from torch.optim.lr_scheduler import LambdaLR
from extern.ld... | Overwrite model.train with this function to make sure train/eval mode does not change anymore. |
33,552 | import itertools
from contextlib import contextmanager, nullcontext
from functools import partial
import numpy as np
import pytorch_lightning as pl
import torch
import torch.nn as nn
from einops import rearrange, repeat
from omegaconf import ListConfig
from pytorch_lightning.utilities.rank_zero import rank_zero_only
fr... | Overwrite model.train with this function to make sure train/eval mode does not change anymore. |
33,553 | import itertools
from contextlib import contextmanager, nullcontext
from functools import partial
import numpy as np
import pytorch_lightning as pl
import torch
import torch.nn as nn
from einops import rearrange, repeat
from omegaconf import ListConfig
from pytorch_lightning.utilities.rank_zero import rank_zero_only
fr... | null |
33,554 | import argparse
import sys
import torch
from diffusers.models import AutoencoderKL, UNet2DConditionModel
from diffusers.schedulers import DDIMScheduler
from diffusers.utils import logging
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
from accelerate import init_empty_weights
from accelerate... | null |
33,555 | import argparse
import contextlib
import importlib
import logging
import os
import sys
import time
import traceback
def load_custom_module(module_path):
def load_custom_modules():
node_paths = ["custom"]
node_import_times = []
for custom_node_path in node_paths:
possible_modules = os.listdir(custom... | null |
33,556 | import torch
def ask_user():
print("Write your array as a list [i,j,k..] with arbitrary positive numbers")
array = input("Input q if you want to quit \n")
return array
The provided code snippet includes necessary dependencies for implementing the `sort_array` function. Write a Python function `def sort_arr... | A very simple example of use of the model Input: encoder nn.Module decoder nn.Module device array to sort (optional) |
33,557 | import torch
import torch.nn as nn
import torch.nn.functional as F
class LeNet(nn.Module):
def __init__(self, in_channels, init_weights=True, num_classes=10):
def forward(self, x):
def _initialize_weights(self):
def test_lenet():
net = LeNet(1)
x = torch.randn(64, 1, 32, 32)
y = net(x)
p... | null |
33,558 | import torch
import torch.nn as nn
class residual_template(nn.Module):
expansion = 4
def __init__(self, in_channels, out_channels, stride=1, identity_downsample=None):
super().__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2... | null |
33,559 | import torch
import torch.nn as nn
class residual_template(nn.Module):
def __init__(self, in_channels, out_channels, stride=1, identity_downsample=None):
def forward(self, x):
class ResNet(nn.Module):
def __init__(self, residual_template, layers, image_channel, num_classes=10):
def _make_layer(self,... | null |
33,560 | import torch
import torch.nn as nn
class residual_template(nn.Module):
expansion = 4
def __init__(self, in_channels, out_channels, stride=1, identity_downsample=None):
super().__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2... | null |
33,561 | import torch
import visdom
import os
def save_checkpoint(filename, model, optimizer, train_acc, epoch):
save_state = {
"state_dict": model.state_dict(),
"acc": train_acc,
"epoch": epoch + 1,
"optimizer": optimizer.state_dict(),
}
print()
print("Saving current parameters"... | null |
33,562 | import torch
import visdom
import os
device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.float32
def check_accuracy(loader, model):
if loader.dataset.train:
print("Checking accuracy on training or validation set")
else:
print("Checking accuracy on test set")
num_correct = ... | null |
33,563 | import torch
import visdom
import os
def load_model(args, model, optimizer):
if args.resume:
model.eval()
if os.path.isfile(args.resume):
print("=> loading checkpoint '{}'".format(args.resume))
checkpoint = torch.load(args.resume)
start_epoch = checkpoint["epoch"... | null |
33,564 | import pandas as pd
import nltk
from nltk.corpus import words
vocabulary = {}
set_words = set(words.words())
def build_vocabulary(curr_email):
idx = len(vocabulary)
for word in curr_email:
if word.lower() not in vocabulary and word.lower() in set_words:
vocabulary[word] = idx
id... | null |
33,565 | from block import (
auxiliary_block,
convolution_block,
inception_block,
)
from tensorflow.keras.layers import (
AveragePooling2D,
Dense,
Dropout,
Input,
MaxPooling2D,
)
from tensorflow.keras import Model
import tensorflow as tf
import typing
def convolution_block(
X: tf.Tensor,
... | Implementation of the popular GoogLeNet aka Inception v1 architecture. Refer to the original paper, page 6 - table 1 for inception block filter sizes. Arguments: input_shape -- shape of the images of the dataset classes -- number of classes for classification Returns: model -- a Model() instance in Keras |
33,566 | from tensorflow.keras.layers import (
Conv2D,
Dense,
Dropout,
Flatten,
Input,
Lambda,
MaxPooling2D,
)
from tensorflow.keras import Model
import tensorflow as tf
import typing
tf.config.run_functions_eagerly(True)
The provided code snippet includes necessary dependencies for implementing the... | Implementation of the AlexNet architecture. Arguments: input_shape -- shape of the images of the dataset classes -- integer, number of classes Returns: model -- a Model() instance in Keras Note: when you read the paper, you will notice that the channels (filters) in the diagram is only half of what I have written below... |
33,567 | from block import block
from tensorflow.keras.layers import (
Activation,
AveragePooling2D,
BatchNormalization,
Conv2D,
Dense,
Flatten,
Input,
MaxPooling2D,
ZeroPadding2D,
)
from tensorflow.keras import Model
import tensorflow as tf
import typing
def make_layer(X: tf.Tensor, layers: ... | Implementation of the popular ResNet architecture. Arguments: name -- name of the architecture layers -- number of blocks per layer input_shape -- shape of the images of the dataset classes -- integer, number of classes Returns: model -- a Model() instance in Keras Model Architecture: Resnet50: CONV2D -> BATCHNORM -> R... |
33,568 | from tensorflow.keras.layers import (
AveragePooling2D,
Conv2D,
Dense,
Flatten,
Input,
)
from tensorflow.keras import Model
import tensorflow as tf
import typing
The provided code snippet includes necessary dependencies for implementing the `LeNet5` function. Write a Python function `def LeNet5(inp... | Implementation of the classic LeNet architecture. Arguments: input_shape -- shape of the images of the dataset classes -- integer, number of classes Returns: model -- a Model() instance in Keras Note: because I want to keep it original, I used tanh activation instead of ReLU activation. however based on newer papers, t... |
33,569 | from tensorflow.keras.layers import (
Activation,
BatchNormalization,
Conv2D,
Dense,
Dropout,
Flatten,
Input,
MaxPooling2D,
)
from tensorflow.keras import Model
import tensorflow as tf
import typing
def make_conv_layer(
X: tf.Tensor,
architecture: typing.List[ typing.Union[int, s... | Implementation of the VGGNet architecture. Arguments: name -- name of the architecture architecture -- number of output channel per convolution layers in VGGNet input_shape -- shape of the images of the dataset classes -- integer, number of classes Returns: model -- a Model() instance in Keras |
33,570 | import os
import tensorflow as tf
import pandas as pd
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
import pickle
import sys
import sys
def filter_train(line):
split_line = tf.strings.split(line, ",", maxsplit=4)
dataset_belonging = split_line[1] # train, ... | null |
33,571 | import os
import tensorflow as tf
import pandas as pd
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
import pickle
import sys
import sys
def filter_test(line):
split_line = tf.strings.split(line, ",", maxsplit=4)
dataset_belonging = split_line[1] # train, t... | null |
33,572 | import os
import tensorflow as tf
import pandas as pd
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
import pickle
tokenizer = tfds.features.text.Tokenizer()
import sys
for line in dataset:
print(line)
import sys
tokenizer = tfds.features.text.Tokenizer()
vocabul... | Build a vocabulary |
33,573 | import os
import tensorflow as tf
import pandas as pd
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
import pickle
import sys
import sys
def my_encoder(text_tensor, label):
encoded_text = encoder.encode(text_tensor.numpy())
return encoded_text, label
def enc... | null |
33,574 | import os
import tensorflow as tf
import math
import tensorflow_hub as hub
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras import layers
from sklearn.metrics import roc_curve
from tensorflow.keras.preprocessing.image import ImageDataGenerator
model = keras.models.lo... | null |
33,575 | import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, regularizers
from tensorflow.keras.datasets import cifar10
model = my_model()
model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer=keras.optimizers.Adam(lr=3e-4),
metric... | null |
33,576 | import os
import matplotlib.pyplot
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow_datasets as tfds
tf.config.experimental.set_memory_growth(physical_devices[0], True)
The provided code snippet includes necessary dependencies for implementing the `normalize_im... | Normalizes images |
33,577 | import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow_datasets as tfds
The provided code snippet includes necessary dependencies for implementing the `normalize_img` function. Write a Python function `def normalize_img(image, label)` to solve the following... | Normalizes images |
33,578 | import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow_datasets as tfds
def augment(image, label):
new_height = new_width = 32
image = tf.image.resize(image, (new_height, new_width))
if tf.random.uniform((), minval=0, maxval=1) < 0.1:
i... | null |
33,579 | import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import mnist
import tensorflow_datasets as tfds
tf.config.experimental.set_memory_growth(physical_devices[0], True)
The provided code snippet includes necessary dependencies for implementin... | Normalizes images |
33,581 | import os
import matplotlib.pyplot
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow_datasets as tfds
(ds_train, ds_test), ds_info = tfds.load(
"mnist",
split=["train", "test"],
shuffle_files=True,
as_supervised=True, # will return tuple (img, la... | null |
33,582 | import os
import matplotlib.pyplot
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow_datasets as tfds
tf.config.experimental.set_memory_growth(physical_devices[0], True)
def my_enc(text_tensor, label):
encoded_text = encoder.encode(text_tensor.numpy())
re... | null |
33,583 | import os
import tensorflow as tf
import pandas as pd
from tensorflow import keras
from tensorflow.keras import layers
directory = "data/mnist_images_csv/"
def read_image(image_file, label):
image = tf.io.read_file(directory + image_file)
image = tf.image.decode_image(image, channels=1, dtype=tf.float32)
r... | null |
33,584 | import os
import tensorflow as tf
import pandas as pd
from tensorflow import keras
from tensorflow.keras import layers
def augment(image, label):
# data augmentation here
return image, label | null |
33,585 | import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.preprocessing.image import ImageDataGenerator
def augment(x, y):
image = tf.image.random_brightness(x, max_delta=0.05)
return image, y | null |
33,586 | import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.preprocessing.image import ImageDataGenerator
def training():
pass | null |
33,587 | import os
import tensorflow as tf
import pandas as pd
from tensorflow import keras
from tensorflow.keras import layers
import pathlib
def process_path(file_path):
image = tf.io.read_file(file_path)
image = tf.image.decode_jpeg(image, channels=1)
label = tf.strings.split(file_path, "\\")
label = tf.stri... | null |
33,588 | import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, regularizers
from tensorflow.keras.datasets import mnist
import pandas as pd
tf.config.experimental.set_memory_growth(physical_devices[0], True)
def read_image(image_path, label):
image = tf.io.read_file(image_path)... | null |
33,589 | import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import cifar10
model = keras.Sequential(
[
keras.Input(shape=(32, 32, 3)),
layers.Conv2D(32, 3, padding="valid", activation="relu"),
layers.MaxPooling2D(),
... | null |
33,590 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorboard.plugins.hparams import api as hp
from tensorflow import keras
from tensorflow.keras import layers
tf.config.experimental.set_memory_growth(physical_devices[0], True)
The pr... | Normalizes images |
33,591 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorboard.plugins.hparams import api as hp
from tensorflow import keras
from tensorflow.keras import layers
tf.config.experimental.set_memory_growth(physical_devices[0], True)
def au... | null |
33,592 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorboard.plugins.hparams import api as hp
from tensorflow import keras
from tensorflow.keras import layers
tf.config.experimental.set_memory_growth(physical_devices[0], True)
(ds_tra... | null |
33,593 | import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
import numpy as np
import io
import sklearn.metrics
from tensorboard.plugins import projector
import cv2
import os
import shutil
def image_grid(data, labels, class_names):
# Data should be in (BATCH_SIZE, H, W, C)
assert data.... | null |
33,594 | import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
import numpy as np
import io
import sklearn.metrics
from tensorboard.plugins import projector
import cv2
import os
import shutil
def get_confusion_matrix(y_labels, logits, class_names):
preds = np.argmax(logits, axis=1)
cm = s... | null |
33,595 | import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
import numpy as np
import io
import sklearn.metrics
from tensorboard.plugins import projector
import cv2
import os
import shutil
def plot_to_image(figure):
"""Converts the matplotlib plot specified by 'figure' to a PNG image and
... | null |
33,596 | import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
import numpy as np
import io
import sklearn.metrics
from tensorboard.plugins import projector
import cv2
import os
import shutil
def create_sprite(data):
"""
Tile images into sprite image.
Add any necessary padding
"""
... | null |
33,597 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
from utils import get_confusion_matrix, plot_confusion_matrix
tf.config.experimental.set_memory_growth(physical_devices[0], T... | Normalizes images |
33,598 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
from utils import get_confusion_matrix, plot_confusion_matrix
tf.config.experimental.set_memory_growth(physical_devices[0], T... | null |
33,599 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
from utils import get_confusion_matrix, plot_confusion_matrix
model = get_model()
def get_model():
model = keras.Sequent... | null |
33,600 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
tf.config.experimental.set_memory_growth(physical_devices[0], True)
tf.summary.trace_on(graph=True, profiler=True)
def my_fu... | null |
33,601 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
from utils import plot_to_projector
tf.config.experimental.set_memory_growth(physical_devices[0], True)
The provided code sn... | Normalizes images |
33,602 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
from utils import plot_to_projector
def augment(image, label):
return image, label | null |
33,603 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
tf.config.experimental.set_memory_growth(physical_devices[0], True)
The provided code snippet includes necessary dependencie... | Normalizes images |
33,604 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
tf.config.experimental.set_memory_growth(physical_devices[0], True)
def augment(image, label):
if tf.random.uniform((), ... | null |
33,605 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
model = get_model()
def get_model():
model = keras.Sequential(
[
layers.Input((32, 32, 3)),
... | null |
33,608 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
model = get_model()
model.compile(
optimizer=keras.optimizers.Adam(lr=0.001),
loss=keras.losses.SparseCategoricalCros... | null |
33,609 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
from utils import plot_to_image, image_grid
tf.config.experimental.set_memory_growth(physical_devices[0], True)
The provided... | Normalizes images |
33,610 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
from utils import plot_to_image, image_grid
tf.config.experimental.set_memory_growth(physical_devices[0], True)
def augment(... | null |
33,611 | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
from utils import plot_to_image, image_grid
model = get_model()
def get_model():
model = keras.Sequential(
[
... | null |
33,612 | import numpy as np
import matplotlib.pyplot as plt
def create_dataset(N, D=2, K=2):
X = np.zeros((N * K, D)) # data matrix (each row = single example)
y = np.zeros(N * K) # class labels
for j in range(K):
ix = range(N * j, N * (j + 1))
r = np.linspace(0.0, 1, N) # radius
t = np.... | null |
33,613 | import numpy as np
import matplotlib.pyplot as plt
def plot_contour(X, y, svm):
# plot the resulting classifier
h = 0.01
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, ... | null |
33,614 | import numpy as np
import cvxopt
from utils import create_dataset, plot_contour
def linear(x, z):
return np.dot(x, z.T) | null |
33,615 | import numpy as np
import cvxopt
from utils import create_dataset, plot_contour
def polynomial(x, z, p=5):
return (1 + np.dot(x, z.T)) ** p | null |
33,616 | import numpy as np
import cvxopt
from utils import create_dataset, plot_contour
def gaussian(x, z, sigma=0.1):
return np.exp(-np.linalg.norm(x - z, axis=1) ** 2 / (2 * (sigma ** 2))) | null |
33,617 | import numpy as np
def linear_regression_normal_equation(X, y):
ones = np.ones((X.shape[0], 1))
X = np.append(ones, X, axis=1)
W = np.dot(np.linalg.pinv(np.dot(X.T, X)), np.dot(X.T, y))
return W | null |
33,618 | import numpy as np
import matplotlib.pyplot as plt
def create_dataset(N, K=2):
N = 100 # number of points per class
D = 2
X = np.zeros((N * K, D)) # data matrix (each row = single example)
y = np.zeros(N * K) # class labels
for j in range(K):
ix = range(N * j, N * (j + 1))
r = n... | null |
33,619 | import numpy as np
import matplotlib.pyplot as plt
def plot_contour(X, y, model, parameters):
# plot the resulting classifier
h = 0.02
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(... | null |
33,620 | import torch
import albumentations as A
from albumentations.pytorch import ToTensorV2
from tqdm import tqdm
import torch.nn as nn
import torch.optim as optim
from model import UNET
from utils import (
load_checkpoint,
save_checkpoint,
get_loaders,
check_accuracy,
save_predictions_as_imgs,
)
DEVICE =... | null |
33,621 | import torch
import torchvision
from dataset import CarvanaDataset
from torch.utils.data import DataLoader
def save_checkpoint(state, filename="my_checkpoint.pth.tar"):
print("=> Saving checkpoint")
torch.save(state, filename) | null |
33,622 | import torch
import torchvision
from dataset import CarvanaDataset
from torch.utils.data import DataLoader
def load_checkpoint(checkpoint, model):
print("=> Loading checkpoint")
model.load_state_dict(checkpoint["state_dict"]) | null |
33,623 | import torch
import torchvision
from dataset import CarvanaDataset
from torch.utils.data import DataLoader
class CarvanaDataset(Dataset):
def __init__(self, image_dir, mask_dir, transform=None):
self.image_dir = image_dir
self.mask_dir = mask_dir
self.transform = transform
self.imag... | null |
33,624 | import torch
import torchvision
from dataset import CarvanaDataset
from torch.utils.data import DataLoader
def check_accuracy(loader, model, device="cuda"):
num_correct = 0
num_pixels = 0
dice_score = 0
model.eval()
with torch.no_grad():
for x, y in loader:
x = x.to(device)
... | null |
33,625 | import torch
import torchvision
from dataset import CarvanaDataset
from torch.utils.data import DataLoader
def save_predictions_as_imgs(
loader, model, folder="saved_images/", device="cuda"
):
model.eval()
for idx, (x, y) in enumerate(loader):
x = x.to(device=device)
with torch.no_grad():
... | null |
33,626 | import torch
import torch.nn as nn
class LeNet(nn.Module):
def __init__(self):
def forward(self, x):
def test_lenet():
x = torch.randn(64, 1, 32, 32)
model = LeNet()
return model(x) | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.