将python列表和numpy数组转换成tensorflow的dataset 只有dataset才能被model.fit函数训练
import tensorflow as tf
import numpy as np
numpy_data = np.arange(16) # 创建numpy数组
numpy_data
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
numpy_dataset = tf.data.Dataset.from_tensor_slices(
numpy_data # numpy数组转tf.Tensor数组(即:TensorSliceDataset)
)
numpy_dataset
for data in numpy_dataset:
print(data)
tf.Tensor(0, shape=(), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor(3, shape=(), dtype=int32)
tf.Tensor(4, shape=(), dtype=int32)
tf.Tensor(5, shape=(), dtype=int32)
tf.Tensor(6, shape=(), dtype=int32)
tf.Tensor(7, shape=(), dtype=int32)
tf.Tensor(8, shape=(), dtype=int32)
tf.Tensor(9, shape=(), dtype=int32)
tf.Tensor(10, shape=(), dtype=int32)
tf.Tensor(11, shape=(), dtype=int32)
tf.Tensor(12, shape=(), dtype=int32)
tf.Tensor(13, shape=(), dtype=int32)
tf.Tensor(14, shape=(), dtype=int32)
tf.Tensor(15, shape=(), dtype=int32)
list_data = list(range(10)) # 创建列表
list_data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list_data = tf.data.Dataset.from_tensor_slices(
list_data # list转tf.Tensor数组(即:TensorSliceDataset)
)
list_data
for data in list_data:
print(data)
tf.Tensor(0, shape=(), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor(3, shape=(), dtype=int32)
tf.Tensor(4, shape=(), dtype=int32)
tf.Tensor(5, shape=(), dtype=int32)
tf.Tensor(6, shape=(), dtype=int32)
tf.Tensor(7, shape=(), dtype=int32)
tf.Tensor(8, shape=(), dtype=int32)
tf.Tensor(9, shape=(), dtype=int32)