Python TensorFlow ``tensorflow.eye()`` 方法详解与代码示例


发布日期 : 2023-02-13 18:44:15 UTC

访问量: 10 次浏览

Python – tensorflow.eye()

TensorFlow是谷歌设计的开源Python库,用于开发机器学习模型和深度学习神经网络。

tensorflow.eye()是用来生成身份矩阵的。

语法:
tensorflow.eye( num_rows, num_columns, batch_shape, dtype, name)

参数:

  • num\_rows :这是一个int32的标量张量,定义了结果矩阵中的行数。
  • num\_columns (可选):它是一个 int32 的标量张量,定义了结果矩阵中的列数。它的默认值是 num\_rows
  • batch\_shape (可选):它是Python整数的列表或元组,或者一个1-D int32 Tensor。如果不是没有,返回的张量将有这个形状的领先批次尺寸。
  • dtype (可选):它定义了返回张量的dtype。默认值是float32。
  • name (可选):它定义了该操作的名称。

返回:
它返回一个形状为 batch\_shape + [num\_rows, num\_columns] 的张量。

示例 1:

# Importing the library
import tensorflow as tf

# Initializing the input
num_rows = 5

# Printing the input
print('num_rows:', num_rows)

# Calculating result
res = tf.eye(num_rows)

# Printing the result
print('res: ', res)

输出:

num_rows: 5
res: tf.Tensor(
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]], shape=(5, 5), dtype=float32)

示例 2:

# Importing the library
import tensorflow as tf

# Initializing the input
num_rows = 5
num_columns = 6
batch_shape = [3]

# Printing the input
print('num_rows:', num_rows)
print('num_columns:', num_columns)
print('batch_shape:', batch_shape)

# Calculating result
res = tf.eye(num_rows, num_columns, batch_shape)

# Printing the result
print('res: ', res)

输出:

num_rows: 5
num_columns: 6
batch_shape: [3]
res: tf.Tensor(
[[[1. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 1. 0.]]

[[1. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 1. 0.]]

[[1. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 1. 0.]]], shape=(3, 5, 6), dtype=float32)