tensorflow简易学习[3]:实现神经网络

Splace Splace     2022-10-02     205

关键词:

  TensorFlow本身是分布式机器学习框架,所以是基于深度学习的,前一篇TensorFlow简易学习[2]:实现线性回归对只一般算法的举例只是为说明TensorFlow的广泛性。本文将通过示例TensorFlow如何创建、训练一个神经网络。

  主要包括以下内容:

    神经网络基础

    基本激励函数

    创建神经网络

  

 神经网络简介

  关于神经网络资源很多,这里推荐吴恩达的一个Tutorial。

 基本激励函数

  关于激励函数的作用,常有解释:不使用激励函数的话,神经网络的每层都只是做线性变换,多层输入叠加后也还是线性变换。因为线性模型的表达能力不够,激励函数可以引入非线性因素(ref1) 关于如何选择激励函数,激励函数的优缺点等可参考已标识ref1, ref2

  常用激励函数有(ref2): tanh, relu, sigmod, softplus

  激励函数在TensorFlow代码实现:

#!/usr/bin/python

'''
Show the most used activation functions in Network
'''

import tensorflow as tf 
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-5, 5, 200)

#1. struct
#following are popular activation functions
y_relu = tf.nn.relu(x)
y_sigmod = tf.nn.sigmoid(x)
y_tanh = tf.nn.tanh(x)
y_softplus = tf.nn.softplus(x)

#2. session
sess = tf.Session()
y_relu, y_sigmod, y_tanh, y_softplus =sess.run([y_relu, y_sigmod, y_tanh, y_softplus])

# plot these activation functions
plt.figure(1, figsize=(8,6))

plt.subplot(221)
plt.plot(x, y_relu, c ='red', label = 'y_relu')
plt.ylim((-1, 5))
plt.legend(loc = 'best')

plt.subplot(222)
plt.plot(x, y_sigmod, c ='b', label = 'y_sigmod')
plt.ylim((-1, 5))
plt.legend(loc = 'best')

plt.subplot(223)
plt.plot(x, y_tanh, c ='b', label = 'y_tanh')
plt.ylim((-1, 5))
plt.legend(loc = 'best')

plt.subplot(224)
plt.plot(x, y_softplus, c ='c', label = 'y_softplus')
plt.ylim((-1, 5))
plt.legend(loc = 'best')

plt.show()

 结果:

        

创建神经网络

  创建层

  定义函数用于创建隐藏层/输出层: 

#add a layer and return outputs of the layer
def add_layer(inputs, in_size, out_size, activation_function=None):
    #1. initial weights[in_size, out_size]
    Weights = tf.Variable(tf.random_normal([in_size,out_size]))
    #2. bias: (+0.1)
    biases = tf.Variable(tf.zeros([1,out_size]) + 0.1)
    #3. input*Weight + bias
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    #4. activation
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs 

 

  定义网络结构

  此处定义一个三层网络,即:输入-单层隐藏层-输出层。可通过以上函数添加层数。网络为全连接网络。

# 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)

  训练

  利用梯度下降,训练1000次。

loss function: suqare error
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))
GD = tf.train.GradientDescentOptimizer(0.1)
train_step = GD.minimize(loss)

    完整代码

#!/usr/bin/python

'''
Build a simple network
'''

import tensorflow as tf 
import numpy as np

#1. add_layer
def add_layer(inputs, in_size, out_size, activation_function=None):
    #1. initial weights[in_size, out_size]
    Weights = tf.Variable(tf.random_normal([in_size,out_size]))
    #2. bias: (+0.1)
    biases = tf.Variable(tf.zeros([1,out_size]) + 0.1)
    #3. input*Weight + bias
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    #4. activation
    ## when activation_function is None then outlayer 
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs

##begin build network struct##
##network: 1 * 10 * 1
#2. create 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

#3. placehoder: waiting for the training data
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])

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

#6. loss function: suqare error
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))
GD = tf.train.GradientDescentOptimizer(0.1)
train_step = GD.minimize(loss)
## End build network struct ###

## Initial the variables
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
    init = tf.initialize_all_variables()
else:
    init = tf.global_variables_initializer()


## Session 
sess = tf.Session()
sess.run(init)

# called in the visual

## Traing
for step in range(1000):
    #当运算要用到placeholder时,就需要feed_dict这个字典来指定输入
    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(1)

sess.close()

结果:

      

 

 至此TensorFlow简易学习完结。

 

 

 --------------------------------------

 

说明:本列为前期学习时记录,为基本概念和操作,不涉及深入部分。文字部分参考在文中注明,代码参考莫凡 

 

  

tensorflow实现迁移学习

此例程出自《TensorFlow实战Google深度学习框架》6.5.2小节卷积神经网络迁移学习。数据集来自http://download.tensorflow.org/example_images/flower_photos.tgz,及谷歌提供的Inception-v3模型https://storage.googleapis.com/download.tensorflow.org/ 查看详情

用tensorflow神经网络实现一个简易的图片分类器(代码片段)

文章写的不清晰请大家原谅QAQ  这篇文章我们将用 CIFAR-10数据集做一个很简易的图片分类器。在 CIFAR-10数据集包含了60,000张图片。在此数据集中,有10个不同的类别,每个类别中有6,000个图像。每幅图像的大小为32x32像... 查看详情

简单神经网络tensorflow实现

学习TensorFlow笔记importtensorflowastf#定义变量#Variable定义张量及shapew1=tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))w2=tf.Variable(tf.random_normal([3,1],stddev=1,seed=1))withtf.Session()assess:print(ses 查看详情

机器学习-tensorflow2.0安装简易教程

1.打开AnacondaPrompt2.pipinstalltensorflow==2.0-ihttps://pypi.douban.com/simple过程出现选择,选y,最后等待完成安装。3.测试 4.在pycharm中找到上面路径的anaconda3下的python.exe,完成设置。 查看详情

tensorflow逻辑回归原理与实现(超详细)

逻辑回归原理与实现学习目标1.神经网络基础1.1Logistic回归1.2逻辑回归损失函数2.梯度下降算法3.导数3.1导数3.2导数计算图3.3链式法则3.4逻辑回归的梯度下降4.向量化编程4.1向量化优势4.2向量化实现伪代码5.案例:实现逻辑回归5... 查看详情

tensorflow基础学习二:实现一个神经网络

...在tensorflow中,变量(tf.Variable)的作用就是用来保存和更新神经网络中的参数,在声明变量的同时需要指定其初始值。tensorflow中支持的随机数生成器:函数名称随机数分布主要参数tf.random_normal正态分布平均值、标准差、取值类型tf... 查看详情

tensorflow入门学习3重要算法基础

...经元模型神经元j输入信号权值输出信号总和膜电位阈值BP神经网络简介在人工神经网络的发展历史上,感知机(MultilayerPerceptron,MLP)网 查看详情

tensorflow学习笔记:实现自编码器

...码器的非监督学习算法,书中的代码给出了一个隐藏层的神经网络,本人扩展到了多层,改进了代码。实现多层神经网络时,把每层封装成一个NetLayer对象(本质是单向链表),然后计算隐藏层输出值的时候,运用递归算法,最后... 查看详情

tensorflow学习之路---解决过拟合

...层(函数)5、分析误差和优化数据(改变权重)6、执行神经网络‘‘‘importtensorflowastffromsklearn.datasetsimportload_digitsfromsklearn.model_selectionimporttrain_test_sp 查看详情

pythontensorflow实现sequential深度神经网络回归(代码片段)

... 本文介绍基于Python语言中TensorFlow的Keras接口,实现深度神经网络回归的方法。(基于PythonTensorFlowKeras的深度学习回归代码——keras.Sequential深度神经网络)1写在前面  前期一篇文章TensorFlowDNNRegressor实现深度学习的代码详细介绍... 查看详情

tensorflow实战-tensorflow实现卷积神经网络cnn-第5章

第5章-TensorFlow实现卷积神经网络CNN5.1卷积神经网络简介卷积神经网络CNN最初是为了解决图像识别等问题设计的,当然现在的应用已经不限于图像和视频,也可以用于时间序列信号,比如音频信号、文本数据等。在深度学习出现之... 查看详情

原创深度学习与tensorflow动手实践系列-3第三课:卷积神经网络-基础篇

...【原创深度学习与TensorFlow动手实践系列-3】第三课:卷积神经网络-基础篇   提纲:1.链式反向梯度传到2.卷积神经网络-卷积层3.卷积神经网络-功能层4.实例:卷积神经网络MNIST分类  期待目标:1.清楚神经网络优... 查看详情

tensorflow实现cnn案例笔记(代码片段)

...例1案例2案例3案例4 Tensorflow和CNN: Tensorflow——卷积神经网络(CNN)卷积神经网络工作概述卷积整体结构示例:TensorFlow2 查看详情

tensorflowdnnregressor实现深度学习的代码(代码片段)

...基于Python语言中TensorFlow的tf.estimator接口,实现深度学习神经网络回归的具体方法。(基于PythonTensorFlowEstimator的深度学习回归与分类代码——DNNRegressor)1写在前面  1.本文介绍的是基于TensorFlowtf.estimator接口的深度学习网络,而非T... 查看详情

3.4神经网络概述tensorflow2实现——python实战

文章目录 查看详情

深度学习(08)_rnn-lstm循环神经网络-03-tensorflow进阶实现(代码片段)

全部代码:点击这里查看本文个人博客地址:点击这里查看关于Tensorflow实现一个简单的二元序列的例子可以点击这里查看关于RNN和LSTM的基础可以查看这里这篇博客主要包含以下内容训练一个RNN模型逐字符生成文本数据(... 查看详情

xception实现动物识别(tensorflow)(代码片段)

活动地址:CSDN21天学习挑战赛目录1.任务介绍2.数据处理2.1.数据预处理2.2.可视化数据2.3.配置数据集2.网络设计2.1.Xception简单介绍2.2.设计网络模型3.模型评估3.1.准确率评估3.2.绘制混淆矩阵3.3.进行预测1.任务介绍数据结构为ÿ... 查看详情

深度学习第三周tensorflow实现天气识别(代码片段)

...有)**参考文章地址:🔗深度学习100例-卷积神经网络(CNN)天气识别|第5天**🍖作者:K同学啊文章目录一、本周学习内容:1、使用tensorflow中的模块读取自己的图片数据集二、前言三、电脑环境四、前期... 查看详情