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

 更新时间:2018年02月10日 14:44:31   作者:Mr丶Caleb  
本篇文章主要介绍了tensorflow建立一个简单的神经网络的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

本笔记目的是通过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]. 

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)

运行结果:

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

相关文章

  • python+requests实现接口测试的完整步骤

    python+requests实现接口测试的完整步骤

    这篇文章主要给大家介绍了关于python+requests实现接口测试的完整步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-10-10
  • 如何利用Anaconda配置简单的Python环境

    如何利用Anaconda配置简单的Python环境

    这篇文章主要为大家详细介绍了如何利用Anaconda配置简单的Python环境,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-06-06
  • Python利用蒙特卡罗模拟期权定价

    Python利用蒙特卡罗模拟期权定价

    期权是一种合约,它赋予买方在未来某个时间点以特定价格买卖资产的权利。本文将利用蒙特卡罗模拟期权定价,感兴趣的小伙伴可以了解一下
    2022-04-04
  • PyTorch的张量tensor和自动求导autograd详解

    PyTorch的张量tensor和自动求导autograd详解

    这篇文章主要介绍了PyTorch的张量tensor和自动求导autograd,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-02-02
  • Python基础之教你怎么在M1系统上使用pandas

    Python基础之教你怎么在M1系统上使用pandas

    这篇文章主要介绍了Python基础之教你怎么在M1系统上使用pandas,文中有非常详细的代码示例,对正在学习python基础的小伙伴们有很好地帮助,需要的朋友可以参考下
    2021-05-05
  • 如何获取numpy的第一个非0元素索引

    如何获取numpy的第一个非0元素索引

    这篇文章主要介绍了如何获取numpy的第一个非0元素索引,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-05-05
  • Python分类测试代码实例汇总

    Python分类测试代码实例汇总

    这篇文章主要介绍了Python分类测试代码实例汇总,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • Mac系统中Anaconda环境配置Python json库的方法详解

    Mac系统中Anaconda环境配置Python json库的方法详解

    这篇文章主要为大家介绍了如何在Mac电脑的Anaconda环境中,配置Python语言中,用以编码、解码、处理JSON数据的json库,需要的小伙伴可以参考下
    2023-08-08
  • python实现定时发送邮件到指定邮箱

    python实现定时发送邮件到指定邮箱

    这篇文章主要为大家详细介绍了python实现定时发送邮件到指定邮箱,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-12-12
  • 在Pandas中DataFrame数据合并,连接(concat,merge,join)的实例

    在Pandas中DataFrame数据合并,连接(concat,merge,join)的实例

    今天小编就为大家分享一篇在Pandas中DataFrame数据合并,连接(concat,merge,join)的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01

最新评论