tensorflow2.x cifar2,mnist,飞机车鸟数据读取

import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator

# 加载cifar2训练集,归一化,四维向量化
image_train = ImageDataGenerator(rescale=1.0/255).flow_from_directory(
    directory='./cifar2/train',#路径
    target_size=(32,32),#目标图像大小
    batch_size=20,#图像多少
    class_mode='binary'#分类模式
)
# 加载cifar2测试集,归一化,四维向量化
image_test = ImageDataGenerator(rescale=1.0/255).flow_from_directory(
    directory='./cifar2/test',
    target_size=(32,32),
    batch_size=20,
    class_mode='binary'
)


model.fit(image_train, epochs=2, validation_data=image_test)
import tensorflow.keras.datasets as dts
from tensorflow.keras import utils

# 数据处理
(train_x, train_y), (test_x, test_y) = dts.mnist.load_data()
#(x_train, y_train), (x_test, y_test) = dts.cifar10.load_data()
#(x_train, y_train), (x_test, y_test) = dts.fashion_mnist.load_data()
# 数据转浮点型
train_x = train_x.astype('float32')
test_x = test_x.astype('float32')
# 像素值归一化
train_x /= 255.0
test_x /= 255.0
# 卷积网只能接收四维向量,(batch, 宽, 高,通道数)
train_x, test_x = train_x.reshape(-1, 28, 28, 1), test_x.reshape(-1, 28, 28, 1)
# 对标签进行one-hot处理
train_y, test_y = utils.to_categorical(train_y, 10), utils.to_categorical(test_y, 10)
import numpy as np
import os
import matplotlib.pyplot as plt
from tensorflow.keras import utils
from sklearn.model_selection import train_test_split

imgdir = './data3/data3'
# 依次读取图像像素值并进行归一化处理
def loadimg(imgpath):
    # 读取图像像素值
    img = plt.imread(imgpath)
    img = img/255.0 # 归一化
    return img
imgs = [] # x
labels = [] # y
for path in os.listdir(imgdir):
    img = loadimg(imgdir + '/' + path)
    imgs.append(img)
    labels.append(int(path[0]))
# labels = utils.to_categorical(labels, 3)
# train_test_split只接受numpy.array类
imgs = np.array(imgs)
labels = np.array(labels)
train_x, test_x, train_y, test_y = train_test_split(imgs, labels, train_size=0.7, shuffle=True)

你可能感兴趣的:(tensorflow,深度学习,python)