zoukankan      html  css  js  c++  java
  • 人工智能深度学习入门练习之(15)TensorFlow – 创建张量

    要创建张量,可以使用tf.constant()函数。

    tf.constant(value, dtype, name = "")

    参数说明

    • value: 定义张量的n维数组值,可选
    • dtype: 定义张量数据类型,例如:
      • tf.string: 字符串类型
      • tf.float32: 浮点类型
      • tf.int16: 整型
    • “name”: 张量的名字,可选,默认:“Const_1:0”

    示例

    创建0维张量,即标量,一个数值。

    import tensorflow as tf
    ## rank 0
    # Default name
    r1 = tf.constant(1, tf.int16) 
    print(r1)

    输出

    Tensor("Const:0", shape=(), dtype=int16)
    • "Const:0" – 张量名称
    • shape – 张量形状
    • dtype – 张量数据类型

    示例

    创建命名张量。

    import tensorflow as tf
    # Named my_scalar
    r2 = tf.constant(1, tf.int16, name = "my_scalar") 
    print(r2)

    输出

    Tensor("my_scalar:0", shape=(), dtype=int16)

    张量对象由一个惟一的标签(名称)、一个维度(形状)和一个数据类型(dtype)定义。

    可以指定数据类型来定义张量。

    示例

    指定数据类型来定义张量。

    import tensorflow as tf
    # Decimal
    r1_decimal = tf.constant(1.12345, tf.float32)
    print(r1_decimal)
    # String
    r1_string = tf.constant("Guru99", tf.string)
    print(r1_string)

    输出

    Tensor("Const_1:0", shape=(), dtype=float32)
    Tensor("Const_2:0", shape=(), dtype=string)

    示例

    创建1维张量,即向量/一维数组。

    import tensorflow as tf
    ## Rank 1
    r1_vector = tf.constant([1,3,5], tf.int16)
    print(r1_vector)
    r2_boolean = tf.constant([True, True, False], tf.bool)
    print(r2_boolean)   

    输出

    Tensor("Const_3:0", shape=(3,), dtype=int16)
    Tensor("Const_4:0", shape=(3,), dtype=bool)

    示例

    创建2维张量,即矩阵/2维数组。

    import tensorflow as tf
    ## Rank 2
    r2_matrix = tf.constant([ [1, 2],
                              [3, 4] ],tf.int16)
    print(r2_matrix)    

    输出

    Tensor("Const_5:0", shape=(2, 2), dtype=int16)  

    示例

    创建3维张量。

    import tensorflow as tf
    ## Rank 3
    r3_matrix = tf.constant([ [[1, 2],
                               [3, 4], 
                               [5, 6]] ], tf.int16)
    print(r3_matrix)    

    输出

    Tensor("Const_6:0", shape=(1, 3, 2), dtype=int16)
  • 相关阅读:
    网络性能测试工具iperf详细使用图文教程zz
    linux时间和定时器zz
    sleep
    linux调度器的配置参数zz
    zz升级Mininet自带的OpenvSwitch & 编译OpenvSwitch
    minnet sample
    电信新势力,TIP/CORD能颠覆电信设备商吗?
    【TS】534- TypeScript 可辨识联合
    【拓展】一张图看懂字节跳动8年创业史,太励志了吧
    【CSS】533- CSS 渲染原理以及优化策略
  • 原文地址:https://www.cnblogs.com/huanghanyu/p/13164000.html
Copyright © 2011-2022 走看看