Skip to content

Instantly share code, notes, and snippets.

@crowsonkb
crowsonkb / cov.py
Created January 15, 2021 21:59
Computes the covariance matrix in PyTorch.
"""Computes the covariance matrix in PyTorch."""
def cov_mean(input, unbiased=True, keepdims=False):
n = input.shape[-1] - unbiased
mean = input.mean(dim=-1, keepdims=True)
dev = input - mean
mean = mean if keepdims else mean[..., 0]
return dev @ dev.transpose(-1, -2) / n, mean
from torch.nn import functional as F
from torchvision import transforms
def random_shift(input, max_shift, mode='replicate', value=0):
padded = F.pad(input, max_shift, mode=mode, value=value)
return transforms.RandomCrop(input.shape[2:])(padded)
from torch import nn
class Lambda(nn.Module):
"""Wraps a callable in an :class:`nn.Module` without registering it."""
def __init__(self, func):
super().__init__()
object.__setattr__(self, 'forward', func)
@crowsonkb
crowsonkb / pretty_parse_results.py
Last active June 11, 2019 00:40
Pretty printer for pyparsing.ParseResults
from prettyprinter import register_pretty, pretty_call
import pyparsing as pp
@register_pretty(pp.ParseResults)
def pretty_parse_results(value, ctx):
return pretty_call(ctx, pp.ParseResults, value.asList(), value.asDict())
@crowsonkb
crowsonkb / conf.py
Created June 2, 2019 11:47
Monkey patching pygments inside Sphinx documentation configuration
# The name of the Pygments (syntax highlighting) style to use.
sys.path.append('.')
import pygments.styles
import base16_spacemacs_kat
# pygments.styles.base16_spacemacs_kat = base16_spacemacs_kat
sys.modules['pygments.styles.' + 'base16_spacemacs_kat'] = base16_spacemacs_kat
pygments.styles.STYLE_MAP['base16-spacemacs-kat'] = 'base16_spacemacs_kat::Base16SpacemacsStyle'
pygments_style = 'base16-spacemacs-kat' # 'friendly'
@crowsonkb
crowsonkb / site.cfg
Last active July 25, 2019 11:31
site.cfg for building scipy against MKL on macOS
# This file provides configuration information about non-Python dependencies for
# numpy.distutils-using packages. Create a file like this called "site.cfg" next
# to your package's setup.py file and fill in the appropriate sections. Not all
# packages will use all sections so you should leave out sections that your
# package does not use.
# To assist automatic installation like easy_install, the user's home directory
# will also be checked for the file ~/.numpy-site.cfg .
# The format of the file is that of the standard library's ConfigParser module.
name: "thing"
layer {
name: "data"
type: "Data"
top: "big_data"
top: "label"
include { phase: TRAIN }
transform_param {
mean_value: 103.939
mean_value: 116.779
@crowsonkb
crowsonkb / benchmark.py
Last active January 27, 2019 00:01
A with-statement context manager to benchmark code.
"""A with-statement context manager to benchmark code."""
import time
__all__ = ['Benchmark']
class Benchmark:
"""A with-statement context manager to benchmark code."""
def __init__(self, timer=time.perf_counter):
@crowsonkb
crowsonkb / format_fragments.py
Created January 6, 2019 05:50
The prompt-toolkit utility function format_fragments().
"""The prompt-toolkit utility function :func:`format_fragments`."""
from prompt_toolkit.formatted_text import FormattedText
def format_fragments(fragments, *args, **kwargs):
"""Applies :meth:`str.format` to each text fragment in `fragments`.
Args:
fragments (FormattedText): The input list of text fragments.
import inspect
import typing
from typing import get_type_hints, TypeVar, Any, AnyStr, Generic, Union
from sphinx.util import logging
from sphinx.util.inspect import Signature
try:
from typing_extensions import Protocol
except ImportError: