sam*_*815 5 python image machine-learning tensorflow keras-2
如果我有一个数据集
dataset = tf.keras.preprocessing.image_dataset_from_directory(
directory,
labels="inferred",
label_mode="int",
class_names=None,
color_mode="rgb",
batch_size=32,
image_size=(32, 32),
shuffle=True,
seed=None,
validation_split=None,
subset=None,
interpolation="bilinear",
follow_links=False,
)
Run Code Online (Sandbox Code Playgroud)
如何将其分成 x 和 y 数组?x 数组将是 IMG 数组,y 数组将包含每个 img 的类别。
这将为您完成分离。您需要做的是创建一个目录,我们将其命名为 c:\train。现在,您需要在该目录中创建一系列子目录,每个类一个。例如,如果您有狗的图像和猫的图像,并且您想要构建一个分类器来区分图像是猫还是狗,则在 train 目录中创建两个子目录。将一个目录命名为 cats,将另一个子目录命名为 dogs。现在将所有猫的图像放入 cat 子目录中,并将所有狗的图像放入 dogs 子目录中。现在假设您想要使用 75% 的图像进行训练,使用 25% 的图像进行验证。现在使用下面的代码创建训练集和验证集。
train_batch_size = 50 # Set the training batch size you desire
valid_batch_size = 50 # Set this so that .25 X total sample/valid_batch_size is an integer
dir = r'c:\train'
img_size = 224 # Set this to the desired image size you want to use
train_set = tf.keras.preprocessing.image_dataset_from_directory(
directory=dir, labels='inferred', label_mode='categorical', class_names=None,
color_mode='rgb', batch_size=train_batch_size, image_size=(img_size, img_size),
shuffle=True, seed=None, validation_split=.25, subset="training",
interpolation='nearest', follow_links=False)
valid_set = tf.keras.preprocessing.image_dataset_from_directory(
directory=dir, labels='inferred', label_mode='categorical', class_names=None,
color_mode='rgb', batch_size=valid_batch_size, image_size=(img_size, img_size),
shuffle=False, seed=None, validation_split=.25, subset="validation",
interpolation='nearest', follow_links=False)
Run Code Online (Sandbox Code Playgroud)
使用 labels='inferred' 标签将是子目录的名称。在示例中它们将是猫和狗。当 label_mode='categorical' 时,标签数据是一个热向量,因此当您编译模型时,设置 loss='CategoricalCrossentropy'。注意,训练集 shuffle 设置为 true,而验证集 shuffle 设置为 False。当您构建模型时,顶层应有 2 个节点,并且激活应为 softmax。当您使用 model.fit 训练模型时,最好每个时期检查一次验证集。假设在狗猫示例中,您有 1000 张狗图像和 1000 张猫图像,总共 2000 张。75% = 1500 将用于训练,500 将用于验证。如果设置 valid_batch_size=50,则每个时期将需要 10 个步骤来检查所有验证图像。同样,如果 train_batch_size=50,则需要 30 个步骤来完成训练集。运行 model.fit 时,设置steps_per_epoch=30 和validation_steps=10。实际上我更喜欢使用 tf.keras.preprocessing.image.ImageDataGenerator 来生成数据集。它相似但更通用。文档在这里。如果喜欢它,因为它允许您根据需要指定预处理函数,并且还允许您重新调整图像值。通常您希望使用 1/255 作为重新缩放值。
如果你只想分割训练数据,你可以使用 sklearn 中的 train_test_split。文档在这里。,下面的代码展示了如何将其分成训练集、验证集和测试集。假设您需要 80% 的数据用于训练,10% 用于验证,10% 用于测试。假设 X 是 np 图像数组,y 是关联的标签数组。下面的代码显示了分割
from sklearn.model_selection import train_test_split
X_train, X_tv, y_train, y_tv = train_test_split( X, y, train_size=0.8, random_state=42)
X_test, X_valid, y_test, y_valid=train_test_split(X_tv,y_tv, train_size=.5, randon_state=20)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6792 次 |
最近记录: |