假设原函数为 f(x) = 5x^2 + 3,为了估计出这个函数,定义参数未知的函数g(x, w) = w0 x^2 + w1 x + w2,现要找出适合的w使g(x, w) ≈ f(x)。将这个问题转化为求解参数w使得损失函数L(w) = ∑ (f(x) - g(x, w))^2最小,求解过程使用了随机梯度下降(Stochastic Gradient Descent)。求解问题的代码如下:

 import numpy as np
 import tensorflow as tf

 # Placeholders are used to feed values from python to TensorFlow ops. We define
 # two placeholders, one for input feature x, and one for output y.
 x = tf.placeholder(tf.float32)
 y = tf.placeholder(tf.float32)

 # Assuming we know that the desired function is a polynomial of 2nd degree, we
 # allocate a vector of size 3 to hold the coefficients. The variable will be
 # automatically initialized with random noise.
 w = tf.get_variable("w", shape=[3, 1])

 # We define yhat to be our estimate of y.
 f = tf.stack([tf.square(x), x, tf.ones_like(x)], 1)
 yhat = tf.squeeze(tf.matmul(f, w), 1)

 # The loss is defined to be the l2 distance between our estimate of y and its
 # true value. We also added a shrinkage term, to ensure the resulting weights
 # would be small.
 loss = tf.nn.l2_loss(yhat - y) + 0.1 * tf.nn.l2_loss(w)

 # We use the Adam optimizer with learning rate set to 0.1 to minimize the loss.
 train_op = tf.train.AdamOptimizer(0.1).minimize(loss)

 def generate_data():
     x_val = np.random.uniform(-10.0, 10.0, size=100)
     y_val = 5 * np.square(x_val) + 3
     return x_val, y_val

 sess = tf.Session()
 # Since we are using variables we first need to initialize them.
 sess.run(tf.global_variables_initializer())
 for _ in range(1000):
     x_val, y_val = generate_data()
     _, loss_val = sess.run([train_op, loss], {x: x_val, y: y_val})
     print(loss_val)
 print(sess.run([w]))

求解过程如下:

4380421.0
3147655.5
4625718.5
3493661.0
3061016.0
3057624.5
3104206.2
……
103.7392
98.461266
113.29772
104.56809
89.75495
……
17.354445
17.66056
17.716873
18.782757
16.015532
[array([[4.9863739e+00],
       [6.9120852e-04],
       [3.8031762e+00]], dtype=float32)]

TensorFlow样例一的更多相关文章

  1. Tensorflow样例代码分析cifar10

    github地址:https://github.com/tensorflow/models.git 本文分析tutorial/image/cifar10教程项目的cifar10_input.py代码. ...

  2. TensorFlow最佳实践样例

    以下代码摘自<Tensor Flow:实战Google深度学习框架> 本套代码是在 http://www.cnblogs.com/shanlizi/p/9033330.html 基础上进行 ...

  3. TensorFlow入门之MNIST样例代码分析

    这几天想系统的学习一下TensorFlow,为之后的工作打下一些基础.看了下<TensorFlow:实战Google深度学习框架>这本书,目前个人觉得这本书还是对初学者挺友好的,作者站在初 ...

  4. tensorflow学习笔记----tensorflow在windows的安装及TensorBoard中mnist样例

    前言:                                                                                                 ...

  5. TensorFlow图像预处理完整样例

    参考书 <TensorFlow:实战Google深度学习框架>(第2版) 以下TensorFlow程序完成了从图像片段截取,到图像大小调整再到图像翻转及色彩调整的整个图像预处理过程. #! ...

  6. 80、tensorflow最佳实践样例程序

    ''' Created on Apr 21, 2017 @author: P0079482 ''' #-*- coding:utf-8 -*- import tensorflow as tf #定义神 ...

  7. 吴裕雄 python 神经网络——TensorFlow TFRecord样例程序

    import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_dat ...

  8. YOLOv4 资源环境配置和测试样例效果

    YOLOv4 资源环境配置和测试样例效果 基本环境:cuda=10.0,cudnn>=7.0, opencv>=2.4 一.下载yolov4 git clone https://githu ...

  9. C++的性能C#的产能?! - .Net Native 系列《三》:.NET Native部署测试方案及样例

    之前一文<c++的性能, c#的产能?!鱼和熊掌可以兼得,.NET NATIVE初窥> 获得很多朋友支持和鼓励,也更让我坚定做这项技术的推广者,希望能让更多的朋友了解这项技术,于是先从官方 ...

随机推荐

  1. async 异步协程进阶

    协程通过 async/await 语法进行声明,是编写异步应用的推荐方式 例如新定义一个协程(coroutine object): async def foo(): return 42 首先先来介绍下 ...

  2. .NET基础拾遗(1)类型语法基础和内存管理基础【转】

    http://www.cnblogs.com/edisonchou/p/4787775.html Index : (1)类型语法.内存管理和垃圾回收基础 (2)面向对象的实现和异常的处理 (3)字符串 ...

  3. C# 篇基础知识9——特性、程序集和反射

    特性(Attribute)是用于为程序元素添加额外信息的一种机制.比如记录文件修改时间或代码作者.提示某方法已经过期.描述如何序列化数据等等.方法.变量.属性.类.接口.结构体以及程序集等都是程序元素 ...

  4. APP inventor 学习

    中文教程:https://web.17coding.net/ 网页在线开发:http://app.gzjkw.net/#1 ai2.appinventor.mit.edu http://appinve ...

  5. CentOS 7----Apache基于域名的虚拟主机配置

    配置/etc/hosts文件,192.168.1.209 对应的域名如下: 192.168.1.209 www.name1.com 编辑每个域名的配置文件: <VirtualHost 192.1 ...

  6. windows centos php-beast 安装

    https://github.com/imaben/php-beast-binaries windows下 可以直接在这里下载dll 根据自己的php版本  还有是不是线程安全的 来选择下载对应的 放 ...

  7. vue项目打包后运行报错400如何解决

    昨天一个Vue项目打包后,今天测试,发现无论localhost还是服务器上都运行不了,报错如下: Failed to load resource: the server responded with ...

  8. win10鼠标右击 新建文件夹 反应缓慢、迟钝

    1. 先使用360杀毒,步骤如下: 2.修改注册表 https://jingyan.baidu.com/article/363872ec9e25972e4ba16f82.html 3.  如果仍未解决 ...

  9. Anniversary party POJ - 2342

    题目链接 经典的树形dp,最大独立集,对于每个点就有2个状态,选/不选 设\(dp_{i,0}\)表示不选第i个,\(dp_{i,1}\)表示选第i个,容易得到其状态转移 \(dp_{i,0} = \ ...

  10. windows远程linux的方法(不用xshell)

    先cmd进入DOS,再输入命令ssh root@要远程的linux的ip 输入密码 即可进入linux后台.如下图,即为edr后台,可以见到unabackup服务了. 如果是多次远程不同IP,第二次远 ...