TensorFlow学习

TensorFlow学习

TensorFlow基本概念

  • 使用graph(图)来表示计算任务
  • 在使用被称之为会话(session)的上下文(contenxt)中执行图
  • 使用tensor(张量)表示数据
  • 通过Variable变量维护状态和更新参数。变量包含张量(Tensor)存放于内存的缓存区。
  • 使用feed和fetch可以为任意的操作(arbitrary operation)赋值或者从其中获取数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
In [2]: import tensorflow as tf
In [3]: hello = tf.constant("Hello")
In [4]: s = tf.Session()
In [5]: s.run(hello)
Out[5]: b'Hello'
In [6]: b = tf.constant(10)
In [7]: a = tf.constant(20)
In [8]: s.run(a+b)
Out[8]: 30

Tensor

Variable创建变量

讲一个张量传入构造函数Variable()

1
2
3
weights = tf.Variable(tf.random_normal([784, 200], stddev=0.35),
name="weights")
biases = tf.Variable(tf.zeros([200]), name="biases")

常量

placeholder

类似于占位符号

1
2
3
4
5
6
7
8
9
10
import tensorflow as tf
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)
add = tf.add(a, b)
mul = tf.mul(a, b)
with tf.Session() as sess:
# Run every operation 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}))
# output:

Session

最小二乘法

损失函数

损失函数(loss function)是用来估量你模型的预测值$f(x)$与真实值$Y$的不一致程度,它是一个非负实值函数,通常使用$L(Y, f(x))$来表示,损失函数越小,模型的鲁棒性就越好。

最小二乘法的损失函数

$$
L(Y, f(x)) = \sum^n_{i=1}(Y-f(x))^2
$$

在实际的应用中,常常会使用均方差(MSE)作为衡量指标。
$$
MSE = \frac{1}{n}(\sum^n_{i=1}(Y-f(x))^2)
$$

线性拟合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import tensorflow as tf
import numpy
import matplotlib.pyplot as plt
rng = numpy.random
# 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.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")
# Construct a linear model 直线模型
activation = tf.add(tf.mul(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.initialize_all_variables()
# 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()
坚持技术分享,您的支持将鼓励我继续创作!