其实神经网络很好实现,稍微有点基础的基本都可以实现出来.主要都是利用上面这个公式来做的。
这是神经网络的整体框架,一共是三层,分为输入层,隐藏层,输出层。现在我们先来讲解下从输出层到到第一个隐藏层。
使用的编译器是jupyter notebook
import numpy as np
#定义X,W1,B1
X = np.array([1.0, 0.5])
w1 = np.array([[0.1, 0.3, 0.5],[0.2, 0.4, 0.6]])
b1 = np.array([0.1, 0.2, 0.3])
#查看他们的形状
print(X.shape)
print(w1.shape)
print(b1.shape)
#求点积
np.dot(X,w1)
def sigmod(x):
return 1/(1 + np.exp(-x))
Z1 = sigmod(A1)
Z1
#定义w2,b2
w2 = np.array([[0.1,0.4],[0.2,0.5],[0.3,0.6]])
b2 = np.array([0.1,0.2])
#查看他们的行状
print(w2.shape)
print(b2.shape)
A2 = np.dot(Z1,w2) + b2
A2
Z2 = sigmod(A2)
Z2
#定义恒等函数
def identity_function(x):
return x
#定义w3,b3
w3 = np.array([[0.1,0.3],[0.2,0.4]])
b3 = np.array([0.1,0.2])
A3 = np.dot(Z2,w3) + b3
Y = identity_function(A3)
Y
将上面的整合一下
#整理
#定义一个字典,将权重全部放入字典
def init_network():
network = {
}
network['w1'] = np.array([[0.1,0.3,0.5],[0.2,0.4,0.6]])
network['w2'] = np.array([[0.1,0.4],[0.2,0.5],[0.3,0.6]])
network['w3'] = np.array([[0.1,0.3],[0.2,0.4]])
network['b1'] = np.array([0.1, 0.2, 0.3])
network['b2'] = np.array([0.1,0.2])
network['b3'] = np.array([0.1,0.2])
return network
#定义函数,导入权重与x,得到Y
def forward(network,x):
w1,w2,w3 = network['w1'],network['w2'],network['w3']
b1,b2,b3 = network['b1'],network['b2'],network['b3']
A1 = np.dot(x,w1) + b1
A2 = np.dot(A1,w2) + b2
A3 = np.dot(A2,w3) + b3
Y = identity_function(A3)
Y
#调用函数
network = init_network()
X = np.array([1.0,0.5])
Y = forward(network,X)
转载:https://blog.csdn.net/HHsHH1234/article/details/116174513
查看评论