import tensorflow as tf
a = tf.fill([1,2],3.)
print("a:",a)
print("a的次方:",tf.pow(a,3))
print("a的平方:",tf.square(a))
print("a的开放:",tf.sqrt(a))
"""
a: tf.Tensor([[3. 3.]], shape=(1, 2), dtype=float32)
a的次方: tf.Tensor([[27. 27.]], shape=(1, 2), dtype=float32)
a的平方: tf.Tensor([[9. 9.]], shape=(1, 2), dtype=float32)
a的开放: tf.Tensor([[1.7320508 1.7320508]], shape=(1, 2), dtype=float32)
"""
import tensorflow as tf
a = tf.ones([3,2])
b = tf.fill([2,3],3.)
print("a:",a)
print("b:",b)
print("a*b:",tf.matmul(a,b))
"""
a: tf.Tensor(
[[1. 1.]
[1. 1.]
[1. 1.]], shape=(3, 2), dtype=float32)
b: tf.Tensor(
[[3. 3. 3.]
[3. 3. 3.]], shape=(2, 3), dtype=float32)
a*b: tf.Tensor(
[[6. 6. 6.]
[6. 6. 6.]
[6. 6. 6.]], shape=(3, 3), dtype=float32)
"""
把特征和标签配对。
import tensorflow as tf
features = tf.constant([12,23,10,17])
labels = tf.constant([0,1,1,0])
dataset = tf.data.Dataset.from_tensor_slices((features,labels))
for element in dataset:
print(element)
"""
(<tf.Tensor: shape=(), dtype=int32, numpy=12>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: shape=(), dtype=int32, numpy=23>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=10>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=17>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
"""
实现函数对参数的求导运算。
import tensorflow as tf
with tf.GradientTape() as tape:
x = tf.Variable(tf.constant(3.0))
y = tf.pow(x,2)
grad = tape.gradient(y,x)
print(grad)
"""
tf.Tensor(6.0, shape=(), dtype=float32)
"""
可以枚举出每一个元素,并在元素前加上索引号。
seq = ['one','two','three']
for i,element in enumerate(seq):
print(i,element)
"""
0 one
1 two
2 three
"""
常用用独热编码表示标签,
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)
"""
result of labels1: tf.Tensor(
[[0. 1. 0.]
[1. 0. 0.]
[0. 0. 1.]], shape=(3, 3), dtype=float32)
"""
在前向传播过程中,输出的值符合概率分布,才能与独热码进行比较,因此,用softmax,让输出的值符合概率分布,结果为0.256,0.695,0.048,它们的和为1.
0.256表示为第0类鸢尾花的概率是25.6%
softmax是让n分类的n个输出,符合概率分布,概率值在0-1之间,和为1.
import tensorflow as tf
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
"""
After softmax,y_pro is : tf.Tensor([0.25598174 0.69583046 0.04818781], shape=(3,), dtype=float32)
The sum of y_pro: tf.Tensor(1.0, shape=(), dtype=float32)
"""
import tensorflow as tf
x = tf.Variable(4)
x.assign_sub(1) #自减操作
print("x:",x) #4-1=3
"""
x: <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>
"""
import numpy as np
import tensorflow as tf
test = np.array([[1,2,3],[2,3,4],[5,4,3],[8,7,2]])
print("test:\n",test)
print("每一列的最大值的索引:",tf.argmax(test,axis=0))
print("每一行的最大值索引:",tf.argmax(test,axis=1))
"""
test:
[[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)
"""