TensorFlow之常量的使用1

发布于:2025-03-29 ⋅ 阅读:(24) ⋅ 点赞:(0)

前言

TensorFlow中定义的数据叫做Tensor(张量), Tensor又分为常量和变量。
常量一旦定义值不能改变。使用tf.constant定义常量。

示例

示例1

使用tf.constant定义常量。

import tensorflow as tf

t = tf.constant([[1., 2., 3.], [4., 5., 6.]])

# 可以像numpy的ndarray一样使用tensor
print(t)
print(t[:, 1:])
print(t[..., 1]) # 或t[:, 1]


print(t+10) # 每个元素都加10
print(tf.square(t)) # 每个元素都做平方
print(t @ tf.transpose(t)) # @表示矩阵的点乘

结果如下:

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

示例2

常量tensor和numpy中的ndarray的转化:

import tensorflow as tf
import numpy as np

t = tf.constant([[1., 2., 3.], [4., 5., 6.]])

# .numpy()可以把tensor转化为ndarray
print(t.numpy())
print(np.square(t)) 
np_t = np.array([[1., 2., 3.], [4., 5., 6.]])
# 直接使用ndarray生成一个tensor
print(tf.constant(np_t))

结果如下:

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

示例3

生成标量:

import tensorflow as tf

# scalar
t = tf.constant(2.718)
print(t.numpy())
print(t.shape)

结果如下:

2.718
()

网站公告

今日签到

点亮在社区的每一天
去签到