Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 内循环神经网络_Python_Tensorflow_Keras - Fatal编程技术网

Python 内循环神经网络

Python 内循环神经网络,python,tensorflow,keras,Python,Tensorflow,Keras,我有这样的smth for q in range(10): # generate some samples x = Input(batch_shape=(n_batch, xx.shape[1])) x = Dense(20)(x) x = LeakyReLU(alpha=0.001)(x) y = Dense(1)(x) y = LeakyReLU(alpha=0.001)(y) model = Model(inputs=x, outputs=y)

我有这样的smth

for q in range(10):
   # generate some samples
   x = Input(batch_shape=(n_batch, xx.shape[1]))
   x = Dense(20)(x)
   x = LeakyReLU(alpha=0.001)(x)
   y = Dense(1)(x)
   y = LeakyReLU(alpha=0.001)(y)
   model = Model(inputs=x, outputs=y) 
   model.compile(loss='mean_squared_error', optimizer='Adam', metrics=['accuracy'])
   for i in range(10):
      model.fit(x, y, epochs=1, batch_size=n_batch, verbose=0, shuffle=False)
      model.reset_states()

我想知道神经网络是为每个q从头开始构建的,还是保留了前一个q的所有内容?如果保留,我如何为每个q分别重置和构建、编译和拟合神经网络?

当您使用keras或tensorflow创建一个层时,tensorflow会向其图形中添加一个或多个节点,每次添加优化器、损失函数或激活函数时,它都会执行相同的操作并为它们添加一个节点

调用
model.fit()时,
tensorflow从其根开始执行其图形。如果在循环中添加节点,则不会删除以前的节点。它们会占用内存空间,并且会降低您的性能

该怎么办?这非常简单,重新初始化权重并重新使用相同的节点。您的代码不会有太大的变化,只需使用for循环向下移动示例生成,并定义一个重新初始化的函数即可

我还把第二个for循环降下来,把历元数增加到10,如果你有理由的话,你可以把它放回for循环

def reset_weights(model):
    session = K.get_session()
    for layer in model.layers: 
        if hasattr(layer, 'kernel_initializer'):
            layer.kernel.initializer.run(session=session)

x = Input(batch_shape=(n_batch, xx.shape[1]))
x = Dense(20)(x)
x = LeakyReLU(alpha=0.001)(x)
y = Dense(1)(x)
y = LeakyReLU(alpha=0.001)(y)
model = Model(inputs=x, outputs=y) 
model.compile(loss='mean_squared_error', optimizer='Adam', metrics=['accuracy'])
for q in range(10):
    #generate some samples
    model.fit(x, y, epochs=10, batch_size=n_batch, verbose=1, shuffle=False)
    model.reset_states()
    reset_weights(model)

谢谢你,美韩。要重新初始化LSTM wiegths,我需要包括if hasattr(层,'recurrential\u initializer'):layer.recurrential\u initializer.run(session=session)?此外,我还收到了此错误,AttributeError:“VarianceScaling”对象没有属性“run”。您需要运行初始值设定项来重置权重,对于循环初始值设定项,您可以查看: