初学tensorflow-线性回归

通过tensorflow拟合y=a^2-0.5+槽点,以下为代码,分步解析

1、导入功能包

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
import numpy as np
import matplotlib.pyplot as plt

2、设置需要拟合的函数及数据

x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5 + noise

3、设计隐层的权重、偏置等

def add_layer(inputs, in_size, out_size, activation_function=None):
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs
  • 偏置不能设置为0,令其加0.1.权重用numpy数组随机初始化,通常比全零效果好。
  • input为输入数据,insize为输入维度,outsize为输出维度,activation_function为激活函数。
  • tf.variable为tensorflow的变量声明,tf.constant表示常量,tf.add(a,b)表示相加,tf.assign(a,b)表示将b赋值给a,tf.matmul(a,b)表示相乘。

    4、设计网络的输入层

    xs = tf.placeholder(tf.float32, [None, 1]) ys = tf.placeholder(tf.float32, [None, 1])
  • tensorflow通过占位符placeholder来进行数据的输入,[None,1]表示任意行1列的数据,必须包括类型

    5、设计网络的隐层

    l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu) prediction = add_layer(l1, 10, 1, activation_function=None)
  • 回归一般用relu函数即可。如上,隐层为两层,每层包含10个神经元。

    6、模型编译

    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
  • 设计网络的损失函数与优化器,常用的优化器还包括SGD、Adam、Momentum等,优化器能加速网络的训练速度,与学习率相关。

    7、参数初始化

    sess = tf.Session() init = tf.global_variables_initializer() sess.run(init)
  • 整个程序内只要包含变量,必须用tf.global——进行初始化。另外,所有的操作都必须通过会话即session.run(xxx)来执行。

    8、模型训练

    for i in range(1000):
    sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
  • feeddict包含的是输入数据,将数据输入至train_step中进行训练。

    9、代码已上传本人github,其主要根据莫烦代码修改而成。

参考文献:1、莫烦tensorflow教程

打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2015-2021 高腾腾
  • Powered by Hexo Theme Ayer
  • PV: UV:

谢谢大爷

支付宝
微信