概览
TensorFlow 是 Google 推出的机器学习开源平台,支持 CNN、RNN 和 LSTM 等深度神经网络。这里记录一下怎么在 Windows 下安装和使用 TensorFlow。
安装
Python 3.5.x
请确保机器已经安装 Python 3.5.x 版本,如果没有到这里下载安装。
TensorFlow
在命令行输入如下命令,下载、安装 Tensorflow:
C:\> pip3 install --upgrade tensorflow
使用
一、Hello world
编写如下 python 程序文件,命名为 helloworld.py:
import tensorflow as tf
import os
# 这个变量控制输出 tensorflow 的调试日志级别
# 0: all logs shown (that's the default setting)
# 1: filter out INFO logs
# 2: additionally filter out WARNING logs
# 3: additionally filter out ERROR logs.
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print (sess.run(hello))
在命令行中执行 python 命令:
python helloworld.py
产生如下输出:
b'Hello, TensorFlow!'
二、数据计算
编写 calc.py 程序文件如下:
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
a = tf.constant(2)
b = tf.constant(3)
with tf.Session() as sess:
print ("a=2, b=3")
print ("Addition with constants: %i" % sess.run(a+b))
print ("Multiplication with constants: %i" % sess.run(a*b))
执行结果如下:
a=2, b=3
Addition with constants: 5
Multiplication with constants: 6
三、placeholder 用法
placeholder 是计算节点的数据占位符,可以在网络执行时通过 feed_dict 动态填充数据,具体示例代码如下:
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)
add = tf.add(a, b)
mul = tf.multiply(a, b)
with tf.Session() as sess:
# Run every oerpation with variable input
print ("Addition with variables: %i" % sess.run(add, feed_dict={a: 2, b: 3}))
print ("Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b:3}))
执行结果如下:
Addition with variables: 5
Multiplication with variables: 6
四、线性回归
下面是一段基于梯度下降的线性回归学习算法:
import tensorflow as tf
import numpy
import os
import matplotlib.pyplot as plt
rng = numpy.random
# 这个变量控制输出 tensorflow 的调试日志级别
# 0: all logs shown (that's the default setting)
# 1: filter out INFO logs
# 2: additionally filter out WARNING logs
# 3: additionally filter out ERROR logs.
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# Parameters
learning_rate = 0.01
training_epochs = 2000
display_step = 50
# Training Data
train_X = numpy.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1])
train_Y = numpy.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3])
n_samples = train_X.shape[0]
# tf Graph Input
X = tf.placeholder("float")
Y = tf.placeholder("float")
# Create Model
# Set model weights
W = tf.get_variable("weight", initializer=rng.randn())
b = tf.get_variable("bias", initializer=rng.randn())
# Construct a linear model
activation = tf.add(tf.multiply(X, W), b)
# Minimize the squared errors
cost = tf.reduce_sum(tf.pow(activation-Y, 2))/(2*n_samples) #L2 loss
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) #Gradient descent
# Initializing the variables
init = tf.global_variables_initializer()
# Launch the graph
with tf.Session() as sess:
sess.run(init)
# Fit all training data
for epoch in range(training_epochs):
for (x, y) in zip(train_X, train_Y):
sess.run(optimizer, feed_dict={X: x, Y: y})
#Display logs per epoch step
if epoch % display_step == 0:
print ("Epoch:", '%04d' % (epoch+1), "cost=", \
"{:.9f}".format(sess.run(cost, feed_dict={X: train_X, Y:train_Y})), \
"W=", sess.run(W), "b=", sess.run(b))
print ("Optimization Finished!")
print ("cost=", sess.run(cost, feed_dict={X: train_X, Y: train_Y}), \
"W=", sess.run(W), "b=", sess.run(b))
#Graphic display
plt.plot(train_X, train_Y, 'ro', label='Original data')
plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
plt.legend()
plt.show()
上述代码输出结果是:
Epoch: 0001 cost= 2.270673752 W= 0.0199863 b= 0.218542
Epoch: 0051 cost= 0.092837997 W= 0.320129 b= 0.294043
Epoch: 0101 cost= 0.091003135 W= 0.315933 b= 0.324222
Epoch: 0151 cost= 0.089380413 W= 0.311988 b= 0.352606
Epoch: 0201 cost= 0.087945282 W= 0.308277 b= 0.379302
Epoch: 0251 cost= 0.086676069 W= 0.304787 b= 0.40441
Epoch: 0301 cost= 0.085553691 W= 0.301504 b= 0.428025
Epoch: 0351 cost= 0.084561057 W= 0.298417 b= 0.450236
Epoch: 0401 cost= 0.083683245 W= 0.295513 b= 0.471126
Epoch: 0451 cost= 0.082907043 W= 0.292782 b= 0.490773
Epoch: 0501 cost= 0.082220614 W= 0.290213 b= 0.509251
Epoch: 0551 cost= 0.081613660 W= 0.287798 b= 0.52663
Epoch: 0601 cost= 0.081076942 W= 0.285525 b= 0.542976
Epoch: 0651 cost= 0.080602333 W= 0.283388 b= 0.55835
Epoch: 0701 cost= 0.080182679 W= 0.281378 b= 0.572809
Epoch: 0751 cost= 0.079811595 W= 0.279488 b= 0.58641
Epoch: 0801 cost= 0.079483464 W= 0.27771 b= 0.599203
Epoch: 0851 cost= 0.079193428 W= 0.276037 b= 0.611233
Epoch: 0901 cost= 0.078937046 W= 0.274465 b= 0.622547
Epoch: 0951 cost= 0.078710355 W= 0.272985 b= 0.633187
Epoch: 1001 cost= 0.078509949 W= 0.271594 b= 0.643194
Epoch: 1051 cost= 0.078332819 W= 0.270286 b= 0.652607
Epoch: 1101 cost= 0.078176200 W= 0.269055 b= 0.66146
Epoch: 1151 cost= 0.078037746 W= 0.267898 b= 0.669786
Epoch: 1201 cost= 0.077915415 W= 0.266809 b= 0.677617
Epoch: 1251 cost= 0.077807248 W= 0.265786 b= 0.684983
Epoch: 1301 cost= 0.077711672 W= 0.264823 b= 0.69191
Epoch: 1351 cost= 0.077627227 W= 0.263917 b= 0.698426
Epoch: 1401 cost= 0.077552564 W= 0.263065 b= 0.704554
Epoch: 1451 cost= 0.077486590 W= 0.262264 b= 0.710318
Epoch: 1501 cost= 0.077428304 W= 0.26151 b= 0.715739
Epoch: 1551 cost= 0.077376805 W= 0.260801 b= 0.720839
Epoch: 1601 cost= 0.077331312 W= 0.260135 b= 0.725634
Epoch: 1651 cost= 0.077291131 W= 0.259508 b= 0.730145
Epoch: 1701 cost= 0.077255622 W= 0.258918 b= 0.734387
Epoch: 1751 cost= 0.077224284 W= 0.258363 b= 0.738377
Epoch: 1801 cost= 0.077196598 W= 0.257842 b= 0.74213
Epoch: 1851 cost= 0.077172138 W= 0.257351 b= 0.745661
Epoch: 1901 cost= 0.077150561 W= 0.256889 b= 0.748981
Epoch: 1951 cost= 0.077131495 W= 0.256455 b= 0.752104
Optimization Finished!
cost= 0.077115 W= 0.256055 b= 0.754983
五、图形化展示
matplotlib 是 Python 的 2D 图形绘制库,借此可以直观展示算法结果。
如果还没有安装 matplotlib,在命令行输入如下命令进行安装:
python -m pip install matplotlib
在第四部分的代码头部添加库的导入:
import matplotlib.pyplot as plt
在代码的最后添加图形绘制的逻辑如下:
#Graphic display
plt.plot(train_X, train_Y, 'ro', label='Original data')
plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
plt.legend()
plt.show()
代码执行完生成如下绘图: