TensorFlow2.1入门笔记1

基础知识

张量(Tensor):多维数组(列表) 阶:张量的维数

0阶张量表示标量,例:a=1 2 3
1阶张量表示向量(一维数组),例:a=[1,2,3]
2阶张量表示矩阵(二维数组)可以有i行j列,每个元素可以用行号和列号共同索引到,例:a=[[1,2,3],[4,5,6],[7,8,9]]
判断张量是几阶的,看t=[[[[[…的括号有多少个
张量表示0阶到n阶的数组

TensorFlow的数据类型

tf.int,tf.float

tf.int32,tf.float32,tf.float64

tf.bool
tf.string

如何创建一个Tensor

直接创建

tf.constant(张量内容,dtype=数据类型(可选,本机默认是tf.int32))
例:

import tensorflow as tf

a = tf.constant([1, 5], dtype=tf.int64)
print("a:", a)
print("a.dtype:", a.dtype)
#运行结果
#a: tf.Tensor([1 5], shape=(2,), dtype=int64)
#a.dtype: <dtype: 'int64'>
#a.shape: (2,)

将numpy的数据类型转换为Tensor

tf.convert_to_tensor(数据名,dtype=数据类型(可选,本机默认是tf.int32))

import tensorflow as tf
import numpy as np

a = np.arange(0, 5)
b = tf.convert_to_tensor(a, dtype=tf.int64)
print("a:", a)
print("b:", b)
#运行结果:
# a: [0 1 2 3 4]
# # b: tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int64)

创建全为某个值的张量:

全为0:tf.zeros(维度)
全为1:tf.ones(维度)
维度:一维直接写个数,二维[行,列],多维[n,m,j,k…]
全为指定值的张量:tf.fill(维度,指定值)

import tensorflow as tf

a = tf.zeros([2, 3])
b = tf.ones(4)
c = tf.fill([2, 2], 9)
print("a:", a)
print("b:", b)
print("c:", c)
#运行结果
# a: tf.Tensor([[0. 0. 0.][0. 0. 0.]], shape=(2, 3), dtype=float32)
# b: tf.Tensor([1. 1. 1. 1.], shape=(4,), dtype=float32)
# c: tf.Tensor([[9 9][9 9]], shape=(2, 2), dtype=int32)

生成指定维度符合正态分布的张量

tf.random.normal(维度,mean=均值,stddev=标准差)(默认mean=0,stddev=1)
要想数据更加集中可以生成截断式正态分布的随机数:
tf.random.truncated_normal(维度,mean=均值,stddev=标准差)
可以让数据在(μ-2σ,μ+2σ)间

import tensorflow as tf

d = tf.random.normal([2, 2], mean=0.5, stddev=1)
print("d:", d)
e = tf.random.truncated_normal([2
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值