我基于“ Binary classification, soerendip”构建了一个NN,以不断预测二进制数。以下代码是培训过程的简化:
import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
X, Y = make_classification(n_samples=50000, n_features=10, n_informative=8,
n_redundant=0, n_clusters_per_class=2)
Y = np.array([Y, -(Y-1)]).T # The model currently needs one column for each class
X, X_test, Y, Y_test = train_test_split(X, Y)
# Parameters
learning_rate = 0.001
training_epochs = 12
batch_size = 1
display_step = 1
# Network Parameters
n_hidden_1 = 10 # 1st layer number of features
n_hidden_2 = 10 # 2nd layer number of features
n_input = 10 # Number of feature
n_classes = 2 # Number of classes to predict
# tf Graph input
x = tf.placeholder("float", [None, n_input], name = 'x')
y = tf.placeholder("float", [None, n_classes], name = 'y')
# Create model
def multilayer_perceptron(x, weights, biases):
# Hidden layer with RELU activation
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
layer_1 = tf.nn.relu(layer_1)
# Hidden layer with RELU activation
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
layer_2 = tf.nn.relu(layer_2)
# Output layer with linear activation
out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
return out_layer
# Store layers weight & bias
weights = {
'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
# Construct model
pred = multilayer_perceptron(x, weights, biases)
# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Initializing the variables
init = tf.global_variables_initializer()
# Launch the graph
saver = tf.train.Saver()
#export_dir="/tmp/new"
#builder = tf.saved_model.builder.SavedModelBuilder(export_dir)
#if low_level == True:
with tf.Session() as sess:
sess.run(init)
# Training cycle
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(len(X)/batch_size)
X_batches = np.array_split(X, total_batch)
Y_batches = np.array_split(Y, total_batch)
# Loop over all batches
for i in range(total_batch):
batch_x, batch_y = X_batches[i], Y_batches[i]
# Run optimization op (backprop) and cost op (to get loss value)
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
y: batch_y})
# Compute average loss
avg_cost += c / total_batch
if epoch % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
print("Optimization Finished!")
save_path = saver.save(sess, "/tmp/model.ckpt")
print("Model saved in path: %s" % save_path)
为了恢复和测试,我使用以下功能:
def restoring(X_test,Y_test):
saver = tf.train.import_meta_graph("/tmp/model.ckpt.meta")
with tf.Session() as sess:
#now restore the variables
sess.run(tf.global_variables_initializer())
saver.restore(sess, "/tmp/model.ckpt")
#print("weightsh1",weights['h1'].eval())
#print("weightsh2",weights['h2'].eval())
#print("weightsout",weights['out'].eval())
#print("biasb1",biases['b1'].eval())
#print("biasb2",biases['b2'].eval())
#print("biasout",biases['out'].eval())
#np.savetxt("weightsh1_check.txt",weights['h1'].eval())
#np.savetxt("weightsh2_check.txt",weights['h2'].eval())
#np.savetxt("weightsout_check.txt",weights['out'].eval())
#np.savetxt("biasb1_check.txt",biases['b1'].eval())
#np.savetxt("biasb2_check.txt",biases['b2'].eval())
#np.savetxt("biasout_check.txt",biases['out'].eval())
#coord = tf.train.Coordinator()
#threads = tf.train.start_queue_runners(coord=coord)
aa = []
for ss in np.arange(len(X_test)):
aaa = X_test[ss]
aaa = aaa.reshape(1,10)
aa.extend(sess.run(pred,feed_dict={x: aaa}))
#coord.request_stop()
#coord.join(threads)
aa = np.array(aa)
bb = np.argmax(aa,1)
cc = Y_test[:,1]
dd=np.equal(bb, cc)
accur_val = np.sum(dd)/len(X_test)
print('Accuracy of validation:')
print(accur_val)
精度通常> 90%,并且变量也可以根据需要恢复。在我的真实示例中,我面临以下挑战:首先,我使用来自api的时间序列数据,该数据每分钟更新一次。不幸的是,它涉及机密数据,但是,即使make_classification()
并不完美,该示例也足以理解该问题。如果还不够好,请在下面评论,我会解决的。
当我使用以下流程时,恢复工作正常:
当我使用以下流程时,准确性通常会大大下降。
测试大小通常为200分钟左右,以便第一个api下载结果为:
data_test_input [t200] = [d0,d1,... d200]效果良好(> 90%)。
首次成功训练和测试模型后,我再次下载了一些更新的数据,例如这个:
data_test_input [t203] = [d3,d4,... d203]结果不佳(40-60%)
我通常会假设我的精度至少约为前一个值,但是事实证明,每次都会随机设置。是什么原因导致此问题,或者我做错了什么?
非常感谢您!