深度学习分享7:tensorflow常用函数1(求导,独热码,柔性最大值,最大索引)

第七章

#对函数求导
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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值