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 about_html(self): """Get the html for the /about page. Currently unused for any functionality. :rtype: str """ if self._about_html: return self._about_html else: self._about_html = request.get(self.about_url) return self._about_ht...
Get the html for the /about page. Currently unused for any functionality. :rtype: str
about_html
python
pytube/pytube
pytube/contrib/channel.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/channel.py
Unlicense
def _extract_videos(raw_json: str) -> Tuple[List[str], Optional[str]]: """Extracts videos from a raw json page :param str raw_json: Input json extracted from the page or the last server response :rtype: Tuple[List[str], Optional[str]] :returns: Tuple containing a list of up ...
Extracts videos from a raw json page :param str raw_json: Input json extracted from the page or the last server response :rtype: Tuple[List[str], Optional[str]] :returns: Tuple containing a list of up to 100 video watch ids and a continuation token, if more videos are av...
_extract_videos
python
pytube/pytube
pytube/contrib/channel.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/channel.py
Unlicense
def playlist_id(self): """Get the playlist id. :rtype: str """ if self._playlist_id: return self._playlist_id self._playlist_id = extract.playlist_id(self._input_url) return self._playlist_id
Get the playlist id. :rtype: str
playlist_id
python
pytube/pytube
pytube/contrib/playlist.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/playlist.py
Unlicense
def html(self): """Get the playlist page html. :rtype: str """ if self._html: return self._html self._html = request.get(self.playlist_url) return self._html
Get the playlist page html. :rtype: str
html
python
pytube/pytube
pytube/contrib/playlist.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/playlist.py
Unlicense
def ytcfg(self): """Extract the ytcfg from the playlist page html. :rtype: dict """ if self._ytcfg: return self._ytcfg self._ytcfg = extract.get_ytcfg(self.html) return self._ytcfg
Extract the ytcfg from the playlist page html. :rtype: dict
ytcfg
python
pytube/pytube
pytube/contrib/playlist.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/playlist.py
Unlicense
def initial_data(self): """Extract the initial data from the playlist page html. :rtype: dict """ if self._initial_data: return self._initial_data else: self._initial_data = extract.initial_data(self.html) return self._initial_data
Extract the initial data from the playlist page html. :rtype: dict
initial_data
python
pytube/pytube
pytube/contrib/playlist.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/playlist.py
Unlicense
def sidebar_info(self): """Extract the sidebar info from the playlist page html. :rtype: dict """ if self._sidebar_info: return self._sidebar_info else: self._sidebar_info = self.initial_data['sidebar'][ 'playlistSidebarRenderer']['items']...
Extract the sidebar info from the playlist page html. :rtype: dict
sidebar_info
python
pytube/pytube
pytube/contrib/playlist.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/playlist.py
Unlicense
def _paginate( self, until_watch_id: Optional[str] = None ) -> Iterable[List[str]]: """Parse the video links from the page source, yields the /watch?v= part from video link :param until_watch_id Optional[str]: YouTube Video watch id until which the playlist should be rea...
Parse the video links from the page source, yields the /watch?v= part from video link :param until_watch_id Optional[str]: YouTube Video watch id until which the playlist should be read. :rtype: Iterable[List[str]] :returns: Iterable of lists of YouTube watch ids
_paginate
python
pytube/pytube
pytube/contrib/playlist.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/playlist.py
Unlicense
def _build_continuation_url(self, continuation: str) -> Tuple[str, dict, dict]: """Helper method to build the url and headers required to request the next page of videos :param str continuation: Continuation extracted from the json response of the last page :rtype: Tuple[str...
Helper method to build the url and headers required to request the next page of videos :param str continuation: Continuation extracted from the json response of the last page :rtype: Tuple[str, dict, dict] :returns: Tuple of an url and required headers for the next http ...
_build_continuation_url
python
pytube/pytube
pytube/contrib/playlist.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/playlist.py
Unlicense
def _extract_videos(raw_json: str) -> Tuple[List[str], Optional[str]]: """Extracts videos from a raw json page :param str raw_json: Input json extracted from the page or the last server response :rtype: Tuple[List[str], Optional[str]] :returns: Tuple containing a list of up ...
Extracts videos from a raw json page :param str raw_json: Input json extracted from the page or the last server response :rtype: Tuple[List[str], Optional[str]] :returns: Tuple containing a list of up to 100 video watch ids and a continuation token, if more videos are av...
_extract_videos
python
pytube/pytube
pytube/contrib/playlist.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/playlist.py
Unlicense
def trimmed(self, video_id: str) -> Iterable[str]: """Retrieve a list of YouTube video URLs trimmed at the given video ID i.e. if the playlist has video IDs 1,2,3,4 calling trimmed(3) returns [1,2] :type video_id: str video ID to trim the returned list of playlist URLs at ...
Retrieve a list of YouTube video URLs trimmed at the given video ID i.e. if the playlist has video IDs 1,2,3,4 calling trimmed(3) returns [1,2] :type video_id: str video ID to trim the returned list of playlist URLs at :rtype: List[str] :returns: List of ...
trimmed
python
pytube/pytube
pytube/contrib/playlist.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/playlist.py
Unlicense
def url_generator(self): """Generator that yields video URLs. :Yields: Video URLs """ for page in self._paginate(): for video in page: yield self._video_url(video)
Generator that yields video URLs. :Yields: Video URLs
url_generator
python
pytube/pytube
pytube/contrib/playlist.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/playlist.py
Unlicense
def last_updated(self) -> Optional[date]: """Extract the date that the playlist was last updated. For some playlists, this will be a specific date, which is returned as a datetime object. For other playlists, this is an estimate such as "1 week ago". Due to the fact that this value is r...
Extract the date that the playlist was last updated. For some playlists, this will be a specific date, which is returned as a datetime object. For other playlists, this is an estimate such as "1 week ago". Due to the fact that this value is returned as a string, pytube does a best-effort parsin...
last_updated
python
pytube/pytube
pytube/contrib/playlist.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/playlist.py
Unlicense
def length(self): """Extract the number of videos in the playlist. :return: Playlist video count :rtype: int """ count_text = self.sidebar_info[0]['playlistSidebarPrimaryInfoRenderer'][ 'stats'][0]['runs'][0]['text'] count_text = count_text.replace(',','') ...
Extract the number of videos in the playlist. :return: Playlist video count :rtype: int
length
python
pytube/pytube
pytube/contrib/playlist.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/playlist.py
Unlicense
def views(self): """Extract view count for playlist. :return: Playlist view count :rtype: int """ # "1,234,567 views" views_text = self.sidebar_info[0]['playlistSidebarPrimaryInfoRenderer'][ 'stats'][1]['simpleText'] # "1,234,567" count_text =...
Extract view count for playlist. :return: Playlist view count :rtype: int
views
python
pytube/pytube
pytube/contrib/playlist.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/playlist.py
Unlicense
def __init__(self, query): """Initialize Search object. :param str query: Search query provided by the user. """ self.query = query self._innertube_client = InnerTube(client='WEB') # The first search, without a continuation, is structured differently ...
Initialize Search object. :param str query: Search query provided by the user.
__init__
python
pytube/pytube
pytube/contrib/search.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/search.py
Unlicense
def completion_suggestions(self): """Return query autocompletion suggestions for the query. :rtype: list :returns: A list of autocomplete suggestions provided by YouTube for the query. """ if self._completion_suggestions: return self._completion_suggestio...
Return query autocompletion suggestions for the query. :rtype: list :returns: A list of autocomplete suggestions provided by YouTube for the query.
completion_suggestions
python
pytube/pytube
pytube/contrib/search.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/search.py
Unlicense
def results(self): """Return search results. On first call, will generate and return the first set of results. Additional results can be generated using ``.get_next_results()``. :rtype: list :returns: A list of YouTube objects. """ if self._results: ...
Return search results. On first call, will generate and return the first set of results. Additional results can be generated using ``.get_next_results()``. :rtype: list :returns: A list of YouTube objects.
results
python
pytube/pytube
pytube/contrib/search.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/search.py
Unlicense
def get_next_results(self): """Use the stored continuation string to fetch the next set of results. This method does not return the results, but instead updates the results property. """ if self._current_continuation: videos, continuation = self.fetch_and_parse(self._current...
Use the stored continuation string to fetch the next set of results. This method does not return the results, but instead updates the results property.
get_next_results
python
pytube/pytube
pytube/contrib/search.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/search.py
Unlicense
def fetch_and_parse(self, continuation=None): """Fetch from the innertube API and parse the results. :param str continuation: Continuation string for fetching results. :rtype: tuple :returns: A tuple of a list of YouTube objects and a continuation string. ...
Fetch from the innertube API and parse the results. :param str continuation: Continuation string for fetching results. :rtype: tuple :returns: A tuple of a list of YouTube objects and a continuation string.
fetch_and_parse
python
pytube/pytube
pytube/contrib/search.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/search.py
Unlicense
def fetch_query(self, continuation=None): """Fetch raw results from the innertube API. :param str continuation: Continuation string for fetching results. :rtype: dict :returns: The raw json object returned by the innertube API. """ query_results =...
Fetch raw results from the innertube API. :param str continuation: Continuation string for fetching results. :rtype: dict :returns: The raw json object returned by the innertube API.
fetch_query
python
pytube/pytube
pytube/contrib/search.py
https://github.com/pytube/pytube/blob/master/pytube/contrib/search.py
Unlicense
def load_and_init_from_playback_file(filename, mock_urlopen): """Load a gzip json playback file and create YouTube instance.""" pb = load_playback_file(filename) # Mock the responses to YouTube mock_url_open_object = mock.Mock() mock_url_open_object.read.side_effect = [ pb['watch_html'].enc...
Load a gzip json playback file and create YouTube instance.
load_and_init_from_playback_file
python
pytube/pytube
tests/conftest.py
https://github.com/pytube/pytube/blob/master/tests/conftest.py
Unlicense
def playlist_html(): """Youtube playlist HTML loaded on 2020-01-25 from https://www.youtube.com/playlist?list=PLzMcBGfZo4-mP7qA9cagf68V06sko5otr """ file_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "mocks", "playlist.html.gz", ) with gzip.open(file_p...
Youtube playlist HTML loaded on 2020-01-25 from https://www.youtube.com/playlist?list=PLzMcBGfZo4-mP7qA9cagf68V06sko5otr
playlist_html
python
pytube/pytube
tests/conftest.py
https://github.com/pytube/pytube/blob/master/tests/conftest.py
Unlicense
def playlist_long_html(): """Youtube playlist HTML loaded on 2020-01-25 from https://www.youtube.com/playlist?list=PLzMcBGfZo4-mP7qA9cagf68V06sko5otr """ file_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "mocks", "playlist_long.html.gz", ) with gzip.o...
Youtube playlist HTML loaded on 2020-01-25 from https://www.youtube.com/playlist?list=PLzMcBGfZo4-mP7qA9cagf68V06sko5otr
playlist_long_html
python
pytube/pytube
tests/conftest.py
https://github.com/pytube/pytube/blob/master/tests/conftest.py
Unlicense
def playlist_submenu_html(): """Youtube playlist HTML loaded on 2020-01-24 from https://www.youtube.com/playlist?list=PLZHQObOWTQDMsr9K-rj53DwVRMYO3t5Yr """ file_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "mocks", "playlist_submenu.html.gz", ) with ...
Youtube playlist HTML loaded on 2020-01-24 from https://www.youtube.com/playlist?list=PLZHQObOWTQDMsr9K-rj53DwVRMYO3t5Yr
playlist_submenu_html
python
pytube/pytube
tests/conftest.py
https://github.com/pytube/pytube/blob/master/tests/conftest.py
Unlicense
def stream_dict(): """Youtube instance initialized with video id WXxV9g7lsFE.""" file_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "mocks", "yt-video-WXxV9g7lsFE-html.json.gz", ) with gzip.open(file_path, "rb") as f: content = json.loads(f.read().deco...
Youtube instance initialized with video id WXxV9g7lsFE.
stream_dict
python
pytube/pytube
tests/conftest.py
https://github.com/pytube/pytube/blob/master/tests/conftest.py
Unlicense
def channel_videos_html(): """Youtube channel HTML loaded on 2021-05-05 from https://www.youtube.com/c/ProgrammingKnowledge/videos """ file_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "mocks", "channel-videos.html.gz", ) with gzip.open(file_path, 'rb...
Youtube channel HTML loaded on 2021-05-05 from https://www.youtube.com/c/ProgrammingKnowledge/videos
channel_videos_html
python
pytube/pytube
tests/conftest.py
https://github.com/pytube/pytube/blob/master/tests/conftest.py
Unlicense
def base_js(): """Youtube base.js files retrieved on 2022-02-04 and 2022-04-15 from https://www.youtube.com/watch?v=vmzxpUsN0uA and https://www.youtube.com/watch?v=Y4-GSFKZmEg respectively """ base_js_files = [] for file in ["base.js-2022-02-04.gz", "base.js-2022-04-15.gz"]: file_path = ...
Youtube base.js files retrieved on 2022-02-04 and 2022-04-15 from https://www.youtube.com/watch?v=vmzxpUsN0uA and https://www.youtube.com/watch?v=Y4-GSFKZmEg respectively
base_js
python
pytube/pytube
tests/conftest.py
https://github.com/pytube/pytube/blob/master/tests/conftest.py
Unlicense
def test_safe_filename(): """Unsafe characters get stripped from generated filename""" assert helpers.safe_filename("abc1245$$") == "abc1245" assert helpers.safe_filename("abc##") == "abc"
Unsafe characters get stripped from generated filename
test_safe_filename
python
pytube/pytube
tests/test_helpers.py
https://github.com/pytube/pytube/blob/master/tests/test_helpers.py
Unlicense
def test_filters(test_input, expected, cipher_signature): """Ensure filters produce the expected results.""" result = [s.itag for s in cipher_signature.streams.filter(**test_input)] assert result == expected
Ensure filters produce the expected results.
test_filters
python
pytube/pytube
tests/test_query.py
https://github.com/pytube/pytube/blob/master/tests/test_query.py
Unlicense
def test_empty(test_input, cipher_signature): """Ensure :meth:`~pytube.StreamQuery.last` and :meth:`~pytube.StreamQuery.first` return None if the resultset is empty. """ query = cipher_signature.streams.filter(video_codec="vp20") fn = getattr(query, test_input) assert fn() is None
Ensure :meth:`~pytube.StreamQuery.last` and :meth:`~pytube.StreamQuery.first` return None if the resultset is empty.
test_empty
python
pytube/pytube
tests/test_query.py
https://github.com/pytube/pytube/blob/master/tests/test_query.py
Unlicense
def test_order_by(cipher_signature): """Ensure :meth:`~pytube.StreamQuery.order_by` sorts the list of :class:`Stream <Stream>` instances in the expected order. """ itags = [ s.itag for s in cipher_signature.streams.filter(type="audio").order_by("itag") ] expected_itags = [ ...
Ensure :meth:`~pytube.StreamQuery.order_by` sorts the list of :class:`Stream <Stream>` instances in the expected order.
test_order_by
python
pytube/pytube
tests/test_query.py
https://github.com/pytube/pytube/blob/master/tests/test_query.py
Unlicense
def test_order_by_descending(cipher_signature): """Ensure :meth:`~pytube.StreamQuery.desc` sorts the list of :class:`Stream <Stream>` instances in the reverse 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 the reverse order.
test_order_by_descending
python
pytube/pytube
tests/test_query.py
https://github.com/pytube/pytube/blob/master/tests/test_query.py
Unlicense
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