1.构建数据管道
可以从 Numpy array, Pandas DataFrame, Python generator, csv文件, 文本文件, 文件路径, tfrecords文件等方式构建数据管道。
其中通过Numpy array, Pandas DataFrame, 文件路径构建数据管道是最常用的方法
1.1.从Numpy array构建数据管道
import tensorflow as tf
import numpy as np
from sklearn import datasets
iris = datasets.load_iris()
ds1 = tf.data.Dataset.from_tensor_slices((iris["data"],iris["target"]))
1.2.从 Pandas DataFrame构建数据管道
import tensorflow as tf
from sklearn import datasets
import pandas as pd
iris = datasets.load_iris()
#pandas.DataFrame( data, index, columns, dtype, copy)
#data源数据,index每一行得索引名称,columns每一列得索引名称
dfiris = pd.DataFrame(iris["data"],columns = iris.feature_names)
#to_dict 可以对DataFrame类型的数据进行转换
ds2 = tf.data.Dataset.from_tensor_slices((dfiris.to_dict("list"),iris["target"]))
1.3.从Python generator构建数据管道
import tensorflow as tf
from matplotlib import pyplot as plt
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# 定义一个从文件中读取图片的generator
#class_mode:"categorical"会返回2D的one-hot编码标签
#"binary"返回1D的二值标签."sparse"返回1D的整数标签
image_generator = ImageDataGenerator(rescale=1.0/255).flow_from_directory(
"./data/cifar2/test/",
target_size=(32, 32),
batch_size=20,
class_mode='binary')
#classes: 为子文件夹的列表;class_indices可获得文件夹名与类的序号的对应字典
classdict = image_generator.class_indices
print(classdict)
def generator():
for features,label in image_generator:
yield (features,label)
ds3 = tf.data.Dataset.from_generator(generator,
output_types=(tf.float32,tf.int32))
1.4.从csv文件构建数据管道
ds4 = tf.data.experimental.make_csv_dataset(
file_pattern = ["./data/titanic/train.csv","./data/titanic/test.csv"],
batch_size=3,
label_name="Survived",
na_value="",
num_epochs=1,
ignore_errors=True)
- CSV 文件的每列都会有一个列名。dataset 的构造函数会自动识别这些列名。如果文件的第一行不包含列名,那么需要将列名通过字符串列表传给函数中得column_names=
- 如果我们要有选择地加载csv文件中地某些列作为训练地属性,可以使用make_cvs_dataset函数中地select_columns参数进行指定:select_columns = columns_to_use
- 如果cvs文件列中包含我们预测地类别属性,需要使用make_cvs_dataset函数中地label_name进行指定
1.5 从文本文件构建数据管道
ds5 = tf.data.TextLineDataset(
filenames = ["./data/titanic/train.csv","./data/titanic/test.csv"]
).skip(1) #略去第一行header
1.6.从文件路径构建数据管道
ds6 = tf.data.Dataset.list_files("./data/cifar2/train/*/*.jpg")
1.7.从tfrecords文件构建数据管道
import os
import numpy as np
# inpath:原始数据路径 outpath:TFRecord文件输出路径
def create_tfrecords(inpath,outpath):
writer = tf.io.TFRecordWriter(outpath)
dirs = os.listdir(inpath)
for index, name in enumerate(dirs):
class_path = inpath +"/"+ name+"/"
for img_name in os.listdir(class_path):
img_path = class_path + img_name
img = tf.io