一小时学会TensorFlow2之基本操作1实例代码

目录
  • 概述
  • 创建数据
    • 创建常量
    • 创建数据序列
    • 创建图变量
    • tf.zeros
    • tf.ones
    • tf.zeros_like
    • tf.ones_like
    • tf.fill
    • tf.gather
  • tf.random
    • 正态分布
    • 均匀分布
    • 打乱顺序
  • 获取数据信息
    • 获取数据维度
    • 数据是否为张量
  • 数据转换
    • 转换成张量
    • 转换数据类型
    • 转换成 numpy

概述

TensorFlow2 的基本操作和 Numpy 的操作很像. 今天带大家来看一看 TensorFlow 的基本数据操作.

创建数据

详细讲解一下 TensorFlow 创建数据的集中方法.

创建常量

tf.constant() 格式为:

tf.constant(value,dtype,shape,name)

参数:

  • value: 常量值
  • dtype: 数据类型
  • shape: 表示生成常量数的维度
  • name: 数据名称

例子:

# 创建常量1
c1 = tf.constant(1)
print(c1)

# 创建常量, 类型为bool
c2 = tf.constant([True, False])
print(c2)

# 创建常量1, 类型为float32, 大小为3*3
c3 = tf.constant(0.1, shape=[2, 2])
print(c3)

# 创建常量, 类型为string字符串
c4 = tf.constant("Hello World!")
print(c4)

输出结果:

tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor([ True False], shape=(2,), dtype=bool)
tf.Tensor(
[[0.1 0.1]
[0.1 0.1]], shape=(2, 2), dtype=float32)
tf.Tensor(b'Hello World!', shape=(), dtype=string)

创建数据序列

格式:

range(start, limit, delta=1, dtype=None, name='range')

参数:

  • start: 开始位置
  • limit: 序列的上限
  • delta: 相当于 Numpy 的 step, 步长
  • detype: 数据类型
  • name: 数据名称, 默认为 “range”

例子:

# 创建数字序列
r1 = tf.range(4)
print(r1)

输出结果:

tf.Tensor([0 1 2 3], shape=(4,), dtype=int32)

创建图变量

格式:

tf.Variable.init(initial_value, trainable=True, collections=None, validate_shape=True, name=None)

参数:

参数名称 参数类型 参数含义
initial_value 所有可以转换为 Tensor 的类型 变量的初始值
trainable bool 如果为 True, 会把它加入到 GraphKeys.TRAINABLE_VARIABLES, 才能对它使用 Optimizer
collections list 指定该图变量的类型, 默认为 [GraphKeys.GLOBAL_VARIABLES]
validate_shape bool 如果为 False, 则不进行类型和维度检查
name string 数据名称

例子:

# 创建图变量
v1 = tf.Variable(tf.range(6))
print(v1)
print(isinstance(v1, tf.Tensor))  # False
print(isinstance(v1, tf.Variable))  # True
print(tf.is_tensor(v1))  # True

输出结果:

False
True
True

tf.zeros

tf.zeros 可以帮助我们创建一个所有参数为 0 的 tensor 对象. 类似于 np.zeros.

格式:

tf.zeros(shape, dtype=tf.dtypes.float32, name=None)

参数:

  • shape: 数组的形状
  • dype: 数据类型, 默认为float32
  • name: 数据名称

例子:

# 创建参数为0的tensor
z1 = tf.zeros([1])
print(z1)

z2 = tf.zeros([3, 3])
print(z2)

输出结果:

tf.Tensor([0.], shape=(1,), dtype=float32)
tf.Tensor(
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]], shape=(3, 3), dtype=float32)

tf.ones

tf.ones 用法和 tf.zeros 一样, 可以帮助我们创建一个所有参数为 1 的 tensor 对象.

tf.ones(shape, dtype=tf.dtypes.float32, name=None)

参数:

  • shape: 数组的形状
  • dype: 数据类型, 默认为 float32
  • name: 数据名称

