Keras可以使用的现有模型

官网:https://keras.io/api/applications/

一些使用的列子:

 ResNet50:分类预测

import keras
from keras.applications.resnet50 import ResNet50
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np

model = ResNet50(weights='imagenet')

img_path = 'elephant.jpg'
img = keras.utils.load_img(img_path, target_size=(224, 224))
x = keras.utils.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

preds = model.predict(x)
# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print('Predicted:', decode_predictions(preds, top=3)[0])
# Predicted: [(u'n02504013', u'Indian_elephant', 0.82658225), (u'n01871265', u'tusker', 0.1122357), (u'n02504458', u'African_elephant', 0.061040461)]

VGG16:用作特征提取器时,不需要最后的全连接层,所以实例化模型时参数 include_top=False

import keras
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input
import numpy as np

model = VGG16(weights='imagenet', include_top=False)

img_path = 'elephant.jpg'
img = keras.utils.load_img(img_path, target_size=(224, 224))
x = keras.utils.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

features = model.predict(x)

网上例子解释:

from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import decode_predictions
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
from keras.utils.vis_utils import plot_model
import numpy as np

#加载VGG16模型,这里指定weights='imagenet'来自动下载并加载预训练的模型参数
model = VGG16(weights='imagenet', include_top=True);
image_path = 'E:/dog.jpg';
#加载图片,并且接企鹅为224*224
img = image.load_img(image_path, target_size=(224, 224));
#图片转为array格式
x = image.img_to_array(img)
#假设有一张灰度图,读取之后的shape是( 360, 480),而模型的输入要求是( 1, 360 , 480 ) 或者是 ( 360 , 480 ,1 ),
# 那么可以通过np.expand_dims(a,axis=0)或者np.expand_dims(a,axis=-1)将形状改变为满足模型的输入
x = np.expand_dims(x, axis=0)
#对数据进行归一化处理x/255
x = preprocess_input(x)

#放入模型预测
features = model.predict(x)
#decode_predictions() 用于解码ImageNet模型的预测结果,一般带两个参数:features表示输入批处理的预测,top默认是5,设置3表示返回3个概率最大的值
result = decode_predictions(features, top=3)

#展示结果,并且保存图片
plot_model(model, 'E:/model.png', show_shapes=True)
print(result)

VGG19:

from keras.applications.vgg19 import VGG19
from keras.applications.vgg19 import preprocess_input
from keras.models import Model
import numpy as np

base_model = VGG19(weights='imagenet')
model = Model(inputs=base_model.input, outputs=base_model.get_layer('block4_pool').output)

img_path = 'elephant.jpg'
img = keras.utils.load_img(img_path, target_size=(224, 224))
x = keras.utils.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

block4_pool_features = model.predict(x)

Fine-tune InceptionV3:微调训练一个新类别

from keras.applications.inception_v3 import InceptionV3
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D

# create the base pre-trained model
base_model = InceptionV3(weights='imagenet', include_top=False)

# add a global spatial average pooling layer
x = base_model.output
x = GlobalAveragePooling2D()(x)
# let's add a fully-connected layer
x = Dense(1024, activation='relu')(x)
# and a logistic layer -- let's say we have 200 classes
predictions = Dense(200, activation='softmax')(x)

# this is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)

# first: train only the top layers (which were randomly initialized)
# i.e. freeze all convolutional InceptionV3 layers
for layer in base_model.layers:
    layer.trainable = False

# compile the model (should be done *after* setting layers to non-trainable)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')

# train the model on the new data for a few epochs
model.fit(...)

# at this point, the top layers are well trained and we can start fine-tuning
# convolutional layers from inception V3. We will freeze the bottom N layers
# and train the remaining top layers.

# let's visualize layer names and layer indices to see how many layers
# we should freeze:
for i, layer in enumerate(base_model.layers):
   print(i, layer.name)

# we chose to train the top 2 inception blocks, i.e. we will freeze
# the first 249 layers and unfreeze the rest:
for layer in model.layers[:249]:
   layer.trainable = False
