TensorFlow1.0 - C2 Guide - 4 Low

2019-08-12  本文已影响0人  左心Chris

1 Intro

组成 tf.Graph 和 tf.Session
简单的输入constant,placeholder,feeding,Datasets
layers和feature columns和初始化方法
loss和optimizer来训练

sess = tf.Session()
sess.run({'ab':(a, b), 'total':total})

tf.random_uniform每次同时产生的是一个数据

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
z = x + y
print(sess.run(z, feed_dict={x: 3, y: 4.5}))
print(sess.run(z, feed_dict={x: [1, 3], y: [2, 4]}))
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

完整代码

x = tf.constant([[1], [2], [3], [4]], dtype=tf.float32)
y_true = tf.constant([[0], [-1], [-2], [-3]], dtype=tf.float32)

linear_model = tf.layers.Dense(units=1)

y_pred = linear_model(x)
loss = tf.losses.mean_squared_error(labels=y_true, predictions=y_pred)

optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)
for i in range(100):
  _, loss_value = sess.run((train, loss))
  print(loss_value)

print(sess.run(y_pred))

2 Tensors

有两个属性data type和shape
有四种类型
rank和shape

rank_three_tensor = tf.ones([3, 4, 5])
matrix = tf.reshape(rank_three_tensor, [6, 10])  # Reshape existing content into
                                                 # a 6x10 matrix
matrixB = tf.reshape(matrix, [3, -1])  #  Reshape existing content into a 3x20
                                       # matrix. -1 tells reshape to calculate
                                       # the size of this dimension.
matrixAlt = tf.reshape(matrixB, [4, 3, -1])  # Reshape existing content into a
                                             #4x3x5 tensor

3 Variables

创建变量
collection和device placement
使用和初始化变量
共享变量

my_variable = tf.get_variable("my_variable", [1, 2, 3])

会有默认初始化方法,也可以设置初始化方法

session.run(tf.global_variables_initializer())
# Now all variables are initialized.
session.run(my_variable.initializer)
print(session.run(tf.report_uninitialized_variables()))

一个变量初始化依赖别的变量

v = tf.get_variable("v", shape=(), initializer=tf.zeros_initializer())
w = tf.get_variable("w", initializer=v.initialized_value() + 1)

4 Graphs and Sessions

5 Save and Restore

6 Control Flow

7 Ragged Tensors

上一篇下一篇

猜你喜欢

热点阅读