# 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个隐藏层的神经元
# 构建具有一个神经元的输出层
prediction = add_layer(h1,10,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()

# 参考资料

《TensorFlow技术解析与实战》——李嘉璇

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

11-10 1164

10-11 2万+
06-12 1478
10-24 489
05-05 208
05-09 1390
08-23 2665
04-17 197
08-17 1万+

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。