运行下面的代码后,我获得了精度值,并且可以获得所有Ws和bs的值。我的问题是,将来如何使用输出对事物进行分类?以及如何保存模型?
#########################################
################ SETUP ##################
training_epochs = 500
n_neurons_in_h1 = 60
n_neurons_in_h2 = 60
learning_rate = 0.01
n_features = 3
n_classes = 3
X = tf.placeholder(tf.float32, [None, n_features], name='features')
Y = tf.placeholder(tf.float32, [None, n_classes], name='labels')
W1 = tf.Variable(tf.truncated_normal([n_features, n_neurons_in_h1], mean=0, stddev=1 / np.sqrt(n_features)), name='weights1')
b1 = tf.Variable(tf.truncated_normal([n_neurons_in_h1],mean=0, stddev=1 / np.sqrt(n_features)), name='biases1')
y1 = tf.nn.tanh((tf.matmul(X, W1)+b1), name='activationLayer1')
W2 = tf.Variable(tf.random_normal([n_neurons_in_h1, n_neurons_in_h2],mean=0,stddev=1/np.sqrt(n_features)),name='weights2')
b2 = tf.Variable(tf.random_normal([n_neurons_in_h2],mean=0,stddev=1/np.sqrt(n_features)),name='biases2')
y2 = tf.nn.sigmoid((tf.matmul(y1,W2)+b2),name='activationLayer2')
Wo = tf.Variable(tf.random_normal([n_neurons_in_h2, n_classes], mean=0, stddev=1/np.sqrt(n_features)), name='weightsOut')
bo = tf.Variable(tf.random_normal([n_classes], mean=0, stddev=1/np.sqrt(n_features)), name='biasesOut')
a = tf.nn.softmax((tf.matmul(y2, Wo) + bo), name='activationOutputLayer')
cross_entropy = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(a),reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(a, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name="Accuracy")
#########################################
############### GET DATA ################
(为简洁起见,已删除)
数据的格式为[var1,var2,var3,标签]。被分成培训的80%和测试的20%。
#########################################
################ RUN ####################
# initialization of all variables
initial = tf.global_variables_initializer()
#creating a session
with tf.Session() as sess:
sess.run(initial)
# training loop over the number of epoches
batchsize=10
for epoch in range(training_epochs):
for i in range(len(tr_features)):
start=i
end=i+batchsize
x_batch=tr_features[start:end]
y_batch=tr_labels[start:end]
# feeding training data/examples
sess.run(train_step, feed_dict={X:x_batch , Y:y_batch})
i+=batchsize
# feeding testing data to determine model accuracy
y_pred = sess.run(tf.argmax(a, 1), feed_dict={X: ts_features})
y_true = sess.run(tf.argmax(ts_labels, 1))
acc = sess.run(accuracy, feed_dict={X: ts_features, Y: ts_labels})
# print accuracy for each epoch
print('epoch',epoch, acc)
print ('---------------')
print(y_pred, y_true)
答案 0 :(得分:0)
您可以使用tf.train.Saver()
类保存模型(权重+附加值)。此类的save
方法将保存所有内容,而restore
方法将加载由save
方法创建的文件,因此您无需重新训练即可进行预测。
查看文档:{{3}}