微信监控机器学习、深度学习训练过程
作者:McGrady
个人博客:http://mcgrady.cn/
训练复杂的机器学习、深度学习模型,往往需要几十分钟、几小时,甚至需要几天,真的是等到花儿也谢了,看结果的时候,经常不断的通过命令查看服务器Log文件,来查看loss、accuracy、混淆矩阵等等结果。
今天刷知乎才发现可以用itchat来做,通过微信端来查看模型训练进展,可视化loss,可视化准确率,甚至可以用微信来控制程序启动,终止,查看参数等等操作!!!有木有很方便!!!四不四特别酷!!!这样就不用时刻盯着屏幕,盯着log文件了。
无挂断后台执行:
nohup python tensorflow_itchat.py
模型跑起来后,就可以去看电影,打篮球,撩妹(划掉,程序员不擅长),睡觉(这个才是猿类的恩赐,哈哈),看看手机,就能知道模型训练的如何,是否需要进一步操作,调整,以便计划下一步工作。
看到知乎上一个脑洞大开的哥哥的回答:
能盯着loss看一个小时,想象自己就是搜索点。然后幻想自己是个游戏里的小人在山谷里摸索,到处都是战争迷雾,我的视野还特别小。看到带周期波动的下降就会感觉自己在一个圆筒的滑梯里忽左忽右的出溜。看到上升就会突然紧张,再瞄一下acc比较train和val,像一个赌徒企图从绝望中看到希望。loss再度下降时会产生强烈的快感,觉得艰难地翻过了一座小山。快要收敛时安慰自己,前方还会有深渊。最后收敛时告诉自己,就是这里了,我累了。然后休息一下,分析分析,终于决定:算了再加一层吧……
写的比较匆忙,后续添加一些tools,以便后续调用。
用例子mnist手写识别当Demo,代码链接:https://github.com/TracyMcgrady6/TF_itchat
效果:
from __future__ import print_function
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import itchat
import matplotlib.pyplot as plt
itchat.auto_login(hotReload=True)
# Parameters
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
learning_rate = 0.1
num_steps = 500
batch_size = 128
display_step = 100
# Network Parameters
n_hidden_1 = 256 # 1st layer number of neurons
n_hidden_2 = 256 # 2nd layer number of neurons
num_input = 784 # MNIST data input (img shape: 28*28)
num_classes = 10 # MNIST total classes (0-9 digits)
# tf Graph input
X = tf.placeholder("float", [None, num_input])
Y = tf.placeholder("float", [None, num_classes])
# Store layers weight & bias
weights = {
'h1': tf.Variable(tf.random_normal([num_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, num_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([num_classes]))
}
# Create model
def neural_net(x):
# Hidden fully connected layer with 256 neurons
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
# Hidden fully connected layer with 256 neurons
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
# Output fully connected layer with a neuron for each class
out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
return out_layer
# Construct model
logits = neural_net(X)
# Define loss and optimizer
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)
# Evaluate model (with test logits, for dropout to be disabled)
correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()
# Start training
x = []
y = []
with tf.Session() as sess:
# Run the initializer
sess.run(init)
for step in range(1, num_steps + 1):
batch_x, batch_y = mnist.train.next_batch(batch_size)
# Run optimization op (backprop)
sess.run(train_op, feed_dict={X: batch_x, Y: batch_y})
if step % display_step == 0 or step == 1:
# Calculate batch loss and accuracy
loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,
Y: batch_y})
print("Step " + str(step) + ", Minibatch Loss= " + \
"{:.4f}".format(loss) + ", Training Accuracy= " + \
"{:.3f}".format(acc))
x.append(step)
itchat.send("Step " + str(step) + ", Minibatch Loss= " + \
"{:.4f}".format(loss) + ", Training Accuracy= " + \
"{:.3f}".format(acc))
y.append("{:.3f}".format(acc))
print("Optimization Finished!")
itchat.send("Optimization Finished!")
# Calculate accuracy for MNIST test images
acc = sess.run(accuracy, feed_dict={X: mnist.test.images,
Y: mnist.test.labels})
print("Testing Accuracy:", float(acc))
itchat.send("Testing Accuracy:" + str(float(acc)))
plt.title('Loss')
plt.xlabel('Step')
plt.ylabel('Accuracy')
plt.plot(x, y, 'r', label='broadcast')
plt.grid()
plt.savefig('/Users/t-mac/Desktop/a.jpg')
itchat.send_image('/Users/t-mac/Desktop/a.jpg')
Python爱好者社区历史文章大合集:
Python爱好者社区历史文章列表(每周append更新一次)
关注后在公众号内回复“课程”即可获取:
小编的Python入门免费视频课程!!!
【最新免费微课】小编的Python快速上手matplotlib可视化库!!!
崔老师爬虫实战案例免费学习视频。
陈老师数据分析报告制作免费学习视频。
玩转大数据分析!Spark2.X+Python 精华实战课程免费学习视频。