一.Tensorflow2之张量

一.什么是张量

Tensorflow中的Tensor就是张量,是多维数组,多维列表,用阶表示张量的维数。

0阶张量:叫标量,表示的是一个单独的数,如s=1 2 3
1阶张量:叫向量,表示的是一个数组,如v=[1, 2, 3]
2阶张量:叫矩阵,表示的是一个二维数组,它可以有i行j列个元素,每 ·	个元素用它的行号和列号共同索引到,如m= [[1, 2, 3], [4, 5, 6], [7, 8, 9]],矩阵m中,元素2的索引就是矩阵m的第0行第1列
维数名字例子
0-D0标量 scalars=1 2 3
1-D1向量 vectorv=[1, 2, 3]
2-D2矩阵 matrixm= [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n-Dn张量 tensort= [[[[…]]]]

张量可以表示0阶到n阶的数组

二.数据类型

Tensorflow的数据类型有32位整型、32位浮点、64位浮点、布尔型、字符串型等等
1.tf.int, tf.float…
tf.int32, tf.float32, tf.float64
2.tf.bool
tf.constant([True, False])
3.tf.string
tf.constant(“Hello, world!”)

三.如何创建一个Tensor

创建一个张量

tf.constant(张量内容, dtype=数据类型(可选))

import tensorflow as tf
a=tf.constant([1,5], dtype=tf.int64)
print(a)
print(a.dtype)
print(a.shape)
b=tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=tf.int64)
print(b)
print(b.dtype)
print(b.shape)

结果如下:
tf.Tensor([1 5], shape=(2,), dtype=int64)
<dtype: 'int64'>
(2,)
tf.Tensor(
[[1 2 3]
 [4 5 6]
 [7 8 9]], shape=(3, 3), dtype=int64)
<dtype: 'int64'>
(3, 3)

shape:
(2,)说明是一维,张量里有2个元素
(3, 3)说明是二维,3行3列

numpy的数据类型转为Tensor

很多时候数据是由numpy格式给出的,可进行如下转换
tf.convert_to_tensor(数据名, dtype=数据类型(可选))

import tensorflow as tf
import numpy as np
a = np.arange(0, 5)
b = tf.convert_to_tensor(a, dtype=tf.int64)
print(a)
print(b)

结果如下:
[0 1 2 3 4]
tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int64)

创建全为0的张量

tf.zeros(维度)

创建全为1的张量

tf.ones(维度)

创建全为指定值的张量

tf.fill(维度, 指定值)

import tensorflow as tf
a = tf.zeros([2, 3])
b = tf.ones(4)
c = tf.fill([2, 2], 9)
print(a)
print(b)
print(c)

结果如下:
tf.Tensor(
[[0. 0. 0.]
 [0. 0. 0.]], shape=(2, 3), dtype=float32)
 
tf.Tensor([1. 1. 1. 1.], shape=(4,), dtype=float32)

tf.Tensor(
[[9 9]
 [9 9]], shape=(2, 2), dtype=int32)

维度:
一维 直接写个数
二维 用[行, 列]
多维 用[n, m, j, k…],方括号里写每个维度的元素个数

生成正态分布的随机数,默认均值为0,标准差为1

tf.random.normal(维度, mean=均值, stddev=标准差)

生成截断式正态分布的随机数

tf.random.truncated_normal(维度, mean=均值, stddev=标准差)
如果随机生成的数据的取值在(μ-2σ, μ+2σ)之外则重新生成,保证了生成值在均值附近
μ:均值。 σ:标准差

import tensorflow as tf
# 生成2行2列的张量,里面的元素符合以0.5为均值、1为标准差的分布
d = tf.random.normal([2, 2], mean=0.5, stddev=1)
print(d)
e = tf.random.truncated_normal([2, 2], mean=0.5, stddev=1)
print(e)

结果如下:
tf.Tensor(
[[ 0.5845902  -0.24298191]
 [ 0.33859766 -0.06390637]], shape=(2, 2), dtype=float32)
tf.Tensor(
[[-0.0460096   0.24721915]
 [ 1.0170765  -1.1602036 ]], shape=(2, 2), dtype=float32)

生成均匀分布随机数

tf.random.uniform(维度, minval=最小值, maxval=最大值)
最小最大前闭后开[minval, maxval)

import tensorflow as tf
f = tf.random.uniform([2, 2], minval=0, maxval=1)
print(f)

结果如下:

tf.Tensor(
[[0.18191743 0.49436307]
 [0.65454197 0.27141154]], shape=(2, 2), dtype=float32)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值