Keras函数记录

预处理

直接从文件生成图片数据

  ImageDataGenerator,循环生成图片,在重复生成图片之前,会把所有图片都遍历一遍。而且如果图片总量不是生成批量的倍数的话,在生成重复图片的前一次的批量是不完整的。

import tensorflow as tf
from tensorflow import keras 
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt

datagen = ImageDataGenerator(   #定义生成图片的模式,添加各种变换等,都是在范围内随机
    rotation_range=40,          #图片旋转的范围        
    width_shift_range=0.2,      #图片水平位移的范围
    height_shift_range=0.2,     #图片垂直位移的范围
    shear_range=0.2,            #图片变倾斜的角度
    zoom_range=0.2,             #图片缩放的范围
    horizontal_flip=True,       #50%几率水平镜像
    fill_mode='nearest')         
gener = datagen.flow_from_directory(        #图片数据生成器
    'D:/Datasets/dogs-vs-cats/train/test',  #生成路径。这个文件夹中应该包括各个类别的图片,且每类图片保存在单独的文件夹中
    target_size = (150,150),                #生成图片的尺寸
    batch_size=1,                           #每次生成多少图片数据
    class_mode='binary')                    #生成图片的标签格式,这里只有两类,所以为二元标签,一个标量0或1
for i,j in gener:#生成的是:图片,标签
    i/=255.
    print(j)
    plt.imshow(i[0])
    plt.show() 

模型

显示各层输出

  使用

  activation_model = models.Model( inputs = model.input, outputs = model_outputs)

  来对原模型生成模型,生成的模型预测样本时能输出原模型对应层的计算结果。model.input是原模型model的输入层,model_outputs是这个模型的某些层,可以使用如:

  model_outputs = [l.output for l in model.layers] #返回了原模型的所有层的输出

  来定义。然后

  activation = activation_model.predict(a_input)

  获取某个输入的对应各个层的输出。

你可能感兴趣的:(Keras函数记录)