Tensorflow中的数据类型和常用函数

Tensorflow中的数据类型和常用函数

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

维数 名字 例子
0-D 0 标量 scalar s=123
1-D 1 向量 vector v=[1,2,3]
2-D 2 矩阵 matrix m=[[1,2,3],[4,5,6],[7,8,9]]
n-D n 张量 tensor t=[[[[......]]]] n个

张量可以表示0阶到n阶数组(列表)。

数据类型

tf.int 32tf.float 32tf.float 64

布尔类型:tf.constant([True,False])

字符串类型:tf.constant("hallo 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)

tf.Tensor([1 5], shape=(2,), dtype=int64)  # shape中','隔开了一个数字,表明是一维的,2表示有两个数值。
<dtype: 'int64'>
(2,)

将numpy的数据类型转换为tensor数据类型

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(维度,指定值)

维度:一维 直接写个数;二维 用[行,列];多维 用[n,m,j,k......]

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)

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

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

tf.random.normal([2,2],mean = 0.5,stddev=1)

<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[ 2.2596548 ,  1.8583959 ],
       [-0.80588806, -1.4749051 ]], dtype=float32)>

生成截断式正态分布随机数:tf.random.truncated_normal(维度,mean=均值,stddev=标准差)

tf.random.truncated_normal([2,2],mean=0.5,stddev=1)

<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[-1.2615949,  0.564474 ],
       [-1.1084144,  1.1451273]], dtype=float32)>

注意:tf.truncated_normal中如果随机生成数据的取值在\((\mu -2\sigma,\mu+2\sigma)\)之内则重新生成,保证了生成值在均值附近。

生成均匀分布随机数:tf.random.uniform(维度,minval=最小值,maxval=最大值)

tf.random.uniform([2,2],minval=-1,maxval=1)

<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[-0.01930571,  0.16274714],
       [-0.1265943 ,  0.96586275]], dtype=float32)>

注:最小最大为前闭后开

张量(Tensor)上的常用函数

强制tensor转换为该数据类型:tf.cast(张量名,dtype=数据类型)

计算张量维度上元素的最小值:tf.reduce_min(张量名)

计算张量维度上元素的最大值: tf.reduce_max(张量名)

理解axisaxis = 0表示跨行(也就是我们数学上矩阵中按某一列计算),axis = 1表示跨列(某一行),如果不指定axis,则所有元素参与计算。

计算张量沿着指定维度的平均值:tf.reduce_mean(张量名,axis=操作轴)

计算张量沿着指定维度的和:tf.reduce_sum(张量名,axis=操作轴)

x = tf.constant([[1,2,3],[4,5,6]])
print(tf.reduce_sum(x,axis=1))# 每一行的相加

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

tf.Variable

tf.Variable()将变量标记为“可训练”,被标记的变量会在反向传播中记录梯度信息。神经网络训练中,常用该函数标记待训练参数。

使用:tf.Variable(初始值)

w = tf.Variable(tf.random.normal([2,2],mean = 0,stddev = 1))

# 标记后就可以在反向传播中更新参数w

tf.data.Dataset.from_tensor_slices

切分传入张量的第一位独,生成输入特征/标签对,构建数据集。

data = td.data.Dataset.from_tesor_slices((输入特征,标签))

注:Numpy和Tensor格式都是可以使用该语句读入数据。

import tensorflow as tf
features = tf.constant([12,23,10,17])
labels = tf.constant([0,1,1,0]) 
dataset = tf.data.Dataset.from_tensor_slices((features,labels))
print(dataset)
for element in dataset:
    print(element)
    
<TensorSliceDataset shapes: ((), ()), types: (tf.int32, tf.int32)>
(<tf.Tensor: shape=(), dtype=int32, numpy=12>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: shape=(), dtype=int32, numpy=23>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=10>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=17>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)

tf.GradientTape

with结构记录计算过程,gradient求出张量的梯度。

with tf.GradientTape() as tape:
    grad = tape.gradient(函数,求导参数)
with tf.GradientTape() as tape:
    w = tf.Variable(tf.constant(3.0)) # 标记为可训练
    loss = tf.pow(w,2)  # 定义损失函数
grad = tape.gradient(loss,w) # 对其进行求导 dw^2/dw=2w=2*3= 6
print(grad)

tf.Tensor(6.0, shape=(), dtype=float32)

enumerate

enumerate是python的内建函数,它可遍历每个元素(列表、元组或者字符串),组合为:索引 元素,常在for中使用。

enumerate(列表名)

seq = ['one','two','three']
for i,element in enumerate(seq):
    print(i,element)
    
0 one
1 two
2 three

独热编码 tf.one_hot

独热编码(one-hot encoding),tf.one_hot()将待转换数据,转换为one-hot数据输出。

tf.one_hot(待转换数据,depth=几分类)

classes = 3
labels = tf.constant([1,0,2]) # 输入的元素值最小为0,最大为2
output= tf.one_hot(labels,depth = classes)
print(output)

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

tf.nn.softmax

y = tf.constant([1.01,2.01,-0.66])
y_pro = tf.nn.softmax(y)
print("After softmasx,y_pro is:",y_pro)

After softmasx,y_pro is: tf.Tensor([0.25598174 0.69583046 0.04818781], shape=(3,), dtype=float32)

assign_sub

赋值操作,更新参数的值并返回

调用assign_sub前,先用tf.Variable定义变量w为可训练(可自更新)。

w.assign_sub(w要自减的内容)

w = tf.Variable(4)
w.assign_sub(1)
print(w)

<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>

tf.argmax

返回张量沿着指定维度最大值的索引。

tf.argmax(tensor,axis= 1or0)

import numpy as np
test = np.array([[1,2,3],[2,3,4],[5,4,3],[8,7,2]])
print(test)
print(tf.argmax(test,axis=0)) # 返回每一列(经度)最大值的索引
print(tf.argmax(test,axis=1)) # 返回每一行(维度)最大值的索引

[[1 2 3]
 [2 3 4]
 [5 4 3]
 [8 7 2]]
tf.Tensor([3 3 1], shape=(3,), dtype=int64)
tf.Tensor([2 2 0 0], shape=(4,), dtype=int64)

Tensorflow中的数学运算

对应元素的四则运算:tf.add(tensor1,tensor2) tf.subtract(tensor1,tensor2) tf.multiply(tensor1,tensor2) tf.divide(tensor1,tensor2)

注:只有维度相同的张量才可以做四则运算

平方、次方与开方:tf.square(tensor1) tf.pow(tensor1,n次方数) tf.sqrt(tensor1)

矩阵乘法:tf.matmul(tensor1,tensor2)

posted @ 2020-05-27 21:23  狄昵称  阅读(645)  评论(0编辑  收藏  举报