我在Python编程方面是新手。我在训练时保存了TensorFlow神经网络,如下所示:
n_hidden_1 =200n_hidden_2 =100 # 第一层特征数量n_hidden_3 = 100 # 第二层特征数量n_input = 128 n_output = 128X = tf.placeholder("float", [None, n_input])Y = tf.placeholder("float", [None, n_output])def encoder(x): weights = { 'encoder_w1': tf.Variable(tf.random.truncated_normal([n_input, n_hidden_1],stddev=0.1),name='encoder_w1'), 'encoder_w2': tf.Variable(tf.random.truncated_normal([n_hidden_1, n_hidden_2],stddev=0.1),name='encoder_w2'), 'encoder_w3': tf.Variable(tf.random.truncated_normal([n_hidden_2, n_hidden_3],stddev=0.1),name='encoder_w3'), 'encoder_w4': tf.Variable(tf.random.truncated_normal([n_hidden_3, n_output],stddev=0.1),name='encoder_w4'), } biases = { 'encoder_b1': tf.Variable(tf.random.truncated_normal([n_hidden_1],stddev=0.1),name='encoder_b1'), 'encoder_b2': tf.Variable(tf.random.truncated_normal([n_hidden_2],stddev=0.1),name='encoder_b2'), 'encoder_b3': tf.Variable(tf.random.truncated_normal([n_hidden_3],stddev=0.1),name='encoder_b3'), 'encoder_b4': tf.Variable(tf.random.truncated_normal([n_output],stddev=0.1),name='encoder_b4'), } # 使用sigmoid激活的编码器隐藏层 #1 #layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['encoder_h1']), biases['encoder_b1'])) layer_1 = tf.nn.relu(tf.add(tf.matmul(x, weights['encoder_w1']), biases['encoder_b1'])) layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, weights['encoder_w2']), biases['encoder_b2'])) layer_3 = tf.nn.relu(tf.add(tf.matmul(layer_2, weights['encoder_w3']), biases['encoder_b3'])) layer_4 = tf.nn.sigmoid(tf.add(tf.matmul(layer_3, weights['encoder_w4']), biases['encoder_b4'])) return layer_4y_pred = encoder(X)y_true = Y# 定义损失和优化器,最小化平方误差cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2))learning_rate = tf.placeholder(tf.float32, shape=[])optimizer = tf.train.RMSPropOptimizer(learning_rate=learning_rate).minimize(cost)saver = tf.train.Saver(max_to_keep=1) with tf.Session(config=config) as sess: sess.run(init) traing_epochs = 100 learning_rate_current = 0.001 #0.01 for epoch in range(traing_epochs):> # 代码块.................input_labels.append(x) input_samples.append(y)batch_x = np.asarray(input_samples)batch_y = np.asarray(input_labels _,c = sess.run([optimizer,cost], feed_dict={X:batch_x, Y:batch_y, learning_rate:learning_rate_current})
训练后,我加载了训练好的网络并打印变量,如下所示:
with tf.Session() as sess2: saver2= tf.train.import_meta_graph('../my_model.ckpt.meta') saver2.restore(sess2,'../my_model.ckpt')savevariable=tf.all_variables()
我看到了训练后的保存变量,总共有48个变量(我不明白为什么最初的8个参数增加到了48个值)。我有4个权重和4个偏置,分别用于第1层、第2层、第3层和第4层的初始值。对于预测,我应该使用这48个保存值中的哪4个权重和4个偏置?我非常困惑。以下是打印的保存变量:
<tf.Variable 'encoder_w1:0' shape=(128, 200) dtype=float32_ref>, <tf.Variable 'encoder_w2:0' shape=(200, 100) dtype=float32_ref>, <tf.Variable 'encoder_w3:0' shape=(100, 100) dtype=float32_ref>, <tf.Variable 'encoder_w4:0' shape=(100, 128) dtype=float32_ref>, <tf.Variable 'encoder_b1:0' shape=(200,) dtype=float32_ref>, <tf.Variable 'encoder_b2:0' shape=(100,) dtype=float32_ref>, <tf.Variable 'encoder_b3:0' shape=(100,) dtype=float32_ref>, <tf.Variable 'encoder_b4:0' shape=(128,) dtype=float32_ref>, <tf.Variable 'encoder_w1/RMSProp:0' shape=(128, 200) dtype=float32_ref>, <tf.Variable 'encoder_w1/RMSProp_1:0' shape=(128, 200) dtype=float32_ref>, <tf.Variable 'encoder_w2/RMSProp:0' shape=(200, 100) dtype=float32_ref>, <tf.Variable 'encoder_w2/RMSProp_1:0' shape=(200, 100) dtype=float32_ref>, <tf.Variable 'encoder_w3/RMSProp:0' shape=(100, 100) dtype=float32_ref>, <tf.Variable 'encoder_w3/RMSProp_1:0' shape=(100, 100) dtype=float32_ref>, <tf.Variable 'encoder_w4/RMSProp:0' shape=(100, 128) dtype=float32_ref>, <tf.Variable 'encoder_w4/RMSProp_1:0' shape=(100, 128) dtype=float32_ref>, <tf.Variable 'encoder_b1/RMSProp:0' shape=(200,) dtype=float32_ref>, <tf.Variable 'encoder_b1/RMSProp_1:0' shape=(200,) dtype=float32_ref>, <tf.Variable 'encoder_b2/RMSProp:0' shape=(100,) dtype=float32_ref>, <tf.Variable 'encoder_b2/RMSProp_1:0' shape=(100,) dtype=float32_ref>, <tf.Variable 'encoder_b3/RMSProp:0' shape=(100,) dtype=float32_ref>, <tf.Variable 'encoder_b3/RMSProp_1:0' shape=(100,) dtype=float32_ref>, <tf.Variable 'encoder_b4/RMSProp:0' shape=(128,) dtype=float32_ref>, <tf.Variable 'encoder_b4/RMSProp_1:0' shape=(128,) dtype=float32_ref>, <tf.Variable 'encoder_w1:0' shape=(128, 200) dtype=float32_ref>, <tf.Variable 'encoder_w2:0' shape=(200, 100) dtype=float32_ref>, <tf.Variable 'encoder_w3:0' shape=(100, 100) dtype=float32_ref>, <tf.Variable 'encoder_w4:0' shape=(100, 128) dtype=float32_ref>, <tf.Variable 'encoder_b1:0' shape=(200,) dtype=float32_ref>, <tf.Variable 'encoder_b2:0' shape=(100,) dtype=float32_ref>, <tf.Variable 'encoder_b3:0' shape=(100,) dtype=float32_ref>, <tf.Variable 'encoder_b4:0' shape=(128,) dtype=float32_ref>, <tf.Variable 'encoder_w1/RMSProp:0' shape=(128, 200) dtype=float32_ref>, <tf.Variable 'encoder_w1/RMSProp_1:0' shape=(128, 200) dtype=float32_ref>, <tf.Variable 'encoder_w2/RMSProp:0' shape=(200, 100) dtype=float32_ref>, <tf.Variable 'encoder_w2/RMSProp_1:0' shape=(200, 100) dtype=float32_ref>, <tf.Variable 'encoder_w3/RMSProp:0' shape=(100, 100) dtype=float32_ref>, <tf.Variable 'encoder_w3/RMSProp_1:0' shape=(100, 100) dtype=float32_ref>, <tf.Variable 'encoder_w4/RMSProp:0' shape=(100, 128) dtype=float32_ref>, <tf.Variable 'encoder_w4/RMSProp_1:0' shape=(100, 128) dtype=float32_ref>, <tf.Variable 'encoder_b1/RMSProp:0' shape=(200,) dtype=float32_ref>, <tf.Variable 'encoder_b1/RMSProp_1:0' shape=(200,) dtype=float32_ref>, <tf.Variable 'encoder_b2/RMSProp:0' shape=(100,) dtype=float32_ref>, <tf.Variable 'encoder_b2/RMSProp_1:0' shape=(100,) dtype=float32_ref>, <tf.Variable 'encoder_b3/RMSProp:0' shape=(100,) dtype=float32_ref>, <tf.Variable 'encoder_b3/RMSProp_1:0' shape=(100,) dtype=float32_ref>, <tf.Variable 'encoder_b4/RMSProp:0' shape=(128,) dtype=float32_ref>, <tf.Variable 'encoder_b4/RMSProp_1:0' shape=(128,) dtype=float32_ref>
您能给我一些建议吗?
回答:
首先,您犯了一个错误:
input_labels.append(x) input_samples.append(y)
应该改为:
input_samples.append(x)input_labels.append(y)
回答您的问题:
实际上,您应该有24个变量(见下文),但当您启动第二个会话时,原始的TensorFlow变量仍然存在,而新加载的变量是在这些变量的基础上创建的。因此,总是建议做类似以下的事情:
tf.keras.backend.clear_session()
您的批处理定义有点问题,所以我在示例代码中也进行了修复:
注意:在回答时,OP没有提供可复现的示例,因此我根据初始数据创建了一个,并根据OP的问题进行了注释:
导入所有模块
import numpy as npfrom numpy import random as randomimport tensorflow as tftf.compat.v1.disable_eager_execution()
清除所有会话数据,这些数据在交互式环境中很容易累积。
tf.keras.backend.clear_session()
定义我们稍后需要的所有元素:
X_train = random.rand(100, 128)y_train = random.rand(100, 128)n_hidden_1 =200n_hidden_2 =100 # 第一层特征数量n_hidden_3 = 100 # 第二层特征数量n_input = 128 n_output = 128X = tf.compat.v1.placeholder("float", [None, n_input])Y = tf.compat.v1.placeholder("float", [None, n_output])def encoder(x): weights = { 'encoder_w1': tf.Variable(tf.random.truncated_normal([n_input, n_hidden_1],stddev=0.1),name='encoder_w1'), 'encoder_w2': tf.Variable(tf.random.truncated_normal([n_hidden_1, n_hidden_2],stddev=0.1),name='encoder_w2'), 'encoder_w3': tf.Variable(tf.random.truncated_normal([n_hidden_2, n_hidden_3],stddev=0.1),name='encoder_w3'), 'encoder_w4': tf.Variable(tf.random.truncated_normal([n_hidden_3, n_output],stddev=0.1),name='encoder_w4'), } biases = { 'encoder_b1': tf.Variable(tf.random.truncated_normal([n_hidden_1],stddev=0.1),name='encoder_b1'), 'encoder_b2': tf.Variable(tf.random.truncated_normal([n_hidden_2],stddev=0.1),name='encoder_b2'), 'encoder_b3': tf.Variable(tf.random.truncated_normal([n_hidden_3],stddev=0.1),name='encoder_b3'), 'encoder_b4': tf.Variable(tf.random.truncated_normal([n_output],stddev=0.1),name='encoder_b4'), } # 使用sigmoid激活的编码器隐藏层 #1 #layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['encoder_h1']), biases['encoder_b1'])) layer_1 = tf.nn.relu(tf.add(tf.matmul(x, weights['encoder_w1']), biases['encoder_b1'])) layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, weights['encoder_w2']), biases['encoder_b2'])) layer_3 = tf.nn.relu(tf.add(tf.matmul(layer_2, weights['encoder_w3']), biases['encoder_b3'])) layer_4 = tf.nn.sigmoid(tf.add(tf.matmul(layer_3, weights['encoder_w4']), biases['encoder_b4'])) return layer_4y_pred = encoder(X)y_true = Y# 定义损失和优化器,最小化平方误差cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2))learning_rate = tf.compat.v1.placeholder(tf.float32, shape=[])optimizer = tf.compat.v1.train.RMSPropOptimizer(learning_rate=learning_rate).minimize(cost)saver = tf.compat.v1.train.Saver(max_to_keep=1) init = tf.compat.v1.global_variables_initializer()
开始训练会话:
with tf.compat.v1.Session() as sess: sess.run(init) traing_epochs = 100 learning_rate_current = 0.001 #0.01 # 定义批处理大小 batch_size = 10 num_samples = (X_train.shape[0]) # 开始训练循环 for epoch in range(traing_epochs): print("Epoch " + str(epoch)) # 开始每批处理的训练循环 for i in range(int(num_samples/batch_size)): print("{}/{}".format(batch_size * i, num_samples)) # 获取批处理 batch_x = X_train[i * batch_size:(i + 1) * batch_size] batch_y = y_train[i * batch_size:(i + 1) * batch_size] _,c = sess.run([optimizer,cost], feed_dict={X: batch_x, Y: batch_y, learning_rate: learning_rate_current}) saver.export_meta_graph('../my_model.ckpt.meta') saver.save(sess, '../my_model.ckpt')