例子:

# 创建参数为1的tensor
o1 = tf.ones([1])
print(o1)

o2 = tf.ones([3, 3])
print(o2)

输出结果:

tf.Tensor([1.], shape=(1,), dtype=float32)
tf.Tensor(
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]], shape=(3, 3), dtype=float32)

tf.zeros_like

tf.zeros_like 可以帮我们创建一个与给定 tensor 类型大小一致的 tensor. 类似 np.zeros_like.

格式:

tf.zeros_like(tensor, dype=None, name=None)

参数:

  • tensor: 传入的 tensor
  • dype: 数据类型, 默认为 float32
  • name: 数据名称

例子:

# tf.zeros_like
t1 = tf.range(6)
z1 = tf.zeros_like(t1)
print(z1)

输出结果:

tf.Tensor([0 0 0 0 0 0], shape=(6,), dtype=int32)

tf.ones_like

格式:

tf.ones_like(tensor, dype=None, name=None)

参数:

  • tensor: 传入的 tensor
  • dype: 数据类型, 默认为 float32
  • name: 数据名称

例子:

# tf.ones_like
t1 = tf.range(6)
o1 = tf.ones_like(t1)
print(o1)

输出结果:

tf.Tensor([1 1 1 1 1 1], shape=(6,), dtype=int32)

tf.fill

tf.fill 可以帮助我们创建一个指定形状和内容的 tensor.

格式:

tf.fill(shape, value, name=None)

参数:

  • shape: 数组的形状
  • value: 填充的值
  • name: 数据名称

例子:

# tf.fill
f1 = tf.fill([2, 2], 0)
print(f1)

f2 = tf.fill([3, 3], 6)
print(f2)

输出结果:

[[0 0]
[0 0]], shape=(2, 2), dtype=int32)
tf.Tensor(
[[6 6 6]
[6 6 6]
[6 6 6]], shape=(3, 3), dtype=int32)

tf.gather

tf.gather: 根据索引从参数轴收集切片.

格式:

tf.gather(
    params, indices, validate_indices=None, axis=None, batch_dims=0, name=None
)

参数:

  • params: 传入的张量
  • indices: A Tensor. types 必须是: int32, int64. 里面的每一个元素大小必须在 [0, params.shape[axis]) 范围内
  • axis: 维度, 默认为 0

例子:

input =[ [[[1, 1, 1], [2, 2, 2]],
         [[3, 3, 3], [4, 4, 4]],
         [[5, 5, 5], [6, 6, 6]]],

         [[[7, 7, 7], [8, 8, 8]],
         [[9, 9, 9], [10, 10, 10]],
         [[11, 11, 11], [12, 12, 12]]],

        [[[13, 13, 13], [14, 14, 14]],
         [[15, 15, 15], [16, 16, 16]],
         [[17, 17, 17], [18, 18, 18]]]
         ]
output=tf.gather(input, [0,2],axis=0)

输出结果:

tf.Tensor(
[[[[ 1 1 1]
[ 2 2 2]]

[[ 3 3 3]
[ 4 4 4]]

[[ 5 5 5]
[ 6 6 6]]]

[[[13 13 13]
[14 14 14]]

[[15 15 15]
[16 16 16]]

[[17 17 17]
[18 18 18]]]], shape=(2, 3, 2, 3), dtype=int32)

tf.random

正态分布

tf.random.normal 可以帮我们创建随机数服从正态分布.

格式:

tf.random.normal(
    shape, mean=0.0, stddev=1.0, dtype=tf.dtypes.float32, seed=None, name=None
)

参数:

  • shape: 张量的形状
  • mean: 正态分布的均值, 默认为 0.0
  • stddev: 正态分布的标准差, 默认为 1.0
  • dtype: 数据类型, 默认为 float32
  • seed: 随机数种子
  • name: 数据名称

例子:

# tf.normal
n1 = tf.random.normal([2, 2], mean = 1, stddev=1, seed=0)
print(n1)

输出结果:

tf.Tensor(
[[0.60084236 3.1044393 ]
[1.1710722 1.5465181 ]], shape=(2, 2), dtype=float32)

均匀分布

tf.random.uniform 可以帮我们创建随机数服从均匀分布.
格式:

tf.random.uniform(
    shape, minval=0, maxval=None, dtype=tf.dtypes.float32, seed=None, name=None
)

参数:

  • shape: 张量的形状
  • minval: 均匀分布的最小值, 默认为 0
  • maxvak: 均匀分布的最大值
  • dtype: 数据类型, 默认为 float32
  • seed: 随机数种子
  • name: 数据名称

例子:

# tf.uniform
u1 = tf.random.uniform([2, 2], minval=0, maxval=1)
print(u1)

输出结果:

tf.Tensor(
[[0.7382153 0.6622821 ]
[0.22840345 0.09706533]], shape=(2, 2), dtype=float32)

打乱顺序

tf.random.shuffle 可以帮助我们打乱张量的顺序.

格式:

tf.random.shuffle(
    value, seed=None, name=None
)

参数:

  • value: 要被打乱的张量
  • seed: 随机数种子
  • name: 数据名称

例子:

# tf.shuffle
s1 = tf.random.shuffle(tf.range(10))
print(s1)

输出结果:

tf.Tensor([1 7 3 9 2 6 8 5 4 0], shape=(10,), dtype=int32)

获取数据信息

获取数据维度

tf.rank 的用法和 np.ndim 基本一样.

格式:

rank(input, name=None)  # 类似np.ndim

参数:

  • input: 传入的张量
  • name: 数据名称

例子:

# 获取张量维度
t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
print(tf.rank(t))

输出结果:

tf.Tensor(3, shape=(), dtype=int32)

数据是否为张量

格式:

tf.is_tensor(input)

参数:

  • input: 传入的张量

例子:

# 判断是否为张量
a = tf.constant([1, 2, 3])
b = tf.constant([True, False, False])
c = tf.constant("Hello World")
d = np.arange(6)

print(a)
print(tf.is_tensor(a))

print(b)
print(tf.is_tensor(b))

print(c)
print(tf.is_tensor(c))

print(d)
print(tf.is_tensor(d))

输出结果:

tf.Tensor([1 2 3], shape=(3,), dtype=int32)
True
tf.Tensor([ True False False], shape=(3,), dtype=bool)
True
tf.Tensor(b'Hello World', shape=(), dtype=string)
True
[0 1 2 3 4 5]
False

数据转换

转换成张量

格式:

tf.convert_to_tensor(value, dtype=None, dtype_hint=None, name=None)

参数:

  • value: 需要转换的值
  • dtype: 数据类型
  • dtype_hint: 当 dtype 为 None 时的备选方案
  • name: 数据名称

例子:

# 转换成张量
array = np.arange(6)
print(array.dtype)

array_tf = tf.convert_to_tensor(array)
print(array_tf)

输出结果:

int32
tf.Tensor([0 1 2 3 4 5], shape=(6,), dtype=int32)

转换数据类型

格式:

cast(x, dtype, name=None)

参数:

  • x: 输入的值
  • dtype: 数据类型
  • name: 数据名称

例子:

# 装换数据类型
array_tf = tf.constant(np.arange(6))
print(array_tf)

array_tf = tf.cast(array_tf, dtype=tf.float32)
print(array_tf)

tf_bool = tf.cast(tf.constant([False, True]), dtype=tf.int32)
print(tf_bool)

输出结果:

tf.Tensor([0 1 2 3 4 5], shape=(6,), dtype=int32)
tf.Tensor([0. 1. 2. 3. 4. 5.], shape=(6,), dtype=float32)
tf.Tensor([0 1], shape=(2,), dtype=int32)

转换成 numpy

例子:

# tensor转换成numpy
array_tf = tf.ones([2,2])
array_np = array_tf.numpy()
print(array_np)

