Skip to content

Instantly share code, notes, and snippets.

View thomwolf's full-sized avatar
🚂
training

Thomas Wolf thomwolf

🚂
training
View GitHub Profile
@thomwolf
thomwolf / simple_pytorch_dataset.py
Created October 3, 2017 11:48
A simple pyTorch Dataset class
class DeepMojiDataset(Dataset):
""" A simple Dataset class.
# Arguments:
X_in: Inputs of the given dataset.
y_in: Outputs of the given dataset.
# __getitem__ output:
(torch.LongTensor, torch.LongTensor)
"""
def __init__(self, X_in, y_in):
@thomwolf
thomwolf / smart_batch_sampler.py
Created October 3, 2017 11:50
A pyTorch BatchSampler that enables large epochs on small datasets and balanced sampling from unbalanced datasets
class DeepMojiBatchSampler(object):
"""A Batch sampler that enables larger epochs on small datasets and
has upsampling functionality.
# Arguments:
y_in: Labels of the dataset.
batch_size: Batch size.
epoch_size: Number of samples in an epoch.
upsample: Whether upsampling should be done. This flag should only be
set on binary class problems.
seed: Random number generator seed.
@thomwolf
thomwolf / neuralcoref.py
Last active March 22, 2018 22:04
The Neuralcoref pyTorch model
class Model(nn.Module):
def __init__(self, vocab_size, embed_dim, H1, H2, H3, pairs_in, single_in, drop=0.5):
super(Model, self).__init__()
self.embed = nn.Embedding(vocab_size, embedding_dim)
self.drop = nn.Dropout(drop)
self.pairs = nn.Sequential(nn.Linear(pairs_in, H1), nn.ReLU(), nn.Dropout(drop),
nn.Linear(H1, H2), nn.ReLU(), nn.Dropout(drop),
nn.Linear(H2, H3), nn.ReLU(), nn.Dropout(drop),
nn.Linear(H3, 1),
nn.Linear(1, 1))
@thomwolf
thomwolf / get_params.py
Last active April 3, 2018 08:48
A PyTorch iterator over module parameters that allows to update module parameters (and not only the data tensor).
def get_params(module, memo=None, pointers=None):
""" Returns an iterator over PyTorch module parameters that allows to update parameters
(and not only the data).
! Side effect: update shared parameters to point to the first yield instance
(i.e. you can update shared parameters and keep them shared)
Yields:
(Module, string, Parameter): Tuple containing the parameter's module, name and pointer
"""
if memo is None:
memo = set()
@thomwolf
thomwolf / rectangle_class.py
Last active June 6, 2018 08:29
A simple Python Rectangle class
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
@thomwolf
thomwolf / rectangle_struct.pyx
Created June 6, 2018 09:19
A C structure for a rectangle
cdef struct Rectangle:
float w
float h
@thomwolf
thomwolf / slow_python_loop.py
Last active June 6, 2018 22:46
Example of Python loop to count the occurrences of the word "run" tagged as noun by spaCy in a portion of Wikitext2
def slow_loop(doc_list, word, tag):
n_out = 0
for doc in doc_list:
for tok in doc:
if tok.lower_ == word and tok.tag_ == tag:
n_out += 1
return n_out
def main_nlp_slow(doc_list):
n_out = slow_loop(doc_list, 'run', 'NN')
@thomwolf
thomwolf / download_big_doc.py
Last active June 7, 2018 08:28
Download and parse an extract of wikitext-2 with ~170k words
import urllib.request
import spacy
with urllib.request.urlopen('https://raw.githubusercontent.com/pytorch/examples/master/word_language_model/data/wikitext-2/valid.txt') as response:
text = response.read()
nlp = spacy.load('en')
doc_list = list(nlp(text[:800000].decode('utf8')) for i in range(10))
@thomwolf
thomwolf / slow_loop.py
Last active June 11, 2018 10:06
A Python loop on a list of Python objects
from random import random
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
def check_rectangles(rectangles, threshold):
@thomwolf
thomwolf / fast_cython_loop.pyx
Last active June 11, 2018 13:50
Example of Cython loop to count the occurrences of the word "run" tagged as noun by spaCy in a portion of Wikitext2
%%cython -+
import numpy # Sometime we have a fail to import numpy compilation error if we don't import numpy
from cymem.cymem cimport Pool
from spacy.tokens.doc cimport Doc
from spacy.typedefs cimport hash_t
from spacy.structs cimport TokenC
cdef struct DocElement:
TokenC* c
int length