{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import theano\n",
    "import numpy as np\n",
    "import theano.tensor as T\n",
    "import ch9util\n",
    "from sklearn.cross_validation import train_test_split\n",
    "from sklearn.metrics import r2_score\n",
    "import dautil as dl\n",
    "from IPython.display import HTML\n",
    "import warnings\n",
    "\n",
    "warnings.filterwarnings(action='ignore', category=FutureWarning)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "temp = dl.data.Weather.load()['TEMP'].dropna()\n",
    "X = temp.values[:-1]\n",
    "y = temp.values[1:]\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=16)\n",
    "w = theano.shared(0., name ='w')\n",
    "c = theano.shared(0., name ='c')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "x = T.vector('x')\n",
    "y = T.vector('y')\n",
    "\n",
    "prediction = T.dot(x, w) + c\n",
    "cost = T.sum(T.pow(prediction - y, 2))/(2 * X_train.shape[0])\n",
    "\n",
    "gw = T.grad(cost, w)\n",
    "gc = T.grad(cost, c)\n",
    "\n",
    "learning_rate = 0.01\n",
    "training_steps = 10000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "train = theano.function([x, y], cost, updates =\n",
    "                        [(w, w - learning_rate * gw),\n",
    "                         (c, c - learning_rate * gc)])\n",
    "predict = theano.function([x], prediction)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "for i in range(training_steps):\n",
    "    train(X_train.astype(np.float), y_train)\n",
    "\n",
    "\n",
    "preds = predict(X_test)\n",
    "ch9util.npy_save('theano', preds)\n",
    "r2 = r2_score(preds, y_test)\n",
    "HTML(ch9util.scatter_predictions(preds, y_test, '', r2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.4.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
