code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def test_order_by_ascending(cipher_signature):
"""Ensure :meth:`~pytube.StreamQuery.desc` sorts the list of
:class:`Stream <Stream>` instances in ascending order.
"""
# numerical values
itags = [
s.itag
for s in cipher_signature.streams.filter(type="audio")
.order_by("itag")
... | Ensure :meth:`~pytube.StreamQuery.desc` sorts the list of
:class:`Stream <Stream>` instances in ascending order.
| test_order_by_ascending | python | pytube/pytube | tests/test_query.py | https://github.com/pytube/pytube/blob/master/tests/test_query.py | Unlicense |
def prepare_docstring(s):
"""
Convert a docstring into lines of parseable reST. Return it as a list of
lines usable for inserting into a docutils ViewList (used as argument
of nested_parse().) An empty line is added to act as a separator between
this docstring and following content.
"""
if... |
Convert a docstring into lines of parseable reST. Return it as a list of
lines usable for inserting into a docutils ViewList (used as argument
of nested_parse().) An empty line is added to act as a separator between
this docstring and following content.
| prepare_docstring | python | pybrain/pybrain | docs/sphinx/autodoc_hack.py | https://github.com/pybrain/pybrain/blob/master/docs/sphinx/autodoc_hack.py | BSD-3-Clause |
def performAction(self, action):
"""Incoming action is an int between 0 and 8. The action we provide to
the environment consists of a torque T in {-2 N, 0, 2 N}, and a
displacement d in {-.02 m, 0, 0.02 m}.
"""
self.t += 1
assert round(action[0]) == action[0]
# ... | Incoming action is an int between 0 and 8. The action we provide to
the environment consists of a torque T in {-2 N, 0, 2 N}, and a
displacement d in {-.02 m, 0, 0.02 m}.
| performAction | python | pybrain/pybrain | examples/rl/environments/linear_fa/bicycle.py | https://github.com/pybrain/pybrain/blob/master/examples/rl/environments/linear_fa/bicycle.py | BSD-3-Clause |
def evalRnnOnSeqDataset(net, DS, verbose = False, silent = False):
""" evaluate the network on all the sequences of a dataset. """
r = 0.
samples = 0.
for seq in DS:
net.reset()
for i, t in seq:
res = net.activate(i)
if verbose:
print(t, res)
... | evaluate the network on all the sequences of a dataset. | evalRnnOnSeqDataset | python | pybrain/pybrain | examples/supervised/backprop/parityrnn.py | https://github.com/pybrain/pybrain/blob/master/examples/supervised/backprop/parityrnn.py | BSD-3-Clause |
def multigaussian(x, mean, stddev):
"""Returns value of uncorrelated Gaussians at given scalar point.
x: scalar
mean: vector
stddev: vector
"""
tmp = -0.5 * ((x-mean)/stddev)**2
return np.exp(tmp) / (np.sqrt(2.*np.pi) * stddev) | Returns value of uncorrelated Gaussians at given scalar point.
x: scalar
mean: vector
stddev: vector
| multigaussian | python | pybrain/pybrain | examples/supervised/neuralnets+svm/example_mixturedensity.py | https://github.com/pybrain/pybrain/blob/master/examples/supervised/neuralnets+svm/example_mixturedensity.py | BSD-3-Clause |
def generateClassificationData(size, nClasses=3):
""" generate a set of points in 2D belonging to two or three different classes """
if nClasses==3:
means = [(-1,0),(2,4),(3,1)]
else:
means = [(-2,0),(2,1),(6,0)]
cov = [diag([1,1]), diag([0.5,1.2]), diag([1.5,0.7])]
dataset = Classi... | generate a set of points in 2D belonging to two or three different classes | generateClassificationData | python | pybrain/pybrain | examples/supervised/neuralnets+svm/datasets/datagenerator.py | https://github.com/pybrain/pybrain/blob/master/examples/supervised/neuralnets+svm/datasets/datagenerator.py | BSD-3-Clause |
def generateGridData(x,y, return_ticks=False):
""" Generates a dataset containing a regular grid of points. The x and y arguments
contain start, end, and step each. Returns the dataset and the x and y mesh or ticks."""
x = np.arange(x[0], x[1], x[2])
y = np.arange(y[0], y[1], y[2])
X, Y = np.meshgri... | Generates a dataset containing a regular grid of points. The x and y arguments
contain start, end, and step each. Returns the dataset and the x and y mesh or ticks. | generateGridData | python | pybrain/pybrain | examples/supervised/neuralnets+svm/datasets/datagenerator.py | https://github.com/pybrain/pybrain/blob/master/examples/supervised/neuralnets+svm/datasets/datagenerator.py | BSD-3-Clause |
def generateNoisySines( npoints, nseq, noise=0.3 ):
""" construct a 2-class dataset out of noisy sines """
x = np.arange(npoints)/float(npoints) * 20.
y1 = np.sin(x+rand(1)*3.)
y2 = np.sin(x/2.+rand(1)*3.)
DS = SequenceClassificationDataSet(1,1, nb_classes=2)
for _ in range(nseq):
DS.new... | construct a 2-class dataset out of noisy sines | generateNoisySines | python | pybrain/pybrain | examples/supervised/neuralnets+svm/datasets/datagenerator.py | https://github.com/pybrain/pybrain/blob/master/examples/supervised/neuralnets+svm/datasets/datagenerator.py | BSD-3-Clause |
def makeData(amount = 10000):
"""Return 2D dataset of points in (0, 1) where points in a circle of
radius .4 around the center are blue and all the others are red."""
center = array([0.5, 0.5])
def makePoint():
"""Return a random point and its satellite information.
Satellite is 'blue'... | Return 2D dataset of points in (0, 1) where points in a circle of
radius .4 around the center are blue and all the others are red. | makeData | python | pybrain/pybrain | examples/unsupervised/lsh.py | https://github.com/pybrain/pybrain/blob/master/examples/unsupervised/lsh.py | BSD-3-Clause |
def makePoint():
"""Return a random point and its satellite information.
Satellite is 'blue' if point is in the circle, else 'red'."""
point = random.random((2,)) * 10
vectorLength = lambda x: dot(x.T, x)
return point, 'blue' if vectorLength(point - center) < 25 else 'red' | Return a random point and its satellite information.
Satellite is 'blue' if point is in the circle, else 'red'. | makePoint | python | pybrain/pybrain | examples/unsupervised/lsh.py | https://github.com/pybrain/pybrain/blob/master/examples/unsupervised/lsh.py | BSD-3-Clause |
def drawIndex(probs, tolerant=False):
""" Draws an index given an array of probabilities.
:key tolerant: if set to True, the array is normalized to sum to 1. """
if not sum(probs) < 1.00001 or not sum(probs) > 0.99999:
if tolerant:
probs /= sum(probs)
else:
print((p... | Draws an index given an array of probabilities.
:key tolerant: if set to True, the array is normalized to sum to 1. | drawIndex | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def drawGibbs(vals, temperature=1.):
""" Return the index of the sample drawn by a softmax (Gibbs). """
if temperature == 0:
# randomly pick one of the values with the max value.
m = max(vals)
best = []
for i, v in enumerate(vals):
if v == m:
best.appe... | Return the index of the sample drawn by a softmax (Gibbs). | drawGibbs | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def iterCombinations(tup):
""" all possible of integer tuples of the same dimension than tup, and each component being
positive and strictly inferior to the corresponding entry in tup. """
if len(tup) == 1:
for i in range(tup[0]):
yield (i,)
elif len(tup) > 1:
for prefix in i... | all possible of integer tuples of the same dimension than tup, and each component being
positive and strictly inferior to the corresponding entry in tup. | iterCombinations | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def setAllArgs(obj, argdict):
""" set all those internal variables which have the same name than an entry in the
given object's dictionary.
This function can be useful for quick initializations. """
xmlstore = isinstance(obj, XMLBuildable)
for n in list(argdict.keys()):
if hasattr(obj, n):
... | set all those internal variables which have the same name than an entry in the
given object's dictionary.
This function can be useful for quick initializations. | setAllArgs | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def percentError(out, true):
""" return percentage of mismatch between out and target values (lists and arrays accepted) """
arrout = array(out).flatten()
wrong = where(arrout != array(true).flatten())[0].size
return 100. * float(wrong) / float(arrout.size) | return percentage of mismatch between out and target values (lists and arrays accepted) | percentError | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def formatFromExtension(fname):
"""Tries to infer a protocol from the file extension."""
_base, ext = os.path.splitext(fname)
if not ext:
return None
try:
format = known_extensions[ext.replace('.', '')]
except KeyError:
format = None
return format | Tries to infer a protocol from the file extension. | formatFromExtension | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def saveToFileLike(self, flo, format=None, **kwargs):
"""Save the object to a given file like object in the given format.
"""
format = 'pickle' if format is None else format
save = getattr(self, "save_%s" % format, None)
if save is None:
raise ValueError("Unknown form... | Save the object to a given file like object in the given format.
| saveToFileLike | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def loadFromFileLike(cls, flo, format=None):
"""Load the object to a given file like object with the given protocol.
"""
format = 'pickle' if format is None else format
load = getattr(cls, "load_%s" % format, None)
if load is None:
raise ValueError("Unknown format '%s... | Load the object to a given file like object with the given protocol.
| loadFromFileLike | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def saveToFile(self, filename, format=None, **kwargs):
"""Save the object to file given by filename."""
if format is None:
# try to derive protocol from file extension
format = formatFromExtension(filename)
with open(filename, 'wb') as fp:
self.saveToFileLike(... | Save the object to file given by filename. | saveToFile | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def loadFromFile(cls, filename, format=None):
"""Return an instance of the class that is saved in the file with the
given filename in the specified format."""
if format is None:
# try to derive protocol from file extension
format = formatFromExtension(filename)
wi... | Return an instance of the class that is saved in the file with the
given filename in the specified format. | loadFromFile | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def _getName(self):
"""Returns the name, which is generated if it has not been already."""
if self._name is None:
self._name = self._generateName()
return self._name | Returns the name, which is generated if it has not been already. | _getName | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def fListToString(a_list, a_precision=3):
""" Returns a string representing a list of floats with a given precision """
from numpy import around
s_list = ", ".join(("%g" % around(x, a_precision)).ljust(a_precision+3)
for x in a_list)
return "[%s]" % s_list | Returns a string representing a list of floats with a given precision | fListToString | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def tupleRemoveItem(tup, index):
""" remove the item at position index of the tuple and return a new tuple. """
l = list(tup)
return tuple(l[:index] + l[index + 1:]) | remove the item at position index of the tuple and return a new tuple. | tupleRemoveItem | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def confidenceIntervalSize(stdev, nbsamples):
""" Determine the size of the confidence interval, given the standard deviation and the number of samples.
t-test-percentile: 97.5%, infinitely many degrees of freedom,
therefore on the two-sided interval: 95% """
# CHECKME: for better precision, maybe get t... | Determine the size of the confidence interval, given the standard deviation and the number of samples.
t-test-percentile: 97.5%, infinitely many degrees of freedom,
therefore on the two-sided interval: 95% | confidenceIntervalSize | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def threaded(callback=lambda * args, **kwargs: None, daemonic=False):
"""Decorate a function to run in its own thread and report the result
by calling callback with it."""
def innerDecorator(func):
def inner(*args, **kwargs):
target = lambda: callback(func(*args, **kwargs))
... | Decorate a function to run in its own thread and report the result
by calling callback with it. | threaded | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def garbagecollect(func):
"""Decorate a function to invoke the garbage collector after each execution.
"""
def inner(*args, **kwargs):
result = func(*args, **kwargs)
gc.collect()
return result
return inner | Decorate a function to invoke the garbage collector after each execution.
| garbagecollect | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def memoize(func):
"""Decorate a function to 'memoize' results by holding it in a cache that
maps call arguments to returns."""
cache = {}
def inner(*args, **kwargs):
# Dictionaries and lists are unhashable
args = tuple(args)
# Make a set for checking in the cache, since the orde... | Decorate a function to 'memoize' results by holding it in a cache that
maps call arguments to returns. | memoize | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def storeCallResults(obj, verbose=False):
"""Pseudo-decorate an object to store all evaluations of the function in the returned list."""
results = []
oldcall = obj.__class__.__call__
def newcall(*args, **kwargs):
result = oldcall(*args, **kwargs)
results.append(result)
if verbose... | Pseudo-decorate an object to store all evaluations of the function in the returned list. | storeCallResults | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def multiEvaluate(repeat):
"""Decorate a function to evaluate repeatedly with the same arguments, and return the average result """
def decorator(func):
def inner(*args, **kwargs):
result = 0.
for dummy in range(repeat):
result += func(*args, **kwargs)
... | Decorate a function to evaluate repeatedly with the same arguments, and return the average result | multiEvaluate | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def _import(name):
"""Return module from a package.
These two are equivalent:
> from package import module as bar
> bar = _import('package.module')
"""
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
try:
mod = getattr(mod, c... | Return module from a package.
These two are equivalent:
> from package import module as bar
> bar = _import('package.module')
| _import | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def gray2int(g, size):
""" Transforms a Gray code back into an integer. """
res = 0
for i in reversed(list(range(size))):
gi = (g >> i) % 2
if i == size - 1:
bi = gi
else:
bi = bi ^ gi
res += bi * 2 ** i
return res | Transforms a Gray code back into an integer. | gray2int | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def asBinary(i):
""" Produces a string from an integer's binary representation.
(preceding zeros removed). """
if i > 1:
if i % 2 == 1:
return asBinary(i >> 1) + '1'
else:
return asBinary(i >> 1) + '0'
else:
return str(i) | Produces a string from an integer's binary representation.
(preceding zeros removed). | asBinary | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def one_to_n(val, maxval):
""" Returns a 1-in-n binary encoding of a non-negative integer. """
a = zeros(maxval, float)
a[val] = 1.
return a | Returns a 1-in-n binary encoding of a non-negative integer. | one_to_n | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def canonicClassString(x):
""" the __class__ attribute changed from old-style to new-style classes... """
if isinstance(x, object):
return repr(x.__class__).split("'")[1]
else:
return repr(x.__class__) | the __class__ attribute changed from old-style to new-style classes... | canonicClassString | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def decrementAny(tup):
""" the closest tuples to tup: decrementing by 1 along any dimension.
Never go into negatives though. """
res = []
for i, x in enumerate(tup):
if x > 0:
res.append(tuple(list(tup[:i]) + [x - 1] + list(tup[i + 1:])))
return res | the closest tuples to tup: decrementing by 1 along any dimension.
Never go into negatives though. | decrementAny | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def reachable(stepFunction, start, destinations, _alreadyseen=None):
""" Determines the subset of destinations that can be reached from a set of starting positions,
while using stepFunction (which produces a list of neighbor states) to navigate.
Uses breadth-first search.
Returns a dictionary with reach... | Determines the subset of destinations that can be reached from a set of starting positions,
while using stepFunction (which produces a list of neighbor states) to navigate.
Uses breadth-first search.
Returns a dictionary with reachable destinations and their distances.
| reachable | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def flood(stepFunction, fullSet, initSet, relevant=None):
""" Returns a list of elements of fullSet linked to some element of initSet
through the neighborhood-setFunction (which must be defined on all elements of fullSet).
:key relevant: (optional) list of relevant elements: stop once all relevant elements... | Returns a list of elements of fullSet linked to some element of initSet
through the neighborhood-setFunction (which must be defined on all elements of fullSet).
:key relevant: (optional) list of relevant elements: stop once all relevant elements are found.
| flood | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def crossproduct(ss, row=None, level=0):
"""Returns the cross-product of the sets given in `ss`."""
if row is None:
row = []
if len(ss) > 1:
return reduce(operator.add,
[crossproduct(ss[1:], row + [i], level + 1) for i in ss[0]])
else:
return [row + [i] for ... | Returns the cross-product of the sets given in `ss`. | crossproduct | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def permuteToBlocks(arr, blockshape):
"""Permute an array so that it consists of linearized blocks.
Example: A two-dimensional array of the form
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
would be turned into an array like this with (2, 2) blocks:
0 1 4 5 2 3 6... | Permute an array so that it consists of linearized blocks.
Example: A two-dimensional array of the form
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
would be turned into an array like this with (2, 2) blocks:
0 1 4 5 2 3 6 7 8 9 12 13 10 11 14 15
| permuteToBlocks | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def triu2flat(m):
""" Flattens an upper triangular matrix, returning a vector of the
non-zero elements. """
dim = m.shape[0]
res = zeros(dim * (dim + 1) / 2)
index = 0
for row in range(dim):
res[index:index + dim - row] = m[row, row:]
index += dim - row
return res | Flattens an upper triangular matrix, returning a vector of the
non-zero elements. | triu2flat | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def flat2triu(a, dim):
""" Produces an upper triangular matrix of dimension dim from the elements of the given vector. """
res = zeros((dim, dim))
index = 0
for row in range(dim):
res[row, row:] = a[index:index + dim - row]
index += dim - row
return res | Produces an upper triangular matrix of dimension dim from the elements of the given vector. | flat2triu | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def blockList2Matrix(l):
""" Converts a list of matrices into a corresponding big block-diagonal one. """
dims = [m.shape[0] for m in l]
s = sum(dims)
res = zeros((s, s))
index = 0
for i in range(len(l)):
d = dims[i]
m = l[i]
res[index:index + d, index:index + d] = m
... | Converts a list of matrices into a corresponding big block-diagonal one. | blockList2Matrix | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def blockCombine(l):
""" Produce a matrix from a list of lists of its components. """
l = [list(map(mat, row)) for row in l]
hdims = [m.shape[1] for m in l[0]]
hs = sum(hdims)
vdims = [row[0].shape[0] for row in l]
vs = sum(vdims)
res = zeros((hs, vs))
vindex = 0
for i, row in enumer... | Produce a matrix from a list of lists of its components. | blockCombine | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def avgFoundAfter(decreasingTargetValues, listsOfActualValues, batchSize=1, useMedian=False):
""" Determine the average number of steps to reach a certain value (for the first time),
given a list of value sequences.
If a value is not always encountered, the length of the longest sequence is used.
Return... | Determine the average number of steps to reach a certain value (for the first time),
given a list of value sequences.
If a value is not always encountered, the length of the longest sequence is used.
Returns an array. | avgFoundAfter | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def matchingDict(d, selection, require_existence=False):
""" Determines if the dictionary d conforms to the specified selection,
i.e. if a (key, x) is in the selection, then if key is in d as well it must be x
or contained in x (if x is a list). """
for k, v in list(selection.items()):
if k in d... | Determines if the dictionary d conforms to the specified selection,
i.e. if a (key, x) is in the selection, then if key is in d as well it must be x
or contained in x (if x is a list). | matchingDict | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def subDict(d, allowedkeys, flip=False):
""" Returns a new dictionary with a subset of the entries of d
that have on of the (dis-)allowed keys."""
res = {}
for k, v in list(d.items()):
if (k in allowedkeys) ^ flip:
res[k] = v
return res | Returns a new dictionary with a subset of the entries of d
that have on of the (dis-)allowed keys. | subDict | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def dictCombinations(listdict):
""" Iterates over dictionaries that go through every possible combination
of key-value pairs as specified in the lists of values for each key in listdict."""
listdict = listdict.copy()
if len(listdict) == 0:
return [{}]
k, vs = listdict.popitem()
res = dic... | Iterates over dictionaries that go through every possible combination
of key-value pairs as specified in the lists of values for each key in listdict. | dictCombinations | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def r_argmax(v):
""" Acts like scipy argmax, but break ties randomly. """
if len(v) == 1:
return 0
maxbid = max(v)
maxbidders = [i for (i, b) in enumerate(v) if b==maxbid]
return choice(maxbidders) | Acts like scipy argmax, but break ties randomly. | r_argmax | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def all_argmax(x):
""" Return the indices of all values that are equal to the maximum: no breaking ties. """
m = max(x)
return [i for i, v in enumerate(x) if v == m] | Return the indices of all values that are equal to the maximum: no breaking ties. | all_argmax | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def sparse_orth(d):
""" Constructs a sparse orthogonal matrix.
The method is described in:
Gi-Sang Cheon et al., Constructions for the sparsest orthogonal matrices,
Bull. Korean Math. Soc 36 (1999) No.1 pp.199-129
"""
from scipy.sparse import eye
from scipy import r_, pi, sin, cos
i... | Constructs a sparse orthogonal matrix.
The method is described in:
Gi-Sang Cheon et al., Constructions for the sparsest orthogonal matrices,
Bull. Korean Math. Soc 36 (1999) No.1 pp.199-129
| sparse_orth | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def binArr2int(arr):
""" Convert a binary array into its (long) integer representation. """
from numpy import packbits
tmp2 = packbits(arr.astype(int))
return sum(val * 256 ** i for i, val in enumerate(tmp2[::-1])) | Convert a binary array into its (long) integer representation. | binArr2int | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def seedit(seed=0):
""" Fixed seed makes for repeatability, but there may be two different
random number generators involved. """
import random
import numpy
random.seed(seed)
numpy.random.seed(seed) | Fixed seed makes for repeatability, but there may be two different
random number generators involved. | seedit | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def weightedUtest(g1, w1, g2, w2):
""" Determines the confidence level of the assertion:
'The values of g2 are higher than those of g1'.
(adapted from the scipy.stats version)
Twist: here the elements of each group have associated weights,
corresponding to how often they are present (i.e. tw... | Determines the confidence level of the assertion:
'The values of g2 are higher than those of g1'.
(adapted from the scipy.stats version)
Twist: here the elements of each group have associated weights,
corresponding to how often they are present (i.e. two identical entries with
weight w are... | weightedUtest | python | pybrain/pybrain | pybrain/utilities.py | https://github.com/pybrain/pybrain/blob/master/pybrain/utilities.py | BSD-3-Clause |
def __init__(self, indim, start=0, stop=1, step=0.1):
""" initializes the gaussian process object.
:arg indim: input dimension
:key start: start of interval for sampling the GP.
:key stop: stop of interval for sampling the GP.
:key step: stepsize for sampling int... | initializes the gaussian process object.
:arg indim: input dimension
:key start: start of interval for sampling the GP.
:key stop: stop of interval for sampling the GP.
:key step: stepsize for sampling interval.
:note: start, stop, step can either be scalars... | __init__ | python | pybrain/pybrain | pybrain/auxiliary/gaussprocess.py | https://github.com/pybrain/pybrain/blob/master/pybrain/auxiliary/gaussprocess.py | BSD-3-Clause |
def trainOnDataset(self, dataset):
""" takes a SequentialDataSet with indim input dimension and scalar target """
assert (dataset.getDimension('input') == self.indim)
assert (dataset.getDimension('target') == 1)
self.trainx = dataset.getField('input')
self.trainy = ravel(dataset... | takes a SequentialDataSet with indim input dimension and scalar target | trainOnDataset | python | pybrain/pybrain | pybrain/auxiliary/gaussprocess.py | https://github.com/pybrain/pybrain/blob/master/pybrain/auxiliary/gaussprocess.py | BSD-3-Clause |
def addDataset(self, dataset):
""" adds the points from the dataset to the training set """
assert (dataset.getDimension('input') == self.indim)
assert (dataset.getDimension('target') == 1)
self.trainx = r_[self.trainx, dataset.getField('input')]
self.trainy = r_[self.trainy, ra... | adds the points from the dataset to the training set | addDataset | python | pybrain/pybrain | pybrain/auxiliary/gaussprocess.py | https://github.com/pybrain/pybrain/blob/master/pybrain/auxiliary/gaussprocess.py | BSD-3-Clause |
def __init__(self):
""" initialize algorithms with standard parameters (typical values given in parentheses)"""
# --- BackProp parameters ---
# learning rate (0.1-0.001, down to 1e-7 for RNNs)
self.alpha = 0.1
# alpha decay (0.999; 1.0 = disabled)
self.alphadecay = 1.0
... | initialize algorithms with standard parameters (typical values given in parentheses) | __init__ | python | pybrain/pybrain | pybrain/auxiliary/gradientdescent.py | https://github.com/pybrain/pybrain/blob/master/pybrain/auxiliary/gradientdescent.py | BSD-3-Clause |
def init(self, values):
""" call this to initialize data structures *after* algorithm to use
has been selected
:arg values: the list (or array) of parameters to perform gradient descent on
(will be copied, original not modified)
"""
assert isinstance(value... | call this to initialize data structures *after* algorithm to use
has been selected
:arg values: the list (or array) of parameters to perform gradient descent on
(will be copied, original not modified)
| init | python | pybrain/pybrain | pybrain/auxiliary/gradientdescent.py | https://github.com/pybrain/pybrain/blob/master/pybrain/auxiliary/gradientdescent.py | BSD-3-Clause |
def __call__(self, gradient, error=None):
""" calculates parameter change based on given gradient and returns updated parameters """
# check if gradient has correct dimensionality, then make array """
assert len(gradient) == len(self.values)
gradient_arr = asarray(gradient)
if s... | calculates parameter change based on given gradient and returns updated parameters | __call__ | python | pybrain/pybrain | pybrain/auxiliary/gradientdescent.py | https://github.com/pybrain/pybrain/blob/master/pybrain/auxiliary/gradientdescent.py | BSD-3-Clause |
def importanceMixing(oldpoints, oldpdf, newpdf, newdistr, forcedRefresh = 0.01):
""" Implements importance mixing. Given a set of points, an old and a new pdf-function for them
and a generator function for new points, it produces a list of indices of the old points to be reused and a list of new points.
Par... | Implements importance mixing. Given a set of points, an old and a new pdf-function for them
and a generator function for new points, it produces a list of indices of the old points to be reused and a list of new points.
Parameter (optional): forced refresh rate.
| importanceMixing | python | pybrain/pybrain | pybrain/auxiliary/importancemixing.py | https://github.com/pybrain/pybrain/blob/master/pybrain/auxiliary/importancemixing.py | BSD-3-Clause |
def reduceDim(data, dim, func='pca'):
"""Reduce the dimension of datapoints to dim via principal component
analysis.
A matrix of shape (n, d) specifies n points of dimension d.
"""
try:
pcaFunc = globals()[func]
except KeyError:
raise ValueError('Unknown function to calc princip... | Reduce the dimension of datapoints to dim via principal component
analysis.
A matrix of shape (n, d) specifies n points of dimension d.
| reduceDim | python | pybrain/pybrain | pybrain/auxiliary/pca.py | https://github.com/pybrain/pybrain/blob/master/pybrain/auxiliary/pca.py | BSD-3-Clause |
def pca(data, dim):
""" Return the first dim principal components as colums of a matrix.
Every row of the matrix resembles a point in the data space.
"""
assert dim <= data.shape[1], \
"dim must be less or equal than the original dimension"
# We have to make a copy of the original data an... | Return the first dim principal components as colums of a matrix.
Every row of the matrix resembles a point in the data space.
| pca | python | pybrain/pybrain | pybrain/auxiliary/pca.py | https://github.com/pybrain/pybrain/blob/master/pybrain/auxiliary/pca.py | BSD-3-Clause |
def pPca(data, dim):
"""Return a matrix which contains the first `dim` dimensions principal
components of data.
data is a matrix which's rows correspond to datapoints. Implementation of
the 'probabilistic PCA' algorithm.
"""
num = data.shape[1]
data = asmatrix(makeCentered(data))
# Pick... | Return a matrix which contains the first `dim` dimensions principal
components of data.
data is a matrix which's rows correspond to datapoints. Implementation of
the 'probabilistic PCA' algorithm.
| pPca | python | pybrain/pybrain | pybrain/auxiliary/pca.py | https://github.com/pybrain/pybrain/blob/master/pybrain/auxiliary/pca.py | BSD-3-Clause |
def __init__(self, inp, target=1, nb_classes=0, class_labels=None):
"""Initialize an empty dataset.
`inp` is used to specify the dimensionality of the input. While the
number of targets is given by implicitly by the training samples, it can
also be set explicity by `nb_classes`. To give... | Initialize an empty dataset.
`inp` is used to specify the dimensionality of the input. While the
number of targets is given by implicitly by the training samples, it can
also be set explicity by `nb_classes`. To give the classes names, supply
an iterable of strings as `class_labels`. | __init__ | python | pybrain/pybrain | pybrain/datasets/classification.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py | BSD-3-Clause |
def load_matlab(cls, fname):
"""Create a dataset by reading a Matlab file containing one variable
called 'data' which is an array of nSamples * nFeatures + 1 and
contains the class in the first column."""
from mlabwrap import mlab #@UnresolvedImport
d = mlab.load(fname)
r... | Create a dataset by reading a Matlab file containing one variable
called 'data' which is an array of nSamples * nFeatures + 1 and
contains the class in the first column. | load_matlab | python | pybrain/pybrain | pybrain/datasets/classification.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py | BSD-3-Clause |
def load_libsvm(cls, f):
"""Create a dataset by reading a sparse LIBSVM/SVMlight format file
(with labels only)."""
nFeat = 0
# find max. number of features
for line in f:
n = int(line.split()[-1].split(':')[0])
if n > nFeat:
nFeat = n
... | Create a dataset by reading a sparse LIBSVM/SVMlight format file
(with labels only). | load_libsvm | python | pybrain/pybrain | pybrain/datasets/classification.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py | BSD-3-Clause |
def __add__(self, other):
"""Adds the patterns of two datasets, if dimensions and type match."""
if type(self) != type(other):
raise TypeError('DataSets to be added must agree in type')
elif self.indim != other.indim:
raise TypeError('DataSets to be added must agree in in... | Adds the patterns of two datasets, if dimensions and type match. | __add__ | python | pybrain/pybrain | pybrain/datasets/classification.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py | BSD-3-Clause |
def assignClasses(self):
"""Ensure that the class field is properly defined and nClasses is set.
"""
if len(self['class']) < len(self['target']):
if self.outdim > 1:
raise IndexError('Classes and 1-of-k representation out of sync!')
else:
s... | Ensure that the class field is properly defined and nClasses is set.
| assignClasses | python | pybrain/pybrain | pybrain/datasets/classification.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py | BSD-3-Clause |
def getClass(self, idx):
"""Return the label of given class."""
try:
return self.class_labels[idx]
except IndexError:
print("error: classes not defined yet!") | Return the label of given class. | getClass | python | pybrain/pybrain | pybrain/datasets/classification.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py | BSD-3-Clause |
def _convertToOneOfMany(self, bounds=(0, 1)):
"""Converts the target classes to a 1-of-k representation, retaining the
old targets as a field `class`.
To supply specific bounds, set the `bounds` parameter, which consists of
target values for non-membership and membership."""
if ... | Converts the target classes to a 1-of-k representation, retaining the
old targets as a field `class`.
To supply specific bounds, set the `bounds` parameter, which consists of
target values for non-membership and membership. | _convertToOneOfMany | python | pybrain/pybrain | pybrain/datasets/classification.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py | BSD-3-Clause |
def splitByClass(self, cls_select):
"""Produce two new datasets, the first one comprising only the class
selected (0..nClasses-1), the second one containing the remaining
samples."""
leftIndices, dummy = where(self['class'] == cls_select)
rightIndices, dummy = where(self['class']... | Produce two new datasets, the first one comprising only the class
selected (0..nClasses-1), the second one containing the remaining
samples. | splitByClass | python | pybrain/pybrain | pybrain/datasets/classification.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py | BSD-3-Clause |
def castToRegression(self, values):
"""Converts data set into a SupervisedDataSet for regression. Classes
are used as indices into the value array given."""
regDs = SupervisedDataSet(self.indim, 1)
fields = self.getFieldNames()
fields.remove('target')
for f in fields:
... | Converts data set into a SupervisedDataSet for regression. Classes
are used as indices into the value array given. | castToRegression | python | pybrain/pybrain | pybrain/datasets/classification.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py | BSD-3-Clause |
def stratifiedSplit(self, testfrac=0.15, evalfrac=0):
"""Stratified random split of a sequence data set, i.e. (almost) same
proportion of sequences in each class for all fragments. Return
(training, test[, eval]) data sets.
The parameter `testfrac` specifies the fraction of total sequen... | Stratified random split of a sequence data set, i.e. (almost) same
proportion of sequences in each class for all fragments. Return
(training, test[, eval]) data sets.
The parameter `testfrac` specifies the fraction of total sequences in
the test dataset, while `evalfrac` specifies the f... | stratifiedSplit | python | pybrain/pybrain | pybrain/datasets/classification.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py | BSD-3-Clause |
def getSequenceClass(self, index=None):
"""Return a flat array (or single scalar) comprising one class per
sequence as given by last pattern in each sequence."""
lastSeq = self.getNumSequences() - 1
if index is None:
classidx = r_[self['sequence_index'].astype(int)[1:, 0] - 1... | Return a flat array (or single scalar) comprising one class per
sequence as given by last pattern in each sequence. | getSequenceClass | python | pybrain/pybrain | pybrain/datasets/classification.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py | BSD-3-Clause |
def removeSequence(self, index):
"""Remove sequence (including class field) from the dataset."""
self.assignClasses()
self.linkFields(['input', 'target', 'class'])
SequentialDataSet.removeSequence(self, index)
self.unlinkFields(['class']) | Remove sequence (including class field) from the dataset. | removeSequence | python | pybrain/pybrain | pybrain/datasets/classification.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py | BSD-3-Clause |
def save_netcdf(self, flo, **kwargs):
"""Save the current dataset to the given file as a netCDF dataset to be
used with Alex Graves nnl_ndim program in
task="sequence classification" mode."""
# make sure classes are defined properly
assert len(self['class']) == len(self['target']... | Save the current dataset to the given file as a netCDF dataset to be
used with Alex Graves nnl_ndim program in
task="sequence classification" mode. | save_netcdf | python | pybrain/pybrain | pybrain/datasets/classification.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py | BSD-3-Clause |
def setVectorFormat(self, vf):
"""Determine which format to use for returning vectors. Use the property vectorformat.
:key type: possible types are '1d', '2d', 'list'
'1d' - example: array([1,2,3])
'2d' - example: array([[1,2,3]])
'list' - example... | Determine which format to use for returning vectors. Use the property vectorformat.
:key type: possible types are '1d', '2d', 'list'
'1d' - example: array([1,2,3])
'2d' - example: array([[1,2,3]])
'list' - example: [1,2,3]
'none' - no conv... | setVectorFormat | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def _convertArray2d(self, vector, column=False):
"""Converts the incoming `vector` to a 2d vector with shape (1,x), or
(x,1) if `column` is set, where x is the number of elements."""
a = asarray(vector)
sh = a.shape
# also reshape scalar values to 2d-index
if len(sh) == 0... | Converts the incoming `vector` to a 2d vector with shape (1,x), or
(x,1) if `column` is set, where x is the number of elements. | _convertArray2d | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def addField(self, label, dim):
"""Add a field to the dataset.
A field consists of a string `label` and a numpy ndarray of dimension
`dim`."""
self.data[label] = zeros((0, dim), float)
self.endmarker[label] = 0 | Add a field to the dataset.
A field consists of a string `label` and a numpy ndarray of dimension
`dim`. | addField | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def setField(self, label, arr):
"""Set the given array `arr` as the new array of field `label`,"""
as_arr = asarray(arr)
self.data[label] = as_arr
self.endmarker[label] = as_arr.shape[0] | Set the given array `arr` as the new array of field `label`, | setField | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def linkFields(self, linklist):
"""Link the length of several fields given by the list of strings
`linklist`."""
length = self[linklist[0]].shape[0]
for l in linklist:
if self[l].shape[0] != length:
raise OutOfSyncError
self.link = linklist | Link the length of several fields given by the list of strings
`linklist`. | linkFields | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def unlinkFields(self, unlinklist=None):
"""Remove fields from the link list or clears link given by the list of
string `linklist`.
This method has no effect if fields are not linked."""
link = self.link
if unlinklist is not None:
for l in unlinklist:
... | Remove fields from the link list or clears link given by the list of
string `linklist`.
This method has no effect if fields are not linked. | unlinkFields | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def getDimension(self, label):
"""Return the dimension/number of columns for the field given by
`label`."""
try:
dim = self.data[label].shape[1]
except KeyError:
raise KeyError('dataset field %s not found.' % label)
return dim | Return the dimension/number of columns for the field given by
`label`. | getDimension | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def getLength(self):
"""Return the length of the linked data fields. If no linked fields exist,
return the length of the longest field."""
if self.link == []:
try:
length = self.endmarker[max(self.endmarker)]
except ValueError:
return 0
... | Return the length of the linked data fields. If no linked fields exist,
return the length of the longest field. | getLength | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def _resizeArray(self, a):
"""Increase the buffer size. It should always be one longer than the
current sequence length and double on every growth step."""
shape = list(a.shape)
shape[0] = (shape[0] + 1) * 2
return resize(a, shape) | Increase the buffer size. It should always be one longer than the
current sequence length and double on every growth step. | _resizeArray | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def _appendUnlinked(self, label, row):
"""Append `row` to the field array with the given `label`.
Do not call this function from outside, use ,append() instead.
Automatically casts vector to a 2d (or higher) shape."""
if self.data[label].shape[0] <= self.endmarker[label]:
se... | Append `row` to the field array with the given `label`.
Do not call this function from outside, use ,append() instead.
Automatically casts vector to a 2d (or higher) shape. | _appendUnlinked | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def append(self, label, row):
"""Append `row` to the array given by `label`.
If the field is linked with others, the function throws an
`OutOfSyncError` because all linked fields always have to have the same
length. If you want to add a row to all linked fields, use appendLink
i... | Append `row` to the array given by `label`.
If the field is linked with others, the function throws an
`OutOfSyncError` because all linked fields always have to have the same
length. If you want to add a row to all linked fields, use appendLink
instead. | append | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def appendLinked(self, *args):
"""Add rows to all linked fields at once."""
assert len(args) == len(self.link)
for i, l in enumerate(self.link):
self._appendUnlinked(l, args[i]) | Add rows to all linked fields at once. | appendLinked | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def getLinked(self, index=None):
"""Access the dataset randomly or sequential.
If called with `index`, the appropriate line consisting of all linked
fields is returned and the internal marker is set to the next line.
Otherwise the marked line is returned and the marker is moved to the
... | Access the dataset randomly or sequential.
If called with `index`, the appropriate line consisting of all linked
fields is returned and the internal marker is set to the next line.
Otherwise the marked line is returned and the marker is moved to the
next line. | getLinked | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def getField(self, label):
"""Return the entire field given by `label` as an array or list,
depending on user settings."""
# Note: label_data should always be a np.array, so this will never
# actually clone a list (performances are O(1)).
label_data = self.data[label][:self.endma... | Return the entire field given by `label` as an array or list,
depending on user settings. | getField | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def convertField(self, label, newtype):
"""Convert the given field to a different data type."""
try:
self.setField(label, self.data[label].astype(newtype))
except KeyError:
raise KeyError('convertField: dataset field %s not found.' % label) | Convert the given field to a different data type. | convertField | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def clear(self, unlinked=False):
"""Clear the dataset.
If linked fields exist, only the linked fields will be deleted unless
`unlinked` is set to True. If no fields are linked, all data will be
deleted."""
self.reset()
keys = self.link
if keys == [] or unlinked:
... | Clear the dataset.
If linked fields exist, only the linked fields will be deleted unless
`unlinked` is set to True. If no fields are linked, all data will be
deleted. | clear | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def reconstruct(cls, filename):
"""Read an incomplete data set (option arraysonly) into the given one. """
# FIXME: Obsolete! Kept here because of some old files...
obj = cls(1, 1)
for key, val in pickle.load(file(filename)).items():
obj.setField(key, val)
return obj | Read an incomplete data set (option arraysonly) into the given one. | reconstruct | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def save_pickle(self, flo, protocol=0, compact=False):
"""Save data set as pickle, removing empty space if desired."""
if compact:
# remove padding of zeros for each field
for field in self.getFieldNames():
temp = self[field][0:self.endmarker[field] + 1, :]
... | Save data set as pickle, removing empty space if desired. | save_pickle | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def batches(self, label, n, permutation=None):
"""Yield batches of the size of n from the dataset.
A single batch is an array of with dim columns and n rows. The last
batch is possibly smaller.
If permutation is given, batches are yielded in the corresponding
order."""
... | Yield batches of the size of n from the dataset.
A single batch is an array of with dim columns and n rows. The last
batch is possibly smaller.
If permutation is given, batches are yielded in the corresponding
order. | batches | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def randomBatches(self, label, n):
"""Like .batches(), but the order is random."""
permutation = random.shuffle(list(range(len(self))))
return self.batches(label, n, permutation) | Like .batches(), but the order is random. | randomBatches | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def replaceNansByMeans(self):
"""Replace all not-a-number entries in the dataset by the means of the
corresponding column."""
for d in self.data.values():
means = scipy.nansum(d[:self.getLength()], axis=0) / self.getLength()
for i in range(self.getLength()):
... | Replace all not-a-number entries in the dataset by the means of the
corresponding column. | replaceNansByMeans | python | pybrain/pybrain | pybrain/datasets/dataset.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py | BSD-3-Clause |
def addSample(self, inp, target, importance=None):
""" adds a new sample consisting of input, target and importance.
:arg inp: the input of the sample
:arg target: the target of the sample
:key importance: the importance of the sample. If left None, the
impo... | adds a new sample consisting of input, target and importance.
:arg inp: the input of the sample
:arg target: the target of the sample
:key importance: the importance of the sample. If left None, the
importance will be set to 1.0
| addSample | python | pybrain/pybrain | pybrain/datasets/importance.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/importance.py | BSD-3-Clause |
def _evaluateSequence(self, f, seq, verbose = False):
""" return the importance-ponderated MSE over one sequence. """
totalError = 0
ponderation = 0.
for input, target, importance in seq:
res = f(input)
e = 0.5 * dot(importance.flatten(), ((target-res).flatten()**... | return the importance-ponderated MSE over one sequence. | _evaluateSequence | python | pybrain/pybrain | pybrain/datasets/importance.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/importance.py | BSD-3-Clause |
def __init__(self, statedim, actiondim):
""" initialize the reinforcement dataset, add the 3 fields state, action and
reward, and create an index marker. This class is basically a wrapper function
that renames the fields of SupervisedDataSet into the more common reinforcement
... | initialize the reinforcement dataset, add the 3 fields state, action and
reward, and create an index marker. This class is basically a wrapper function
that renames the fields of SupervisedDataSet into the more common reinforcement
learning names. Instead of 'episodes' though, we de... | __init__ | python | pybrain/pybrain | pybrain/datasets/reinforcement.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/reinforcement.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.