tensorflow很强大,很灵活。但对于新手并不友好,主要不是复杂,准确来说是繁琐。因为拆开一个个点来看,都不复杂,就像积木似的。
但每次为了拼一层,要做大量的事情,就是太琐碎了。正因为如此,才有了tflearn,keras这样的封装。keras原本是为theano封装的,theano本身就是一个高性能的矩阵运算库,算不上深度学习库,后来又兼容的tensorflow,CNTK等。
keras为了通用,注定要封装更多层次的抽象,对于源码理解就带来了困难。而tflearn的粒度正好适中,它就是为tensorflow而生,而且它生成的结构也是tensor,用session.run是可以直接计算的。
本文理解一下tflearn内建的操作符,就是tensorlayer里号称的中等程度的封装,其实tflearn也有。
http://s5/mw690/001rxTlvzy7eVpT5OZe04&690
import tensorflow as tf
import tflearn
#这里下载并加载minist数据集
import tflearn.datasets.mnist as mnist
trainX, trainY, testX, testY = mnist.load_data(one_hot=True)
# 为演示效果,直接使用tersorflow的placeholder
with tf.Graph().as_default():
# 输入、输出变量
X = tf.placeholder("float", [None, 784])
Y = tf.placeholder("float", [None, 10])
#这里是参数,就是WX+b
W1 = tf.Variable(tf.random_normal([784, 256]))
W2 = tf.Variable(tf.random_normal([256, 256]))
W3 = tf.Variable(tf.random_normal([256, 10]))
b1 = tf.Variable(tf.random_normal([256]))
b2 = tf.Variable(tf.random_normal([256]))
b3 = tf.Variable(tf.random_normal([10]))
# 下面就是一个多层感知器
def dnn(x):
# TFlearn有一个prelu的激活函数
x = tflearn.prelu(tf.add(tf.matmul(x, W1), b1))
tflearn.summaries.monitor_activation(x) # Monitor activation
x = tflearn.prelu(tf.add(tf.matmul(x, W2), b2))
tflearn.summaries.monitor_activation(x) # Monitor activation
x = tf.nn.softmax(tf.add(tf.matmul(x, W3), b3))
return x
net = dnn(X)
# tflearn提供的计算交叉熵损失的函数
loss = tflearn.categorical_crossentropy(net, Y)
# tflearn提供的计算测试集准确性的函数
acc = tflearn.metrics.accuracy_op(net, Y)
# 下面是优化函数
optimizer = tflearn.SGD(learning_rate=0.1, lr_decay=0.96, decay_step=200)
step = tflearn.variable("step", initializer='zeros', shape=[])
optimizer.build(step_tensor=step)
optim_tensor = optimizer.get_tensor()
# 使用 TFLearn Trainer
trainop = tflearn.TrainOp(loss=loss, optimizer=optim_tensor,
metric=acc, batch_size=128,
step_tensor=step)
trainer = tflearn.Trainer(train_ops=trainop, tensorboard_verbose=0)
# Training for 10 epochs.
trainer.fit({X: trainX, Y: trainY}, val_feed_dicts={X: testX, Y: testY},
n_epoch=10, show_metric=True)
这个粒度的封装,其实很适合与tensorflow一起使用,比那个tensorlayer好用太多。
关于作者:魏佳斌,互联网产品/技术总监,北京大学光华管理学院(MBA),特许金融分析师(CFA),资深产品经理/码农。偏爱python,深度关注互联网趋势,人工智能,AI金融量化。致力于使用最前沿的认知技术去理解这个复杂的世界。
扫描下方二维码,关注:AI量化实验室(ailabx),了解AI量化最前沿技术、资讯。
http://s8/mw690/001rxTlvzy7eVpSci3R57&690