INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Write a byte of data to the specified cmd register of the device. | def write_byte_data(self, addr, cmd, val):
"""Write a byte of data to the specified cmd register of the device.
"""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
# Construct a string of data to send with the command register and byte value.
... |
Write a word ( 2 bytes ) of data to the specified cmd register of the device. Note that this will write the data in the endianness of the processor running Python ( typically little endian ) ! | def write_word_data(self, addr, cmd, val):
"""Write a word (2 bytes) of data to the specified cmd register of the
device. Note that this will write the data in the endianness of the
processor running Python (typically little endian)!
"""
assert self._device is not None, 'Bus mus... |
Write a block of data to the specified cmd register of the device. The amount of data to write should be the first byte inside the vals string/ bytearray and that count of bytes of data to write should follow it. | def write_block_data(self, addr, cmd, vals):
"""Write a block of data to the specified cmd register of the device.
The amount of data to write should be the first byte inside the vals
string/bytearray and that count of bytes of data to write should follow
it.
"""
# Just u... |
Write a buffer of data to the specified cmd register of the device. | def write_i2c_block_data(self, addr, cmd, vals):
"""Write a buffer of data to the specified cmd register of the device.
"""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
# Construct a string of data to send, including room for the command re... |
Perform a smbus process call by writing a word ( 2 byte ) value to the specified register of the device and then reading a word of response data ( which is returned ). | def process_call(self, addr, cmd, val):
"""Perform a smbus process call by writing a word (2 byte) value to
the specified register of the device, and then reading a word of response
data (which is returned).
"""
assert self._device is not None, 'Bus must be opened before operatio... |
Returns file s CDN url. | def cdn_url(self):
"""Returns file's CDN url.
Usage example::
>>> file_ = File('a771f854-c2cb-408a-8c36-71af77811f3b')
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/
You can set default effects::
>>> file_.default_... |
Returns file s store aware * datetime * in UTC format. | def datetime_stored(self):
"""Returns file's store aware *datetime* in UTC format.
It might do API request once because it depends on ``info()``.
"""
if self.info().get('datetime_stored'):
return dateutil.parser.parse(self.info()['datetime_stored']) |
Returns file s remove aware * datetime * in UTC format. | def datetime_removed(self):
"""Returns file's remove aware *datetime* in UTC format.
It might do API request once because it depends on ``info()``.
"""
if self.info().get('datetime_removed'):
return dateutil.parser.parse(self.info()['datetime_removed']) |
Returns file s upload aware * datetime * in UTC format. | def datetime_uploaded(self):
"""Returns file's upload aware *datetime* in UTC format.
It might do API request once because it depends on ``info()``.
"""
if self.info().get('datetime_uploaded'):
return dateutil.parser.parse(self.info()['datetime_uploaded']) |
Creates a File Copy on Uploadcare or Custom Storage. File. copy method is deprecated and will be removed in 4. 0. 0. Please use create_local_copy and create_remote_copy instead. | def copy(self, effects=None, target=None):
"""Creates a File Copy on Uploadcare or Custom Storage.
File.copy method is deprecated and will be removed in 4.0.0.
Please use `create_local_copy` and `create_remote_copy` instead.
Args:
- effects:
Adds CDN... |
Creates a Local File Copy on Uploadcare Storage. | def create_local_copy(self, effects=None, store=None):
"""Creates a Local File Copy on Uploadcare Storage.
Args:
- effects:
Adds CDN image effects. If ``self.default_effects`` property
is set effects will be combined with default effects.
- store:... |
Creates file copy in remote storage. | def create_remote_copy(self, target, effects=None, make_public=None,
pattern=None):
"""Creates file copy in remote storage.
Args:
- target:
Name of a custom storage connected to the project.
- effects:
Adds CDN image eff... |
Constructs File instance from file information. | def construct_from(cls, file_info):
"""Constructs ``File`` instance from file information.
For example you have result of
``/files/1921953c-5d94-4e47-ba36-c2e1dd165e1a/`` API request::
>>> file_info = {
# ...
'uuid': '1921953c-5d94-4e47-ba36-... |
Uploads a file and returns File instance. | def upload(cls, file_obj, store=None):
"""Uploads a file and returns ``File`` instance.
Args:
- file_obj: file object to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to None.
- False - do not st... |
Uploads file from given url and returns FileFromUrl instance. | def upload_from_url(cls, url, store=None, filename=None):
"""Uploads file from given url and returns ``FileFromUrl`` instance.
Args:
- url (str): URL of file to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to N... |
Uploads file from given url and returns File instance. | def upload_from_url_sync(cls, url, timeout=30, interval=0.3,
until_ready=False, store=None, filename=None):
"""Uploads file from given url and returns ``File`` instance.
Args:
- url (str): URL of file to upload to
- store (Optional[bool]): Should the... |
Returns CDN urls of all files from group without API requesting. | def file_cdn_urls(self):
"""Returns CDN urls of all files from group without API requesting.
Usage example::
>>> file_group = FileGroup('0513dda0-582f-447d-846f-096e5df9e2bb~2')
>>> file_group.file_cdn_urls[0]
'https://ucarecdn.com/0513dda0-582f-447d-846f-096e5df9e2... |
Returns file group s create aware * datetime * in UTC format. | def datetime_created(self):
"""Returns file group's create aware *datetime* in UTC format."""
if self.info().get('datetime_created'):
return dateutil.parser.parse(self.info()['datetime_created']) |
Constructs FileGroup instance from group information. | def construct_from(cls, group_info):
"""Constructs ``FileGroup`` instance from group information."""
group = cls(group_info['id'])
group._info_cache = group_info
return group |
Creates file group and returns FileGroup instance. | def create(cls, files):
"""Creates file group and returns ``FileGroup`` instance.
It expects iterable object that contains ``File`` instances, e.g.::
>>> file_1 = File('6c5e9526-b0fe-4739-8975-72e8d5ee6342')
>>> file_2 = File('a771f854-c2cb-408a-8c36-71af77811f3b')
... |
Base method for storage operations. | def _base_opration(self, method):
""" Base method for storage operations.
"""
uuids = self.uuids()
while True:
chunk = list(islice(uuids, 0, self.chunk_size))
if not chunk:
return
rest_request(method, self.storage_url, chunk) |
Extract uuid from each item of specified seq. | def uuids(self):
""" Extract uuid from each item of specified ``seq``.
"""
for f in self._seq:
if isinstance(f, File):
yield f.uuid
elif isinstance(f, six.string_types):
yield f
else:
raise ValueError(
... |
A common function for building methods of the list showing. | def _list(api_list_class, arg_namespace, **extra):
""" A common function for building methods of the "list showing".
"""
if arg_namespace.starting_point:
ordering_field = (arg_namespace.ordering or '').lstrip('-')
if ordering_field in ('', 'datetime_uploaded', 'datetime_created'):
... |
Iterates over the iter_content and draws a progress bar to stdout. | def bar(iter_content, parts, title=''):
""" Iterates over the "iter_content" and draws a progress bar to stdout.
"""
parts = max(float(parts), 1.0)
cells = 10
progress = 0
step = cells / parts
draw = lambda progress: sys.stdout.write(
'\r[{0:10}] {1:.2f}% {2}'.format(
'#... |
Makes REST API request and returns response as dict. | def rest_request(verb, path, data=None, timeout=conf.DEFAULT,
retry_throttled=conf.DEFAULT):
"""Makes REST API request and returns response as ``dict``.
It provides auth headers as well and takes settings from ``conf`` module.
Make sure that given ``path`` does not contain leading slash.
... |
Makes Uploading API request and returns response as dict. | def uploading_request(verb, path, data=None, files=None, timeout=conf.DEFAULT):
"""Makes Uploading API request and returns response as ``dict``.
It takes settings from ``conf`` module.
Make sure that given ``path`` does not contain leading slash.
Usage example::
>>> file_obj = open('photo.jp... |
Set the state of Home Mode | def home_mode_set_state(self, state, **kwargs):
"""Set the state of Home Mode"""
# It appears that surveillance station needs lowercase text
# true/false for the on switch
if state not in (HOME_MODE_ON, HOME_MODE_OFF):
raise ValueError('Invalid home mode state')
api... |
Returns the status of Home Mode | def home_mode_status(self, **kwargs):
"""Returns the status of Home Mode"""
api = self._api_info['home_mode']
payload = dict({
'api': api['name'],
'method': 'GetInfo',
'version': api['version'],
'_sid': self._sid
}, **kwargs)
respon... |
Return a list of cameras. | def camera_list(self, **kwargs):
"""Return a list of cameras."""
api = self._api_info['camera']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'List',
'version': api['version'],
}, **kwargs)
response = self._get_j... |
Return a list of cameras matching camera_ids. | def camera_info(self, camera_ids, **kwargs):
"""Return a list of cameras matching camera_ids."""
api = self._api_info['camera']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'GetInfo',
'version': api['version'],
'cam... |
Return bytes of camera image. | def camera_snapshot(self, camera_id, **kwargs):
"""Return bytes of camera image."""
api = self._api_info['camera']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'GetSnapshot',
'version': api['version'],
'cameraId': c... |
Disable camera. | def camera_disable(self, camera_id, **kwargs):
"""Disable camera."""
api = self._api_info['camera']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'Disable',
'version': 9,
'idList': camera_id,
}, **kwargs)
... |
Return motion settings matching camera_id. | def camera_event_motion_enum(self, camera_id, **kwargs):
"""Return motion settings matching camera_id."""
api = self._api_info['camera_event']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'MotionEnum',
'version': api['version']... |
Update motion settings matching camera_id with keyword args. | def camera_event_md_param_save(self, camera_id, **kwargs):
"""Update motion settings matching camera_id with keyword args."""
api = self._api_info['camera_event']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'MDParamSave',
'ver... |
Update cameras and motion settings with latest from API. | def update(self):
"""Update cameras and motion settings with latest from API."""
cameras = self._api.camera_list()
self._cameras_by_id = {v.camera_id: v for i, v in enumerate(cameras)}
motion_settings = []
for camera_id in self._cameras_by_id.keys():
motion_setting =... |
Set the state of Home Mode | def set_home_mode(self, state):
"""Set the state of Home Mode"""
state_parameter = HOME_MODE_OFF
if state:
state_parameter = HOME_MODE_ON
return self._api.home_mode_set_state(state_parameter) |
>>> replace_ext ( one/ two/ three. four. doc. html ) one/ two/ three. four. html >>> replace_ext ( one/ two/ three. four. DOC. html ) one/ two/ three. four. html >>> replace_ext ( one/ two/ three. four. DOC html ) one/ two/ three. four. html | def replace_ext(file_path, new_ext):
"""
>>> replace_ext('one/two/three.four.doc', '.html')
'one/two/three.four.html'
>>> replace_ext('one/two/three.four.DOC', '.html')
'one/two/three.four.html'
>>> replace_ext('one/two/three.four.DOC', 'html')
'one/two/three.four.html'
"""
if not ne... |
Determine if li is the last list item for a given list | def is_last_li(li, meta_data, current_numId):
"""
Determine if ``li`` is the last list item for a given list
"""
if not is_li(li, meta_data):
return False
w_namespace = get_namespace(li, 'w')
next_el = li
while True:
# If we run out of element this must be the last list item
... |
Find consecutive li tags that have content that have the same list id. | def get_single_list_nodes_data(li, meta_data):
"""
Find consecutive li tags that have content that have the same list id.
"""
yield li
w_namespace = get_namespace(li, 'w')
current_numId = get_numId(li, w_namespace)
starting_ilvl = get_ilvl(li, w_namespace)
el = li
while True:
... |
The ilvl on an li tag tells the li tag at what level of indentation this tag is at. This is used to determine if the li tag needs to be nested or not. | def get_ilvl(li, w_namespace):
"""
The ilvl on an li tag tells the li tag at what level of indentation this
tag is at. This is used to determine if the li tag needs to be nested or
not.
"""
ilvls = li.xpath('.//w:ilvl', namespaces=li.nsmap)
if len(ilvls) == 0:
return -1
return in... |
The numId on an li tag maps to the numbering dictionary along side the ilvl to determine what the list should look like ( unordered digits lower alpha etc ) | def get_numId(li, w_namespace):
"""
The numId on an li tag maps to the numbering dictionary along side the ilvl
to determine what the list should look like (unordered, digits, lower
alpha, etc)
"""
numIds = li.xpath('.//w:numId', namespaces=li.nsmap)
if len(numIds) == 0:
return -1
... |
Based on the passed in list_type create a list objects ( ol/ ul ). In the future this function will also deal with what the numbering of an ordered list should look like. | def create_list(list_type):
"""
Based on the passed in list_type create a list objects (ol/ul). In the
future this function will also deal with what the numbering of an ordered
list should look like.
"""
list_types = {
'bullet': 'ul',
}
el = etree.Element(list_types.get(list_type... |
vMerge is what docx uses to denote that a table cell is part of a rowspan. The first cell to have a vMerge is the start of the rowspan and the vMerge will be denoted with restart. If it is anything other than restart then it is a continuation of another rowspan. | def get_v_merge(tc):
"""
vMerge is what docx uses to denote that a table cell is part of a rowspan.
The first cell to have a vMerge is the start of the rowspan, and the vMerge
will be denoted with 'restart'. If it is anything other than restart then
it is a continuation of another rowspan.
"""
... |
gridSpan is what docx uses to denote that a table cell has a colspan. This is much more simple than rowspans in that there is a one - to - one mapping from gridSpan to colspan. | def get_grid_span(tc):
"""
gridSpan is what docx uses to denote that a table cell has a colspan. This
is much more simple than rowspans in that there is a one-to-one mapping
from gridSpan to colspan.
"""
w_namespace = get_namespace(tc, 'w')
grid_spans = tc.xpath('.//w:gridSpan', namespaces=t... |
When calculating the rowspan for a given cell it is required to find all table cells below the initial cell with a v_merge. This function will return the td element at the passed in index taking into account colspans. | def get_td_at_index(tr, index):
"""
When calculating the rowspan for a given cell it is required to find all
table cells 'below' the initial cell with a v_merge. This function will
return the td element at the passed in index, taking into account colspans.
"""
current = 0
for td in tr.xpath(... |
For bold italics and underline. Simply checking to see if the various tags are present will not suffice. If the tag is present and set to False then the style should not be present. | def style_is_false(style):
"""
For bold, italics and underline. Simply checking to see if the various tags
are present will not suffice. If the tag is present and set to False then
the style should not be present.
"""
if style is None:
return False
w_namespace = get_namespace(style, ... |
The function will return True if the r tag passed in is considered bold. | def is_bold(r):
"""
The function will return True if the r tag passed in is considered bold.
"""
w_namespace = get_namespace(r, 'w')
rpr = r.find('%srPr' % w_namespace)
if rpr is None:
return False
bold = rpr.find('%sb' % w_namespace)
return style_is_false(bold) |
The function will return True if the r tag passed in is considered italicized. | def is_italics(r):
"""
The function will return True if the r tag passed in is considered
italicized.
"""
w_namespace = get_namespace(r, 'w')
rpr = r.find('%srPr' % w_namespace)
if rpr is None:
return False
italics = rpr.find('%si' % w_namespace)
return style_is_false(italics... |
The function will return True if the r tag passed in is considered underlined. | def is_underlined(r):
"""
The function will return True if the r tag passed in is considered
underlined.
"""
w_namespace = get_namespace(r, 'w')
rpr = r.find('%srPr' % w_namespace)
if rpr is None:
return False
underline = rpr.find('%su' % w_namespace)
return style_is_false(un... |
Certain p tags are denoted as Title tags. This function will return True if the passed in p tag is considered a title. | def is_title(p):
"""
Certain p tags are denoted as ``Title`` tags. This function will return
True if the passed in p tag is considered a title.
"""
w_namespace = get_namespace(p, 'w')
styles = p.xpath('.//w:pStyle', namespaces=p.nsmap)
if len(styles) == 0:
return False
style = st... |
It turns out that r tags can contain both t tags and drawing tags. Since we need both this function will return them in the order in which they are found. | def get_text_run_content_data(r):
"""
It turns out that r tags can contain both t tags and drawing tags. Since we
need both, this function will return them in the order in which they are
found.
"""
w_namespace = get_namespace(r, 'w')
valid_elements = (
'%st' % w_namespace,
'%... |
Checks to see if the whole p tag will end up being bold or italics. Returns a tuple ( boolean boolean ). The first boolean will be True if the whole line is bold False otherwise. The second boolean will be True if the whole line is italics False otherwise. | def whole_line_styled(p):
"""
Checks to see if the whole p tag will end up being bold or italics. Returns
a tuple (boolean, boolean). The first boolean will be True if the whole
line is bold, False otherwise. The second boolean will be True if the whole
line is italics, False otherwise.
"""
... |
There is a separate file called numbering. xml that stores how lists should look ( unordered digits lower case letters etc. ). Parse that file and return a dictionary of what each combination should be based on list Id and level of indentation. | def get_numbering_info(tree):
"""
There is a separate file called numbering.xml that stores how lists should
look (unordered, digits, lower case letters, etc.). Parse that file and
return a dictionary of what each combination should be based on list Id and
level of indentation.
"""
if tree i... |
Some things that are considered lists are actually supposed to be H tags ( h1 h2 etc. ) These can be denoted by their styleId | def get_style_dict(tree):
"""
Some things that are considered lists are actually supposed to be H tags
(h1, h2, etc.) These can be denoted by their styleId
"""
# This is a partial document and actual h1 is the document title, which
# will be displayed elsewhere.
headers = {
'heading ... |
There is a separate file holds the targets to links as well as the targets for images. Return a dictionary based on the relationship id and the target. | def get_relationship_info(tree, media, image_sizes):
"""
There is a separate file holds the targets to links as well as the targets
for images. Return a dictionary based on the relationship id and the
target.
"""
if tree is None:
return {}
result = {}
# Loop through each relation... |
f is a ZipFile that is open Extract out the document data numbering data and the relationship data. | def _get_document_data(f, image_handler=None):
'''
``f`` is a ``ZipFile`` that is open
Extract out the document data, numbering data and the relationship data.
'''
if image_handler is None:
def image_handler(image_id, relationship_dict):
return relationship_dict.get(image_id)
... |
Return the list type. If numId or ilvl not in the numbering dict then default to returning decimal. | def get_ordered_list_type(meta_data, numId, ilvl):
"""
Return the list type. If numId or ilvl not in the numbering dict then
default to returning decimal.
This function only cares about ordered lists, unordered lists get dealt
with elsewhere.
"""
# Early return if numId or ilvl are not val... |
Build the list structure and return the root list | def build_list(li_nodes, meta_data):
"""
Build the list structure and return the root list
"""
# Need to keep track of all incomplete nested lists.
ol_dict = {}
# Need to keep track of the current indentation level.
current_ilvl = -1
# Need to keep track of the current list id.
cur... |
This will return a single tr element with all tds already populated. | def build_tr(tr, meta_data, row_spans):
"""
This will return a single tr element, with all tds already populated.
"""
# Create a blank tr element.
tr_el = etree.Element('tr')
w_namespace = get_namespace(tr, 'w')
visited_nodes = []
for el in tr:
if el in visited_nodes:
... |
This returns a table object with all rows and cells correctly populated. | def build_table(table, meta_data):
"""
This returns a table object with all rows and cells correctly populated.
"""
# Create a blank table element.
table_el = etree.Element('table')
w_namespace = get_namespace(table, 'w')
# Get the rowspan values for cells that have a rowspan.
row_span... |
Generate the string data that for this particular t tag. | def get_t_tag_content(
t, parent, remove_bold, remove_italics, meta_data):
"""
Generate the string data that for this particular t tag.
"""
if t is None or t.text is None:
return ''
# Need to escape the text so that we do not accidentally put in text
# that is not valid XML.
... |
P tags are made up of several runs ( r tags ) of text. This function takes a p tag and constructs the text that should be part of the p tag. | def get_element_content(
p,
meta_data,
is_td=False,
remove_italics=False,
remove_bold=False,
):
"""
P tags are made up of several runs (r tags) of text. This function takes a
p tag and constructs the text that should be part of the p tag.
image_handler should be ... |
Remove all tags that have the tag name tag | def _strip_tag(tree, tag):
"""
Remove all tags that have the tag name ``tag``
"""
for el in tree.iter():
if el.tag == tag:
el.getparent().remove(el) |
file_path is a path to the file on the file system that you want to be converted to html. image_handler is a function that takes an image_id and a relationship_dict to generate the src attribute for images. ( see readme for more details ) fall_back is a function that takes a file_path. This function will only be called... | def convert(file_path, image_handler=None, fall_back=None, converter=None):
"""
``file_path`` is a path to the file on the file system that you want to be
converted to html.
``image_handler`` is a function that takes an image_id and a
relationship_dict to generate the src attribute for image... |
Find the location of a dataset on disk downloading if needed. | def find(dataset, url):
'''Find the location of a dataset on disk, downloading if needed.'''
fn = os.path.join(DATASETS, dataset)
dn = os.path.dirname(fn)
if not os.path.exists(dn):
print('creating dataset directory: %s', dn)
os.makedirs(dn)
if not os.path.exists(fn):
if sys.... |
Load the MNIST digits dataset. | def load_mnist(flatten=True, labels=False):
'''Load the MNIST digits dataset.'''
fn = find('mnist.pkl.gz', 'http://deeplearning.net/data/mnist/mnist.pkl.gz')
h = gzip.open(fn, 'rb')
if sys.version_info < (3, ):
(timg, tlab), (vimg, vlab), (simg, slab) = pickle.load(h)
else:
(timg, tl... |
Load the CIFAR10 image dataset. | def load_cifar(flatten=True, labels=False):
'''Load the CIFAR10 image dataset.'''
def extract(name):
print('extracting data from {}'.format(name))
h = tar.extractfile(name)
if sys.version_info < (3, ):
d = pickle.load(h)
else:
d = pickle.load(h, encoding='... |
Plot an array of images. | def plot_images(imgs, loc, title=None, channels=1):
'''Plot an array of images.
We assume that we are given a matrix of data whose shape is (n*n, s*s*c) --
that is, there are n^2 images along the first axis of the array, and each
image is c squares measuring s pixels on a side. Each row of the input wi... |
Create a plot of weights visualized as bottom - level pixel arrays. | def plot_layers(weights, tied_weights=False, channels=1):
'''Create a plot of weights, visualized as "bottom-level" pixel arrays.'''
if hasattr(weights[0], 'get_value'):
weights = [w.get_value() for w in weights]
k = min(len(weights), 9)
imgs = np.eye(weights[0].shape[0])
for i, weight in en... |
Create a plot of conv filters visualized as pixel arrays. | def plot_filters(filters):
'''Create a plot of conv filters, visualized as pixel arrays.'''
imgs = filters.get_value()
N, channels, x, y = imgs.shape
n = int(np.sqrt(N))
assert n * n == N, 'filters must contain a square number of rows!'
assert channels == 1 or channels == 3, 'can only plot gray... |
Create a callable that generates samples from a dataset. | def batches(arrays, steps=100, batch_size=64, rng=None):
'''Create a callable that generates samples from a dataset.
Parameters
----------
arrays : list of ndarray (time-steps, data-dimensions)
Arrays of data. Rows in these arrays are assumed to correspond to time
steps, and columns to ... |
Encode a text string by replacing characters with alphabet index. | def encode(self, txt):
'''Encode a text string by replacing characters with alphabet index.
Parameters
----------
txt : str
A string to encode.
Returns
-------
classes : list of int
A sequence of alphabet index values corresponding to the... |
Create a callable that returns a batch of training data. | def classifier_batches(self, steps, batch_size, rng=None):
'''Create a callable that returns a batch of training data.
Parameters
----------
steps : int
Number of time steps in each batch.
batch_size : int
Number of training examples per batch.
rn... |
Draw a sequential sample of class labels from this network. | def predict_sequence(self, labels, steps, streams=1, rng=None):
'''Draw a sequential sample of class labels from this network.
Parameters
----------
labels : list of int
A list of integer class labels to get the classifier started.
steps : int
The number ... |
Add a convolutional weight array to this layer s parameters. | def add_conv_weights(self, name, mean=0, std=None, sparsity=0):
'''Add a convolutional weight array to this layer's parameters.
Parameters
----------
name : str
Name of the parameter to add.
mean : float, optional
Mean value for randomly-initialized weigh... |
Encode a dataset using the hidden layer activations of our network. | def encode(self, x, layer=None, sample=False, **kwargs):
'''Encode a dataset using the hidden layer activations of our network.
Parameters
----------
x : ndarray
A dataset to encode. Rows of this dataset capture individual data
points, while columns represent the... |
Decode an encoded dataset by computing the output layer activation. | def decode(self, z, layer=None, **kwargs):
'''Decode an encoded dataset by computing the output layer activation.
Parameters
----------
z : ndarray
A matrix containing encoded data from this autoencoder.
layer : int or str or :class:`Layer <layers.Layer>`, optional
... |
Find a layer output name for the given layer specifier. | def _find_output(self, layer):
'''Find a layer output name for the given layer specifier.
Parameters
----------
layer : None, int, str, or :class:`theanets.layers.Layer`
A layer specification. If this is None, the "middle" layer in the
network will be used (i.e.,... |
Compute R^2 coefficient of determination for a given input. | def score(self, x, w=None, **kwargs):
'''Compute R^2 coefficient of determination for a given input.
Parameters
----------
x : ndarray (num-examples, num-inputs)
An array containing data to be fed into the network. Multiple
examples are arranged as rows in this a... |
Return expressions that should be computed to monitor training. | def monitors(self, **kwargs):
'''Return expressions that should be computed to monitor training.
Returns
-------
monitors : list of (name, expression) pairs
A list of named monitor expressions to compute for this network.
'''
monitors = super(Classifier, self... |
Compute a greedy classification for the given set of data. | def predict(self, x, **kwargs):
'''Compute a greedy classification for the given set of data.
Parameters
----------
x : ndarray (num-examples, num-variables)
An array containing examples to classify. Examples are given as the
rows in this array.
Returns
... |
Compute class posterior probabilities for the given set of data. | def predict_proba(self, x, **kwargs):
'''Compute class posterior probabilities for the given set of data.
Parameters
----------
x : ndarray (num-examples, num-variables)
An array containing examples to predict. Examples are given as the
rows in this array.
... |
Compute the logit values that underlie the softmax output. | def predict_logit(self, x, **kwargs):
'''Compute the logit values that underlie the softmax output.
Parameters
----------
x : ndarray (num-examples, num-variables)
An array containing examples to classify. Examples are given as the
rows in this array.
Re... |
Compute the mean accuracy on a set of labeled data. | def score(self, x, y, w=None, **kwargs):
'''Compute the mean accuracy on a set of labeled data.
Parameters
----------
x : ndarray (num-examples, num-variables)
An array containing examples to classify. Examples are given as the
rows in this array.
y : nda... |
Extract a single batch of data to pass to the model being trained. | def batch_at(features, labels, seq_begins, seq_lengths):
'''Extract a single batch of data to pass to the model being trained.
Parameters
----------
features, labels : ndarray
Arrays of the input features and target labels.
seq_begins : ndarray
Array of the start offsets of the spee... |
Returns a callable that chooses sequences from netcdf data. | def batches(dataset):
'''Returns a callable that chooses sequences from netcdf data.'''
seq_lengths = dataset.variables['seqLengths'].data
seq_begins = np.concatenate(([0], np.cumsum(seq_lengths)[:-1]))
def sample():
chosen = np.random.choice(
list(range(len(seq_lengths))), BATCH_SI... |
Load a saved network from a pickle file on disk. | def load(self, path):
'''Load a saved network from a pickle file on disk.
This method sets the ``network`` attribute of the experiment to the
loaded network model.
Parameters
----------
filename : str
Load the keyword arguments and parameters of a network fr... |
Create a matrix of randomly - initialized weights. | def random_matrix(rows, cols, mean=0, std=1, sparsity=0, radius=0, diagonal=0, rng=None):
'''Create a matrix of randomly-initialized weights.
Parameters
----------
rows : int
Number of rows of the weight matrix -- equivalently, the number of
"input" units that the weight matrix connects... |
Create a vector of randomly - initialized values. | def random_vector(size, mean=0, std=1, rng=None):
'''Create a vector of randomly-initialized values.
Parameters
----------
size : int
Length of vecctor to create.
mean : float, optional
Mean value for initial vector values. Defaults to 0.
std : float, optional
Standard d... |
Get the outputs from a network that match a pattern. | def outputs_matching(outputs, patterns):
'''Get the outputs from a network that match a pattern.
Parameters
----------
outputs : dict or sequence of (str, theano expression)
Output expressions to filter for matches. If this is a dictionary, its
``items()`` will be processed for matches.... |
Get the parameters from a network that match a pattern. | def params_matching(layers, patterns):
'''Get the parameters from a network that match a pattern.
Parameters
----------
layers : list of :class:`theanets.layers.Layer`
A list of network layers to retrieve parameters from.
patterns : sequence of str
A sequence of glob-style patterns ... |
Construct common regularizers from a set of keyword arguments. | def from_kwargs(graph, **kwargs):
'''Construct common regularizers from a set of keyword arguments.
Keyword arguments not listed below will be passed to
:func:`Regularizer.build` if they specify the name of a registered
:class:`Regularizer`.
Parameters
----------
graph : :class:`theanets.g... |
A list of Theano variables used in this loss. | def variables(self):
'''A list of Theano variables used in this loss.'''
result = [self._target]
if self._weights is not None:
result.append(self._weights)
return result |
Build a Theano expression for computing the accuracy of graph output. | def accuracy(self, outputs):
'''Build a Theano expression for computing the accuracy of graph output.
Parameters
----------
outputs : dict of Theano expressions
A dictionary mapping network output names to Theano expressions
representing the outputs of a computat... |
Helper method to create a new weight matrix. | def add_weights(self, name, nin, nout, mean=0, std=0, sparsity=0, radius=0,
diagonal=0):
'''Helper method to create a new weight matrix.
Parameters
----------
name : str
Name of parameter to define.
nin : int, optional
Size of "input" ... |
Helper method for defining a basic loop in theano. | def _scan(self, inputs, outputs, name='scan', step=None, constants=None):
'''Helper method for defining a basic loop in theano.
Parameters
----------
inputs : sequence of theano expressions
Inputs to the scan operation.
outputs : sequence of output specifiers
... |
Create a rate parameter ( usually for a recurrent network layer ). | def _create_rates(self, dist='uniform', size=None, eps=1e-4):
'''Create a rate parameter (usually for a recurrent network layer).
Parameters
----------
dist : {'uniform', 'log'}, optional
Distribution of rate values. Defaults to ``'uniform'``.
size : int, optional
... |
Construct an activation function by name. | def build(name, layer, **kwargs):
'''Construct an activation function by name.
Parameters
----------
name : str or :class:`Activation`
The name of the type of activation function to build, or an
already-created instance of an activation function.
layer : :class:`theanets.layers.Laye... |
Train a model using a training and validation set. | def itertrain(self, train, valid=None, **kwargs):
'''Train a model using a training and validation set.
This method yields a series of monitor values to the caller. After every
iteration, a pair of monitor dictionaries is generated: one evaluated on
the training dataset, and another eva... |
Select a random sample of n items from xs. | def reservoir(xs, n, rng):
'''Select a random sample of n items from xs.'''
pool = []
for i, x in enumerate(xs):
if len(pool) < n:
pool.append(x / np.linalg.norm(x))
continue
j = rng.randint(i + 1)
if j < n:
pool... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.