文章目录

  • ML、DL、CNN学习记录3
    • Transfer Learning

ML、DL、CNN学习记录3

# coding: utf-8
# Date:2020/8/15 19:16
# @Author: hcf
# @Name: layer_name_intro
import osimport numpy as np
import pandas as pd# import keras
import tensorflow.keras as keras# 序贯模型
from keras.models import Sequential, Model
# 模型的层
from tensorflow.python.keras.layers import Conv2D, MaxPool2D, Flatten, ReLU, Dense
# 数据集合
from keras.datasets import mnist
"""
from . import mnist
from . import imdb
from . import reuters
from . import cifar10
from . import cifar100
from . import boston_housing
from . import fashion_mnist
"""
# 加载已经训练完成的模型
from tensorflow.python.keras.models import load_model
# 梯度下降方法
from tensorflow.python.keras.optimizer_v2.gradient_descent import SGD
# one-hot 编码
from tensorflow.python.keras.utils.np_utils import to_categorical
# 图片读取,写入(op)
import cv2
# 交叉熵
from tensorflow.python.keras.losses import categorical_crossentropyif __name__ == '__main__':# 加载的数据在c盘的 .keras文件夹中# 训练集:60 000# 测试集:10 000(x_train,y_train), (x_test,y_test) = mnist.load_data()# print(x_train)# print(type(x_train))# print(x_train.shape)# ==================================# 数据预处理# ==================================# 每张图的结构 (28,28) ==> (28,28,1)# 所以需要进行转换x_train = x_train.reshape((-1, 28, 28, 1))x_test = x_test.reshape((-1, 28, 28, 1))# 数据类型的one-hot编码# 1            2            3           4          ... 10# 1000000000   010000000    0010000000  0001000000 ... 0000000001y_train = to_categorical(y_train)y_test = to_categorical(y_test)''' 进行数据处理output_path = 'mnist/'if not os.path.exists(output_path):os.makdir(output_path)m,w,h = x_train.shapefor i in range(m):img = x_train[i]c = y_train[i]if not os.path.exists():img_path = os.path.join(output_path, str(c))os.mkdir(img_path)img_path = os.path.join(output_path, str(c))cv2.imwrite(img_path + str(i)+'.png',img)'''# =================================================# 模型建立# =================================================# 判断模型是否已经存在后if os.path.exists('model_mnist.h5'):print('加载模型!!!')model = load_model('model_mnist.h5')else:# 代表序贯模型model = Sequential()# Image(28,28,1)# filter: 过滤器 ==> 生成的下一层通道数目# 卷积核大小 kernel_size = 5  ==> (5, 5)# 激活函数activation = relu# 初始的输入层 才需要设置 input_shape=(28, 28, 1)model.add(Conv2D(filters=6, kernel_size=5, padding='same', activation='relu', input_shape=(28, 28, 1)))# padding 是否增加 全零model.add(MaxPool2D(pool_size=(2, 2), padding='same'))# 一个二维的卷积层conv_layer = Conv2D(filters=16, kernel_size=5, padding='same', activation='relu')# 可以设置  让这一层不进行训练conv_layer.trainable = Falsemodel.add(conv_layer)# padding 是否增加 全零model.add(MaxPool2D(pool_size=(2, 2), padding='same'))# 拉平(向量化)model.add(Flatten())# 全连接model.add(Dense(64, activation='relu'))# 主义数据需要 one-hot编码model.add(Dense(10, activation='softmax'))print('model structure')# 打印网络模型信息model.summary()# ================================# 模型训练# ================================# 给定损失函数, 损失函数用于判断模型工作好不好的,决定了模型结果的好坏# 交叉熵 = cross Entropy  =  -ln(y_pred(yi))# loss = -sum(y_pred(yi))# For example :# 误差损失平方和 loss = sum(yi- yi_pred)**2#     0    0     1    0     预测结果  交叉熵# P1  0.1  0.2  0.4  0.3    Yes      -ln0.4# P2  0.01 0.02 0.90 0.07   Yes      -ln0.9# 但是 P2 的效果更好,# 损失loss:交叉熵# 优化器SGD:梯度下降#       epoch 一个 epoch 中有若干个 batch#       梯度下降是每个batch中进行梯度下降# metrics: 准确率model.compile(loss=categorical_crossentropy, optimizer=SGD(lr=0.001), metrics=['acc'])# epochs=10 : 训练多少轮# batch_size=128: 每轮训练中将 128 个当做一批# model.fit(x_train, y_train, batch_size=128, epochs=10, validation_split=[x_test,y_test]])history = model.fit(x_train, y_train, batch_size=128, epochs=10, validation_split=0.1)# 可以打印结果,print(history.history)model.save('model_mnist.h5')# y_test_pred = model.predict(x_test)result =model.evaluate(x_test, y_test)print('测试结果:', result)# ================================================================================# 访问模型隐层# ================================================================================from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictionsfrom keras.preprocessing import imagebase_model = modelimg_path = 'son.png'output_path = './Layer/'img = image.load_img(img_path, target_size=(224,224))x = image.img_to_array(img)x = np.expand_dims(x, axis=0)x = preprocess_input(x)if not os.path.exists(output_path):os.mkdir(output_path)# 遍历模型的每一层for layer in base_model.layers:# 打印层信息# <tensorflow.python.keras.layers.convolutional.Conv2D object at 0x000001F2DC259828>print(layer)layer_path_name = os.path.join(output_path, layer.name)# 打印层名print(layer_path_name)if not os.path.exists(layer_path_name):os.mkdir(layer_path_name)# 将某一隐藏层作为模型的输出model = Model(inputs=base_model.input, outputs=layer.output)# 进行图片预测feature_maps = model.predict(x[:, :, 0])[0]if len(feature_maps.shape) < 2:continue# 获取这一层的通道数目channel_size = feature_maps.shape[2]for c in range(channel_size):# 获取某一通道的图像feature_map = feature_maps[:, :, c]# 最大最小值得差 大于0.1时候if np.ptp(feature_map) > 0.1:feature_map = 255*(feature_map - np.min(feature_map)) / np.ptp(feature_map)  # 将255改成其他值,看相应结果feature_map_path = os.path.join(output_path, layer.name, str(c+1)+'.jpg')# 存储 layer 层,第 c 个通道的图像cv2.imwrite(feature_map_path, feature_map)print('='*40)

