小编Kse*_*iya的帖子

Keras自定义图层,具有可训练的重量

我需要在Keras(1.1)中创建具有可训练权重(与输入相同的形状)的自定义图层.我尝试通过随机值初始化权重.有我的'mylayer.py'文件:

from keras import backend as K
from keras.engine.topology import Layer
import numpy as np
from numpy import random

class MyLayer(Layer):

def __init__(self,**kwargs):
    super(MyLayer, self).__init__(**kwargs)

def build(self, input_shape):
    # Create a trainable weight variable for this layer.
    self.W_init = np.random(input_shape)
    self.W = K.variable(self.W_init, name="W")
    self.trainable_weights = [self.W]
    super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!

def call(self, x):
    num, n, m = x.shape
    res=np.empty(num,1,1)
    for i in range(num):
        res[i,0,0]=K.dot(x[i,:,:], self.W[i,:,:])
    return res

def compute_output_shape(self, input_shape):
    return (input_shape[0], 1,1)
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用它时: …

python layer keras

6
推荐指数
0
解决办法
3879
查看次数

标签 统计

keras ×1

layer ×1

python ×1