{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import tensorflow as tf\n", "import numpy as np" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Step: 0 [k, b] [0.054201454, 0.10031855]\n", "Step: 100 [k, b] [0.10048652, 0.19973609]\n", "Step: 200 [k, b] [0.10003704, 0.1999799]\n", "Step: 300 [k, b] [0.10000283, 0.19999847]\n", "Step: 400 [k, b] [0.10000023, 0.19999987]\n", "Step: 500 [k, b] [0.10000023, 0.19999987]\n" ] } ], "source": [ "x_data = np.random.rand(100)\n", "y_data = x_data * 0.1 + 0.2\n", "\n", "# 线性模型的斜率 & 偏置量\n", "k = tf.Variable(0.)\n", "b = tf.Variable(0.)\n", "y = k * x_data + b\n", "\n", "# 二次代价函数\n", "loss = tf.reduce_mean(tf.square(y_data - y))\n", "# 梯度下降\n", "optimizer = tf.train.GradientDescentOptimizer(0.2)\n", "# 最小化代价函数\n", "train = optimizer.minimize(loss)\n", "\n", "# 线性模型中，k, b作为变量，会在梯度下降法的作用下不断变化，以使得 loss函数越来越小\n", "with tf.Session() as sess:\n", " tf.global_variables_initializer().run()\n", " for step in range(501):\n", " sess.run(train)\n", " if step % 100 == 0:\n", " print(\"Step: \", step, \"[k, b]\", sess.run([k, b]))" ] } ], "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.5.3" } }, "nbformat": 4, "nbformat_minor": 2 }