1.人工神经网咯的概念介绍
人工神经网络(Artificial Neural Network,缩写ANN),是一种模仿生物神经网络的结构和功能的数学模型或计算模型。神经网络由大量的人工神经元联结进行计算。
2.人工神经网络原理
个人工神经细胞的计算如下图所示,其中:输入(Input);权重(Weight):左边五个灰色圆底字母w代表浮点数;激励函数(Activation Function):大圆,所有经过权重调整后的输入加起来,形成单个的激励值;输出(Output):神经细胞的输出。如果最后计算的结果激励值大于阈值1.0,则神经细胞就输出1;如果激励值小于阈值则输出0。这和一个生物神经细胞的兴奋状态或抑制状态是等价的。
下面图是通过神经网络实现逻辑表达式与运算:(参考NG斯坦福机器学习讲义)
3.激励函数
神经网络中的神经元中都有激励函数(activation function),常见的激励函数参考维基百科:
4.神经网络学习TensorFlow的实现代码
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, dtype=np.float32)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5 + noise
#plot the real data
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data, y_data)
plt.ion()#本次运行请注释,全局运行不要注释
plt.show()
#利用占位符定义我们所需的神经网络的输入。
#tf.placeholder()就是代表占位符,这里的None代表无论输入有多少都可以,因为输入只有一个特征,所以这里是1。
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
#搭建网络
#这里使用 Tensorflow 自带的激励函数tf.nn.relu。
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
prediction = add_layer(l1, 10, 1, activation_function=None)
#计算预测值prediction和真实值的误差,对二者差的平方求和再取平均。
#在tf.reduce_sum等函数中,有一个reduction_indices参数,表示函数的处理维度。
#当没有reduction_indices这个参数,此时该参数取默认值None,将把input_tensor降到0维,也就是一个数
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
reduction_indices=[1]))
#tf.train.GradientDescentOptimizer()中的值通常都小于1,这里取的是0.1,代表以0.1的效率来最小化误差loss。
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
#init = tf.initialize_all_variables() # tf 马上就要废弃这种写法
init = tf.global_variables_initializer() # 替换成这样就好
sess = tf.Session()
sess.run(init)
for i in range(1000):
# training
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i % 50 == 0:
# to see the step improvement
#print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))
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)
人工神经网络通过不断的学习,不断优化,最终的图形输出如下:
参考
杨老师( eastmount)的神经网络和机器学习基础入门分享
建议直接看"莫烦大神"网易云课程,进行人工神经网络学习