TensorFlow2.0——张量

一、张量的介绍

张量(tensor)即多维数组。张量的阶数:表示张量的维度,如下图所示:

维数

阶数 名字 实例
0-D 0 标量scalar s=1
1-D 1 向量vector s=[1,2,3,4]
2-D 2 矩阵matrix  m=[[1,2],[3,4]]
n-D n 张量tensor t=[[[...]]]

 

 

二、张量的数据类型

类型名 tf.dtype 实例
 正型 int32  a = tf.constant(1)
浮点型  float32  a = tf.constant(1.0
double型  float64  a = tf.constant(1.0,dtype=tf.double)
bool型   bool  a = tf.constant([True,False])
字符型   string  a = tf.constant('hello,word!')

 

 

三、张量的创建与属性

1、张量的创建

代码示例:

import tensorflow as tf

# 创建张量,下面以创建2*2的矩阵为例
a=tf.constant([[1,2],[3,4]])    # 创建一个常量
b=tf.zeros(shape=[2,2])         # 创建全为0的张量
c=tf.ones(shape=[2,2])          # 创建全为0的张量
d=tf.fill(dims=[2,2],value=1)   # 创建一个填充值全为1的张量
# e=tf.random.normal(shape=[2,2],mean=0,stddev=1.0)   # 创建正态分布随机数的张量
# f=tf.random.truncated_normal(shape=[2,2],mean=0,stddev=1.0)   # 创建截断式正态分布随机数的张量

print('a:\n',a)
print('b:\n',b)
print('c:\n',c)
print('d:\n',d)

输出结果:

a张量为:
 tf.Tensor(
[[1 2]
 [3 4]], shape=(2, 2), dtype=int32)
b张量为:
 tf.Tensor(
[[0. 0.]
 [0. 0.]], shape=(2, 2), dtype=float32)
c张量为:
 tf.Tensor(
[[1. 1.]
 [1. 1.]], shape=(2, 2), dtype=float32)
d张量为:
 tf.Tensor(
[[1 1]
 [1 1]], shape=(2, 2), dtype=int32)

 

 2、张量的属性

属性 说明
tensor.name 张量名,是一个tensor的唯一标识,创建时如果没有指定name,那么系统将自动分配一个name。
tensor.shape 形状,描述张量维度信息。
tensor.dtype 数据类型。
posted @ 2020-11-17 12:16  我不是高斯分布  阅读(320)  评论(0编辑  收藏  举报