Python TensorFlow 从 NumPy 数组创建数据集教程


发布日期 : 2019-08-04 15:08:51 UTC

访问量: 10 次浏览

在Tensorflow中加载NumPy数据

在这篇文章中,我们将研究在Tensorflow中用Python编程语言加载Numpy数据的方法。

使用 tf.data.Dataset.from\_tensor\_slices() 函数

在这种方法下,我们使用 tf.data.Dataset.from\_tensor\_slices() 方法加载一个Numpy数组,我们可以通过使用TensorFlow模块中的 tf.data.Dataset.from\_tensor\_slices() 方法以对象的形式获得数组的片断。

语法 :
tf.data.Dataset.from_tensor_slices(list)

返回:返回被切片元素的对象。

示例 1:

在这个例子中,我们使用 tf.data.Dataset.from\_tensor\_slices() 方法,来获取二维阵列的切片,然后将其加载到变量 gfg 中。

# import modules
import tensorflow as tf
import numpy as np

# Creating data
arr = np.array([[1, 2, 3, 4],
                [4, 5, 6, 0],
                [2, 0, 7, 8],
                [3, 7, 4, 2]])

# using tf.data.Dataset.from_tensor_slices() 
# method
gfg = tf.data.Dataset.from_tensor_slices(arr)

for i in gfg:
    print(i.numpy())

输出:

[1 2 3 4]
[4 5 6 0]
[2 0 7 8]
[3 7 4 2]

示例 2:

在这个例子中,我们将使用Python编程语言中TensorFlow库的 tf.data.Dataset.from\_tensor\_slices() 函数加载变量 gfgNumPy 列表。

# import modules
import tensorflow as tf
import numpy as np

# Creating data
list = [[5, 10], [3, 6], [1, 2], [5, 0]]

# using tf.data.Dataset.from_tensor_slices()
# method
gfg = tf.data.Dataset.from_tensor_slices(list)

for i in gfg:
    print(i.numpy())

输出:

[ 5 10]
[3 6]
[1 2]
[5 0]