python - 生成模型越来越长

标签 python python-2.7 tensorflow keras

我用这个函数来生成keras模型:

def nn_model(n1,n2=None,n3=None):
    model = Sequential()
    model.add(Dense(n1, input_dim=len(features), init='he_normal'))
    model.add(PReLU())
    if n2 != None:
        model.add(Dense(n2, init = 'he_normal'))
        model.add(PReLU())
    if n3 != None:
        model.add(Dense(n3, init = 'he_normal'))
        model.add(PReLU())
    model.add(Dense(1, init='he_normal'))
    model.compile(loss='mae', optimizer='adadelta')
    return(model)

运行代码:

N1 = [10,9,8,7,6]
N2 = [8, 7, 6, 5, 4, 3, None]
N3 = [6, 5, 4, 3, 2, None]
test_list = [item for item in product(N1,N2,N3) if sorted(item, reverse = True) == list(item)][start_index:]
for m,(n1,n2,n3) in enumerate(test_list):
    model = nn_model(n1,n2,n3)
    # fit model and predict 

它工作正常,但每次我调用它时,返回已编译模型的速度会变慢。如果我重新启动 Python,我会像往常一样再次工作,但每次迭代后它都会变慢。在 30 次迭代之后,它花了将近 5 分钟,而第一次调用用了 10 秒。 我运行的模型在形状和大小上都相似,所以这不是问题。如果我首先或在 10 次迭代后生成相同的模型,那么在 10 次迭代后它会更长。

有谁知道这可能来自哪里以及如何避免它(无需每 5 次迭代重新启动 python)。 我在 IPython 中运行它,在 GTX650Ti(1Go 内部存储器)的 tensorflow 后端上。 还值得注意的是我的 RAM 消耗缓慢增长(通过调用约 50-100Mo)。

最佳答案

所有模型都是在默认的 TF 图中创建的,该图会随着时间的推移而变大。

解决方案是在图形范围内创建模型,或者使用以下 Keras 实用程序清除默认图形:

from keras import backend as K
K.clear_session()

关于python - 生成模型越来越长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40848193/

相关文章:

python - sqlite3.OperationalError : no such column. 但那不是一列

python-2.7 - SQLAlchemy 混合属性比较器

tensorflow - 在Linux上安装 tensorflow

python - tf.train.ExponentialMovingAverage 和 tf.train.MomentumOptimizer 有什么区别?

python - ValueError : `validation_split` is only supported for Tensors or NumPy arrays, 发现 : (keras. preprocessing.sequence.TimeseriesGenerator 对象)

python - 将特定数量的空行附加到 Pandas 数据帧

Python数据结构,字典?

python从同时运行的进程访问和更新mysql

python - 如何在python中不使用[]将列表写入文件

python - 使用 Tipfy 获取 HTTP GET 变量