Tensorflow框架-张量、计算图、会话

                                                     张量、计算图、会话

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

一、张量:

    1、张量(tensor):多维数组(列表)。阶:张量的维数。

维数名字例子
0-D0标量 scalars = 123
1-D1向量 vectorv = [1, 2, 3]
2-D2矩阵 matrixm = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n-Dn张量 tensort = [[1, 2, 3], [4, 5, 6], [7, 8, 9]...]        [[[[....(n个)

        张量可以表示0阶到n阶数组(列表)

    2、vim编辑器设置:

        vim ~/.vimrc  写入:

        set ts=4    # 使Tab等效于四个空格

        set nu       # 使vim显示行号

    3、数据类型:

        (1) 有符号整型:

数据类型描述
tf.int88位有符号整型
tf.int1616位有符号整型
tf.int3232位有符号整型
tf.int6464位有符号整型
tf.qint8量化的8位有符号整型
tf.qint16量化的16位有符号整型
tf.qint32量化的32位有符号整型

        (2) 无符号整型:

数据类型描述
tf.uint88位无符号整型
tf.uint1616位无符号整型
tf.uint3232位无符号整型
tf.uint6464位无符号整型
tf.quint8量化的8位无符号整型
tf.quint16量化的16位无符号整型
tf.quint32量化的32位无符号整型

        (3) 浮点型:

数据类型描述
tf.float1616位半精度浮点数
tf.float3232位单精度浮点数
tf.float6464位双精度浮点数
tf.bfloat1616位截断浮点数

        (4) 字符串型: 

        (5) 布尔型:    

        (6) 复数型:         

        (7) 句柄:     

        (8) 任意类型的值:          

    4、张量计算:                

import tensorflow as tf

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

result = a + b
print(result)

# 1.0运行结果:
Tensor("add:0", shape=(2,), dtype=float32)
# 2.0运行结果:
tf.Tensor([4. 6.], shape=(2,), dtype=float32)

    对应数学计算:

        \begin{Bmatrix} 1.0&2.0 \end{Bmatrix} + \begin{Bmatrix} 3.0&4.0 \end{Bmatrix} = \begin{Bmatrix} 1.0+3.0&2.0+4.0 \end{Bmatrix} = \begin{Bmatrix} 4.0&6.0 \end{Bmatrix}

二、计算图:

    1、计算图(Graph):搭建神经网络的计算过程,只搭建,不运算。

    

        y = XW=x1*w1 + x2*w2

    2、实例:       

import tensorflow as tf

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

y = tf.matmul(x, w)
print(y)

# 1.0运行结果:
Tensor("MatMul:0", shape=(1, 1), dtype=float32)
# 2.0运行结果:
tf.Tensor([[11.]], shape=(1, 1), dtype=float32)
# 注释:
tf.matmul:矩阵相乘

        对应数学公式:

            \begin{Bmatrix} 3.0 & 4.0 \end{Bmatrix} * \begin{Bmatrix} 1.0\\ 2.0 \end{Bmatrix} =\begin{Bmatrix} 3.0*1.0+4.0*2.0 \end{Bmatrix}=\begin{Bmatrix} 11.0 \end{Bmatrix}

三、会话:

    1、会话(Session):执行计算图中的节点运算。2.0版本取消了会话 

        语法:

            with tf.Session() as sess:

                print(sess.run(y))

    2、示例:

import tensorflow as tf

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

y = tf.matmul(x, w)
print(y)

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

# 运行结果:
Tensor("MatMul:0", shape=(1, 1), dtype=float32)
[[11.]]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值