1. 常量tf.constant
1.1 导入相应的库
在介绍基础的API之前,我们先导入相应的python库:
# matplotlib 用于绘图
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
# 处理数据的库
import numpy as np
import sklearn
import pandas as pd
# 系统库
import os
import sys
import time
# TensorFlow的库
import tensorflow as tf
from tensorflow import keras
1.2 tf.constant的索引操作
tf.constant是定义tensor形式的常量的工具。我们先来看下关于tf.constant的索引操作:
"""
索引操作
"""
# 定义二维矩阵的tensor常量
t = tf.constant([[1., 2., 3.], [4., 5., 6.]])
print(t) # 打印出来该tensor
print(t[:,1:]) # 取第二列之后的子矩阵
print(t[...,1]) # 取第二列
输出结果为:
对tf.tensor做索引操作得到的数据的类型也是tf.tensor形式的。
1.3 tf.constant的算子操作
"""
# 算子操作
"""
print(t+10)# 每个元素上都加10
print(tf.square(t)) # 每个元素都平方
print(t @ tf.transpose(t)) # t 乘以 t的转置
输出结果为:
1.4 numpy与tf.constant之间的转化
"""
# numpy 与 tf.constant之间的转化
"""
print(t.numpy()) # t的numpy形式
print(np.square(t)) # 输出t的numpy形式的平方
np_t = np.array([[1., 2., 3.], [4., 5., 6.]])
print(tf.constant(np_t)) # numpy和tf.constant之间的转换
输出结果为:
2. 字符串tf.strings
tf.strings涉及到的操作一般是取字符长度以及字符串编码:
"""
字符串:tf.strings
"""
t = tf.constant(["cafe", "coffee", "咖啡"]) # 定义字符串tensor常量
print(tf.strings.length(t, unit="UTF8_CHAR")) # 以UTF8的形式输出字符串的长度
print(tf.strings.unicode_decode(t, "UTF8")) # 以UTF8的格式编码字符串
输出结果为:
3. ragged tensor
在TensorFlow中,RaggedTensor指的是不完整的张量,比如上个例子中,对于tensor:
t = tf.constant(["cafe", "coffee", "咖啡"])
返回的结果为:
之所以类型是tf.RaggedTensor是因为其不是一个二维矩阵。因为第一个张量元素的长度是4,第二个是6,第三个是2。
3.1 ragged tensor的索引操作
r = tf.ragged.constant([[11, 12], [21, 22, 23], [], [41]])
# 索引操作
print(r) # 打印该ragged.tensor
print(r[1]) # 打印ragged.tensor的第二个数据
print(r[1:2]) # 打印ragged.tensor 1:2之间的数据
输出结果为:
3.2 ragged tensor的算子操作
r2 = tf.ragged.constant([[51, 52], [], [71]])
print(tf.concat([r, r2], axis = 0)) # 两个ragged tensor在0维度进行拼接
输出结果为:
3.3 ragged tensor 转化为普通的tensor
"""
# 将ragged tensor 转化为 普通的 tensor
"""
r = tf.ragged.constant([[11, 12], [21, 22, 23], [], [41]])
print(r.to_tensor()) # 用0自动补齐
输出结果为:
4. sparse tensor
4.1 sparse tensor的基本使用
ragged tensor可以通过 to_tensor() 补齐,但是补齐的零元素都是在非零元素的后面
sparse tensor 可以在指定位置上补齐:
s = tf.SparseTensor(indices=[[0,1], [1,0], [2,3]], # 非零元素的坐标
values=[1., 2., 3.], # 非零元素的值
dense_shape = [3, 4]) # 张量的维度
print(s)
print(tf.sparse.to_dense(s)) # 补齐sparsetensor
输出结果为:
4.2 sparse tensor的算子操作
# sparse tensor支持的算子类型,不支持加法
s2 = s * 2.0 # 乘法
print(s2)
print(tf.sparse.to_dense(s2))
s4 = tf.constant([[10., 20.],
[30., 40.],
[50., 60.],
[70., 80.],])
print(tf.sparse.sparse_dense_matmul(s, s4)) # 矩阵乘法
输出结果为:
5. 变量tf.Variable
5.1 tf.Varible的定义
"""
变量:tf.Variable
"""
v = tf.Variable([[1., 2.,3.], [4., 5., 6.]])
print(v)
print(v.value()) # 打印具体的tensor
print(v.numpy()) # 打印具体的值
输出结果为:
4.2 变量的赋值
"""
# 变量的重新赋值,只能用assign函数,不能用“=”
"""
v.assign(2*v) # 整体重新赋值
print(v.numpy())
v[0,1].assign(42) # 单元素重新赋值
print(v.numpy())
v[1].assign([6., 6., 6.]) # 单维度重新赋值
print(v.numpy())
输出结果为: