tensorflow2.x——tf.constant()函数介绍和示例

tf.constant()函数介绍和示例
tf.constant(value, shape, dtype=None, name=None)
释义:生成常量

  • value,值
  • shape,数据形状
  • dtype,数据类型
  • name,名称

1.示例:

# Constant 1-D Tensor populated with value list.
tensor = tf.constant([1, 2, 3, 4, 5, 6]) => [1 2 3 4 5 6]

# Constant 1-D Tensor populated with value list.
tensor = tf.constant([1, 2, 3, 4, 5, 6], shape=(2,3))
     => [[1 2 3], [4 5 6]]

# Constant 2-D tensor populated with scalar value -1.
tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]
                                             [-1. -1. -1.]]

2.讲解:

import numpy as np 
import tensorflow as tf 
t = tf.constant([1, 2, 3, 4, 5, 6], shape=(2, 3))
print(t)
print(t[:,1:])
print(t[:,1])
print(t[..., 1]

结果:

tf.Tensor( [[1 2 3] [4 5 6]], shape=(2, 3), dtype=int32)
tf.Tensor([[2 3] [5 6]], shape=(2, 2), dtype=int32)
tf.Tensor([2 5],shape=(2,), dtype=int32) tf.Tensor([2 5], shape=(2,), dtype=int32)

#operations 
print(t+10) 
print(tf.square(t))
print(t @ tf.transpose(t)) # t * t.T 

结果:

tf.Tensor(
[[11 12 13]
[14 15 16]], shape=(2, 3), dtype=int32)
tf.Tensor(
[[ 1 4 9]
[16 25 36]], shape=(2, 3), dtype=int32)
tf.Tensor(
[[14 32]
[32 77]], shape=(2, 2), dtype=int32)

# numpy conversion 
print(t.numpy()) #转换为numpy的一个实例
print(np.square(t)) # 直接使用numpy运算
np_t = np.array([[1, 2, 3],[4, 5, 6]])
print(tf.constant(np_t)) #将numpy的数组变为tensorflow的张量

结果:

[[1 2 3]
[4 5 6]]
[[ 1 4 9]
[16 25 36]]
tf.Tensor(
[[1 2 3]
[4 5 6]], shape=(2, 3), dtype=int32)

# Scalars (0维数组,标量)
t = tf.constant(2.146)
print(t.numpy())
print(t)
print(t.shape)

结果:

2.146
tf.Tensor(2.146, shape=(), dtype=float32)
()

你可能感兴趣的:(TensorFlow)