{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import numpy\n",
    "import matplotlib.pyplot as plt\n",
    "import time\n",
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES']='0'\n",
    "rng = numpy.random"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Parameters\n",
    "learning_rate = 0.001\n",
    "training_epochs = 1000\n",
    "display_step = 50"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Training Data\n",
    "train_X = numpy.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,\n",
    "                         7.042,10.791,5.313,7.997,5.654,9.27,3.1])\n",
    "train_Y = numpy.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,\n",
    "                         2.827,3.465,1.65,2.904,2.42,2.94,1.3])\n",
    "batch_size = 1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.text.Text at 0x7f34c42eef50>"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 6020 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7f34c43029d0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#show data\n",
    "plt.plot(train_X, train_Y, 'ro', label='Original data')\n",
    "plt.xlabel('X')\n",
    "plt.ylabel('Y')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "tf.reset_default_graph()\n",
    "\n",
    "# define the input and output by tf.placeholder\n",
    "X = tf.placeholder(\"float\")\n",
    "Y = tf.placeholder(\"float\")\n",
    "\n",
    "# define the model parameters by tf.Variable\n",
    "W = tf.Variable(rng.randn(), name=\"weight\")\n",
    "b = tf.Variable(rng.randn(), name=\"bias\")\n",
    "\n",
    "# Construct a linear model\n",
    "pred = tf.add(tf.multiply(X, W), b)\n",
    "\n",
    "# Mean squared error loss\n",
    "loss = tf.losses.mean_squared_error(pred,Y)\n",
    "\n",
    "# Gradient descent optimizer\n",
    "train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)\n",
    "\n",
    "# Initialize the variables (i.e. assign their default value)\n",
    "init = tf.global_variables_initializer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch: 0050 loss= 0.444443822 W= 0.46224645 b= -0.7996302\n",
      "Epoch: 0100 loss= 0.237902671 W= 0.42063576 b= -0.4917235\n",
      "Epoch: 0150 loss= 0.117740810 W= 0.38700098 b= -0.24283682\n",
      "Epoch: 0200 loss= 0.051182397 W= 0.3598134 b= -0.041656807\n",
      "Epoch: 0250 loss= 0.017356552 W= 0.33783707 b= 0.120960854\n",
      "Epoch: 0300 loss= 0.003065306 W= 0.32007325 b= 0.25240776\n",
      "Epoch: 0350 loss= 0.000040617 W= 0.3057144 b= 0.35865855\n",
      "Epoch: 0400 loss= 0.003167185 W= 0.29410788 b= 0.44454327\n",
      "Epoch: 0450 loss= 0.009334750 W= 0.28472605 b= 0.5139657\n",
      "Epoch: 0500 loss= 0.016698735 W= 0.27714252 b= 0.5700818\n",
      "Epoch: 0550 loss= 0.024205076 W= 0.27101275 b= 0.6154403\n",
      "Epoch: 0600 loss= 0.031287968 W= 0.26605794 b= 0.65210444\n",
      "Epoch: 0650 loss= 0.037676625 W= 0.2620528 b= 0.68174094\n",
      "Epoch: 0700 loss= 0.043274194 W= 0.2588154 b= 0.70569676\n",
      "Epoch: 0750 loss= 0.048082255 W= 0.2561985 b= 0.72506124\n",
      "Epoch: 0800 loss= 0.052153651 W= 0.25408322 b= 0.7407138\n",
      "Epoch: 0850 loss= 0.055565566 W= 0.25237337 b= 0.753366\n",
      "Epoch: 0900 loss= 0.058402263 W= 0.2509913 b= 0.76359254\n",
      "Epoch: 0950 loss= 0.060747214 W= 0.2498741 b= 0.77185977\n",
      "Epoch: 1000 loss= 0.062676080 W= 0.24897112 b= 0.7785413\n",
      "Optimization Finished, spend time: 13.1325409412!\n",
      "Training loss= 0.1552547 W= 0.24897112 b= 0.7785413 \n",
      "\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 12920 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7f34c46150d0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Start training\n",
    "with tf.Session() as sess:\n",
    "    t_start = time.time()\n",
    "    sess.run(init)\n",
    "    # Fit all training data\n",
    "    for epoch in range(training_epochs):\n",
    "        for (x, y) in zip(train_X, train_Y):\n",
    "            sess.run(train_op, feed_dict={X: x, Y: y})\n",
    " \n",
    "        #Display logs per epoch step\n",
    "        if (epoch+1) % display_step == 0:\n",
    "            loss_np = sess.run(loss, feed_dict={X: x, Y:y})\n",
    "            print \"Epoch:\", '%04d' % (epoch+1), \"loss=\", \"{:.9f}\".format(loss_np), \\\n",
    "                \"W=\", sess.run(W), \"b=\", sess.run(b)\n",
    "\n",
    "    print \"Optimization Finished, spend time: {}!\".format(time.time()-t_start)\n",
    "    training_cost = sess.run(loss, feed_dict={X: train_X, Y: train_Y})\n",
    "    print \"Training loss=\", training_cost, \"W=\", sess.run(W), \"b=\", sess.run(b), '\\n'\n",
    "\n",
    "    #Graphic display\n",
    "    plt.plot(train_X, train_Y, 'ro', label='Original data')\n",
    "    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')\n",
    "    plt.xlabel('X')\n",
    "    plt.ylabel('Y')\n",
    "    plt.legend()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "# assemble a graph\n",
    "tf.reset_default_graph()\n",
    "a = tf.Variable(1,name='a',trainable=True)\n",
    "b = tf.constant(2,name='b')\n",
    "c = a+b\n",
    "assign = tf.assign(a,5)\n",
    "\n",
    "# execute a graph\n",
    "with tf.Session() as sess:\n",
    "    sess.run(tf.global_variables_initializer())\n",
    "    _,out_c = sess.run([assign,c])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "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.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
