美文网首页
Tensorflow基本概念

Tensorflow基本概念

作者: YANWeichuan | 来源:发表于2018-08-03 15:52 被阅读0次

TensorFlow Core


TensorFlow Core 程序看作由两个互相独立的部分组成:

  • 构建计算图 (tf.Graph)
  • 运行计算图(tf.Session)

计算图是静态的,只有通过Session运行,进行动态运算才能得到结果

计算图

  • 操作(简称“op”):图的节点,操作描述了消耗和生成张量的计算
  • 张量:图的边,它们代表将流经图的值。大多数 TensorFlow 函数会返回 tf.Tensors

会话 (Session)

定义好图后,session运行才能得到结果

a = tf.constant(3.0, dtype=tf.float32)
b = tf.constant(4.0) # also tf.float32 implicitly
total = a + b
sess = tf.Session()
print(sess.run(total))

输出结果

7.0

数据


  • 供给placehold
  • 数据集
  • 特征列

供给placehold

图可以参数化以便接受外部输入,也称为占位符。占位符表示承诺在稍后提供值,它就像函数参数。
示例代码

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]}))

上述操作的结果是输出以下内容:

7.5
[ 3.  7.]

数据集

数据集是将数据流式传输到模型的首选方法。要从数据集中获取可运行的 tf.Tensor,您必须先将其转换成 tf.data.Iterator,然后调用迭代器的 get_next 方法。
示例代码

my_data = [
    [0, 1,],
    [2, 3,],
    [4, 5,],
    [6, 7,],
]
slices = tf.data.Dataset.from_tensor_slices(my_data)
next_item = slices.make_one_shot_iterator().get_next()

while True:
  try:
    print(sess.run(next_item))
  except tf.errors.OutOfRangeError:
    break

输出
[0 1]
[2 3]
[4 5]
[6 7]

特征列

见前文 >>>

层layer


  • 创建层
  • 初始化
  • 执行

示例代码

#创建
x = tf.placeholder(tf.float32, shape=[None, 3])
linear_model = tf.layers.Dense(units=1)
y = linear_model(x)

#初始化
init = tf.global_variables_initializer()
sess.run(init)

#执行
print(sess.run(y, {x: [[1, 2, 3],[4, 5, 6]]}))

#输出结果
[[-3.41378999]
 [-9.14999008]]

训练


  • 定义数据
  • 定义模型
  • 损失和优化器
  • 训练

示例代码

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))

最后预测的结果y_pred和实际值y_true的比较

 print(sess.run(y_pred))

[[-0.6822085]  #y_true = 0
 [-1.3305767]  #y_true = -1
 [-1.9789449] #y_true = -2
 [-2.627313 ]] #y_true = -3

几个概念

  • batchsize:批大小,也就是在一次模型迭代/训练过程中所使用的样本数目
  • iteration:1个iteration等于使用batchsize个样本训练一次;
  • epoch:1个epoch等于使用训练集中的全部样本训练一次;也就是训练整个数据集的重复数。

举个例子,训练集有1000个样本,batchsize=10,那么:训练完整个样本集需要:100次iteration,1次epoch

调试工具TensorBoard


首先将计算图保存为 TensorBoard 摘要文件,具体操作如下所示:

a = tf.constant(3.0, dtype=tf.float32)
b = tf.constant(4.0) # also tf.float32 implicitly
total = a + b
writer = tf.summary.FileWriter('.')
writer.add_graph(tf.get_default_graph())

这将在当前目录中生成一个 event 文件,其名称格式如下:

events.out.tfevents.{timestamp}.{hostname}

现在,在新的终端中使用以下 shell 命令启动 TensorBoard:

tensorboard --logdir .

生成结果在命令行中有网址,拷贝到浏览器打开如下:

相关文章

网友评论

      本文标题:Tensorflow基本概念

      本文链接:https://www.haomeiwen.com/subject/hdayvftx.html