输出结果:

[[1. 1.]
[1. 1.]]

到此这篇关于一小时学会TensorFlow2之基本操作1的文章就介绍到这了,更多相关TensorFlow2基本操作内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 详解TensorFlow2实现线性回归

    目录 概述 MSE 线性回归 公式 梯度下降 线性回归实现 计算 MSE 梯度下降 迭代训练 主函数 完整代码 概述 线性回归 (Linear Regression) 是利用回归分析来确定两种或两种以上变量间相互依赖的定量关系. 对线性回归还不是很了解的同学可以看一下这篇文章: python深度总结线性回归 MSE 均方误差 (Mean Square Error): 是用来描述连续误差的一种方法. 公式: y_predict: 我们预测的值y_real: 真实值 线性回归 公式 w: weigh

  • 一小时学会TensorFlow2之基本操作2实例代码

    目录 索引操作 简单索引 Numpy 式索引 使用 : 进行索引 tf.gather tf.gather_nd tf.boolean_mask 切片操作 简单切片 step 切片 维度变换 tf.reshape tf.transpose tf.expand_dims tf.squeeze Boardcasting tf.boardcast_to tf.tile 数学运算 加减乘除 log & exp pow & sqrt 矩阵相乘 @ 索引操作 简单索引 索引 (index) 可以帮助我们

  • tensorflow2.0实现复杂神经网络(多输入多输出nn,Resnet)

    常见的'融合'操作 复杂神经网络模型的实现离不开"融合"操作.常见融合操作如下: (1)求和,求差 # 求和 layers.Add(inputs) # 求差 layers.Subtract(inputs) inputs: 一个输入张量的列表(列表大小至少为 2),列表的shape必须一样才能进行求和(求差)操作. 例子: input1 = keras.layers.Input(shape=(16,)) x1 = keras.layers.Dense(8, activation='rel

  • 详解TensorFlow2实现前向传播

    目录 概述 会用到的函数 张量最小值 张量最大值 数据集分批 迭代 截断正态分布 relu 激活函数 one_hot assign_sub 准备工作 train 函数 run 函数 完整代码 概述 前向传播 (Forward propagation) 是将上一层输出作为下一层的输入, 并计算下一层的输出, 一直到运算到输出层为止. 会用到的函数 张量最小值 ```reduce_min``函数可以帮助我们计算一个张量各个维度上元素的最小值. 格式: tf.math.reduce_min( inpu

  • tensorflow2 自定义损失函数使用的隐藏坑

    Keras的核心原则是逐步揭示复杂性,可以在保持相应的高级便利性的同时,对操作细节进行更多控制.当我们要自定义fit中的训练算法时,可以重写模型中的train_step方法,然后调用fit来训练模型. 这里以tensorflow2官网中的例子来说明: import numpy as np import tensorflow as tf from tensorflow import keras x = np.random.random((1000, 32)) y = np.random.rando

  • tensorflow2.0教程之Keras快速入门

    Keras 是一个用于构建和训练深度学习模型的高阶 API.它可用于快速设计原型.高级研究和生产. keras的3个优点: 方便用户使用.模块化和可组合.易于扩展 1.导入tf.keras tensorflow2推荐使用keras构建网络,常见的神经网络都包含在keras.layer中(最新的tf.keras的版本可能和keras不同) import tensorflow as tf from tensorflow.keras import layers print(tf.__version__

  • 一小时学会TensorFlow2之基本操作1实例代码

    目录 概述 创建数据 创建常量 创建数据序列 创建图变量 tf.zeros tf.ones tf.zeros_like tf.ones_like tf.fill tf.gather tf.random 正态分布 均匀分布 打乱顺序 获取数据信息 获取数据维度 数据是否为张量 数据转换 转换成张量 转换数据类型 转换成 numpy 概述 TensorFlow2 的基本操作和 Numpy 的操作很像. 今天带大家来看一看 TensorFlow 的基本数据操作. 创建数据 详细讲解一下 TensorF

  • 一小时学会TensorFlow2之Fashion Mnist

    目录 描述 Tensorboard 创建 summary 存入数据 metrics metrics.Mean() metrics.Accuracy() 变量更新 &重置 案例 pre_process 函数 get_data 函数 train 函数 test 函数 main 函数 完整代码 可视化 描述 Fashion Mnist 是一个类似于 Mnist 的图像数据集. 涵盖 10 种类别的 7 万 (6 万训练集 + 1 万测试集) 个不同商品的图片. Tensorboard Tensorbo

  • 一小时学会TensorFlow2之全连接层

    目录 概述 keras.layers.Dense keras.Squential 概述 全链接层 (Fully Connected Layer) 会把一个特质空间线性变换到另一个特质空间, 在整个网络中起到分类器的作用. keras.layers.Dense keras.layers.Dense可以帮助我们实现全连接. 格式: tf.keras.layers.Dense( units, activation=None, use_bias=True, kernel_initializer='glo

  • 一小时学会TensorFlow2之大幅提高模型准确率

    目录 过拟合 Regulation 公式 例子 动量 公式 例子 学习率递减 过程 例子 Early Stopping Dropout 过拟合 当训练集的的准确率很高, 但是测试集的准确率很差的时候就, 我们就遇到了过拟合 (Overfitting) 的问题. 如图: 过拟合产生的一大原因是因为模型过于复杂. 下面我们将通过讲述 5 种不同的方法来解决过拟合的问题, 从而提高模型准确度. Regulation Regulation 可以帮助我们通过约束要优化的参数来防止过拟合. 公式 未加入 r

  • 一小时学会TensorFlow2之自定义层

    目录 概述 Sequential Model & Layer 案例 数据集介绍 完整代码 概述 通过自定义网络, 我们可以自己创建网络并和现有的网络串联起来, 从而实现各种各样的网络结构. Sequential Sequential 是 Keras 的一个网络容器. 可以帮助我们将多层网络封装在一起. 通过 Sequential 我们可以把现有的层已经我们自己的层实现结合, 一次前向传播就可以实现数据从第一层到最后一层的计算. 格式: tf.keras.Sequential( layers=No

  • Python入门教程 超详细1小时学会Python

    为什么使用Python    假设我们有这么一项任务:简单测试局域网中的电脑是否连通.这些电脑的ip范围从192.168.0.101到192.168.0.200. 思路:用shell编程.(Linux通常是bash而Windows是批处理脚本).例如,在Windows上用ping ip 的命令依次测试各个机器并得到控制台输出.由于ping通的时候控制台文本通常是"Reply from ... " 而不通的时候文本是"time out ... " ,所以,在结果中进行

  • Java执行hadoop的基本操作实例代码

    Java执行hadoop的基本操作实例代码 向HDFS上传本地文件 public static void uploadInputFile(String localFile) throws IOException{ Configuration conf = new Configuration(); String hdfsPath = "hdfs://localhost:9000/"; String hdfsInput = "hdfs://localhost:9000/user/

  • C++语言数据结构 串的基本操作实例代码

    C语言数据结构 串的基本操作实例代码 输出结果: 实现代码: #include<iostream> using namespace std; typedef int Status; #define Max 20 #define OK 1 #define ERROR 0 #define OVERLOE -2 typedef struct//堆分配表示串 { char *ch; int length; }HString; //====================================

  • python 文件的基本操作 菜中菜功能的实例代码

    python  文件的基本操作 菜中菜 文件操作 ​ open():打开 ​ file:文件的位置(路径) ​ mode:操作文件模式 ​ encoding:文件编码方式 ​ f :文件句柄 f = open("1.txt",mode = 'r',encoding = 'utf-8') print(f.read()) f.close 1.文件操作模式: ​ r,w,a(重要) ​ rb,wb,ab(次要) ​ r+,w+,a+ 1.1 r/w/a 1. r操作: f = open('1

随机推荐