运行代码:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D LR = 0.1
REAL_PARAMS = [1.2, 2.5]
INIT_PARAMS = [[5, 4],
[5, 1],
[2, 4.5]][2] x = np.linspace(-1, 1, 200, dtype=np.float32) # x data y_fun = lambda a, b: np.sin(b*np.cos(a*x))
tf_y_fun = lambda a, b: tf.sin(b*tf.cos(a*x)) noise = np.random.randn(200)/10
y = y_fun(*REAL_PARAMS) + noise # target # tensorflow graph
a, b = [tf.Variable(initial_value=p, dtype=tf.float32) for p in INIT_PARAMS]
pred = tf_y_fun(a, b)
mse = tf.reduce_mean(tf.square(y-pred))
train_op = tf.train.GradientDescentOptimizer(LR).minimize(mse) a_list, b_list, cost_list = [], [], []
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for t in range(400):
a_, b_, mse_ = sess.run([a, b, mse])
a_list.append(a_); b_list.append(b_); cost_list.append(mse_) # record parameter changes
result, _ = sess.run([pred, train_op]) # training # visualization codes:
print('a=', a_, 'b=', b_)
plt.figure(1)
plt.scatter(x, y, c='b') # plot data
plt.plot(x, result, 'r-', lw=2) # plot line fitting
# 3D cost figure
fig = plt.figure(2); ax = Axes3D(fig)
a3D, b3D = np.meshgrid(np.linspace(-2, 7, 30), np.linspace(-2, 7, 30)) # parameter space
cost3D = np.array([np.mean(np.square(y_fun(a_, b_) - y)) for a_, b_ in zip(a3D.flatten(), b3D.flatten())]).reshape(a3D.shape)
ax.plot_surface(a3D, b3D, cost3D, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'), alpha=0.5)
ax.scatter(a_list[0], b_list[0], zs=cost_list[0], s=300, c='r') # initial parameter place
ax.set_xlabel('a'); ax.set_ylabel('b')
ax.plot(a_list, b_list, zs=cost_list, zdir='z', c='r', lw=3) # plot 3D gradient descent
plt.show()

运行结果:

TensorFlow从入门到理解(六):可视化梯度下降的更多相关文章

  1. TensorFlow从入门到理解

    一.<莫烦Python>学习笔记: TensorFlow从入门到理解(一):搭建开发环境[基于Ubuntu18.04] TensorFlow从入门到理解(二):你的第一个神经网络 Tens ...

  2. TensorFlow从入门到理解(二):你的第一个神经网络

    运行代码: from __future__ import print_function import tensorflow as tf import numpy as np import matplo ...

  3. TensorFlow从入门到理解(五):你的第一个循环神经网络RNN(回归例子)

    运行代码: import tensorflow as tf import numpy as np import matplotlib.pyplot as plt BATCH_START = 0 TIM ...

  4. TensorFlow从入门到理解(四):你的第一个循环神经网络RNN(分类例子)

    运行代码: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # set rando ...

  5. TensorFlow从入门到理解(三):你的第一个卷积神经网络(CNN)

    运行代码: from __future__ import print_function import tensorflow as tf from tensorflow.examples.tutoria ...

  6. TensorFlow从入门到理解(一):搭建开发环境【基于Ubuntu18.04】

    *注:教程及本文章皆使用Python3+语言,执行.py文件都是用终端(如果使用Python2+和IDE都会和本文描述有点不符) 一.安装,测试,卸载 TensorFlow官网介绍得很全面,很完美了, ...

  7. NN优化方法对照:梯度下降、随机梯度下降和批量梯度下降

    1.前言 这几种方法呢都是在求最优解中常常出现的方法,主要是应用迭代的思想来逼近.在梯度下降算法中.都是环绕下面这个式子展开: 当中在上面的式子中hθ(x)代表.输入为x的时候的其当时θ參数下的输出值 ...

  8. 超简单tensorflow入门优化程序&&tensorboard可视化

    程序1 任务描述: x = 3.0, y = 100.0, 运算公式 x×W+b = y,求 W和b的最优解. 使用tensorflow编程实现: #-*- coding: utf-8 -*-) im ...

  9. TensorFlow学习——入门篇

    本文主要通过一个简单的 Demo 介绍 TensorFlow 初级 API 的使用方法,因为自己也是初学者,因此本文的目的主要是引导刚接触 TensorFlow 或者 机器学习的同学,能够从第一步开始 ...

随机推荐

  1. A1117. Eddington Number

    British astronomer Eddington liked to ride a bike. It is said that in order to show off his skill, h ...

  2. Django 获取访问者信息

    request内的META里有请求用户的信息 #定义视图方法 def get_ip(request): #打印头部所以信息 # print(request.META) # 获取ip信息 if &quo ...

  3. smartProgram学习笔记

    背景:转正前要完成这样一个编程课的学习.平时写代码只是完成基本的功能,没有养成良好的习惯,感觉这样的课程还是要好好学习下,要不真是不知道什么叫写代码. Week1 为什么要写好代码? 因为平时读:写代 ...

  4. 关于MySQL索引的最左前缀匹配原则原理说明说明

    假设有2个这样的SQL SELECT * FROM table WHERE a = 1 AND c = 3; // c不走索引 SELECT * FROM table WHERE a = 1 AND ...

  5. 团体程序设计天梯赛(CCCC) L3014 周游世界 BFS证明

    团体程序设计天梯赛代码.体现代码技巧,比赛技巧.  https://github.com/congmingyige/cccc_code

  6. appium 切换native/ webview,findby,还有页面元素定位一直小于0的问题的解决

    之前一直有个bug没有解决. 今天,终于解决了. 疑问过程: app是混合应用,项目做了H5优化之后,以前的用例执行总会失败,体现在原来的一个元素点击无反馈 排查原因:1.项目做了H5优化,2.测试的 ...

  7. (BFS) leetcode 690. Employee Importance

    690. Employee Importance Easy 377369FavoriteShare You are given a data structure of employee informa ...

  8. C# 实现身份验证之WEB Service篇

    在这个WEB API横行的时代,讲WEB Service技术却实显得有些过时了,过时的技术并不代表无用武之地,有些地方也还是可以继续用他的,我之所以会讲解WEB Service,源于我最近面试时被问到 ...

  9. centos7下安装pip以及mysql等软件

    1.安装pip 安装失败了的提示: No package pip available.Error: Nothing to do 解决方法: 需要先安装扩展源EPEL. EPEL(http://fedo ...

  10. Nginx简单手册

    Nginx 变量 变量名 注解 $arg_name 请求中的的参数名,即“?”后面的arg_name=arg_value形式的arg_name $args  请求中的参数值 $binary_remot ...