前言:
关于“神经网络”这个词想必对人工智能感兴趣额的早已经熟得不能再熟悉了,在机器学习和认知科学领域,人工神经网络(artificial neural network,缩写ANN),简称神经网络(neural network,缩写NN)或类神经网络,是一种模仿生物神经网络(动物的中枢神经系统,特别是大脑)的结构和功能的数学模型或计算模型,用于对函数进行估计或近似。神经网络由大量的人工神经元联结进行计算。大多数情况下人工神经网络能在外界信息的基础上改变内部结构,是一种自适应系统。现代神经网络是一种非线性统计性数据建模工具。
本章将从神经网络的最基本出发,用最简单明了的语言来介绍神经网络算法。
本文主要涉及到的知识点有:
- 前向传播
- 优化
- 反向传播
-
算法思想:从线性思想到最基础神经网络
在这里我们经常困惑于经常提到的“神经元”,其实神经网络的结构远没有神经元那样复杂和可怕,下面我们通过以前学到的东西进行一个组合,就会发现原来神经网络竟然是这样的简单,别再忽悠我说“神经元”了。
线性分类
在对数据进行分类的时候,比如二分类问题,最简单的是找到一条直线将不同数据分割到数据的两边。如下图所示:
image.png
当是线性多分类问题的时候通常用一种前面学到的算法—softmax算法。
这里以图像分类为例吧,假如我们构建的softmax分类器是一个十分类器,输入如图的图像,通过得分函数,得到此图片为猫的概率最大,则分类器认为这个图片是猫。加入不是猫,则可以写出损失函数。
image.png
上述用数学描述如下:
将输入数据x,通常是矩阵,和给定的参数w的乘积加上截距b。结果得到的得分函数和损失函数如下:
image.png
过拟合
归一化
为了使得最后的结果以概率的形的出现,一般都是先指数化数据,在做一个归一化操作。
激活函数
这个在线性模型的基础上加的,目的是为了是在非线性分类中表现出良好的效果
通常选用rule函数作为激活函数,是因为反响传播过程中加入神经网络层次过深,会使得sigmod函数的导数趋近于0。
反向传播
就是算一下每个数据对损失函数造成了多大影响。
例如:
image.png
优化
通常用梯度下降,这里用到的梯度下降就是机器学习核心思想,就是通过前向传播得到损失函数,通过反向传播得到每个数据对最终损失函数的影响大小(导数),通过梯度下降迭代更新参数,使得损失函数最小。
-
神经网络算法
把前面的内容进行组合,得到的数据叫做前向传播,(其实大多数是学过的内容,就多一个激活函数。)在加上用梯度下降来更新参数,就组成了神经网络的精髓。加入初始化多个参数就会得到多个损失函数,也就是通常说的“神经元".
以上就简单表达一下最简单的神经网络,下面就以例子为例构建一个最简单的神经网络模型来体现一下神经网络的强大吧。代码直接附上了,有什么不懂可以直接私信哦
下面以分类为例举个例子:
原始数据:
image.png
构建原始数据的代码如下:
import numpy as np
import matplotlib.pyplot as plt
#ubuntu 16.04 sudo pip instal matplotlib
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
np.random.seed(0)
N = 100 # number of points per class
D = 2 # dimensionality
K = 3 # number of classes
X = np.zeros((N*K,D))
y = np.zeros(N*K, dtype='uint8')
for j in range(K):
ix = range(N*j,N*(j+1))
# print(ix[0])
r = np.linspace(0.0,1,N) # radius
print(r)
t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta
X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
y[ix] = j
# print(X)
# print(y)
fig = plt.figure()
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
plt.xlim([-1,1])
plt.ylim([-1,1])
plt.show()
用线性分类器来对数据进行分割,效果如下:
代码可以参照前面的线性softmax分类器
用神经网络进行分类。效果如下:
image.png
代码如下:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
N = 100 # number of points per class
D = 2 # dimensionality
K = 3 # number of classes
X = np.zeros((N*K,D))
y = np.zeros(N*K, dtype='uint8')
print(X)
for j in range(K):
ix = range(N*j,N*(j+1))
r = np.linspace(0.0,1,N) # radius
t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta
X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
y[ix] = j
h = 100 # size of hidden layer
W = 0.01 * np.random.randn(D,h)# x:300*2 2*100
b = np.zeros((1,h))
W2 = 0.01 * np.random.randn(h,K)
b2 = np.zeros((1,K))
# some hyperparameters
step_size = 1e-0
reg = 1e-3 # regularization strength
# gradient descent loop
num_examples = X.shape[0]
for i in range(20000):
# evaluate class scores, [N x K]
hidden_layer = np.maximum(0, np.dot(X, W) + b) # note, ReLU activation hidden_layer:300*100
#print hidden_layer.shape
scores = np.dot(hidden_layer, W2) + b2 #scores:300*3
#print scores.shape
# compute the class probabilities
exp_scores = np.exp(scores)
probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # [N x K]
#print probs.shape
# compute the loss: average cross-entropy loss and regularization
corect_logprobs = -np.log(probs[range(num_examples),y])
data_loss = np.sum(corect_logprobs)/num_examples
reg_loss = 0.5*reg*np.sum(W*W) + 0.5*reg*np.sum(W2*W2)
loss = data_loss + reg_loss
if i % 100 == 0:
print("iteration %d: loss %f" % (i, loss))
# compute the gradient on scores
dscores = probs
dscores[range(num_examples),y] -= 1
dscores /= num_examples
# backpropate the gradient to the parameters
# first backprop into parameters W2 and b2
dW2 = np.dot(hidden_layer.T, dscores)
db2 = np.sum(dscores, axis=0, keepdims=True)
# next backprop into hidden layer
dhidden = np.dot(dscores, W2.T)
# backprop the ReLU non-linearity
dhidden[hidden_layer <= 0] = 0
# finally into W,b
dW = np.dot(X.T, dhidden)
db = np.sum(dhidden, axis=0, keepdims=True)
# add regularization gradient contribution
dW2 += reg * W2
dW += reg * W
# perform a parameter update
W += -step_size * dW
b += -step_size * db
W2 += -step_size * dW2
b2 += -step_size * db2
hidden_layer = np.maximum(0, np.dot(X, W) + b)
scores = np.dot(hidden_layer, W2) + b2
predicted_class = np.argmax(scores, axis=1)
print('training accuracy: %.2f' % (np.mean(predicted_class == y)))
h = 0.02
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = np.dot(np.maximum(0, np.dot(np.c_[xx.ravel(), yy.ravel()], W) + b), W2) + b2
Z = np.argmax(Z, axis=1)
Z = Z.reshape(xx.shape)
fig = plt.figure()
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8)
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.show()
网友评论