tensorflow59 《TensorFlow技术解析与实战》08 第一个tensorflow程序

编程入门 行业动态 更新时间:2024-10-21 11:26:38

tensorflow59 《TensorFlow技术解析与实战》08 <a href=https://www.elefans.com/category/jswz/34/1770593.html style=第一个tensorflow程序"/>

tensorflow59 《TensorFlow技术解析与实战》08 第一个tensorflow程序

# 《TensroFlow技术解析与实战》08 第一个TensorFlow程序
# win10 Tensorflow-gpu1.2.0 python3.5.3
# CUDA v8.0 cudnn-8.0-windows10-x64-v5.1
# filename:nntf08.01.py # $y=ax^{2}+b$import tensorflow as tf
import numpy as np# 构造满足一元二次方程的函数
x_data = np.linspace(-1, 1, 300)[:, np.newaxis] # 构建300个点,在[-1, 1]之间的等差数列
noise = np.random.normal(0, 0.05, x_data.shape) # 加入一些噪声点,使它与x_data的维度一致,并且拟合为0、方差为0.05的正太分布
y_data = np.square(x_data) - 0.5 + noise # y = x^2 - 0.5 + 噪声
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):# 构建权重:in_size * out_size 大小的矩阵weights = tf.Variable(tf.random_normal([in_size, out_size]))# 构建偏置:1 * out_size的矩阵biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)# 矩阵相乘Wx_plus_b = tf.matmul(inputs, weights) + biasesif activation_function is None:outputs = Wx_plus_belse:outputs = activation_function(Wx_plus_b)return outputs #得到输出数据# 构建隐层,假设隐层有10个神经元
h1 = add_layer(xs, 1, 20, activation_function = tf.nn.relu)
# 构建输出层,假设输出层和输入层一样,有1个神经元
prediction = add_layer(h1, 20, 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)init = tf.global_variables_initializer()
with tf.Session() as sess:sess.run(init)for i in range(1000): # 训练1000次sess.run(train_step, feed_dict={xs: x_data, ys: y_data})if i % 50 == 0 : # 每50次打印一次损失值print(sess.run(loss, feed_dict = {xs: x_data, ys: y_data}))
'''
15.5288
0.00650913
0.00399742
...
0.00237057
0.0023616
0.00235646
'''

更多推荐

tensorflow59 《TensorFlow技术解析与实战》08 第一个tensorflow程序

本文发布于:2024-03-08 19:09:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1721974.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第一个   实战   程序   技术   TensorFlow

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!