TensorFlow2.0的基础操作! |
注意:介绍完了初始化全为0的方法之后,也可以初始化为全为1,或者任意一个常数。
例如: 给定一组图片 [64, 32, 32, 3 ]我们怎么把这64张图片随机的打散:首先我们生成一个0-63的索引,本来是顺序的[0,1,2,3…63], 然后打散比如 [1,7,8…] 等等;此外有一点需要注意,打散的时候原来每个照片索引相对应的标签再打散之后还是需要是对应的关系。如何实现呢?下面展示:
代码演示:
In [1]: import tensorflow as tf
In [2]: out=tf.random.uniform([4,10])
In [3]: out
Out[3]:
<tf.Tensor: id=6, shape=(4, 10), dtype=float32, numpy=
array([[0.88357687, 0.32258904, 0.07840157, 0.93425155, 0.69157064,
0.3894565 , 0.3264054 , 0.7723907 , 0.97058046, 0.23372042],
[0.4888407 , 0.11972976, 0.40817046, 0.89883673, 0.6751963 ,
0.3385092 , 0.66311693, 0.6154913 , 0.67760134, 0.43396258],
[0.28959072, 0.98543024, 0.14751756, 0.8581419 , 0.595019 ,
0.3687029 , 0.9161774 , 0.18476939, 0.5543313 , 0.7288394 ],
[0.75870466, 0.6590768 , 0.55011404, 0.6398536 , 0.61781406,
0.7082771 , 0.618503 , 0.97928166, 0.35138845, 0.8519068 ]],
dtype=float32)>
In [4]: y=tf.range(4)
In [5]: y
Out[5]: <tf.Tensor: id=11, shape=(4,), dtype=int32, numpy=array([0, 1, 2, 3], dtype=int32)>
In [6]: y=tf.one_hot(y,depth=10)
In [7]: y
Out[7]:
<tf.Tensor: id=16, shape=(4, 10), dtype=float32, numpy=
array([[1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 1., 0., 0., 0., 0., 0., 0.]], dtype=float32)>
In [8]: loss=tf.keras.losses.mse(y,out)
In [9]: loss
Out[9]: <tf.Tensor: id=20, shape=(4,), dtype=float32, numpy=array([0.33263168, 0.40248507, 0.47200695, 0.45164543], dtype=float32)>
In [10]: loss=tf.reduce_mean(loss)
In [11]: loss
Out[11]: <tf.Tensor: id=23, shape=(), dtype=float32, numpy=0.41469228>
import tensorflow as tf
from tensorflow.keras import layers
x=tf.random.normal((4,32,32,3))
net=layers.Conv2D(16,kernel_size=3) #卷积对象net,卷积核个数166,卷积核大小3×3
net(x) #tensor送入卷积
print(x.shape)
输出结果:
(tf2.0) zhangkf@john:~$ python 1.py
(4, 32, 32, 3)