TF笔记 - tensor, graph, session

2018-05-25  本文已影响31人  闫_锋

基于TF的NN,用张量表示数据,用计算图搭建神经网络,用会话执行计算图,优化线上的权重(参数), 得到模型。

张量: 多维数组(列表)
阶: 张量的维度

0 阶张量称作标量,表示一个单独的数;
举例 S=123

1 阶张量称作向量,表示一个一维数组;
举例 V=[1,2,3]

2 阶张量称作矩阵,表示一个二维数组,它可以有 i 行 j 列个元素,每个元素可以用行号和列号共同索引到;举例 m=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

判断张量是几阶的,就通过张量右边的方括号数,0 个是 0 阶,n 个是 n 阶,张量可以表示 0 阶到 n 阶数组(列表);举例 t=[ [ [… ] ] ]为 3 阶。

import tensorflow as tf

a = tf.constant([1.0, 2.0])
b = tf.constant([3.0, 4.0])

result = a + b
print(result)
#Tensor(“add:0”, shape=(2, ), dtype=float32)
#意思为result是一个名称为add:0的张量,
#shape=(2,)表示一维数组长度为2,
#dtype=float32表示数据类型为浮点型。

with tf.Session() as sess:
  print(sess.run(result))

计算图: 搭建神经网络的计算过程,只搭建不运算。

import tensorflow as tf

x = tf.constant([[1.0, 2.0]])
w = tf.constant([[3.0], [4.0]])

print(x.shape)
#(1, 2)
print(w.shape)
#(2, 1)

y = tf.matmul(x, w)
print(y)
#Tensor(“add:0”, shape=(2, ), dtype=float32)
#意思为result是一个名称为add:0的张量,
#shape=(2,)表示一维数组长度为2,
#dtype=float32表示数据类型为浮点型。

#会话: 执行计算图中的节点运算.
with tf.Session() as sess:
  print(sess.run(y))

#>>> y.shape
#TensorShape([Dimension(1), Dimension(1)])
#>>> print(y.shape)
#(1, 1)

降低TF警告等级

export TF_CPP_MIN_LOG_LEVEL=2
上一篇 下一篇

猜你喜欢

热点阅读