3.tensorflow-非线性拟合实战1

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


#[:,np.newaxis]:增加一维数据
x_data=np.linspace(-0.5,0.5,200)[:,np.newaxis]
bias=np.random.normal(0,0.02,x_data.shape)
y_data=np.square(x_data)+bias


#定义神经网络的输入层
x_input=tf.placeholder(tf.float32, [None,1])
y_input=tf.placeholder(tf.float32, [None,1])


#定义神经网络的中间层
W1=tf.Variable(tf.random_normal([1,10]))
b1=tf.Variable(tf.zeros([1,10]))
Wx_plus_b=tf.matmul(x_input,W1)+b1
l1=tf.nn.tanh(Wx_plus_b)


#定义神经网络输出层
W2=tf.Variable(tf.random_normal([10,1]))
b2=tf.Variable(tf.zeros([1,1]))
Wx_plus_b2=tf.matmul(l1,W2)+b2
prediction=tf.nn.tanh(Wx_plus_b2)


#定义二次损失函数
loss=tf.reduce_mean(tf.square(y_input-prediction))
optimizer=tf.train.GradientDescentOptimizer(0.2).minimize(loss)


#变量初始化
init=tf.global_variables_initializer()


with tf.Session() as sess:
    sess.run(init)
    for _ in range(3000):
        sess.run(optimizer,feed_dict={x_input:x_data,y_input:y_data})
    #获得预测值
    prediction_value = sess.run(prediction,feed_dict={x_input:x_data})    
    
plt.figure()
plt.scatter(x_data,y_data)
plt.plot(x_data,prediction_value,'r-',lw=3)
plt.show()

#输出:

3.tensorflow-非线性拟合实战1_第1张图片

注意:

tf.matmul()方法中的参数要注意位置,输入值在前,权重在后!!

你可能感兴趣的:(tensorflow)