for layer in model.layers[249:]:
   layer.trainable = True

# we need to recompile the model for these modifications to take effect
# we use SGD with a low learning rate
from keras.optimizers import SGD
model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy')

# we train our model again (this time fine-tuning the top 2 inception blocks
# alongside the top Dense layers
model.fit(...)

Build InceptionV3:自定义tensor,输入V3

from keras.applications.inception_v3 import InceptionV3
from keras.layers import Input

# this could also be the output a different Keras model or layer
input_tensor = Input(shape=(224, 224, 3))

model = InceptionV3(input_tensor=input_tensor, weights='imagenet', include_top=True)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/394080.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

基于scrapy框架的单机爬虫与分布式爬虫

我们知道,对于scrapy框架来说,不仅可以单机构建复杂的爬虫项目,还可以通过简单的修改,将单机版爬虫改为分布式的,大大提高爬取效率。下面我就以一个简单的爬虫案例,介绍一下如何构建一个单机版的爬虫&#…

修改vue-layer中title

左侧目录树点击时同步目录树名称 试了很多方法 layer.title(新标题,index)不知道为啥不行 最后用了获取html树来修改了 watch: {$store.state.nowTreePath: function(newVal, oldVal) {if (document.querySelectorAll(".lv-title") && document.q…

AD高速板常见问题和过流自锁

可以使用电机减速器来增大电机的扭矩,低速运行的步进电机更要加上减速机 减速电机就是普通电机加上了减速箱,这样便降低了转速增大了扭矩 HDMI布线要求: 如要蛇形使其等长,不要在HDMI的一端绕线。 HDMI走线时两边拉线&#xff0…

见智未来:数据可视化引领智慧城市之潮

在数字时代的浪潮中,数据可视化崭露头角,为打造智慧城市注入了强大的活力。不再被深奥的数据所束缚,我们通过数据可视化这一工具,可以更加接近智慧城市的未来。下面我就以可视化从业者的角度来简单聊聊这个话题。 数据可视化首先为…

wps快速生成目录及页码设置(自备)

目录 第一步目录整理 标题格式设置 插入页码(罗马和数字) 目录生成(从罗马尾页开始) ​编辑目录格式修改 第一步目录整理 1罗马标题 2罗马标题1一级标题 1.1 二级标题 1.2二级标题2一级标题 2.1 二级标题 2.2二级标题3一级标…

HTML5+CSS3+JS小实例:锥形渐变彩虹按钮

实例:锥形渐变彩虹按钮 技术栈:HTML+CSS+JS 效果: 源码: 【HTML】 <!DOCTYPE html> <html lang="zh-CN"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /…

【ansible】认识ansible,了解常用的模块

目录 一、ansible是什么&#xff1f; 二、ansible的特点&#xff1f; 三、ansible与其他运维工具的对比 四、ansible的环境部署 第一步&#xff1a;配置主机清单 第二步&#xff1a;完成密钥对免密登录 五、ansible基于命令行完成常用的模块学习 模块1&#xff1a;comma…

huggingface库LocalTokenNotFoundError:需要提供token

今天刚开始学习huggingface&#xff0c;跑示例的时候出了不少错&#xff0c;在此记录一下&#xff1a; (gpu) F:\transformer\transformers\examples\pytorch\image-classification>.\run.bat Traceback (most recent call last):File "F:\transformer\transformers\e…

6.s081 学习实验记录(七)Multithreading

文章目录 一、Uthread: switching between threads简介提示实验代码实验结果 二、Using threads简介实验代码 三、Barrier简介实验代码实验结果 一、Uthread: switching between threads 简介 切换到 thread 分支 git fetchgit checkout threadmake clean 实现用户态线程的…

SHOT特征描述符、对应关系可视化以及ICP配准

一、SHOT特征描述符可视化 C #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/search/kdtree.h> #include <pcl/io/pcd_io.h> #include <pcl/features/normal_3d_omp.h>//使用OMP需要添加的头文件 #include <boo…

考完PMP如何让学习价值最大化?考PRINCE2!

01什么是PRINCE2 PRINCE2的全称是Project IN Controlled Environment。也就是受控环境下的项目管理&#xff0c;国际项目管理师认证&#xff0c;在国际上被称为王者认证。PRINCE2描述了如何以一种逻辑性的、有组织的方法&#xff0c;按照明确的步骤对项目进行管理。 95%以上全…

软件实例分享,酒店酒水寄存管理系统软件教程

软件实例分享&#xff0c;酒店酒水寄存管理系统软件教程 一、前言 以下软件教程以 佳易王酒水寄存管理系统软件V16.0为例说明 软件文件下载可以点击最下方官网卡片——软件下载——试用版软件下载 1、寄存的商品名称可以预先设置 2、寄存人可以使用手.机号识别 3、会员充值…

C#,计算几何,贝塞耳插值(Bessel‘s interpolation)的算法与源代码

Friedrich Wilhelm Bessel 1 贝塞耳插值&#xff08;Bessels interpolation&#xff09; 首先要区别于另外一个读音接近的插值算法&#xff1a;贝塞尔插值&#xff08;Bzier&#xff09;。 &#xff08;1&#xff09;读音接近&#xff0c;但不是一个人&#xff1b; &#x…

嵌入式调试工具之GDB

在单片机开发中&#xff0c;我们可以通过集成式的IDE 来进行调试&#xff0c;比如 MDK、IAR 等。 GDB 工具是 GNU 项目调试器&#xff0c;基于命令行使用。和其他的调试器一样&#xff0c;可使用 GDB工具单步运行程序、单步执行、跳入/跳出函数、设置断点、查看变量等等&#…

基于SSM的宁夏旅游网站平台(有报告)。Javaee项目。ssm项目。

演示视频&#xff1a; 基于SSM的宁夏旅游网站平台&#xff08;有报告&#xff09;。Javaee项目。ssm项目。 项目介绍&#xff1a; 采用M&#xff08;model&#xff09;V&#xff08;view&#xff09;C&#xff08;controller&#xff09;三层体系结构&#xff0c;通过Spring …

《苍穹外卖》知识梳理P11-Apache POI导出报表

一.Apache POI 可以通过Apache POI处理excel文件&#xff0c;核心操作是读和写 应用场景 银行网银交易明细各种业务系统导出Excel报表批量导入业务数据 使用步骤 1.导入maven坐标 <dependency><groupId>org.apache.poi</groupId><artifactId>poi&…

使用C++,实现高精度加减乘除法运算!

我的个人主页 {\large \mathsf{{\color{Red} 我的个人主页} } } 我的个人主页 我的专栏&#xff1a; \mathcal{{\color{Green} 我的专栏&#xff1a;} } 我的专栏&#xff1a; 《精选文章》《算法》《每日一道编程题》《高精度算法》 文章目录 前言高精度计算初始模版string 转…

游泳听音乐最好的耳机推荐,游泳防水耳机排行榜推荐

在当今社会&#xff0c;随着人民生活水平的不断提高&#xff0c;人们对健康生活的追求也越来越高。运动成为了人们日常生活中不可或缺的一部分&#xff0c;而游泳作为一种全身性的锻炼方式&#xff0c;更是受到了广大人群的喜爱。然而&#xff0c;对于音乐爱好者来说&#xff0…

【机构vip教程】​python(1):python正则表达式匹配指定的字符开头和指定的字符结束

一&#xff0c;使用python的re.findall函数&#xff0c;匹配指定的字符开头和指定的字符结束 代码示例&#xff1a; 1 import re 2 # re.findall函数;匹配指定的字符串开头和指定的字符串结尾(前后不包含指定的字符串) 3 str01 hello word 4 str02 re.findall((?<e).*?…

Java学习笔记------static

static 创建Javabean类 public class student {private int age;private String name;private String gender;public student() {}public student(int age, String name, String gender) {this.age age;this.name name;this.gender gender;}/*** 获取* return age*/public…