tensorflow的基本运行方式--demo程序

1. tensorflow的运行流程以下

  • 加载数据及定义超参数
  • 构建网络
  • 训练模型
  • 评估模型和进行预测

2. tensorflow demo实现

demo以下:优化目标为: y = x 2 0.5 python

# -*- coding: utf-8 -*-
""" Created on Wed Apr 18 20:30:10 2018 @author: spfhy discription: tensorflow 的运行方式示例 """

import tensorflow as tf
import numpy as np

#1. 生成输入数据,学习方程为:y = x^2 - 0.5,构造知足这个方程的一堆x,y,同时加入噪点
x_data = np.linspace(-1,1,30)[:,np.newaxis] #300*1的二维数组做为输入

noise = np.random.normal(0,0.05,x_data.shape)

y_data = np.square(x_data) - 0.5 +noise

#定义 x,y的占位符

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

#构建隐匿层,假设隐匿层有20个神经元
h1 = add_layer(xs,1,20,activation_function=tf.nn.relu)
#构建输出层,假设输出层和输入层同样,有1个神经元
prediction = add_layer(h1,20,1,activation_function=None)

#构建损失函数:计算输出层的预测值和真实值间的偏差,对两者差的方求和再取平均,获得损失
#函数,运用梯度降低法,以0.1的学习速率最小化损失:

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()
sess = tf.Session()
sess.run(init)

for i in range(1000):
    sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
    if i%50 == 0:
        print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))

本文时学习《TensorFlow 技术解析与实践》的学习笔记,代码摘抄自该书;web

参考文献:李嘉璇《TensorFlow 技术解析与实践》算法