美文网首页
TensorFlow(五)非线性回归训练示例

TensorFlow(五)非线性回归训练示例

作者: Oo晨晨oO | 来源:发表于2017-10-15 03:17 被阅读304次

上篇文章中, 我们演示了一个简单的线性回归Demo.
在了解了回归算法中的正向传播和反向传播之后, 我们可以用梯度下降法来进行一个非线性回归的示例.

此次示例中, 我们设置输入样本神经元只有一个, 中间神经元有10个, 输出神经元1个.

神经图.jpg

这里用到了matplotlib.pyplot库, 用来画出我们的训练样本数据图像和我们训练得到的回归图像.

在看下面代码的时候注意, 如果你对回归算法的学习开始于吴恩达先生的深度学习课程, 那么你要注意下面代码中的权重W与样本数据X的顺序与转置问题(相乘顺序与行列转置正好相反, 得到的结果是一样的)

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

#使用numpy来生成500个随机点 (500行 1列)
x_data = np.linspace(-0.5, 0.5, 500)[:, np.newaxis]
#生成干扰值, 矩阵形状与x_data一样
noise = np.random.normal(0, 0.02, x_data.shape)
y_data = np.square(x_data) + noise

#定义两个placeholder
x = tf.placeholder(tf.float32, [None, 1])
y = tf.placeholder(tf.float32, [None, 1])

#定义神经网络中间层(输入层1个神经元, 中间层10个, 所以定义权值的时候是[1, 10], 分别关联输入层和中间层)
Weights_L1 = tf.Variable(tf.random_normal([1, 10]))
biases_L1 = tf.Variable(tf.zeros([1, 10]))
Wx_plus_b_L1 = tf.matmul(x, Weights_L1) + biases_L1
L1 = tf.nn.tanh(Wx_plus_b_L1)

#定义输出层
Weights_L2 = tf.Variable(tf.random_normal([10, 1]))
biases_L2 = tf.Variable(tf.zeros([1, 1]))
Wx_plus_b_L2 = tf.matmul(L1, Weights_L2) + biases_L2
prediction = tf.nn.tanh(Wx_plus_b_L2)

#二次代价函数
loss = tf.reduce_mean(tf.square(y-prediction))
#使用梯度下降法训练
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

with tf.Session() as sess:
    #变量初始化
    sess.run(tf.global_variables_initializer())
    
    for _ in range(2000):
        sess.run(train_step, feed_dict={x: x_data, y: y_data})
        
    #获得预测值
    prediction_value = sess.run(prediction, feed_dict={x: x_data})
    #画图
    plt.figure()
    plt.scatter(x_data, y_data)
    plt.plot(x_data, prediction_value, 'r-', lw=5)
    plt.show()

得到的图像如下

训练结果图.png

可以看到500个数据样本训练2000次之后得到的回归数据图, 与二次图像还是很拟合的.

相关文章

  • TensorFlow(五)非线性回归训练示例

    在上篇文章中, 我们演示了一个简单的线性回归Demo.在了解了回归算法中的正向传播和反向传播之后, 我们可以用梯度...

  • 3: TensorFlow示例

    TensorFlow示例 该示例演示了一些Tensorflow的基本功能: 什么是TensorFlow 如何输入数...

  • Tensorflow 初体验

    跑了一个完整tensorflow示例,通过定义简单的一个layer,搭建网络,定义训练参数,进行训练后即可进行较为...

  • tensorflow非线性回归例子

    1、例子一 显示结果 2、例子2当把x_data扩展到【-1,1】是效果并不理想考虑真假一层神经网路,并且把靠近输...

  • TensorFlow 训练模型

    TensorFlow支持同步训练和异步训练两种模型训练方式。 异步训练 异步训练即TensorFlow上每个节点上...

  • TensorFlow(六)手写数字识别训练示例

    数据集 我们要训练机器学习, 那么就要用到训练数据. 这次我们使用MNIST_data数据集 在程序中要导入该数据...

  • TF Lite Demos

    本专题收录 TensorFlow Lite 的示例,供学习交流之用。

  • tensorboard错误 :TensorBoard attem

    训练tensorflow运行 tensorboard出错 命令: 错误:ERROR:tensorflow:Tens...

  • tensorflow

    tensorflow : 使用预训练词向量 tf.Session() :Session 是 Tensorflow ...

  • (五)TensorFlow.js的XOR示例

    这是一个使用TensorFlow.js进行异或(XOR)分类的示例,使用Parcel作为打包工具. 这个例子主要需...

网友评论

      本文标题:TensorFlow(五)非线性回归训练示例

      本文链接:https://www.haomeiwen.com/subject/mpjquxtx.html