我已经设法在Tensorflow中训练CNN模型,其输入是患病和健康患者的一维ECG信号。该体系结构由CNN-Max池组成 - CNN-Max池 - CNN-Max池 - CNN-Max池 - 完全连接 - 完全连接 - Softmax。
我使用此代码定义成本函数并训练网络:
# How we train
train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)
# Just initialize
sess.run(tf.global_variables_initializer())
# Define accuracy
correct_prediction = tf.equal(tf.argmax(y,1),
tf.argmax(y_,1),name='correct_pred')
accuracy = tf.reduce_mean(tf.cast(
correct_prediction, "float"),name='accuracy')
#%% Actually train
train= np.reshape(train,[-1,length,1])
test= np.reshape(test,[-1,length,1])
epochs = 200
train_acc = np.zeros(epochs//10)
test_acc = np.zeros(epochs//10)
start_time = time.time()
for i in tqdm(range(epochs), ascii=True):
# Record summary data, and the accuracy
if (i+1) % 10 == 0:
# Check accuracy on train set
TRA = accuracy.eval(feed_dict={x: train,
y_: onehot_train, keep_prob: 0.75})
train_acc[i//10] = TRA
# And now the validation set
TEA = accuracy.eval(feed_dict={x: test,
y_: onehot_test, keep_prob: 0.75})
test_acc[i//10] = TEA
print("Epoch:", '%04d' % (i+1), ", Train accuracy=", "{:.9f}".format(TRA),
", Test accuracy=", "{:.9f}".format(TEA),"--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
train_step.run(feed_dict={x: train,\
y_: onehot_train, keep_prob: 0.75})
在200个时代之后,模型的准确度达到了约95%。
训练结束后我保存了我的模型
#%% Save the weights
saver = tf.train.Saver()
saved_path=saver.save(sess , 'SavedModel/SCD')
但是当我使用保存的模型来精确评估列车数据时,它显示了54%的准确度。我无法弄清楚问题是什么。
from __future__ import print_function
from __future__ import division
import scipy.io as sio
import numpy as np
import tensorflow as tf
import time as time
from scipy import stats
import math
tf.set_random_seed(1)
saver = tf.train.import_meta_graph('SCD.meta')
sess=tf.Session()
saver.restore(sess, tf.train.latest_checkpoint('./'))
graph = tf.get_default_graph()
X =graph.get_tensor_by_name("X:0")
Y=graph.get_tensor_by_name("labels:0")
accuracy=graph.get_tensor_by_name("accuracy:0")
keep_prob = graph.get_tensor_by_name("keep_prob:0")
dropout=0.75
batch_accuracy=sess.run([accuracy], feed_dict={X: train, Y: onehot_train, keep_prob: dropout})
batch_accuracy为0.54370368。为什么保存模型的准确性与主要训练模型不同?