tensorflow建立一个简单的神经网络的方法


Posted in Python onFebruary 10, 2018

本笔记目的是通过tensorflow实现一个两层的神经网络。目的是实现一个二次函数的拟合。

如何添加一层网络

代码如下:

def add_layer(inputs, in_size, out_size, activation_function=None):
  # add one more layer and return the output of this layer
  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

注意该函数中是xW+b,而不是Wx+b。所以要注意乘法的顺序。x应该定义为[类别数量, 数据数量], W定义为[数据类别,类别数量]。

创建一些数据

# Make up some real data
x_data = np.linspace(-1,1,300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

numpy的linspace函数能够产生等差数列。start,stop决定等差数列的起止值。endpoint参数指定包不包括终点值。

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)[source] 
Return evenly spaced numbers over a specified interval. 
Returns num evenly spaced samples, calculated over the interval [start, stop].

tensorflow建立一个简单的神经网络的方法

noise函数为添加噪声所用,这样二次函数的点不会与二次函数曲线完全重合。

numpy的newaxis可以新增一个维度而不需要重新创建相应的shape在赋值,非常方便,如上面的例子中就将x_data从一维变成了二维。

添加占位符,用作输入

# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])

添加隐藏层和输出层

# add hidden layer
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
# add output layer
prediction = add_layer(l1, 10, 1, activation_function=None)

计算误差,并用梯度下降使得误差最小

# the error between prediciton and real data
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

完整代码如下:

from __future__ import print_function
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

def add_layer(inputs, in_size, out_size, activation_function=None):
  # add one more layer and return the output of this layer
  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

# Make up some real data
x_data = np.linspace(-1,1,300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
# add hidden layer
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
# add output layer
prediction = add_layer(l1, 10, 1, activation_function=None)

# the error between prediciton and real data
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
           reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

# important step
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)

# plot the real data
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data, y_data)
plt.ion()
plt.show()

for i in range(1000):
  # training
  sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
  if i % 50 == 0:
    # to visualize the result and improvement
    try:
      ax.lines.remove(lines[0])
    except Exception:
      pass
    prediction_value = sess.run(prediction, feed_dict={xs: x_data})
    # plot the prediction
    lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
    plt.pause(0.1)

运行结果:

tensorflow建立一个简单的神经网络的方法

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python3使用urllib模块制作网络爬虫
Apr 08 Python
Python程序退出方式小结
Dec 09 Python
mac系统安装Python3初体验
Jan 02 Python
几个适合python初学者的简单小程序,看完受益匪浅!(推荐)
Apr 16 Python
Python分布式进程中你会遇到的问题解析
May 28 Python
python3 自动识别usb连接状态,即对usb重连的判断方法
Jul 03 Python
python单例模式原理与创建方法实例分析
Oct 26 Python
Python笔记之代理模式
Nov 20 Python
python 判断一组数据是否符合正态分布
Sep 23 Python
关于django python manage.py startapp 应用名出错异常原因解析
Dec 15 Python
OpenCV中resize函数插值算法的实现过程(五种)
Jun 05 Python
python神经网络 tf.name_scope 和 tf.variable_scope 的区别
May 04 Python
python取代netcat过程分析
Feb 10 #Python
浅谈Python黑帽子取代netcat
Feb 10 #Python
python3爬取淘宝信息代码分析
Feb 10 #Python
Python中property属性实例解析
Feb 10 #Python
Java编程迭代地删除文件夹及其下的所有文件实例
Feb 10 #Python
Python中协程用法代码详解
Feb 10 #Python
Python实现简单生成验证码功能【基于random模块】
Feb 10 #Python
You might like
php flv视频时间获取函数
2010/06/29 PHP
DOM XPATH获取img src值的query
2013/09/23 PHP
php 在线导入mysql大数据程序
2015/06/11 PHP
PHP弹出对话框技巧详细解读
2015/09/26 PHP
PHP如何搭建百度Ueditor富文本编辑器
2018/09/21 PHP
在jquery中combobox多选的不兼容问题总结
2013/12/24 Javascript
基于jQuery倾斜打开侧边栏菜单特效代码
2015/09/15 Javascript
javascript动态获取登录时间和在线时长
2016/02/25 Javascript
vue.js中mint-ui框架的使用方法
2017/05/12 Javascript
详解vue中computed 和 watch的异同
2017/06/30 Javascript
浅谈vue+webpack项目调试方法步骤
2017/09/11 Javascript
在 Angular中 使用 Lodash 的方法
2018/02/11 Javascript
微信小程序上传文件到阿里OSS教程
2019/05/20 Javascript
微信小程序封装分享与分销功能过程解析
2019/08/13 Javascript
微信小程序实现注册登录功能(表单校验、错误提示)
2019/12/10 Javascript
node.js使用http模块创建服务器和客户端完整示例
2020/02/10 Javascript
Laravel 如何在blade文件中使用Vue组件的示例代码
2020/06/28 Javascript
Vue解决移动端弹窗滚动穿透问题
2020/12/15 Vue.js
理解python多线程(python多线程简明教程)
2014/06/09 Python
微信 用脚本查看是否被微信好友删除
2016/10/28 Python
python爬虫获取京东手机图片的图文教程
2017/12/29 Python
Python rstrip()方法实例详解
2018/11/11 Python
关于PyTorch 自动求导机制详解
2019/08/18 Python
pygame库实现移动底座弹球小游戏
2020/04/14 Python
分布式数据库需要考虑哪些问题
2013/12/08 面试题
非功能性需求都包括哪些方面
2013/10/29 面试题
大学生毕业自我评价范文分享
2013/11/07 职场文书
优秀毕业生求职信范文
2014/01/02 职场文书
物业工作计划书
2014/01/10 职场文书
商业项目策划方案
2014/06/05 职场文书
美术第二课堂活动总结
2014/07/08 职场文书
尊老爱幼演讲稿
2014/09/04 职场文书
意外伤害赔偿协议书范文
2014/09/23 职场文书
2015年共青团工作总结
2015/05/15 职场文书
优秀学生主要事迹怎么写
2015/11/04 职场文书
Redis唯一ID生成器的实现
2022/07/07 Redis