(6) 非线性回归神经网络案例

总结:

1.Tensorflow之神经网络nn模块详解:https://blog.csdn.net/qq_36653505/article/details/81105894

2.激活函数作用:https://www.zhihu.com/question/22334626/answer/798881688 https://www.cnblogs.com/bonelee/p/8242705.html

案例:

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

生成样本:

#生成200个均匀分布的点,生成的数据是200行1列,这些数据是训练样本
#np.newaxis的作用是在这一位置增加一个一维.(https://blog.csdn.net/molu_chase/article/details/78619731)
xData=np.linspace(-0.5,0.5,200)[:,np.newaxis]
#生成随机值的干扰项
noise=np.random.normal(0,0.02,xData.shape)
yData=np.square(xData)+noise
#定义两个placeholder,形状为 1 列
x=tf.placeholder(tf.float32,[None,1])
y=tf.placeholder(tf.float32,[None,1])

#定义神经网络中间层
weight1=tf.Variable(tf.random.normal([1,10])) #权值连接着输入层与中间层,输入层为 1 个神经元,中间层 10 个神经元
biase1=tf.Variable(tf.zeros([1,10])) # 偏置值初始化为0
sum1=tf.matmul(x,weight1)+biase1 #sum1是信号总和
##tf.nn.tanh是激活函数
mid=tf.nn.tanh(sum1)

#定义神经网络输出层
weight2=tf.Variable(tf.random.normal([10,1]))#此权值连接着中间层与输出层,中间层为 10 个神经元,输出层 1 个神经元
biase2=tf.Variable(tf.zeros([1,1])) #输出层只有 1 个神经元
sum2=tf.matmul(mid,weight2)+biase2 #sum2是信号总和
prediction=tf.nn.tanh(sum2)

#定义代价函数/损失函数
loss=tf.reduce_mean(tf.square(y-prediction))
#使用梯度下降法作为优化器,最小化损失函数loss
train=tf.train.GradientDescentOptimizer(0.1).minimize(loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    #训练2000次模型
    for i in range(2000):
        sess.run(train,feed_dict={x:xData,y:yData})
    #算出预测值和真实值进行比较,下图中的蓝点是训练数据,红线训练出的模型
    prediction_value=sess.run(prediction,feed_dict={x:xData})
    #画图表示
    plt.figure()
    plt.scatter(xData,yData)
    plt.plot(xData,prediction_value,'r-',lw=5)
    plt.show()

发布了71 篇原创文章 · 获赞 3 · 访问量 1919

猜你喜欢

转载自blog.csdn.net/qq_34405401/article/details/104340653