程序员深度学习

神经网络入门(F) 添加神经层

2019-07-09  本文已影响11人  zidea
MachineLearninginMarketing

添加和定义神经层

神经层中包括一个激励函数,不过在今天的神经层我们暂时不使用激励函数来改变我们线性函数。在每一个神经层中都会包含 weight(权重)、 biases(偏值)和激励函数。这也是我们在节点。
简单的过程就是求解方程系数 Weight 和 biases。在 TensorFlow 输入和输出都是张量

def add_layer(inputs, in_size, out_size, activation_function=None):
    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
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)

如果 activation_function 是 None 表示,模型为线性的方式而不是非线性的方程

if activation_function is None:

用于解决我们平时生活当中不能用线性方程解决和概括的问题。线性方程是我们加班越多领导就越喜欢而且拿的也更多。其实也不一定因为我们是由极限的,而且一天就 24 小时所以这个问题就从线性变成非线性的问题。我们将神经网络简化为一个公式,也就是 y = Wx ,我们需要表示上面描述问题,不过这个线性方程并不能改变直线形态,这时候我们就需要激励函数。y AF(Wx) 可以在瓶颈处改变我们函数的形态。AF 就是激励函数,有很多方式例如 relu , sigmoid 或者 tanh。也可以自己定义激励函数来解决问题,不过需要保证这些激励函数是可以微分的。

如何建立神经网络的结构,

import tensorflow as tf
import numpy as np

def add_layer(inputs, in_size, out_size, activation_function=None):
    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

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

xs = tf.placeholder(tf.float32,[None, 1])
ys = tf.placeholder(tf.float32,[None, 1])

hiddenLayer = add_layer(xs, 1, 10, activation_function=tf.nn.relu)

outputLayer = add_layer(hiddenLayer, 10, 1, activation_function=None)

loss = tf.reduce_mean(tf.reduce_sum(
    tf.square(ys - outputLayer), reduction_indices=[1]))

train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

init = tf.initialize_all_variables()
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:
        print(sess.run(loss,feed_dict={xs: x_data, ys: y_data}))

Session(会话)用来执行定义好运算,在 TensorFlow 的会话中会拥有并管理 TensorFlow 程序运行的所有资源,计算完毕之后需要关闭会话。

x_data = np.linspace(-1, 1, 300)[:,np.newaxis]
print(x_data)
[[-1.        ]
 [-0.99331104]

x1 = np.array([1, 2, 3, 4, 5])
# the shape of x1 is (5,)
x1_new = x1[:, np.newaxis]
# now, the shape of x1_new is (5, 1)
# array([[1],
#        [2],
#        [3],
#        [4],
#        [5]])
x1_new = x1[np.newaxis,:]
# now, the shape of x1_new is (1, 5)
# array([[1, 2, 3, 4, 5]])

np.newaxis的作用就是在这一位置增加一个一维,这一位置指的是np.newaxis所在的位置,比较抽象,需要配合例子理解。
x_data 通过为他添加维度表示有 300 例子

noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

创建 y = x*2 -0.5 添加一个 noise 上 y_data 在这条直线附近跳动。
我们创建一个 3 层的神经网结构,输入层、输出层以及隐藏层,输入层是根据输入数据数量作为输入层,这里 x_data 只有一个属性也就是输入只有一个神经元,而隐藏层我们假设有 10 个属性而输出也只有一个属性所以输出也就是 1。
先定义隐藏层

hiddenLayer = add_layer(xs, 1, 10, activation_function=tf.nn.relu)

接下来定义输出层

outputLayer = add_layer(hiddenLayer, 10, 1, activation_function=None)

定义好神经层,我们就可以开始进行预测,在开始预测之前我们需要计算 loss(误差)也就是我们输出层值(预测值)与实际值的差

loss = tf.reduce_mean(tf.reduce_sum(
    tf.square(ys - outputLayer), reduction_indices=[1]))

reduce_sum 对每一个差值进行求和然后在用 reduce_mean 取平均值。
然后就是定义训练,训练过程是让模型怎么通过学习来减少 loss(误差)

train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

其中 GradientDescentOptimizer 为梯度下降算法的优化,通常我们需要传入一个小于 1 数据作为其参数就行。

init = tf.initialize_all_variables()

对所有变量进行初始,并通过会话来调用 Tensorflow 来进行初始化运算

xs = tf.placeholder(tf.float32,[None, 1])
ys = tf.placeholder(tf.float32,[None, 1])

xs 和 ys 通过 placeholder 表示两个占位符,等待运算时候输入数据到占位符,None 表示样板数量不确定

sess.run(train_step, feed_dict={xs: x_data, ys: y_data})

我们可以看出输出的 loss(误差)是在不断减少,所以说明我们训练是有效的。

0.13406475
0.1070772
0.08847566
0.07542249
0.06607084
0.059247475
0.05415783
0.050249428
...
0.0031619053
0.0031612993
0.0031606962
0.0031600953
0.0031594988
上一篇 下一篇

猜你喜欢

热点阅读