Python-深度学习入门的代码记录-(第5章)
提示:注重Python中class对象的使用方法
问题:训练集文件加载
Relu激活函数的实现:
class RULE:
def __init__(self):
self.mask=None
def forward(self,input): #函数运算
self.mask=(input<=0)
out=input.copy()
out[self.mask]=0
return out
def backward(self,dout): #函数求导
dout[self.mask]=0
doutput=dout
return doutput
Sigmoid函数:
class Sigmoid:
def __init__(self):
self.out=None
def forward(self,input):
out=1/(1+np.exp(-input))
self.out=out
return out
def backward(self,dout):
doutput=dout*(1.0-self.out)*self.out
return doutput
神经网络-隐含层&Softmax输出层:
提示:包含矩阵表示,矩阵运算,Y=WX +b
隐含层
class Affine:
def __init__(self,W,b):
self.W=W
self.b=b
self.x=None
self.dW=None
self.db=None
def forward(self,x):
self.x=x
out=np.dot(x,self.W)+self.b
return out
def backward(self,dout):
dx=np.dot(x,self.W.T) # 转置
self.dW=np.dot(self.x.T,dout) # 转置
self.db=np.sum(dout,axis=0)
return dx
Softmax输出层
class SoftmaxWithLoss:
def __init__(self):
self.loss=None
self.y=None
self.t=None
def forward(self,x,t):
self.t=t
self.y=softmax(x)
self.loss=cross_entropy_errot(self.y,self.t)
return self.loss
def backward(self,dout=1):
bacth_size=self.t.shape[0]
dx=(self.y-self.t)/bacth_size
return dx
Softmax代码
def softmax(input):
exp_input=np.exp(input)
sum_exp=np.sum(exp_input)
output=exp_input/sum_exp
return output
损失函数代码
y是输出,t是监督数据
def cross_entropy_error(y, t):
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size)
# 监督数据是one-hot-vector的情况下,转换为正确解标签的索引
if t.size == y.size:
t = t.argmax(axis=1)
batch_size = y.shape[0]
return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size
Softmax&loss-function
def softmax_loss(input, t):
y = softmax(input)
return cross_entropy_error(y, t)