非线性回归

 照常附上视频链接,前30分钟

视频链接

代码是根据视频来的,自己加入了loss输出,

这是代码运行结果,蓝色点是散点图,y=非线性回归,红线是训练出来的模型去拟合蓝色的点,神经元的**函数是tan 

x的取值范围是-0.5到0.5之间取200个

构建模型包括输入层(x)和中间层(10neruals)还有输出层(y)

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#生成从-0.5到正0.5的两百个点,两百行一列,后面的括号是增加了一下维度
x_data = np.linspace(-0.5,0.5,200)[:, np.newaxis]
#生成和X——data形状一样,在0至0.02之间
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个
WeightS_L1 = tf.Variable(tf.random_normal([1, 10]))
#bias初始化为0
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)

#定义神经网络输出层 输出10个
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 step in range(2000):
        sess.run(train_step,feed_dict={x: x_data,y: y_data})
        if step % 20 == 0:
            print(step, sess.run(loss,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()

非线性回归

loss输出 

非线性回归

中间省略,可以看出loss值逐渐变小 

非线性回归