code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
col, row = [math.floor(a) for a in (~self.affine * (x, y))]
return row, col | def index(self, x, y) | Given (x, y) in crs, return the (row, column) on the raster | 10.157124 | 6.7186 | 1.511792 |
# Calculate the window
if bounds and window:
raise ValueError("Specify either bounds or window")
if bounds:
win = bounds_window(bounds, self.affine)
elif window:
win = window
else:
raise ValueError("Specify either bounds o... | def read(self, bounds=None, window=None, masked=False) | Performs a boundless read against the underlying array source
Parameters
----------
bounds: bounding box
in w, s, e, n order, iterable, optional
window: rasterio-style window, optional
bounds OR window are required,
specifying both or neither will rai... | 3.762894 | 3.423414 | 1.099164 |
for i in range(0, len(data), n):
yield data[i:i+n] | def chunks(data, n) | Yield successive n-sized chunks from a slice-able iterable. | 1.919817 | 1.888222 | 1.016733 |
error = True
back_bits = 0
self.dev_write(0x0D, 0x07)
(error, back_data, back_bits) = self.card_write(self.mode_transrec, [req_mode, ])
if error or (back_bits != 0x10):
return (True, None)
return (False, back_bits) | def request(self, req_mode=0x26) | Requests for tag.
Returns (False, None) if no tag is present, otherwise returns (True, tag type) | 6.76021 | 6.592191 | 1.025487 |
back_data = []
serial_number = []
serial_number_check = 0
self.dev_write(0x0D, 0x00)
serial_number.append(self.act_anticl)
serial_number.append(0x20)
(error, back_data, back_bits) = self.card_write(self.mode_transrec, serial_number)
if not erro... | def anticoll(self) | Anti-collision detection.
Returns tuple of (error state, tag ID). | 4.823598 | 4.340934 | 1.111189 |
back_data = []
buf = []
buf.append(self.act_select)
buf.append(0x70)
for i in range(5):
buf.append(uid[i])
crc = self.calculate_crc(buf)
buf.append(crc[0])
buf.append(crc[1])
(error, back_data, back_length) = self.card_writ... | def select_tag(self, uid) | Selects tag for further usage.
uid -- list or tuple with four bytes tag ID
Returns error state. | 4.888722 | 4.193363 | 1.165824 |
buf = []
buf.append(auth_mode)
buf.append(block_address)
for i in range(len(key)):
buf.append(key[i])
for i in range(4):
buf.append(uid[i])
(error, back_data, back_length) = self.card_write(self.mode_auth, buf)
if not (self.dev_... | def card_auth(self, auth_mode, block_address, key, uid) | Authenticates to use specified block address. Tag must be selected using select_tag(uid) before auth.
auth_mode -- RFID.auth_a or RFID.auth_b
key -- list or tuple with six bytes key
uid -- list or tuple with four bytes tag ID
Returns error state. | 3.923576 | 3.737693 | 1.049732 |
buf = []
buf.append(self.act_end)
buf.append(0)
crc = self.calculate_crc(buf)
self.clear_bitmask(0x08, 0x80)
self.card_write(self.mode_transrec, buf)
self.clear_bitmask(0x08, 0x08)
self.authed = False | def halt(self) | Switch state to HALT | 6.805897 | 6.410195 | 1.06173 |
buf = []
buf.append(self.act_read)
buf.append(block_address)
crc = self.calculate_crc(buf)
buf.append(crc[0])
buf.append(crc[1])
(error, back_data, back_length) = self.card_write(self.mode_transrec, buf)
if len(back_data) != 16:
error... | def read(self, block_address) | Reads data from block. You should be authenticated before calling read.
Returns tuple of (error state, read data). | 4.786901 | 4.582163 | 1.044681 |
buf = []
buf.append(self.act_write)
buf.append(block_address)
crc = self.calculate_crc(buf)
buf.append(crc[0])
buf.append(crc[1])
(error, back_data, back_length) = self.card_write(self.mode_transrec, buf)
if not(back_length == 4) or not((back_data... | def write(self, block_address, data) | Writes data to block. You should be authenticated before calling write.
Returns error state. | 2.428475 | 2.371159 | 1.024172 |
if self.debug:
print("Selecting UID " + str(uid))
if self.uid != None:
self.deauth()
self.uid = uid
return self.rfid.select_tag(uid) | def set_tag(self, uid) | Sets tag for further operations.
Calls deauth() if card is already set.
Calls RFID select_tag().
Returns called select_tag() error state. | 5.996481 | 3.261658 | 1.838477 |
self.method = auth_method
self.key = key
if self.debug:
print("Changing used auth key to " + str(key) + " using method " + ("A" if auth_method == self.rfid.auth_a else "B")) | def auth(self, auth_method, key) | Sets authentication info for current tag | 6.766288 | 6.731719 | 1.005135 |
self.method = None
self.key = None
self.last_auth = None
if self.debug:
print("Changing auth key and method to None")
if self.rfid.authed:
self.rfid.stop_crypto()
if self.debug:
print("Stopping crypto1") | def deauth(self) | Resets authentication info. Calls stop_crypto() if RFID is in auth state | 7.152585 | 5.330322 | 1.341867 |
auth_data = (block_address, self.method, self.key, self.uid)
if (self.last_auth != auth_data) or force:
if self.debug:
print("Calling card_auth on UID " + str(self.uid))
self.last_auth = auth_data
return self.rfid.card_auth(self.method, block... | def do_auth(self, block_address, force=False) | Calls RFID card_auth() with saved auth information if needed.
Returns error state from method call. | 3.644982 | 2.983874 | 1.22156 |
addr = self.block_addr(sector, 3)
return self.rewrite(addr, key_a[:6] + auth_bits[:3] + (user_data, ) + key_b[:6]) | def write_trailer(self, sector, key_a=(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF), auth_bits=(0xFF, 0x07, 0x80),
user_data=0x69, key_b=(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF)) | Writes sector trailer of specified sector. Tag and auth must be set - does auth.
If value is None, value of byte is kept.
Returns error state. | 5.885005 | 6.673246 | 0.88188 |
if not self.is_tag_set_auth():
return True
error = self.do_auth(block_address)
if not error:
(error, data) = self.rfid.read(block_address)
if not error:
for i in range(len(new_bytes)):
if new_bytes[i] != None:
... | def rewrite(self, block_address, new_bytes) | Rewrites block with new bytes, keeping the old ones if None is passed. Tag and auth must be set - does auth.
Returns error state. | 3.134577 | 2.788827 | 1.123977 |
if not self.is_tag_set_auth():
return True
error = self.do_auth(block_address)
if not error:
(error, data) = self.rfid.read(block_address)
print(self.sector_string(block_address) + ": " + str(data))
else:
print("Error on " + self.... | def read_out(self, block_address) | Prints sector/block number and contents of block. Tag and auth must be set - does auth. | 5.15459 | 3.95027 | 1.30487 |
byte_6 = ((~c2[3] & 1) << 7) + ((~c2[2] & 1) << 6) + ((~c2[1] & 1) << 5) + ((~c2[0] & 1) << 4) + \
((~c1[3] & 1) << 3) + ((~c1[2] & 1) << 2) + ((~c1[1] & 1) << 1) + (~c1[0] & 1)
byte_7 = ((c1[3] & 1) << 7) + ((c1[2] & 1) << 6) + ((c1[1] & 1) << 5) + ((c1[0] & 1) << 4) + \
... | def get_access_bits(self, c1, c2, c3) | Calculates the access bits for a sector trailer based on their access conditions
c1, c2, c3, c4 are 4 items tuples containing the values for each block
returns the 3 bytes for the sector trailer | 1.274071 | 1.26201 | 1.009558 |
X, y = make_classification(
n_samples=n_samples,
n_features=N_FEATURES,
n_classes=N_CLASSES,
random_state=0,
)
X = X.astype(np.float32)
return X, y | def get_data(n_samples=100) | Get synthetic classification data with n_samples samples. | 1.941426 | 1.867783 | 1.039428 |
model = NeuralNetClassifier(MLPClassifier)
if with_pipeline:
model = Pipeline([
('scale', FeatureUnion([
('minmax', MinMaxScaler()),
('normalize', Normalizer()),
])),
('select', SelectKBest(k=N_FEATURES)), # keep input size consta... | def get_model(with_pipeline=False) | Get a multi-layer perceptron model.
Optionally, put it in a pipeline that scales the data. | 5.144189 | 5.205653 | 0.988193 |
if not output_file:
return
with open(output_file, 'wb') as f:
pickle.dump(model, f)
print("Saved model to file '{}'.".format(output_file)) | def save_model(model, output_file) | Save model to output_file, if given | 2.60254 | 2.428488 | 1.071671 |
model = get_model(with_pipeline=False)
# important: wrap the model with the parsed arguments
parsed = parse_args(kwargs, defaults=DEFAULTS_NET)
model = parsed(model)
X, y = get_data(n_samples=n_samples)
print("Training MLP classifier")
model.fit(X, y)
save_model(model, output_fil... | def net(n_samples=100, output_file=None, **kwargs) | Train an MLP classifier on synthetic data.
n_samples : int (default=100)
Number of training samples
output_file : str (default=None)
If not None, file name used to save the model.
kwargs : dict
Additional model parameters. | 5.748944 | 5.93434 | 0.968759 |
model = get_model(with_pipeline=True)
# important: wrap the model with the parsed arguments
parsed = parse_args(kwargs, defaults=DEFAULTS_PIPE)
model = parsed(model)
X, y = get_data(n_samples=n_samples)
print("Training MLP classifier in a pipeline")
model.fit(X, y)
save_model(mod... | def pipeline(n_samples=100, output_file=None, **kwargs) | Train an MLP classifier in a pipeline on synthetic data.
The pipeline scales the input data before passing it to the net.
Note: This docstring is used to create the help for the CLI.
Parameters
----------
n_samples : int (default=100)
Number of training samples
output_file : str (defau... | 5.998775 | 6.156586 | 0.974367 |
units = [N_FEATURES]
units += [self.hidden_units] * self.num_hidden
units += [N_CLASSES]
sequence = []
for u0, u1 in zip(units, units[1:]):
sequence.append(nn.Linear(u0, u1))
sequence.append(self.nonlin)
sequence.append(nn.Dropout(sel... | def reset_params(self) | (Re)set all parameters. | 3.002907 | 3.013531 | 0.996474 |
y_preds = []
for yp in self.forward_iter(X, training=False):
yp = yp[0] if isinstance(yp, tuple) else yp
y_preds.append(to_numpy(yp.max(-1)[-1]))
y_pred = np.concatenate(y_preds, 0)
return y_pred | def predict(self, X) | Where applicable, return class labels for samples in X.
If the module's forward method returns multiple outputs as a
tuple, it is assumed that the first output contains the
relevant information and the other values are ignored. If all
values are relevant, consider using
:func:`~... | 3.241972 | 3.713423 | 0.873042 |
# pylint: disable=useless-super-delegation
# this is actually a pylint bug:
# https://github.com/PyCQA/pylint/issues/1085
return super().fit(X, y, **fit_params) | def fit(self, X, y, **fit_params) | See ``NeuralNet.fit``.
In contrast to ``NeuralNet.fit``, ``y`` is non-optional to
avoid mistakenly forgetting about ``y``. However, ``y`` can be
set to ``None`` in case it is derived dynamically from
``X``. | 3.131778 | 3.502859 | 0.894063 |
y_probas = []
bce_logits_loss = isinstance(
self.criterion_, torch.nn.BCEWithLogitsLoss)
for yp in self.forward_iter(X, training=False):
yp = yp[0] if isinstance(yp, tuple) else yp
if bce_logits_loss:
yp = torch.sigmoid(yp)
... | def predict_proba(self, X) | Where applicable, return probability estimates for
samples.
If the module's forward method returns multiple outputs as a
tuple, it is assumed that the first output contains the
relevant information and the other values are ignored. If all
values are relevant, consider using
... | 3.072616 | 3.625655 | 0.847465 |
apply_ = partial(_apply_to_data, func=func, unpack_dict=unpack_dict)
if isinstance(data, dict):
if unpack_dict:
return [apply_(v) for v in data.values()]
return {k: apply_(v) for k, v in data.items()}
if isinstance(data, (list, tuple)):
try:
# e.g.list/... | def _apply_to_data(data, func, unpack_dict=False) | Apply a function to data, trying to unpack different data
types. | 2.511514 | 2.675678 | 0.938646 |
if isinstance(ds, torch.utils.data.Subset):
return uses_placeholder_y(ds.dataset)
return isinstance(ds, Dataset) and hasattr(ds, "y") and ds.y is None | def uses_placeholder_y(ds) | If ``ds`` is a ``skorch.dataset.Dataset`` or a
``skorch.dataset.Dataset`` nested inside a
``torch.utils.data.Subset`` and uses
y as a placeholder, return ``True``. | 3.218579 | 2.819751 | 1.141441 |
# Note: This function cannot detect it when a user only returns 1
# item that is exactly of length 2 (e.g. because the batch size is
# 2). In that case, the item will be erroneously split into X and
# y.
try:
X, y = data
return X, y
except ValueError:
# if a 1-tuple/... | def unpack_data(data) | Unpack data returned by the net's iterator into a 2-tuple.
If the wrong number of items is returned, raise a helpful error
message. | 6.980777 | 6.223781 | 1.12163 |
# pylint: disable=anomalous-backslash-in-string
# pytorch DataLoader cannot deal with None so we use 0 as a
# placeholder value. We only return a Tensor with one value
# (as opposed to ``batchsz`` values) since the pytorch
# DataLoader calls __getitem__ for each row in t... | def transform(self, X, y) | Additional transformations on ``X`` and ``y``.
By default, they are cast to PyTorch :class:`~torch.Tensor`\s.
Override this if you want a different behavior.
Note: If you use this in conjuction with PyTorch
:class:`~torch.utils.data.DataLoader`, the latter will call
the dataset... | 9.295887 | 9.258513 | 1.004037 |
y_arr = None
if self.stratified:
# Try to convert y to numpy for sklearn's check_cv; if conversion
# doesn't work, still try.
try:
y_arr = to_numpy(y)
except (AttributeError, TypeError):
y_arr = y
if self._... | def check_cv(self, y) | Resolve which cross validation strategy is used. | 5.013124 | 4.927687 | 1.017338 |
assert os.path.exists(path)
# Add words to the dictionary
with open(path, 'r') as f:
tokens = 0
for line in f:
words = line.split() + ['<eos>']
tokens += len(words)
for word in words:
self.dictio... | def tokenize(self, path) | Tokenizes a text file. | 1.491637 | 1.491631 | 1.000004 |
i, j = -1, -1
match = pattern.match(s)
if not match:
return i, j
for group_name in pattern.groupindex:
i, j = match.span(group_name)
if (i, j) != (-1, -1):
return i, j
return i, j | def _get_span(s, pattern) | Return the span of the first group that matches the pattern. | 2.657565 | 2.386147 | 1.113747 |
if new_value is None:
return s
# BB: ideally, I would like to replace the 'default*' group
# directly but I haven't found a way to do this
i, j = _get_span(s, pattern=P_DEFAULTS)
if (i, j) == (-1, -1):
return s
return '{}{}{}'.format(s[:i], new_value, s[j:]) | def _substitute_default(s, new_value) | Replaces the default value in a parameter docstring by a new value.
The docstring must conform to the numpydoc style and have the form
"something (keyname=<value-to-replace>)"
If no matching pattern is found or ``new_value`` is None, return
the input untouched.
Examples
--------
>>> _repl... | 6.192321 | 7.711853 | 0.802962 |
if not isinstance(dotted_name, str):
return dotted_name
if '.' not in dotted_name:
return dotted_name
args = None
params = None
match = P_PARAMS.match(dotted_name)
if match:
dotted_name = match.group('name')
params = match.group('params')
module, name ... | def _resolve_dotted_name(dotted_name) | Returns objects from strings
Deals e.g. with 'torch.nn.Softmax(dim=-1)'.
Modified from palladium:
https://github.com/ottogroup/palladium/blob/8a066a9a7690557d9b1b6ed54b7d1a1502ba59e3/palladium/util.py
with added support for instantiated objects. | 2.478628 | 2.608825 | 0.950094 |
if not kwargs:
return kwargs
resolved = {}
for k, v in kwargs.items():
resolved[k] = _resolve_dotted_name(v)
return resolved | def parse_net_kwargs(kwargs) | Parse arguments for the estimator.
Resolves dotted names and instantiated classes.
Examples
--------
>>> kwargs = {'lr': 0.1, 'module__nonlin': 'torch.nn.Hardtanh(-2, max_val=3)'}
>>> parse_net_kwargs(kwargs)
{'lr': 0.1, 'module__nonlin': Hardtanh(min_val=-2, max_val=3)} | 4.007349 | 4.906675 | 0.816714 |
yield from _yield_preproc_steps(model)
net_prefixes = []
module_prefixes = []
if isinstance(model, Pipeline):
name = model.steps[-1][0]
net_prefixes.append(name)
module_prefixes.append(name)
net = model.steps[-1][1]
else:
net = model
yield '__'.joi... | def _yield_estimators(model) | Yield estimator and its prefix from the model.
First, pipeline preprocessing steps are yielded (if there are
any). Next the neural net is yielded. Finally, the module is
yielded. | 3.613335 | 2.997896 | 1.20529 |
from numpydoc.docscrape import ClassDoc
defaults = defaults or {}
estimator = _extract_estimator_cls(estimator)
yield "<{}> options:".format(estimator.__name__)
doc = ClassDoc(estimator)
yield from _get_help_for_params(
doc['Parameters'],
prefix=prefix,
defaults=de... | def _get_help_for_estimator(prefix, estimator, defaults=None) | Yield help lines for the given estimator and prefix. | 5.248086 | 4.484794 | 1.170196 |
defaults = defaults or {}
print("This is the help for the model-specific parameters.")
print("To invoke help for the remaining options, run:")
print("python {} -- --help".format(sys.argv[0]))
print()
lines = (_get_help_for_estimator(prefix, estimator, defaults=defaults) for
p... | def print_help(model, defaults=None) | Print help for the command line arguments of the given model.
Parameters
----------
model : sklearn.base.BaseEstimator
The basic model, e.g. a ``NeuralNet`` or sklearn ``Pipeline``.
defautls : dict or None (default=None)
Optionally, change the default values to use custom
defaults. C... | 6.55268 | 7.675014 | 0.853768 |
try:
import fire
except ImportError:
raise ImportError("Using skorch cli helpers requires the fire library,"
" you can install it with pip: pip install fire.")
try:
import numpydoc.docscrape
except ImportError:
raise ImportError("Using skorc... | def parse_args(kwargs, defaults=None) | Apply command line arguments or show help.
Use this in conjunction with the fire library to quickly build
command line interfaces for your scripts.
This function returns another function that must be called with
the estimator (e.g. ``NeuralNet``) to apply the parsed command
line arguments. If the ... | 3.892743 | 3.136794 | 1.240994 |
warnings.warn(
"For filtering gradients, please use skorch.callbacks.Freezer.",
DeprecationWarning)
for pgroup in pgroups:
output = {k: v for k, v in pgroup.items() if k != 'params'}
output['params'] = (p for p in pgroup['params'] if p.requires_grad)
yield output | def filter_requires_grad(pgroups) | Returns parameter groups where parameters
that don't require a gradient are filtered out.
Parameters
----------
pgroups : dict
Parameter groups to be filtered | 4.197609 | 5.088144 | 0.824979 |
warnings.warn(
"For filtering gradients, please use skorch.callbacks.Freezer.",
DeprecationWarning)
return partial(_make_optimizer, optimizer=optimizer, filter_fn=filter_fn) | def filtered_optimizer(optimizer, filter_fn) | Wraps an optimizer that filters out parameters where
``filter_fn`` over ``pgroups`` returns ``False``.
This function can be used, for example, to filter parameters
that do not require a gradient:
>>> from skorch.helper import filtered_optimizer, filter_requires_grad
>>> optimizer = filtered_optimiz... | 9.2477 | 11.770055 | 0.785697 |
std = torch.Tensor([0.229, 0.224, 0.225]).reshape(-1, 1, 1)
mu = torch.Tensor([0.485, 0.456, 0.406]).reshape(-1, 1, 1)
output = t.mul(std)
output.add_(mu)
img = to_pil_image(output)
w, h = img.size
return img.crop((padding, padding, w - padding, h - padding)) | def convert_cell_to_img(t, padding=16) | Converts pytorch tensor into a Pillow Image. The padding will be removed
from the resulting image | 1.987679 | 1.916407 | 1.03719 |
fig, axes = plt.subplots(len(mask_cells), 3, figsize=(12, 10))
for idx, (axes, mask_cell) in enumerate(zip(axes, mask_cells), 1):
ax1, ax2, ax3 = axes
true_mask, predicted_mask, cell = mask_cell
plot_mask_cell(
true_mask, predicted_mask, cell,
'Type {... | def plot_mask_cells(mask_cells, padding=16) | Plots cells with their true mask, predicted mask.
Parameters
----------
mask_cells: list of tuples (`true_mask`, `predicted_mask`, `cell`)
padding: int (default=16)
Padding around mask to remove. | 2.707691 | 2.4028 | 1.12689 |
for ax in [ax1, ax2, ax3]:
ax.grid(False)
ax.set_xticks([])
ax.set_yticks([])
ax1.imshow(true_mask[padding:-padding, padding:-padding], cmap='viridis')
ax1.set_title('True Mask - {}'.format(suffix))
ax2.imshow(
predicted_mask[padding:-padding, padding:-padding], cmap... | def plot_mask_cell(true_mask,
predicted_mask,
cell,
suffix,
ax1,
ax2,
ax3,
padding=16) | Plots a single cell with a its true mask and predicuted mask | 1.80807 | 1.819634 | 0.993645 |
fig, ((ax1, ax2, ax3)) = plt.subplots(1, 3, figsize=(12, 5))
for ax in [ax1, ax2, ax3]:
ax.grid(False)
ax.set_xticks([])
ax.set_yticks([])
ax1.set_title("Type 1")
ax1.imshow(mask_1, cmap='viridis')
ax2.set_title("Type 2")
ax2.imshow(mask_2, cmap='viridis')
ax3.se... | def plot_masks(mask_1, mask_2, mask_3) | Plots three masks | 1.571496 | 1.59604 | 0.984622 |
fig, ((ax1, ax2, ax3)) = plt.subplots(1, 3, figsize=(12, 5))
for ax in [ax1, ax2, ax3]:
ax.grid(False)
ax.set_xticks([])
ax.set_yticks([])
ax1.set_title("Type 1")
ax1.imshow(cell_1)
ax2.set_title("Type 2")
ax2.imshow(cell_2)
ax3.set_title("Type 3")
ax3.imshow... | def plot_cells(cell_1, cell_2, cell_3) | Plots three cells | 1.602179 | 1.628012 | 0.984132 |
value = row[key]
if isinstance(value, bool) or value is None:
return '+' if value else ''
if not isinstance(value, Number):
return value
# determine if integer value
is_integer = float(value).is_integer()
template = '{}' if is_integer e... | def format_row(self, row, key, color) | For a given row from the table, format it (i.e. floating
points and color if applicable). | 5.431599 | 5.28066 | 1.028583 |
sorted_keys = []
if ('epoch' in keys) and ('epoch' not in self.keys_ignored_):
sorted_keys.append('epoch')
for key in sorted(keys):
if not (
(key in ('epoch', 'dur')) or
(key in self.keys_ignored_) or
k... | def _sorted_keys(self, keys) | Sort keys, dropping the ones that should be ignored.
The keys that are in ``self.ignored_keys`` or that end on
'_best' are dropped. Among the remaining keys:
* 'epoch' is put first;
* 'dur' is put last;
* keys that start with 'event_' are put just before 'dur';
*... | 2.676191 | 2.151582 | 1.243825 |
to_tensor_ = partial(to_tensor, device=device)
if is_torch_data_type(X):
return X.to(device)
if isinstance(X, dict):
return {key: to_tensor_(val) for key, val in X.items()}
if isinstance(X, (list, tuple)):
return [to_tensor_(x) for x in X]
if np.isscalar(X):
ret... | def to_tensor(X, device, accept_sparse=False) | Turn input data to torch tensor.
Parameters
----------
X : input data
Handles the cases:
* PackedSequence
* numpy array
* torch Tensor
* scipy sparse CSR matrix
* list or tuple of one of the former
* dict with values of one of the former
device : s... | 1.991021 | 2.138931 | 0.930849 |
if isinstance(X, np.ndarray):
return X
if is_pandas_ndframe(X):
return X.values
if not is_torch_data_type(X):
raise TypeError("Cannot convert this data type to a numpy array.")
if X.is_cuda:
X = X.cpu()
if X.requires_grad:
X = X.detach()
return X... | def to_numpy(X) | Generic function to convert a pytorch tensor to numpy.
Returns X when it already is a numpy array. | 2.854869 | 2.801013 | 1.019228 |
if not indexings:
return [multi_indexing(x, i) for x in data]
return [multi_indexing(x, i, indexing)
for x, indexing in zip(data, indexings)] | def _indexing_list_tuple_of_data(data, i, indexings=None) | Data is a list/tuple of data structures (e.g. list of numpy arrays).
``indexings`` are the indexing functions for each element of
``data``. If ``indexings`` are not given, the indexing functions
for the individual structures have to be determined ad hoc, which
is slower. | 2.891667 | 3.101933 | 0.932215 |
if data is None:
return _indexing_none
if isinstance(data, dict):
# dictionary of containers
return _indexing_dict
if isinstance(data, (list, tuple)):
try:
# list or tuple of containers
# TODO: Is there a better way than just to try to index? Th... | def check_indexing(data) | Perform a check how incoming data should be indexed and return an
appropriate indexing function with signature f(data, index).
This is useful for determining upfront how data should be indexed
instead of doing it repeatedly for each batch, thus saving some
time. | 5.794 | 5.465829 | 1.06004 |
if isinstance(i, np.ndarray):
if i.dtype == bool:
i = tuple(j.tolist() for j in i.nonzero())
elif i.dtype == int:
i = i.tolist()
return i | def _normalize_numpy_indices(i) | Normalize the index in case it is a numpy integer or boolean
array. | 2.919894 | 2.767947 | 1.054895 |
# in case of i being a numpy array
i = _normalize_numpy_indices(i)
# If we already know how to index, use that knowledge
if indexing is not None:
return indexing(data, i)
# If we don't know how to index, find out and apply
return check_indexing(data)(data, i) | def multi_indexing(data, i, indexing=None) | Perform indexing on multiple data structures.
Currently supported data types:
* numpy arrays
* torch tensors
* pandas NDFrame
* a dictionary of the former three
* a list/tuple of the former three
``i`` can be an integer or a slice.
Examples
--------
>>> multi_indexing(np.asar... | 6.409394 | 7.406985 | 0.865318 |
duplicates = set()
seen = set()
for item in flatten(collections):
if item in seen:
duplicates.add(item)
else:
seen.add(item)
return duplicates | def duplicate_items(*collections) | Search for duplicate items in all collections.
Examples
--------
>>> duplicate_items([1, 2], [3])
set()
>>> duplicate_items({1: 'a', 2: 'a'})
set()
>>> duplicate_items(['a', 'b', 'a'])
{'a'}
>>> duplicate_items([1, 2], {3: 'hi', 4: 'ha'}, (2, 3))
{2, 3} | 2.313324 | 3.264578 | 0.708614 |
if not prefix.endswith('__'):
prefix += '__'
return {key[len(prefix):]: val for key, val in kwargs.items()
if key.startswith(prefix)} | def params_for(prefix, kwargs) | Extract parameters that belong to a given sklearn module prefix from
``kwargs``. This is useful to obtain parameters that belong to a
submodule.
Examples
--------
>>> kwargs = {'encoder__a': 3, 'encoder__b': 4, 'decoder__a': 5}
>>> params_for('encoder', kwargs)
{'a': 3, 'b': 4} | 2.583058 | 4.172521 | 0.619064 |
X, y = _none, _none
if isinstance(dataset, Subset):
X, y = data_from_dataset(
dataset.dataset, X_indexing=X_indexing, y_indexing=y_indexing)
X = multi_indexing(X, dataset.indices, indexing=X_indexing)
y = multi_indexing(y, dataset.indices, indexing=y_indexing)
elif ... | def data_from_dataset(dataset, X_indexing=None, y_indexing=None) | Try to access X and y attribute from dataset.
Also works when dataset is a subset.
Parameters
----------
dataset : skorch.dataset.Dataset or torch.utils.data.Subset
The incoming dataset should be a ``skorch.dataset.Dataset`` or a
``torch.utils.data.Subset`` of a
``skorch.dataset.Data... | 2.375902 | 2.564399 | 0.926495 |
from skorch.dataset import Dataset
if isinstance(ds, Subset):
return is_skorch_dataset(ds.dataset)
return isinstance(ds, Dataset) | def is_skorch_dataset(ds) | Checks if the supplied dataset is an instance of
``skorch.dataset.Dataset`` even when it is nested inside
``torch.util.data.Subset``. | 3.131529 | 2.487379 | 1.258967 |
new_fd = isinstance(f, (str, pathlib.Path))
if new_fd:
f = open(f, mode)
try:
yield f
finally:
if new_fd:
f.close() | def open_file_like(f, mode) | Wrapper for opening a file | 2.874571 | 3.202309 | 0.897656 |
map_location = torch.device(target_device)
# The user wants to use CUDA but there is no CUDA device
# available, thus fall back to CPU.
if map_location.type == 'cuda' and not torch.cuda.is_available():
warnings.warn(
'Requested to load data to CUDA but no CUDA devices '
... | def get_map_location(target_device, fallback_device='cpu') | Determine the location to map loaded data (e.g., weights)
for a given target device (e.g. 'cuda'). | 3.584623 | 3.877043 | 0.924576 |
if not use_caching:
yield net
return
y_preds = iter(y_preds)
net.infer = lambda *a, **kw: next(y_preds)
try:
yield net
finally:
# By setting net.infer we define an attribute `infer`
# that precedes the bound method `infer`. By deleting
# the entr... | def cache_net_infer(net, use_caching, y_preds) | Caching context for ``skorch.NeuralNet`` instance. Returns
a modified version of the net whose ``infer`` method will
subsequently return cached predictions. Leaving the context
will undo the overwrite of the ``infer`` method. | 6.357718 | 5.385474 | 1.180531 |
if callable(scoring):
module = getattr(scoring, '__module__', None)
if (
hasattr(module, 'startswith') and
module.startswith('sklearn.metrics.') and
not module.startswith('sklearn.metrics.scorer') and
not module.startswith('sklearn... | def convert_sklearn_metric_function(scoring) | If ``scoring`` is a sklearn metric function, convert it to a
sklearn scorer and return it. Otherwise, return ``scoring`` unchanged. | 2.982777 | 2.990112 | 0.997547 |
if self.name is not None:
return self.name
if self.scoring_ is None:
return 'score'
if isinstance(self.scoring_, str):
return self.scoring_
if isinstance(self.scoring_, partial):
return self.scoring_.func.__name__
if isinst... | def _get_name(self) | Find name of scoring function. | 2.644022 | 2.20519 | 1.199 |
scorer = check_scoring(net, self.scoring_)
scores = _score(
estimator=net,
X_test=X_test,
y_test=y_test,
scorer=scorer,
is_multimetric=False,
)
return scores | def _scoring(self, net, X_test, y_test) | Resolve scoring and apply it to data. Use cached prediction
instead of running inference again, if available. | 2.984687 | 2.824917 | 1.056557 |
history.record(self.name_, current_score)
is_best = self._is_best_score(current_score)
if is_best is None:
return
history.record(self.name_ + '_best', bool(is_best))
if is_best:
self.best_score_ = current_score | def _record_score(self, history, current_score) | Record the current store and, if applicable, if it's the best score
yet. | 3.257334 | 3.083238 | 1.056465 |
h, w = im_shape
ph, pw = patch_size
steps_h = chain(range(0, h - ph, ph), [h - ph])
steps_w = chain(range(0, w - pw, pw), [w - pw])
return product(steps_h, steps_w) | def calcuate_bboxes(im_shape, patch_size) | Calculate bound boxes based on image shape and size of the bounding box
given by `patch_size` | 2.486118 | 2.480249 | 1.002366 |
return partial(MLPModule, output_nonlin=output_nonlin, **kwargs) | def make_classifier(output_nonlin=nn.Softmax(dim=-1), **kwargs) | Return a multi-layer perceptron to be used with
NeuralNetClassifier.
Parameters
----------
input_units : int (default=20)
Number of input units.
output_units : int (default=2)
Number of output units.
hidden_units : int (default=10)
Number of units in hidden layers.
num_... | 5.12056 | 13.552631 | 0.377828 |
units = [self.input_units]
units += [self.hidden_units] * self.num_hidden
units += [self.output_units]
sequence = []
for u0, u1 in zip(units, units[1:]):
sequence.append(nn.Linear(u0, u1))
sequence.append(self.nonlin)
sequence.append(... | def reset_params(self) | (Re)set all parameters. | 2.439693 | 2.403121 | 1.015219 |
getattr(self, method_name)(self, **cb_kwargs)
for _, cb in self.callbacks_:
getattr(cb, method_name)(self, **cb_kwargs) | def notify(self, method_name, **cb_kwargs) | Call the callback method specified in ``method_name`` with
parameters specified in ``cb_kwargs``.
Method names can be one of:
* on_train_begin
* on_train_end
* on_epoch_begin
* on_epoch_end
* on_batch_begin
* on_batch_end | 3.727436 | 4.696158 | 0.79372 |
print_logs = []
for item in self.get_default_callbacks() + (self.callbacks or []):
if isinstance(item, (tuple, list)):
named_by_user = True
name, cb = item
else:
named_by_user = False
cb = item
... | def _yield_callbacks(self) | Yield all callbacks set on this instance including
a set whether its name was set by the user.
Handles these cases:
* default and user callbacks
* callbacks with and without name
* initialized and uninitialized callbacks
* puts PrintLog(s) last | 3.666573 | 3.041601 | 1.205475 |
callbacks, names_set_by_user = OrderedDict(), set()
for name, cb, named_by_user in self._yield_callbacks():
if named_by_user:
names_set_by_user.add(name)
callbacks[name] = callbacks.get(name, []) + [cb]
return callbacks, names_set_by_user | def _callbacks_grouped_by_name(self) | Group callbacks by name and collect names set by the user. | 3.447518 | 2.545224 | 1.354504 |
grouped_cbs, names_set_by_user = self._callbacks_grouped_by_name()
for name, cbs in grouped_cbs.items():
if len(cbs) > 1 and name in names_set_by_user:
raise ValueError("Found duplicate user-set callback name "
"'{}'. Use unique names... | def _uniquely_named_callbacks(self) | Make sure that the returned dict of named callbacks is unique
w.r.t. to the callback name. User-defined names will not be
renamed on conflict, instead an exception will be raised. The
same goes for the event where renaming leads to a conflict. | 3.656778 | 3.459621 | 1.056988 |
callbacks_ = []
class Dummy:
# We cannot use None as dummy value since None is a
# legitimate value to be set.
pass
for name, cb in self._uniquely_named_callbacks():
# check if callback itself is changed
param_callback = geta... | def initialize_callbacks(self) | Initializes all callbacks and save the result in the
``callbacks_`` attribute.
Both ``default_callbacks`` and ``callbacks`` are used (in that
order). Callbacks may either be initialized or not, and if
they don't have a name, the name is inferred from the class
name. The ``initia... | 5.777636 | 5.499453 | 1.050584 |
criterion_params = self._get_params_for('criterion')
self.criterion_ = self.criterion(**criterion_params)
if isinstance(self.criterion_, torch.nn.Module):
self.criterion_ = self.criterion_.to(self.device)
return self | def initialize_criterion(self) | Initializes the criterion. | 2.661075 | 2.615676 | 1.017356 |
msg = "Re-initializing {}".format(name)
if triggered_directly and kwargs:
msg += (" because the following parameters were re-set: {}."
.format(', '.join(sorted(kwargs))))
else:
msg += "."
return msg | def _format_reinit_msg(self, name, kwargs=None, triggered_directly=True) | Returns a message that informs about re-initializing a compoment.
Sometimes, the module or optimizer need to be
re-initialized. Not only should the user receive a message
about this but also should they be informed about what
parameters, if any, caused it. | 3.503405 | 3.479693 | 1.006815 |
kwargs = self._get_params_for('module')
module = self.module
is_initialized = isinstance(module, torch.nn.Module)
if kwargs or not is_initialized:
if is_initialized:
module = type(module)
if (is_initialized or self.initialized_) and self... | def initialize_module(self) | Initializes the module.
Note that if the module has learned parameters, those will be
reset. | 4.873734 | 5.166747 | 0.943289 |
args, kwargs = self._get_params_for_optimizer(
'optimizer', self.module_.named_parameters())
if self.initialized_ and self.verbose:
msg = self._format_reinit_msg(
"optimizer", kwargs, triggered_directly=triggered_directly)
print(msg)
... | def initialize_optimizer(self, triggered_directly=True) | Initialize the model optimizer. If ``self.optimizer__lr``
is not set, use ``self.lr`` instead.
Parameters
----------
triggered_directly : bool (default=True)
Only relevant when optimizer is re-initialized.
Initialization of the optimizer can be triggered directly
... | 5.205043 | 4.930676 | 1.055645 |
self.initialize_virtual_params()
self.initialize_callbacks()
self.initialize_criterion()
self.initialize_module()
self.initialize_optimizer()
self.initialize_history()
self.initialized_ = True
return self | def initialize(self) | Initializes all components of the :class:`.NeuralNet` and
returns self. | 5.187038 | 4.688624 | 1.106303 |
self.module_.eval()
with torch.no_grad():
y_pred = self.infer(Xi, **fit_params)
loss = self.get_loss(y_pred, yi, X=Xi, training=False)
return {
'loss': loss,
'y_pred': y_pred,
} | def validation_step(self, Xi, yi, **fit_params) | Perform a forward step using batched data and return the
resulting loss.
The module is set to be in evaluation mode (e.g. dropout is
not applied).
Parameters
----------
Xi : input data
A batch of the input data.
yi : target data
A batch of t... | 2.941236 | 3.648422 | 0.806167 |
self.module_.train()
self.optimizer_.zero_grad()
y_pred = self.infer(Xi, **fit_params)
loss = self.get_loss(y_pred, yi, X=Xi, training=True)
loss.backward()
self.notify(
'on_grad_computed',
named_parameters=TeeGenerator(self.module_.named... | def train_step_single(self, Xi, yi, **fit_params) | Compute y_pred, loss value, and update net's gradients.
The module is set to be in train mode (e.g. dropout is
applied).
Parameters
----------
Xi : input data
A batch of the input data.
yi : target data
A batch of the target data.
**fit_par... | 4.196836 | 4.340131 | 0.966984 |
step_accumulator = self.get_train_step_accumulator()
def step_fn():
step = self.train_step_single(Xi, yi, **fit_params)
step_accumulator.store_step(step)
return step['loss']
self.optimizer_.step(step_fn)
return step_accumulator.get_step() | def train_step(self, Xi, yi, **fit_params) | Prepares a loss function callable and pass it to the optimizer,
hence performing one optimization step.
Loss function callable as required by some optimizers (and accepted by
all of them):
https://pytorch.org/docs/master/optim.html#optimizer-step-closure
The module is set to be... | 3.778438 | 4.620666 | 0.817726 |
with torch.set_grad_enabled(training):
self.module_.train(training)
return self.infer(Xi) | def evaluation_step(self, Xi, training=False) | Perform a forward step to produce the output used for
prediction and scoring.
Therefore the module is set to evaluation mode by default
beforehand which can be overridden to re-enable features
like dropout by setting ``training=True``. | 5.983888 | 6.206852 | 0.964078 |
self.check_data(X, y)
epochs = epochs if epochs is not None else self.max_epochs
dataset_train, dataset_valid = self.get_split_datasets(
X, y, **fit_params)
on_epoch_kwargs = {
'dataset_train': dataset_train,
'dataset_valid': dataset_valid,
... | def fit_loop(self, X, y=None, epochs=None, **fit_params) | The proper fit loop.
Contains the logic of what actually happens during the fit
loop.
Parameters
----------
X : input data, compatible with skorch.dataset.Dataset
By default, you should be able to pass:
* numpy arrays
* torch tensors
... | 1.882264 | 1.914342 | 0.983243 |
if not self.initialized_:
self.initialize()
self.notify('on_train_begin', X=X, y=y)
try:
self.fit_loop(X, y, **fit_params)
except KeyboardInterrupt:
pass
self.notify('on_train_end', X=X, y=y)
return self | def partial_fit(self, X, y=None, classes=None, **fit_params) | Fit the module.
If the module is initialized, it is not re-initialized, which
means that this method should be used if you want to continue
training a model (warm start).
Parameters
----------
X : input data, compatible with skorch.dataset.Dataset
By default, ... | 2.891182 | 3.144442 | 0.919458 |
if not self.warm_start or not self.initialized_:
self.initialize()
self.partial_fit(X, y, **fit_params)
return self | def fit(self, X, y=None, **fit_params) | Initialize and fit the module.
If the module was already initialized, by calling fit, the
module will be re-initialized (unless ``warm_start`` is True).
Parameters
----------
X : input data, compatible with skorch.dataset.Dataset
By default, you should be able to pass... | 3.552262 | 5.587825 | 0.635715 |
dataset = self.get_dataset(X)
iterator = self.get_iterator(dataset, training=training)
for data in iterator:
Xi = unpack_data(data)[0]
yp = self.evaluation_step(Xi, training=training)
if isinstance(yp, tuple):
yield tuple(n.to(device) ... | def forward_iter(self, X, training=False, device='cpu') | Yield outputs of module forward calls on each batch of data.
The storage device of the yielded tensors is determined
by the ``device`` parameter.
Parameters
----------
X : input data, compatible with skorch.dataset.Dataset
By default, you should be able to pass:
... | 3.217938 | 3.239973 | 0.993199 |
y_infer = list(self.forward_iter(X, training=training, device=device))
is_multioutput = len(y_infer) > 0 and isinstance(y_infer[0], tuple)
if is_multioutput:
return tuple(map(torch.cat, zip(*y_infer)))
return torch.cat(y_infer) | def forward(self, X, training=False, device='cpu') | Gather and concatenate the output from forward call with
input data.
The outputs from ``self.module_.forward`` are gathered on the
compute device specified by ``device`` and then concatenated
using PyTorch :func:`~torch.cat`. If multiple outputs are
returned by ``self.module_.fo... | 3.070382 | 3.17709 | 0.966413 |
x = to_tensor(x, device=self.device)
if isinstance(x, dict):
x_dict = self._merge_x_and_fit_params(x, fit_params)
return self.module_(**x_dict)
return self.module_(x, **fit_params) | def infer(self, x, **fit_params) | Perform a single inference step on a batch of data.
Parameters
----------
x : input data
A batch of the input data.
**fit_params : dict
Additional parameters passed to the ``forward`` method of
the module and to the ``self.train_split`` call. | 3.277649 | 4.0845 | 0.80246 |
y_probas = []
for yp in self.forward_iter(X, training=False):
yp = yp[0] if isinstance(yp, tuple) else yp
y_probas.append(to_numpy(yp))
y_proba = np.concatenate(y_probas, 0)
return y_proba | def predict_proba(self, X) | Return the output of the module's forward method as a numpy
array.
If the module's forward method returns multiple outputs as a
tuple, it is assumed that the first output contains the
relevant information and the other values are ignored. If all
values are relevant, consider usi... | 2.990651 | 3.361262 | 0.889741 |
y_true = to_tensor(y_true, device=self.device)
return self.criterion_(y_pred, y_true) | def get_loss(self, y_pred, y_true, X=None, training=False) | Return the loss for this batch.
Parameters
----------
y_pred : torch tensor
Predicted target values
y_true : torch tensor
True target values.
X : input data, compatible with skorch.dataset.Dataset
By default, you should be able to pass:
... | 4.011488 | 5.656096 | 0.709233 |
if is_dataset(X):
return X
dataset = self.dataset
is_initialized = not callable(dataset)
kwargs = self._get_params_for('dataset')
if kwargs and is_initialized:
raise TypeError("Trying to pass an initialized Dataset while "
... | def get_dataset(self, X, y=None) | Get a dataset that contains the input data and is passed to
the iterator.
Override this if you want to initialize your dataset
differently.
Parameters
----------
X : input data, compatible with skorch.dataset.Dataset
By default, you should be able to pass:
... | 5.681237 | 6.320809 | 0.898815 |
dataset = self.get_dataset(X, y)
if self.train_split:
dataset_train, dataset_valid = self.train_split(
dataset, y, **fit_params)
else:
dataset_train, dataset_valid = dataset, None
return dataset_train, dataset_valid | def get_split_datasets(self, X, y=None, **fit_params) | Get internal train and validation datasets.
The validation dataset can be None if ``self.train_split`` is
set to None; then internal validation will be skipped.
Override this if you want to change how the net splits
incoming data into train and validation part.
Parameters
... | 2.517352 | 2.703944 | 0.930993 |
if training:
kwargs = self._get_params_for('iterator_train')
iterator = self.iterator_train
else:
kwargs = self._get_params_for('iterator_valid')
iterator = self.iterator_valid
if 'batch_size' not in kwargs:
kwargs['batch_size... | def get_iterator(self, dataset, training=False) | Get an iterator that allows to loop over the batches of the
given data.
If ``self.iterator_train__batch_size`` and/or
``self.iterator_test__batch_size`` are not set, use
``self.batch_size`` instead.
Parameters
----------
dataset : torch Dataset (default=skorch.d... | 2.233304 | 2.441692 | 0.914654 |
kwargs = self._get_params_for(prefix)
params = list(named_parameters)
pgroups = []
for pattern, group in kwargs.pop('param_groups', []):
matches = [i for i, (name, _) in enumerate(params) if
fnmatch.fnmatch(name, pattern)]
if match... | def _get_params_for_optimizer(self, prefix, named_parameters) | Parse kwargs configuration for the optimizer identified by
the given prefix. Supports param group assignment using wildcards:
optimizer__lr=0.05,
optimizer__param_groups=[
('rnn*.period', {'lr': 0.3, 'momentum': 0}),
('rnn0', {'lr': 0.1}),
]
... | 3.266442 | 3.036706 | 1.075653 |
params = {}
if not deep:
return params
callbacks_ = getattr(self, 'callbacks_', [])
for key, val in chain(callbacks_, self._default_callbacks):
name = 'callbacks__' + key
params[name] = val
if val is None: # callback deactivated
... | def _get_params_callbacks(self, deep=True) | sklearn's .get_params checks for `hasattr(value,
'get_params')`. This returns False for a list. But our
callbacks reside within a list. Hence their parameters have to
be retrieved separately. | 3.287623 | 3.211314 | 1.023762 |
self._check_deprecated_params(**kwargs)
normal_params, cb_params, special_params = {}, {}, {}
virtual_params = {}
for key, val in kwargs.items():
if self._is_virtual_param(key):
virtual_params[key] = val
elif key.startswith('callbacks'):
... | def set_params(self, **kwargs) | Set the parameters of this class.
Valid parameter keys can be listed with ``get_params()``.
Returns
-------
self | 4.063397 | 4.091221 | 0.993199 |
# model after sklearn.utils._BaseCompostion._set_params
# 1. All steps
if 'callbacks' in params:
setattr(self, 'callbacks', params.pop('callbacks'))
# 2. Step replacement
names, _ = zip(*getattr(self, 'callbacks_'))
for key in params.copy():
... | def _set_params_callback(self, **params) | Special handling for setting params on callbacks. | 4.993812 | 4.767914 | 1.047379 |
# TODO: Remove warning in a future release
if f is not None:
warnings.warn(
"f argument was renamed to f_params and will be removed "
"in the next release. To make your code future-proof it is "
"recommended to explicitly specify keyw... | def save_params(
self, f=None, f_params=None, f_optimizer=None, f_history=None) | Saves the module's parameters, history, and optimizer,
not the whole object.
To save the whole object, use pickle.
``f_params`` and ``f_optimizer`` uses PyTorchs'
:func:`~torch.save`.
Parameters
----------
f_params : file-like object, str, None (default=None)
... | 2.687312 | 2.800648 | 0.959532 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.