model.summary()

Transfer Learning

使用已经存在的模型处理自己的问题,模型的改造

# include_top=True 考虑最后的全连接
# include_top=False 不考虑后面的全连接
model = ResNet50(weights='imagenet', include_top=False)

Input:

输入必须是模型的设定的大小
output:

需要有自己的输出,所以一般来说不需要之前模型的全连接Dense层。

ML、DL、CNN学习记录3相关推荐

  1. ML、DL、CNN学习记录8

    文章目录 ML.DL.CNN学习记录7 强化学习 Makov 贝尔曼方程 Value-Based 知识图谱 图神经网络 ML.DL.CNN学习记录7 强化学习(Reinforcement Learni ...

  2. ML、DL、CNN学习记录7

    文章目录 ML.DL.CNN学习记录7 GAN(Generative Adversarial Network) GAN的学习 GAN的损失函数 GAN 训练 GAN的扩展 DCGAN CGAN Sta ...

  3. ML、DL、CNN学习记录6

    文章目录 ML.DL.CNN学习记录5 VAE VAE 工作流程 VAE's Detail code+explain Model Output GAN GAN原理 CRNN(多用于文字识别) ML.D ...

  4. ML、DL、CNN学习记录5

    文章目录 ML.DL.CNN学习记录4 RNN RNN类别 Word 表示 编码 10000dim - 100dim RNN基本运算 imdb 文本生成模型 模型示例 ML.DL.CNN学习记录4 T ...

  5. ML、DL、CNN学习记录2

    文章目录 ML.DL.CNN学习记录2 图片通道 CNN 卷积 卷积如何操作 卷积核大小 卷积的意义 卷积后大小 卷积后大小计算公式(占的内存) 卷积后大小计算公式(运算时间) 1x1的卷积核 激活函 ...

  6. ml dl el学习_DeepChem —在生命科学和化学信息学中使用ML和DL的框架

    ml dl el学习 Application of Machine Learning and Deep Learning for Drug Discovery, Genomics, Microsoco ...

  7. ML、DL、CNN学习记录1

    文章目录 ML.DL学习记录1 ML .sklearn Tensorflow2.2.0安装问题 ML.DL学习记录1 ML .sklearn # coding: utf-8 # Date:2020/8 ...

  8. DL/T645-2007通信协议指令学习记录

    DL/T645-2007通信协议指令学习记录 DL/T645协议版本 DL/T645通信链路 DL/T645-2007数据格式 地址域 控制码C 数据长度L 数据域 DATA 校验码 CS 数据标识 ...

  9. python/ML/DL学习目录

    第一部分:python语法学习 . /*******环境搭建************/ 1. Anaconda安装 2. Anaconda的使用 3. Spyder的使用中遇到的问题 4. Jupyt ...

最新文章

  1. 王高利:awstats
  2. 如何迁移#SNMP到.NET Core平台的一些体会
  3. linux 进程调度源码分析,Linux调度器源码分析
  4. Python赋值与深浅拷贝
  5. ios 如何在cell中去掉_iOS开发:关于 去除UITableViewCell复用机制 的几种方法
  6. 用Winhex软件定位NTFS文件系统的不明白之处
  7. python dynamic array
  8. win7系统中任务计划程序的使用与查询
  9. 先一XDB实时数据库采集
  10. U盘空间明明够大,为什么却放不进去文件
  11. 导入 xlsx php,php如何使用phpexcel类导入excel表格数据
  12. PLC通讯实现-C#实现AB5000 PLC以太网通讯DTL32(八)
  13. autojs免root脚本引擎开发的QQ空间说说点赞源码
  14. 如何在 iPhone 上恢复已删除的短信
  15. postman 9.16 打不开怎么办
  16. 奔图P3022D黑白激光打印机 评测
  17. word 插入图片显示不全
  18. 模棱两可的生物学概念问题辨析1
  19. Android Paint的使用详解
  20. [Unity3D]Node-Canvas入门案例

热门文章

  1. android7 编译配置摄像头,MTK平台新增摄像头指南 -- 已更新android 7.0路径的更改。...
  2. 20165236 2017-2018-2 《Java程序设计》结对编程练习_四则运算
  3. [BZOJ5286][洛谷P4425][HNOI2018]转盘(线段树)
  4. 20145226夏艺华 《Java程序设计》实验报告一
  5. 庆五一,We7同步发行2.5正式版、2.6 Beta版!
  6. 用Visual C#实现文件下载
  7. java 试题 历届试题 单词分析 题解
  8. (19)Verilog HDL顺序块:begin-end
  9. FPGA设计注意事项
  10. (10)SPI发送verilog与Systemverilog编码