【Tensorflow基础(一)】

这篇博客介绍了Tensorflow的基础,包括数值类型、字符串类型和布尔类型。详细讲解了如何创建不同类型的张量,如标量、向量和矩阵,并讨论了数据精度、类型转换以及全0或全1张量的创建。此外,还提到了Tensorflow中待优化张量的概念。
摘要由CSDN通过智能技术生成
  • 5

  • 6

  • 7

1.数据类型


Tensorflow主要有3种数据类型:数值型,字符串型,布尔型

1.1 数值类型

标量(Scalar) 单个的实数,如 1.2, 3.4 等

向量(Vector) n 个实数的有序集合,通过中括号包裹,如[1.2],[1.2,3.4]等

矩阵(Matrix) n 行 m 列实数的有序集合,如[[1,2],[3,4]]

标量在 TensorFlow 是如何创建的

# python 语言方式创建标量 a = 1.2 # TF 方式创建标量 aa = tf.constant(1.2) type(a), type(aa), tf.is_tensor(aa)

  • 1

  • 2

  • 3

  • 4

  • 5

(float, tensorflow.python.framework.ops.EagerTensor, True)

  • 1

如果要使用 TensorFlow 提供的功能函数, 须通过 TensorFlow 规定的方式去创建张量,而不能使用 Python 语言的标准变量创建方式。

x = tf.constant([1,2.,3.3]) # 打印 TF 张量的相关信息 x

  • 1

  • 2

  • 3

<tf.Tensor: shape=(3,), dtype=float32, numpy=array([1. , 2. , 3.3], dtype=float32)>

  • 1

# 将 TF 张量的数据导出为 numpy 数组格式 x.numpy()

  • 1

  • 2

array([1. , 2. , 3.3], dtype=float32)

  • 1

与标量不同,向量的定义须通过 List 容器传给 tf.constant()函数。

创建一个元素的向量:

# 创建一个元素的向量 a = tf.constant([1.2]) a, a.shape

  • 1

  • 2

  • 3

(<tf.Tensor: id=2, shape=(1,), dtype=float32, numpy=array([1.2], dtype=float32)>, TensorShape([1]))

  • 1

  • 2

创建 3 个元素的向量:

# 创建 3 个元素的向量 a = tf.constant([1,2, 3.]) a, a.shape

  • 1

  • 2

  • 3

(<tf.Tensor: id=3, shape=(3,), dtype=float32, numpy=array([1., 2., 3.], dtype=float32)>, TensorShape([3]))

  • 1

  • 2

定义矩阵

# 创建 2 行 2 列的矩阵 a = tf.constant([[1,2],[3,4]]) a, a.shape

  • 1

  • 2

  • 3

(<tf.Tensor: id=4, shape=(2, 2), dtype=int32, numpy= array([[1, 2], [3, 4]])>, TensorShape([2, 2]))

  • 1

  • 2

  • 3

三维张量可以定义为:

# 创建 3 维张量 tf.constant([[[1,2],[3,4]],[[5,6],[7,8]]])

  • 1

  • 2

<tf.Tensor: id=5, shape=(2, 2, 2), dtype=int32, numpy= array([[[1, 2], [3, 4]],

[[5, 6],

[7, 8]]])>

  • 1

  • 2

  • 3

  • 4

  • 5

  • <
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值