python实现网络多连接_【python实现卷积神经网络】全连接层实现

classDense(Layer):"""A fully-connected NN layer.

Parameters:

-----------

n_units: int

The number of neurons in the layer.

input_shape: tuple

The expected input shape of the layer. For dense layers a single digit specifying

the number of features of the input. Must be specified if it is the first layer in

the network."""

def __init__(self, n_units, input_shape=None):

self.layer_input=None

self.input_shape=input_shape

self.n_units=n_units

self.trainable=True

self.W=None

self.w0=Nonedefinitialize(self, optimizer):#Initialize the weights

limit = 1 /math.sqrt(self.input_shape[0])

self.W= np.random.uniform(-limit, limit, (self.input_shape[0], self.n_units))

self.w0= np.zeros((1, self.n_units))#Weight optimizers

self.W_opt =copy.copy(optimizer)

self.w0_opt=copy.copy(optimizer)defparameters(self):return np.prod(self.W.shape) +np.prod(self.w0.shape)def forward_pass(self, X, training=True):

self.layer_input=Xreturn X.dot(self.W) +self.w0defbackward_pass(self, accum_grad):#Save weights used during forwards pass

W =self.Wifself.trainable:#Calculate gradient w.r.t layer weights

grad_w =self.layer_input.T.dot(accum_grad)

grad_w0= np.sum(accum_grad, axis=0, keepdims=True)#Update the layer weights

self.W =self.W_opt.update(self.W, grad_w)

self.w0=self.w0_opt.update(self.w0, grad_w0)#Return accumulated gradient for next layer

#Calculated based on the weights used during the forward pass

accum_grad =accum_grad.dot(W.T)returnaccum_graddefoutput_shape(self):return (self.n_units, )

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值