changes to dataset
This commit is contained in:
parent
f746a3efe8
commit
174445af8f
@ -1,389 +0,0 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Introduction\n",
|
||||
"\n",
|
||||
"This notebook shows how to set-up a working python envirnoment for the Machine Learning Practical course.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Setting up the software\n",
|
||||
"\n",
|
||||
"Within this course we are going to work with python (using some auxiliary libraries like numpy and scipy). Depending on the infrastracture and working environment (e.g. DICE), root permission may not be not available so the packages cannot be installed in default locations. A convenient python configuration, which allows us to install and update third party libraries easily using package manager, are so called virtual environments. They can be also used to work (and test) the code with different versions of software.\n",
|
||||
"\n",
|
||||
"## Instructions for Windows\n",
|
||||
"\n",
|
||||
"The fastest way to get working setup on Windows is to install Anaconda (http://www.continuum.io) package. It's a python environment with precompiled versions of the most popular scientific python libraries. It also works on MacOS, but numpy is not linked without a fee to a numerical library, hence for MacOS we recommend the following procedure.\n",
|
||||
"\n",
|
||||
"## Instructions for MacOS\n",
|
||||
"\n",
|
||||
" * Install macports following instructions at https://www.macports.org/install.php\n",
|
||||
" * Install the relevant python packages in macports\n",
|
||||
"\n",
|
||||
" ```\n",
|
||||
" sudo port install py27-scipy +openblas\n",
|
||||
" sudo port install py27-ipython +notebook\n",
|
||||
" sudo port install py27-notebook\n",
|
||||
" sudo port install py27-matplotlib\n",
|
||||
" sudo port select --set python python27\n",
|
||||
" sudo port select --set ipython2 py27-ipython\n",
|
||||
" sudo port select --set ipython py27-ipython\n",
|
||||
" ```\n",
|
||||
"\n",
|
||||
"Make sure that your `$PATH` has `/opt/local/bin` before `/usr/bin` so you pick up the version of python you just installed.\n",
|
||||
"\n",
|
||||
"## Instructions for DICE:\n",
|
||||
"\n",
|
||||
"### Directory structure and getting things organised\n",
|
||||
"\n",
|
||||
"To get things somehow standarized between people, and make life of everyone easier, we propse to organise your DICE setup in the following directory structure:\n",
|
||||
"\n",
|
||||
" * `~/mlpractical/` -- for a general course repository\n",
|
||||
" * `~/mlpractical/repos-3rd` -- for stuff you download, build and install (numpy, OpenBlas, virtualenv)\n",
|
||||
" * `~/mlpractical/repo-mlp` -- this is the actual course repository you clone from our website (do not create a dir for it yet!)\n",
|
||||
" * `~/mlpractical/venv` -- this is where virutal envirnoment will make its dir (do not create a dir for it yet!)\n",
|
||||
"\n",
|
||||
"Create now repos-3rd directory (option -p in the below command will automatically create (non-existing) **p**arent directories (mlpractical):\n",
|
||||
"\n",
|
||||
" * `mkdir -p ~/mlpractical/repos-3rd`\n",
|
||||
"\n",
|
||||
"And now, let us set an MLP_WDIR environmental variable (MLP Working DIRectory) that will keep an absolute path of working dir pointing to `~/mlpractial`, **add the below line** to your `~/.bashrc` file (if it does not exists, create one!):\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"export MLP_WDIR=~/mlpractical\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"Now re-source `~/.bashrc` by typing (so the env variables get updated!): `source ~/.bashrc`\n",
|
||||
"\n",
|
||||
"Enter the `repos-3rd` directory by typing: `cd ~/mlpractical/repos-3rd` (or ```cd $MLP_WDIR/repos-3rd``` if you want)\n",
|
||||
"\n",
|
||||
"### Configuring virtual environment\n",
|
||||
"\n",
|
||||
"Make sure you are in `repos-3rd` directory and that MLP_WDIR variable has been exported (you may type export in the terminal and examine the list of availabe variables in the current session), then type:\n",
|
||||
"\n",
|
||||
" * `git clone https://github.com/pypa/virtualenv`\n",
|
||||
" * Enter the cloned repository and type ```./virtualenv.py --python /usr/bin/python2.7 --no-site-packages $MLP_WDIR/venv```\n",
|
||||
" * Activate the environment by typing `source ~/mlpractical/venv/bin/activate` (to leave the virtual environment one may type `decativate`)\n",
|
||||
" * Environments need to be activated every time ones start the new session so we will now create a handy alias to it in `~/.bashrc` script, by typing the below command (note, MLP_WDIR export needs to preceed this command):\n",
|
||||
" \n",
|
||||
" ```alias activate_mlp=\"source $MLP_WDIR/venv/bin/activate\"```\n",
|
||||
" \n",
|
||||
"Then every time you open new session and want to activate the right virtual environment, simply type `activate_mlp` instead `source ~/mlpractical/venv/bin/activate`. Note, you need to re-soure the .bashrc in order alias to be visible in the current session.\n",
|
||||
"\n",
|
||||
"### Installing remaining packages\n",
|
||||
"\n",
|
||||
"Then, before you follow next, install/upgrade the following packages:\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"pip install --upgrade pip\n",
|
||||
"pip install setuptools\n",
|
||||
"pip install setuptools --upgrade\n",
|
||||
"pip install ipython\n",
|
||||
"pip install notebook\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"### Installing numpy\n",
|
||||
"\n",
|
||||
"Note, having virtual environment properly installed one may then run `pip install numpy` to use pip to install numpy, though this will most likely lead to the suboptimal configuration where numpy is linked to ATLAS numerical library, which on DICE is compiled in multi-threaded mode. This means whenever numpy use BLAS accelerated computations (using ATLAS), it will use **all** the available cores at the given machine. This happens because ATLAS can be compiled to either run computations in single *or* multi threaded modes. However, contrary to some other backends, the latter does not allow to use an arbitrary number of threads (specified by the user prior to computation). This is highly suboptimal, as the potential speed-up resulting from paralleism depends on many factors like the communication overhead between threads, the size of the problem, etc. Using all cores for our exercises is not-necessary.\n",
|
||||
"\n",
|
||||
"For which reason, we are going to compile our own version of BLAS package, called *OpenBlas*. It allows to specify the number of threads manually by setting an environmental variable OMP_NUM_THREADS=N, where N is a desired number of parallel threads (please use 1 by default). You can set an environment variable in the current shell by running\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"export OMP_NUM_THREADS=1\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"(note the lack of spaces around the equals sign and use of `export` to define an environment variable which will be available in sub-shells rather than just a variable local to the current shell).\n",
|
||||
"\n",
|
||||
"#### OpenBlas\n",
|
||||
"\n",
|
||||
"Enter again repos-3rd directory (`cd ~/mlpractical/repos-3rd) and copy into terminal the following commands (one at the time):\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"OBDir=$MLP_WDIR/repos-3rd/OpenBLAS\n",
|
||||
"git clone git://github.com/xianyi/OpenBLAS\n",
|
||||
"cd OpenBLAS\n",
|
||||
"make\n",
|
||||
"make PREFIX=$OBDir/lib install\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"Once OpenBLAS is finished compiling we need to ensure the compiled shared library files in the `lib` subdirectory are available to the shared library loader. This can be done by appending the absolute path to the `lib` subdirectory to the `LD_LIBRARY_PATH` environment variable. To ensure this changes persist we will change the bash start up file `~/.bashrc` by opening it in a text editor (e.g. by running `gedit ~/.bashrc`) and adding the following line\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$MLP_WDIR/repos-3rd/OpenBLAS/lib\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"Note, we again are using MLP_WDIR here, so the above line needs to be placed after you set MLP_WDIR.\n",
|
||||
"\n",
|
||||
"After you have edited `.bashrc` run\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"source ~/.bashrc\n",
|
||||
"source ~/mlpractical/venv/bin/activate\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"to rerun the bash start up script make sure the new environment variable is available in the current shell and then reactivate the virtual environment.\n",
|
||||
"\n",
|
||||
"#### Numpy\n",
|
||||
"\n",
|
||||
"To install `numpy` linked against the OpenBLAS libraries we just compiled, first run the following commands (one at a time)\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"cd ~/mlpractical/repos-3rd/\n",
|
||||
"wget http://downloads.sourceforge.net/project/numpy/NumPy/1.9.2/numpy-1.9.2.zip\n",
|
||||
"unzip numpy-1.9.2.zip\n",
|
||||
"cd numpy-1.9.2\n",
|
||||
"echo \"[openblas]\" >> site.cfg\n",
|
||||
"echo \"library_dirs = $OBDir/lib\" >> site.cfg\n",
|
||||
"echo \"include_dirs = $OBDir/include\" >> site.cfg\n",
|
||||
"python setup.py build --fcompiler=gnu95\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"Assuming the virtual environment is activated, the below command will install numpy in a desired space (`~/mlpractical/venv/...`):\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"python setup.py install\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"Now use pip to install remaining packages: `scipy`, `matplotlib`, `argparse`, `nose`,\n",
|
||||
"\n",
|
||||
"### Getting the mlpractical repository\n",
|
||||
"\n",
|
||||
"Clone the course repository from the github, by navigating to `~/mlpractical` directory and typing:\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"git clone https://github.com/CSTR-Edinburgh/mlpractical.git repo-mlp\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"When download is ready, enter the repo-mlp directory (`cd repo-mlp`) and start the actual interactive notebook session by typing:\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"ipython notebook\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"This should start a ipython server which opens a new browser window listing files in `repo-mlp` directory, including `00_Introduction.ipynb.`. Open it and run (from the browser interface) the following examples and exercies."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": false,
|
||||
"scrolled": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%clear\n",
|
||||
"import numpy\n",
|
||||
"# show_config() prints the configuration of numpy numerical backend \n",
|
||||
"# you should be able to see linkage to OpenBlas or some other library\n",
|
||||
"# in case those are empty, it means something went wrong and \n",
|
||||
"# numpy will use a default (slow) pythonic implementation for algebra\n",
|
||||
"numpy.show_config()\n",
|
||||
"#numpy.test()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Also, below we check whether and how much speedup one may expect by using different number of cores:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": false
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"import multiprocessing\n",
|
||||
"import timeit\n",
|
||||
"\n",
|
||||
"num_cores = multiprocessing.cpu_count()\n",
|
||||
"N = 1000\n",
|
||||
"x = numpy.random.random((N,N))\n",
|
||||
"\n",
|
||||
"for i in xrange(0, num_cores):\n",
|
||||
" # first, set the number of threads OpenBLAS\n",
|
||||
" # should use, the below line is equivalent\n",
|
||||
" # to typing export OMP_NUM_THREADS=i+1 in bash shell\n",
|
||||
" print 'Running matrix-matrix product on %i core(s)' % i\n",
|
||||
" os.environ['OMP_NUM_THREADS'] = str(i+1)\n",
|
||||
" %%timeit numpy.dot(x,x.T)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Test whether you can plot and display the figures using pyplot"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": false
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"\n",
|
||||
"x = numpy.linspace(0.0, 2*numpy.pi, 100)\n",
|
||||
"y1 = numpy.sin(x)\n",
|
||||
"y2 = numpy.cos(x)\n",
|
||||
"\n",
|
||||
"plt.plot(x, y1, lw=2, label=r'$\\sin(x)$')\n",
|
||||
"plt.plot(x, y2, lw=2, label=r'$\\cos(x)$')\n",
|
||||
"plt.xlabel('x')\n",
|
||||
"plt.ylabel('y')\n",
|
||||
"plt.legend()\n",
|
||||
"plt.xlim(0.0, 2*numpy.pi)\n",
|
||||
"plt.grid()\n",
|
||||
"plt.show()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Exercises\n",
|
||||
"\n",
|
||||
"Today exercises are meant to get you familiar with ipython notebooks (if you haven't used them so far), data organisation and how to access it. Next week onwars, we will follow with the material covered in lectures.\n",
|
||||
"\n",
|
||||
"## Data providers\n",
|
||||
"\n",
|
||||
"Open (in the browser) `mlp.dataset` module (go to `Home` tab and navigate to mlp package, then click on the link `dataset.py`). Have a look thourgh the code and comments, then follow to exercises.\n",
|
||||
"\n",
|
||||
"<b>General note:</b> you can load the mlp code into your favourite python IDE but it is totally OK if you work (modify & save) the code directly in the browser by opening/modyfing the necessary modules in the tabs.\n",
|
||||
"\n",
|
||||
"### Exercise 1 \n",
|
||||
"\n",
|
||||
"Using MNISTDataProvider, write a code that iterates over the first 5 minibatches of size 100 data-points. Print MNIST digits in 10x10 images grid plot. Images are returned from the provider as tuples of numpy arrays `(features, targets)`. The `features` matrix has shape BxD while the `targets` vector is of size B, where B is the size of a mini-batch and D is dimensionality of the features. By deafult, each data-point (image) is stored in a 784 dimensional vector of pixel intensities normalised to [0,1] range from an inital integer values [0-255]. However, the original spatial domain is two dimensional, so before plotting you need to convert it into 2D matrix (MNIST images have the same number of pixels for height and width).\n",
|
||||
"\n",
|
||||
"Tip: Useful functions for this exercise are: imshow, subplot, gridspec"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": false
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"import matplotlib.gridspec as gridspec\n",
|
||||
"import matplotlib.cm as cm\n",
|
||||
"from mlp.dataset import MNISTDataProvider\n",
|
||||
"\n",
|
||||
"def show_mnist_image(img):\n",
|
||||
" fig = plt.figure()\n",
|
||||
" gs = gridspec.GridSpec(1, 1)\n",
|
||||
" ax1 = fig.add_subplot(gs[0,0])\n",
|
||||
" ax1.imshow(img, cmap=cm.Greys_r)\n",
|
||||
" plt.show()\n",
|
||||
"\n",
|
||||
"def show_mnist_images(batch):\n",
|
||||
" raise NotImplementedError('Write me!')\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": false
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# An example for a single MNIST image\n",
|
||||
"mnist_dp = MNISTDataProvider(dset='valid', batch_size=1, max_num_examples=2, randomize=False)\n",
|
||||
"\n",
|
||||
"for batch in mnist_dp:\n",
|
||||
" features, targets = batch\n",
|
||||
" show_mnist_image(features.reshape(28, 28))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": false
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"#implement here Exercise 1"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Exercise 2\n",
|
||||
"\n",
|
||||
"`MNISTDataProvider` as `targets` currently returns a vector of integers, each element in this vector represents an id of the category `features` data-point represent. Later in the course we are going to need 1-of-K representation of targets, for instance, given the minibatch of size 3 and the corresponding targets vector $[2, 2, 0]$ (and assuming there are only 3 different classes to discriminate between), one needs to convert it into matrix $\\left[ \\begin{array}{ccc}\n",
|
||||
"0 & 0 & 1 \\\\\n",
|
||||
"0 & 0 & 1 \\\\\n",
|
||||
"1 & 0 & 0 \\end{array} \\right]$. \n",
|
||||
"\n",
|
||||
"Implement `__to_one_of_k` method of `MNISTDataProvider` class. Then modify (uncomment) an appropriate line in its `next` method, so the raw targets get converted to `1 of K` coding. Test the code in the cell below."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"collapsed": true
|
||||
},
|
||||
"source": [
|
||||
"### Exercise 3\n",
|
||||
"\n",
|
||||
"Write your own data provider `MetOfficeDataProvider` that wraps the weather data for south Scotland (could be obtained from: http://www.metoffice.gov.uk/hadobs/hadukp/data/daily/HadSSP_daily_qc.txt). The file was also downloaded and stored in `data` directory for your convenience. The provider should return a tuple `(x,t)` of the estimates over an arbitrary time windows (i.e. last N-1 days) for `x` and the N-th day as the one which model should be able to predict, `t`. For now, skip missing data-points (denoted by -99.9) and simply use the next correct value. Make sure the provider works for arbitrary `batch_size` settings, including the case where single mini-batch is equal to all datapoints in the dataset. Test the dataset in the cell below.\n",
|
||||
"\n",
|
||||
"Tip: To follow with this exercise, copy MNISTDataProvider in dataset.py, rename it to `MetOfficeDataProvider` and reimplement necesarry parts (including the arguments you pass to the constructor)."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 2",
|
||||
"language": "python",
|
||||
"name": "python2"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 2
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython2",
|
||||
"version": "2.7.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
105
mlp/dataset.py
105
mlp/dataset.py
@ -42,11 +42,16 @@ class DataProvider(object):
|
||||
raise NotImplementedError()
|
||||
|
||||
def __iter__(self):
|
||||
"""
|
||||
This method says an object is iterable.
|
||||
"""
|
||||
return self
|
||||
|
||||
def next(self):
|
||||
"""
|
||||
Data-specific iteration mechanism.
|
||||
Data-specific iteration mechanism. Called each step
|
||||
(i.e. each iteration in a loop)
|
||||
unitl StopIteration() exception is raised.
|
||||
:return:
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
@ -94,7 +99,7 @@ class MNISTDataProvider(DataProvider):
|
||||
|
||||
def __randomize(self):
|
||||
assert isinstance(self.x, numpy.ndarray)
|
||||
return numpy.random.permute(numpy.arange(0, self.x.shape[0]))
|
||||
return numpy.random.permutation(numpy.arange(0, self.x.shape[0]))
|
||||
|
||||
def next(self):
|
||||
|
||||
@ -117,18 +122,100 @@ class MNISTDataProvider(DataProvider):
|
||||
|
||||
self._curr_idx += self.batch_size
|
||||
|
||||
#return rval_x, self.__to_one_of_k(rval_y)
|
||||
return rval_x, self.__to_one_of_k(rval_y)
|
||||
return rval_x, rval_t
|
||||
|
||||
def __to_one_of_k(self, y):
|
||||
raise NotImplementedError('Write me!')
|
||||
rval = numpy.zeros((y.shape[0], self.num_classes), dtype=numpy.float32)
|
||||
for i in xrange(y.shape[0]):
|
||||
rval[i, y[i]] = 1
|
||||
return rval
|
||||
|
||||
|
||||
class MetOfficeDataProvider_(DataProvider):
|
||||
"""
|
||||
The class iterates over South Scotland Weather, in possibly
|
||||
random order.
|
||||
"""
|
||||
def __init__(self, window_size,
|
||||
batch_size=10,
|
||||
max_num_batches=-1,
|
||||
randomize=True):
|
||||
|
||||
super(MetOfficeDataProvider_, self).\
|
||||
__init__(batch_size, randomize)
|
||||
|
||||
dset_path = './data/HadSSP_daily_qc.txt'
|
||||
assert os.path.isfile(dset_path), (
|
||||
"File %s was expected to exist!." % dset_path
|
||||
)
|
||||
|
||||
raw = numpy.loadtxt(dset_path, skiprows=3, usecols=range(2, 32))
|
||||
|
||||
self.window_size = windows_size
|
||||
#filter out all missing datapoints and
|
||||
#flatten a matrix to a vector, so we will get
|
||||
#a time preserving representation of measurments
|
||||
#with self.x[0] being the first day and self.x[-1] the last
|
||||
self.x = raw[raw < 0].flatten()
|
||||
self._max_num_examples = max_num_examples
|
||||
|
||||
self._rand_idx = None
|
||||
if self.randomize:
|
||||
self._rand_idx = self.__randomize()
|
||||
|
||||
def reset(self):
|
||||
super(MetOfficeDataProvider_, self).reset()
|
||||
if self.randomize:
|
||||
self._rand_idx = self.__randomize()
|
||||
|
||||
def __randomize(self):
|
||||
assert isinstance(self.x, numpy.ndarray)
|
||||
# we generate random indexes starting from window_size, i.e. 10th absolute element
|
||||
# in the self.x vector, as we later during minibatch preparation slice
|
||||
# the self.x container backwards, i.e. given we want to get a training
|
||||
# data-point for 11th day, we look at 10 preeceding days.
|
||||
# Note, we cannot do this, for example, for the 5th day as
|
||||
# we do not have enough observations to make an input (10 days) to the model
|
||||
return numpy.random.permutation(numpy.arange(self.window_size, self.x.shape[0]))
|
||||
|
||||
def next(self):
|
||||
|
||||
has_enough = (self._curr_idx + self.batch_size) <= self.x.shape[0]
|
||||
presented_max = (self._max_num_examples > 0 and
|
||||
self._curr_idx + self.batch_size > self._max_num_examples)
|
||||
|
||||
if not has_enough or presented_max:
|
||||
raise StopIteration()
|
||||
|
||||
if self._rand_idx is not None:
|
||||
range_idx = \
|
||||
self._rand_idx[self._curr_idx:self._curr_idx + self.batch_size]
|
||||
else:
|
||||
range_idx = \
|
||||
numpy.arange(self._curr_idx, self._curr_idx + self.batch_size)
|
||||
|
||||
#build slicing matrix of size minibatch, which will contain batch_size
|
||||
#rows, each keeping indexes that selects windows_size+1 [for (x,t)] elements
|
||||
#from data vector (self.x) that itself stays always sorted w.r.t time
|
||||
range_slices = numpy.zeros((self.batch_size, self.window_size + 1))
|
||||
for i in xrange(0, self.batch_size):
|
||||
range_slices[i,:] = \
|
||||
numpy.arange(range_idx[i], range_idx[i] - self.window_size - 1, -1)[::-1]
|
||||
|
||||
#here we use advanced indexing to select slices from observation vector
|
||||
#last column of rval_x makes our targets t
|
||||
rval_x = self.x[range_slices]
|
||||
|
||||
self._curr_idx += self.batch_size
|
||||
|
||||
return rval_x[:,:-1], rval[:,-1]
|
||||
|
||||
|
||||
class FuncDataProvider(DataProvider):
|
||||
"""
|
||||
Function gets as an argument a list of functions random samples
|
||||
drawn from normal distribution which means are defined by those
|
||||
functions.
|
||||
Function gets as an argument a list of functions defining the means
|
||||
of a normal distribution to sample from.
|
||||
"""
|
||||
def __init__(self,
|
||||
fn_list=[lambda x: x ** 2, lambda x: numpy.sin(x)],
|
||||
@ -138,6 +225,8 @@ class FuncDataProvider(DataProvider):
|
||||
points_per_fn=200,
|
||||
batch_size=10,
|
||||
randomize=True):
|
||||
"""
|
||||
"""
|
||||
|
||||
super(FuncDataProvider, self).__init__(batch_size, randomize)
|
||||
|
||||
@ -164,7 +253,7 @@ class FuncDataProvider(DataProvider):
|
||||
|
||||
def __randomize(self):
|
||||
assert isinstance(self.x, numpy.ndarray)
|
||||
return numpy.random.permute(numpy.arange(0, self.x.shape[0]))
|
||||
return numpy.random.permutation(numpy.arange(0, self.x.shape[0]))
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
Loading…
Reference in New Issue
Block a user