我在 jupyter 笔记本中使用 tensorflow.keras 来生成神经网络来匹配一些现实世界的数据。我第一次运行代码时,它工作正常。神经网络给出了一个与现实世界数据相匹配的模型。问题是,如果我尝试再次运行它,它无法生成任何新模型。由于某种原因,它无法找到匹配的模型,即使在第一次运行期间,它很容易找到很多。我没有收到错误消息或类似的信息。代码就像以前一样运行,并尝试找到适合给定数据的神经网络,但找不到任何数据,无论我将成功标准设置得有多低(下面代码中的“NSE_cut”)。
为了让它创建新模型,我必须重新启动 Jupyter Notebook 内核,这会擦除我迄今为止所做的所有数据和处理。更成问题的是,这意味着我无法在同一次运行中执行多个神经网络模型。我需要能够进行多次神经网络运行。
我做错了什么?为什么这段代码只能在第一次运行时生成模型?
这是代码:
### --- Calculate Neural Network fit for modes --- ###
def nn_fit(reof_ds, q, NSE_cut):
indx_qual_mode = []
best_model = []
best_score = []
best_nse = 0
# ----- Train Tensorflow Hydro-to-TPC models mode-by-mode -----
for mode in reof_ds.mode.values:
keras.backend.clear_session()
print('Building models for mode-'+str(mode).zfill(2))
tpc = reof_ds.temporal_modes.sel(mode=int(mode))
X = q.values.reshape(len(q),1)
Y = tpc.values.reshape(len(q),1)
X_train = X
Y_train = Y
# -- adapt function is to get the mean and STD used to normalize the input data of the model --
normalizer.adapt(X_train)
# ----- Construct the model and get summary -----
model = build_and_compile_model(normalizer)
#if vis_tf_nn==0:
#elif vis_tf_nn==1:
# plot_model(model, to_file='NOAA_WF\\hydro2rtpc_mdl\\'+data_src+'\\site-'+str(gaugeID_list[site])+'_tpc'+str(mode+1).zfill(2)+'.png', show_shapes=True, show_layer_names=True)
# ----- Fit the model -----
train_proc = model.fit(
X_train,
Y_train,
callbacks=[callback],
batch_size=32,
epochs=200,
verbose=0,
#validation_split=0.2
)
# ----- Plot model estimation and original scatter plot -----
X_sim = tf.linspace(np.amin(X), np.amax(X), X.size*10^10)
Y_sim = model.predict(X_sim)
# ----- The second-time REOF mode screening based on quality of regression models. If qualified, export trained model -----
Y_mdl = model.predict(X[:,0])
nse = 1 - ( (np.nansum(np.square( Y - Y_mdl ))) / (np.nansum(np.square( Y - np.nanmean(Y) ))) )
if nse >= NSE_cut: # Moriasi et al., 2007. Consider NSE>0.5 as satisfactory
model.summary()
print(mode, nse)
# ----- Plot training progress -----
plot_loss(train_proc)
best_nse = nse
best_score.append(best_nse)
best_model.append(model)
indx_qual_mode.append(mode)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
plt.scatter(X, Y)
plt.plot(X_sim, Y_sim, color='r')
plt.xlabel('discharge (m3/d)')
plt.ylabel(f"mode {mode}")
plt.xticks(rotation=45, ha='right')
plt.yticks(rotation=45)
plt.legend(['NN-Model','Data'],loc='upper left')
plt.text(0.2,0.5,'NSE: '+"{:.2f}".format(nse), transform=ax.transAxes)
plt.savefig('test.png', dpi=300, bbox_inches='tight')
plt.show()
# ----- Export trained model -----
#best_model.save('test.keras')
# ADDED by Knicely
del Y_mdl, X_sim, Y_sim, X, Y, X_train, Y_train, train_proc, model
keras.backend.clear_session()
return(best_model, indx_qual_mode)
reof_ds 包含旋转经验正交函数的空间和时间模式。
为了清楚问题而进行编辑。
删除模型并清除后台会话。
keras.backend.clear_session()