Tensorflow——神经网络实现非线性回归问题

  • 根据一元二次函数的数据,使用神经网络进行训练,拟合出一元二次函数曲线

在tensorflow下,使用神经网络实现一元二次方程的非线性回归问题,需要进行简单神经网络的设计,

输入层,我们选取在一定范围内随机生成200个数据,对数据进行加噪处理,

中间层(隐藏层):10个神经元,设置相应的权重、偏置,使用tanh()函数作为激活函数

输出层: 隐藏层的输出进入输出层,经过权重、偏置、最后经过激活函数输出最后输出层的值

代码实现:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#使用numpy生成200个随机点,linspace()函数可以生成指定范围内的点,最后列表目的是把数据变成二维数据
x_data = np.linspace(-0.5,0.5,200)[:,np.newaxis]
noise = np.random.normal(0,0.02,x_data.shape)
y_data = np.square(x_data) + noise

#定义两个placeholder(占位符),规定是1列
x = tf.placeholder(tf.float32,[None,1])
y = tf.placeholder(tf.float32,[None,1])

#使用神经网络进行训练测试

#定义神经网络的中间层(隐藏层)
#权重
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)

#初始化变量
init = tf.global_variables_initializer()
#定义会话
with tf.Session() as sess:
    sess.run(init)
    for _ in range(2000):
        #feed操作,需要参数的时候再传入
        sess.run(train_step,feed_dict = {x:x_data,y:y_data})
    
    #获得预测值
    predicton_value = sess.run(prediction,feed_dict = {x:x_data})
    
    #绘图显示
    plt.figure()
    plt.scatter(x_data,y_data)
    plt.plot(x_data,predicton_value,'r-',lw = 5)
    plt.show()
  • 输出结果 

猜你喜欢

转载自blog.csdn.net/gaoyu1253401563/article/details/86008103