ImageDataGenerator的参数自己看文档
from keras.preprocessing import image import numpy as np X_train=np.ones((3,123,123,1)) Y_train=np.array([[1],[2],[2]]) generator=image.ImageDataGenerator(featurewise_center=False, samplewise_center=False, featurewise_std_normalization=False, samplewise_std_normalization=False, zca_whitening=False, zca_epsilon=1e-6, rotation_range=180, width_shift_range=0.2, height_shift_range=0.2, shear_range=0, zoom_range=0.001, channel_shift_range=0, fill_mode='nearest', cval=0., horizontal_flip=True, vertical_flip=True, rescale=None, preprocessing_function=None, data_format='channels_last') a=generator.flow(X_train,Y_train,batch_size=20)#生成的是一个迭代器,可直接用于for循环 ''' batch_size如果小于X的第一维m,next生成的多维矩阵的第一维是为batch_size,输出是从输入中随机选取batch_size个数据 batch_size如果大于X的第一维m,next生成的多维矩阵的第一维是m,输出是m个数据,不过顺序随机 ,输出的X,Y是一一对对应的 如果要直接用于tf.placeholder(),要求生成的矩阵和要与tf.placeholder相匹配 ''' X,Y=next(a) print(Y) X,Y=next(a) print(Y) X,Y=next(a) print(Y) X,Y=next(a)
输出
[[2] [1] [2]] [[2] [2] [1]] [[2] [2] [1]] [[2] [2] [1]]
补充知识:tensorflow 与keras 混用之坑
在使用tensorflow与keras混用是model.save 是正常的但是在load_model的时候报错了在这里mark 一下
其中错误为:TypeError: tuple indices must be integers, not list
再一一番百度后无结果,上谷歌后找到了类似的问题。但是是一对鸟文不知道什么东西(翻译后发现是俄文)。后来谷歌翻译了一下找到了解决方法。故将原始问题文章贴上来警示一下
原训练代码
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator from tensorflow.python.keras.models import Sequential from tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalization from tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense #Каталог с данными для обучения train_dir = 'train' # Каталог с данными для проверки val_dir = 'val' # Каталог с данными для тестирования test_dir = 'val' # Размеры изображения img_width, img_height = 800, 800 # Размерность тензора на основе изображения для входных данных в нейронную сеть # backend Tensorflow, channels_last input_shape = (img_width, img_height, 3) # Количество эпох epochs = 1 # Размер мини-выборки batch_size = 4 # Количество изображений для обучения nb_train_samples = 300 # Количество изображений для проверки nb_validation_samples = 25 # Количество изображений для тестирования nb_test_samples = 25 model = Sequential() model.add(Conv2D(32, (7, 7), padding="same", input_shape=input_shape)) model.add(BatchNormalization()) model.add(Activation('tanh')) model.add(MaxPooling2D(pool_size=(10, 10))) model.add(Conv2D(64, (5, 5), padding="same")) model.add(BatchNormalization()) model.add(Activation('tanh')) model.add(MaxPooling2D(pool_size=(10, 10))) model.add(Flatten()) model.add(Dense(512)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer="Nadam", metrics=['accuracy']) print(model.summary()) datagen = ImageDataGenerator(rescale=1. / 255) train_generator = datagen.flow_from_directory( train_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical') val_generator = datagen.flow_from_directory( val_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical') test_generator = datagen.flow_from_directory( test_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical') model.fit_generator( train_generator, steps_per_epoch=nb_train_samples // batch_size, epochs=epochs, validation_data=val_generator, validation_steps=nb_validation_samples // batch_size) print('Сохраняем сеть') model.save("grib.h5") print("Сохранение завершено!")
模型载入
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator from tensorflow.python.keras.models import Sequential from tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalization from tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense from keras.models import load_model print("Загрузка сети") model = load_model("grib.h5") print("Загрузка завершена!")
报错
/usr/bin/python3.5 /home/disk2/py/neroset/do.py /home/mama/.local/lib/python3.5/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters Using TensorFlow backend. Загрузка сети Traceback (most recent call last): File "/home/disk2/py/neroset/do.py", line 13, in <module> model = load_model("grib.h5") File "/usr/local/lib/python3.5/dist-packages/keras/models.py", line 243, in load_model model = model_from_config(model_config, custom_objects=custom_objects) File "/usr/local/lib/python3.5/dist-packages/keras/models.py", line 317, in model_from_config return layer_module.deserialize(config, custom_objects=custom_objects) File "/usr/local/lib/python3.5/dist-packages/keras/layers/__init__.py", line 55, in deserialize printable_module_name='layer') File "/usr/local/lib/python3.5/dist-packages/keras/utils/generic_utils.py", line 144, in deserialize_keras_object list(custom_objects.items()))) File "/usr/local/lib/python3.5/dist-packages/keras/models.py", line 1350, in from_config model.add(layer) File "/usr/local/lib/python3.5/dist-packages/keras/models.py", line 492, in add output_tensor = layer(self.outputs[0]) File "/usr/local/lib/python3.5/dist-packages/keras/engine/topology.py", line 590, in __call__ self.build(input_shapes[0]) File "/usr/local/lib/python3.5/dist-packages/keras/layers/normalization.py", line 92, in build dim = input_shape[self.axis] TypeError: tuple indices must be integers or slices, not list Process finished with exit code 1
战斗种族解释
убераю BatchNormalization всё работает хорошо. Не подскажите в чём ошибка"htmlcode">
keras.preprocessing.image import ImageDataGenerator keras.models import Sequential keras.layers import Conv2D, MaxPooling2D, BatchNormalization keras.layers import Activation, Dropout, Flatten, Dense
##完美解决
##附上原文链接
https://qa-help.ru/questions/keras-batchnormalization
以上这篇keras的ImageDataGenerator和flow()的用法说明就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新动态
- 凤飞飞《我们的主题曲》飞跃制作[正版原抓WAV+CUE]
- 刘嘉亮《亮情歌2》[WAV+CUE][1G]
- 红馆40·谭咏麟《歌者恋歌浓情30年演唱会》3CD[低速原抓WAV+CUE][1.8G]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[320K/MP3][193.25MB]
- 【轻音乐】曼托凡尼乐团《精选辑》2CD.1998[FLAC+CUE整轨]
- 邝美云《心中有爱》1989年香港DMIJP版1MTO东芝首版[WAV+CUE]
- 群星《情叹-发烧女声DSD》天籁女声发烧碟[WAV+CUE]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[FLAC/分轨][748.03MB]
- 理想混蛋《Origin Sessions》[320K/MP3][37.47MB]
- 公馆青少年《我其实一点都不酷》[320K/MP3][78.78MB]
- 群星《情叹-发烧男声DSD》最值得珍藏的完美男声[WAV+CUE]
- 群星《国韵飘香·贵妃醉酒HQCD黑胶王》2CD[WAV]
- 卫兰《DAUGHTER》【低速原抓WAV+CUE】
- 公馆青少年《我其实一点都不酷》[FLAC/分轨][398.22MB]
- ZWEI《迟暮的花 (Explicit)》[320K/MP3][57.16MB]