tensorflow常用函数

 1 import tensorflow as tf
 2 import  numpy as np
 3 
 4 x = tf.constant([[1, 2, 3], [2, 2, 3]])
 5 print(x)
 6 print(tf.reduce_mean(x))
 7 print(tf.reduce_sum(x, axis=1))
 8 
 9 # 切分传入张量的第一维度,生成输入特征/标签对,构建数据集
10 features = tf.constant([12, 23, 10, 17])
11 labels = tf.constant([0, 1, 1, 0])
12 dataset = tf.data.Dataset.from_tensor_slices((features, labels))
13 print(dataset)
14 for e in dataset:
15     print(e)
16 
17 # with结构记录计算过程,gradient求出张量的梯度
18 with tf.GradientTape() as tape:
19     w = tf.Variable(tf.constant(3.0))
20     loss = tf.pow(w, 2)
21 grad = tape.gradient(loss, w)
22 
23 # enumerate可遍历每个元素,组合为:索引 元素,常在for循环中使用
24 seq = ['one', 'two', 'three']
25 for i, ele in enumerate(seq):
26     print(i, ele)
27 
28 # tf.argmax(张量名,axis=操作轴)放回张量沿指定维度最大值的索引
29 test = np.array([[1, 2, 3], [2, 3, 4], [8, 7, 2]])
30 print(test)
31 print(tf.argmax(test, axis=0))

 

posted @ 2022-07-04 10:36  helloWorldhelloWorld  阅读(39)  评论(0)    收藏  举报