TensorFlow笔记

以下内容摘录自:北京大学TensorFlow笔记及实践

tf.where(条件语句,真返回A,假返回B)

import tensorflow as tf

a = tf.constant([1, 2, 3, 1, 1])
b = tf.constant([0, 1, 3, 4, 5])
c = tf.where(tf.greater(a, b), a, b)  # 若a>b,返回a对应位置元素,否则返回b的元素
print("c:", c)

np.random.RandomState.rand() 返回一个 [0,1) 之间的随机数

np.random.RandomState.rand(维度)

import numpy as np

rdm = np.random.RandomState(seed=1)  # 种子决定了随机值,实际使用中不指定种子
a = rdm.rand()  # 返回一个随机标量 [0,1)
b = rdm.rand(2, 3)  # 返回维度为2行3列的随机数矩阵
print("a:", a)
print("b:", b)


 

常用函数

TensorFlow笔记_第1张图片

TensorFlow笔记_第2张图片

 

TensorFlow笔记_第3张图片

TensorFlow笔记_第4张图片

TensorFlow笔记_第5张图片

 

求导

import tensorflow as tf

with tf.GradientTape() as tape:
    x = tf.Variable(tf.constant(3.0))  #x可训练,可更新
    y = tf.pow(x, 2) #函数名称
grad = tape.gradient(y, x)  #对 x的平方求导 = 2x
print(grad)    #答案是6

枚举 

seq = ['one', 'two', 'three']
for i, element in enumerate(seq):   #枚举,打印序号和值 序号从0开始
    print(i, element)

读热码

import tensorflow as tf

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


输出:
result of labels1: tf.Tensor(
[[0. 1. 0.]
 [1. 0. 0.]
 [0. 0. 1.]], shape=(3, 3), dtype=float32)

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

tf.nn.softmax

只有输出符合概率分布,才能和读热码匹配起来,既变量之和为1,概率最大的设置为1,其他设置为0

TensorFlow笔记_第6张图片

import tensorflow as tf
import math as mt
y = tf.constant([1.01, 2.01, -0.66])
y_pro = tf.nn.softmax(y)

print("After softmax, y_pro is:", y_pro)  # y_pro 符合概率分布

print("The sum of y_pro:", tf.reduce_sum(y_pro))  # 通过softmax后,所有概率加起来和为1


print(mt.e)                             #常量e=2.718281828459045
print(tf.pow(mt.e,1.01))                #e的1.01次方 = 2.745601
print(tf.pow(mt.e,2.01))
print(tf.pow(mt.e,-0.66))

 TensorFlow笔记_第7张图片

assign_sub函数,实现自减1操作

TensorFlow笔记_第8张图片

tf.argmax 返回张量沿着指定维度最大的索引号

TensorFlow笔记_第9张图片

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(TensorFlow)