第七章
#对函数求导
import tensorflow as tf
with tf.GradientTape() as tape:
w=tf.Variable(tf.constant(3.0))
loss=tf.pow(w,2)
grad=tape.gradient(loss,w)
print(grad)
tf.Tensor(6.0, shape=(), dtype=float32)
#独热码
#tf.one_hot()将待转数据转换为独热码形式
#tf.one_hot(待转化数据,depth=几分类)
classes=3
label=tf.constant([2,0,1])
output=tf.one_hot(label,depth=classes)
print(output)
#这里2对应[0. 0. 1.]因为标签2是标签0的概率是0,是1的概率是0,是2的概率是1 。标签0和1是同样的道理
tf.Tensor(
[[0. 0. 1.]
[1. 0. 0.]
[0. 1. 0.]], shape=(3, 3), dtype=float32)
柔性最大值tf.nn.softmax(zLj)
t=通过对输出使用柔性最大值函数,可以使得输出具有统计数据特性,且输出概率和为1,这一点是显而易见的
#自减函数,更新参数的值并返回
#w必须是变量,即tf.Variable
#w.assign_sub(w要自减的内容)
w=tf.Variable(4)
w.assign_sub(1)
print(w)
#这里相当w=w-1
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>
#tf.argmax返回张量沿指定维度最大值的索引tf.argmax(张量名,axis=操作轴)
#axis=0是沿着行方向遍历,行方向是什么方向呢,就是我们画长方形,笔画长的那个方向,比如这里就是[1,2,3]从1到3的方向
#在这个方向上,选择1 2 5 8里最大的8的索引为3,然后2 3 4 7最大的7的索引为3,3 4 3 2中最大的4的索引为1
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)