- 使用tf.constant
In [14]: tf.constant(1) Out[14]: <tf.Tensor: id=34, shape=(), dtype=int32, numpy=1> In [15]: tf.constant([1]) Out[15]: <tf.Tensor: id=35, shape=(1,), dtype=int32, numpy=array([1])>
- 从numpy、list转换
In [4]: tf.convert_to_tensor(np.ones([3,2])) Out[4]: <tf.Tensor: id=1, shape=(3, 2), dtype=float64, numpy= array([[1., 1.], [1., 1.], [1., 1.]])> In [5]: tf.convert_to_tensor([1,2]) Out[5]: <tf.Tensor: id=2, shape=(2,), dtype=int32, numpy=array([1, 2])>
- 使用tf.zeros与tf.ones新建(或者zeros_like\ones_like)
In [6]: tf.zeros([2,3]) Out[6]: <tf.Tensor: id=5, shape=(2, 3), dtype=float32, numpy= array([[0., 0., 0.], [0., 0., 0.]], dtype=float32)> In [9]: tf.ones([2,3]) Out[9]: <tf.Tensor: id=11, shape=(2, 3), dtype=float32, numpy= array([[1., 1., 1.], [1., 1., 1.]], dtype=float32)>
- 使用tf.fill
In [10]: tf.fill([2,2],5) Out[10]: <tf.Tensor: id=14, shape=(2, 2), dtype=int32, numpy= array([[5, 5], [5, 5]])>
- 使用tf.random
In [11]: tf.random.normal([2,2],mean=1,stddev=1) Out[11]: <tf.Tensor: id=20, shape=(2, 2), dtype=float32, numpy= array([[2.4201162, 3.4596694], [1.5751202, 1.7929654]], dtype=float32)> In [12]: tf.random.truncated_normal([2,2],mean=1,stddev=1) Out[12]: <tf.Tensor: id=26, shape=(2, 2), dtype=float32, numpy= array([[-0.4416641 , 0.67318285], [ 1.886663 , 2.2497933 ]], dtype=float32)> In [13]: tf.random.uniform([3,3],minval=0,maxval=1) Out[13]: <tf.Tensor: id=33, shape=(3, 3), dtype=float32, numpy= array([[9.2511845e-01, 2.5272369e-04, 3.9773893e-01], [3.6400330e-01, 8.9616191e-01, 1.0065639e-01], [1.7627370e-01, 1.8939865e-01, 7.1537638e-01]], dtype=float32)>
创建tensor的几种常用方式
最新推荐文章于 2023-11-13 19:57:48 发布