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

# 《TensroFlow技术解析与实战》第一个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) + biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        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
'''
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

猜你喜欢

转载自blog.csdn.net/weixin_39393712/article/details/80738301