# TensorFlow入门基础：双层神经网络进行函数拟合

TensorFlow 专栏收录该内容
3 篇文章 0 订阅

(1) 生成目标数据

(2) 构建网络

(3) 训练模型

(4) 模型评估

# 生成目标数据

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
x = np.linspace(-1,1,500)[:,np.newaxis]
noise = np.random.normal(0,0.2,x.shape)
fx = 2*x**2-2
y = fx + noise
subplot(2,1,1)
plot(x,fx)
legend(['Target'])
subplot(2,1,2)
plot(x,y,'.')
legend(['Sample'])
show()

xs = tf.placeholder(tf.float32,[None,1])
ys = tf.placeholder(tf.float32,[None,1])

# 构建模型

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

# 构建具有10个神经元的隐藏层
# 构建具有5个神经元的隐藏层
# 构建具有一个神经元的输出层
prediction = add_layer(h2,5,1,activation_function = None)

loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) # 设置学习率为0.1

# 训练模型

init = tf.global_variables_initializer()
sess = tf.Session()                      # 创建会话
record_loss = np.zeros(1000)             # 记录损失值变化
sess.run(init)                           # 初始化所有变量
for i in range(1000):
sess.run(train_step,feed_dict={xs: x,ys: y})
record_loss[i] = sess.run(loss,feed_dict={xs: x,ys: y})
plot(record_loss)
legend(['Loss'])
show()

# 模型评估

plot(x,sess.run(prediction,feed_dict={xs: x}))
plot(x,y,'.')
plot(x,fx,'--')
legend(['Prediction','Sample','Target'])
show()

• 0
点赞
• 1
评论
• 5
收藏
• 一键三连
• 扫一扫，分享海报

05-21 3297
07-06 751
10-29 292
07-16 3201
04-06 1032
09-18 176
10-19 367
12-28 3290
09-24 6362
04-20 2021