PS:这些文档是自己学习的点滴记录 导入出来 只是为了自己查看方便 不适合大众阅读 请忽略 谢谢
Tensorflow 常用函数学习
1:将numpy数据类型 转换为Tensor数据类型 使用 tf.convert_to_tensor(数据名字,dtype=数据类型)
2:#强制Tensor数据类型转换函数 tf.cast(Tensor,dtype = 数据类型)
3:计算张量维度上元素的最小值 tf.reduce_min(张量名)
最大值: tf.reuduce_max(Tensor)
4:axis 通过调整axis用来控制执行维度 axis=0 则跨行执行 down axis=1 跨列执行 across 如果不指定axis的值 则所有的值均参与运算
5:tf.Variable
tf.Variable()函数将变量标记为“可训练”,被标记的变量会在反向传播中记录梯度信息。神经网络训练中,常用tf.Variable()函数来标记待训练的参数
w = tf.Variable(tf.random.normal([2,2],mean=0,stddev=1))
6:四则运算函数 实现张量的加减乘除 注意:只有维度相同的张量才能做四则运算
1、实现两个Tensor对应元素相加 tf.add(Tensor1,Tensor2)
2、实现两个Tensor对应元素相减 tf.subtract(Tensor1,Tensor2)
3、实现两个张量对应元素相乘 tf.multiply(Tensor1, Tensor2)
4、实现两个张量对应元素相除 tf.divide(Tensor1,Tensor2)
7:平方 次方 与 开方
1、tf.square(Tensor) 2、tf.pow(Tensor,幂) 3、tf.sqrt(Tensor)
8:矩阵乘法 tf.matmul(矩阵1,矩阵2)
9:独热编码 (one-hot encoding):在分类问题中,常用独热编码做标签 标记类别: 1表示是 0表示非 tf.one_hot()
10: tf.nn.softmax()函数 assign_sub()自更新函数
11:tf.argmax(Tensor,axis =0|1) 返回张量延指定维度最大值的索引
import tensorflow as tf
import numpy as np
a = np.arange(2,6,step =1.5,dtype =np.int)
b =tf.convert_to_tensor(a,tf.float32)
print(a)
print(b)
#b的输出 有 shape=(3,)说明b是一个一维的张量 Tensor 有三个元素
[2 3 4]
tf.Tensor([2. 3. 4.], shape=(3,), dtype=float32)
2.以下六条语句分别展示了TF2中常用的生成数据的函数
全0 全1 填充 正太分布 截断正太 均匀分布
a = tf.zeros(shape=(2,2),dtype=tf.float32,name="哈哈")
b = tf.ones(shape=[2,4],dtype=tf.float32)
c = tf.fill(dims=[3,3,3],value=6)
d = tf.random.normal(shape=(4,4),mean=0.5,stddev=1.0,seed=500)
e = tf.random.truncated_normal(shape=(4,4),mean=0.5,stddev=1.0,seed=500)
f = tf.random.uniform(shape=(2,2),minval=1,maxval=10,dtype=tf.float32)
x = tf.constant([[1,2,3],[4,5,6]],dtype=tf.float32)
y = tf.reduce_mean(x,axis=0)
print(y)
z = tf.reduce_sum(x,axis=1)
print(z)
w = tf.reduce_mean(x)
print(w)
tf.Tensor([2.5 3.5 4.5], shape=(3,), dtype=float32)
tf.Tensor([ 6. 15.], shape=(2,), dtype=float32)
tf.Tensor(3.5, shape=(), dtype=float32)
classes = 3
labels = tf.constant([1,0,2])
output = tf.one_hot(labels,classes)
print(output)
tf.Tensor(
[[0. 1. 0.]
[1. 0. 0.]
[0. 0. 1.]], shape=(3, 3), dtype=float32)