Tensorflow 安装

Tensorflow 安装

1
2
3
4
5
6
7
8
9
10
yum install -y python-pip

mkdir /root/.pip
cat > /root/.pip/pip.conf <<EOF
[global]
index-url = http://10.1.14.235/python-pypi/simple
trusted-host = 10.1.14.235
EOF

pip install tesorflow

TensorBoard

1
2
3
4
5
6
7
8
import tensorflow as tf
a = tf.constant(2)
b = tf.constant(3)
x = tf.add(a, b)
with tf.Session() as sess:
writer = tf.summary.FileWriter('./graphs', sess.graph)
print(sess.run(x))
writer.close() # close the writer when you’re done using it

tensorflow中一般有两步,第一步是定义图,第二步是在session中进行图中的计算。

常数

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
# 常量
tf.constant(value, dtype=None, shape=None, name='Const', verify_shape=False)

# 全零矩阵常量
tf.zeros(shape, dtype=tf.float32, name=None)
# 同纬全零矩阵常量
tf.zeros_like(input_tensor, dtype=None, name=None, optimize=True)
# 全1矩阵常量
tf.ones(shape, dtype=tf.float32, name=None)
# 同纬全1矩阵常量
tf.ones_like(input_tensor, dtype=None, name=None, optimize=True)
#
tf.fill(dims, value, name=None)

tf.linspace(start, stop, num, name=None)
tf.range(start, limit=None, delta=1, dtype=None, name='range')

# 随机数
tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)
# 截断正态分布
tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None,
name=None)
tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None,
name=None)
tf.random_shuffle(value, seed=None, name=None)
tf.random_crop(value, size, seed=None, name=None)
tf.multinomial(logits, num_samples, seed=None, name=None)
tf.random_gamma(shape, alpha, beta=None, dtype=tf.float32, seed=None, name=None)

变量

1
2
3
4
x = tf.Variable()
x.initializer # 初始化
x.eval() # 读取里面的值
x.assign() # 分配值给这个变量

在使用变量之前必须对其进行初始化,初始化可以看作是一种变量的分配值操作。

1
2
3
4
# 一次性初始化所有的变量
sess.run(tf.global_variables_initializer())
# 初始化部分变量
sess.run(w.initializer) # w是定义好的变量

取出变量

1
w.eval(session=sess)

占位符

tensorflow中一般有两步,第一步是定义图,第二步是在session中进行图中的计算。对于图中我们暂时不知道值的量,我们可以定义为占位符,之后再用feed_dict去赋值。

1
tf.placeholder(dtype, shape=None, name=None)

例子:

1
2
3
4
5
a = tf.placeholder(tf.float32, shape=[3])
b = tf.constant([5, 5, 5], tf.float32)
c = a + b
with tf.Session() as sess:
print(sess.run(c, feed_dict={a: [1, 2, 3]}))

选择逻辑

1
2
3
4
res = tf.where(
tf.less(residual, delta), # 条件
0.5 * residual**2, # 条件满足时
delta * residual - 0.5 * delta**2) # 条件不满足时

线性回归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 输入输出占位符
X = tf.placeholder(tf.float32, shape=[], name='input') # shape=[]表示标量(scalar)
Y = tf.placeholder(tf.float32, shape=[], name='label')
# 参数
w = tf.get_variable('weight', shape=[], initializer=tf.truncated_normal_initializer())
b = tf.get_variable('bias', shape=[], initializer=tf.zeros_initializer())

Y_predicted = w * X + b
loss = tf.square(Y - Y_predicted, name='loss') # 均方误差

# 会自动求导,然后更新参数
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-3).minimize(loss)

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(100):
total_loss = 0
for x, y in data: # 样本数据放在data
_, l = sess.run([optimizer, loss], feed_dict={X: x, Y: y})
total_loss += l
print("Epoch {0}: {1}".format(i, total_loss / n_samples))

完整源码见这里

模型构建步骤

构建计算图

  1. 定义输入和输出的占位符(placeholder)
  2. 定义模型中需要用到的权重
  3. 定义推断模型,构建网络
  4. 定义损失函数作为优化对象
  5. 定义优化器进行优化

执行构件图

  1. 第一次进行运算的时候,初始化模型的所有参数
  2. 传入训练数据,可以打乱顺序
  3. 网络前向传播,计算出当前参数下的网络输出
  4. 根据网络输出和目标计算出loss
  5. 通过loss方向传播更新网络中的参数

结构化

1
2
3
4
with tf.name_scope(name_of_taht_scope):
# declare op_1
# declare op_2
# ...
显示 Gitment 评论