原文链接:machinelearningmastery.com/use-pre-tra…
前置条件:
- Windows10操作系统
- 下载并安装Anaconda,配置conda镜像源(国内源)
- 基于Anaconda安装jupyter notebook、tensorflow、keras及其依赖组件
- 使用pip安装keras
- 下载"VGG训练模型":1️⃣从github下载 2️⃣从百度云盘下载(提取码: pbz5)
- 下载"物品分类表":1️⃣从百度网盘下载( 提取码: y8fq )
VGG模型的物品分类结果:
-
有83.12%的几率是“边境牧羊犬”
-
有52.12%的几率是“拖卡”
-
有93.01%的几率是“咖啡杯”
Step1 Anaconda安装与配置
1.1 windows10下Anaconda安装教程
1.2 配置conda镜像源,文件位于:C:\Users\To Kill a MockinBird\.condarc
编辑“.condarc”文件, 插入内容:
channels:
- http://mirrors.ustc.edu.cn/anaconda/pkgs/free/
show_channel_urls: true
ssl_verify: true
report_errors: true
1.3检查Anaconda安装结果
- 进入cmd,执行查看Anaconda版本号:
- 执行指令:
conda -V
注:安装成功则会输出Anaconda的版本号,如有异常请重新安装
Step2 安装jupyter notebook、tensorflow
2.1 基于Anaconda创建独立的python-v3.6环境
目前python37对tensorflow的支持还不是特别友好,推荐使用python3.6版本
运行cmd执行指令:
conda create -n tf-20190930 python=3.6
tf-20190930: 这是自定义的名称
- 创建成功后,可以通过指令查看已创建python运行环境:
conda info --env
2.2 基于独立的python环境安装jupyter的内核ipykernel
- 安装jupyter前,先安装ipykernel,它是jupyter的内核
- 激活独立的python环境:
conda activate tf-20190930
- 安装ipykernel:
conda install ipykernel
2.3 安装jupyter
- 执行指令安装jupyter:
conda install nb_conda
- (非常重要)将ipykernel内核写入jupyte, 执行指令:
python -m ipykernel install --user --name tf-20190930 --display-name 'tf-20190930'
参数 | 描述 |
---|---|
--user | 表示用户名(tf-20190930) |
--name | 表示python独立环境的名称(tf-20190930) |
--display-name | 表示在Jupyter NoteBook中的展示名称(tf-20190930) |
2.4 pip安装keras(keras包含VGG16、VGG19)
- 如果无法直接下载,需要配置pip源,这里我们配置为阿里镜像源
- windows下pip的配置文件位于:
C:\Users\To Kill a MockinBird\pip.ini
(注:文件不存在则在该路径下主动创建)
- Linux下pip的配置文件位于:
/root/.pip/pip.conf
2.5启动Jupyter的两种方式
- 第一种方式,从Anaconda GUI界面启动
- 第二种方式,从cmd命令行启动
- 启动成功
Step3 "VGG模型"、"物品分类表(imagenet_class_index.json)"存放在于指定目录
3.1 预训练模型默认存储路径
- windows10下默认路径:
C:\Users\To Kill a MockinBird\.keras\models
;- Linux下默认路径:
/root/.keras/
3.2 Jupyter新建python程序,通过API调用VGG模型
3.3 调用VGG模型对图片类型进行分类,代码如下:
# 加载VGG16模型
model = VGG16()
from keras.preprocessing.image import load_img
# 加载图像资源,图像默认存储路径:C:\Users\To Kill a MockinBird\dots.jpg
image = load_img('dots.jpg', target_size=(224, 224))
from keras.preprocessing.image import img_to_array
# 将图片像素转换为numpy数组
image = img_to_array(image)
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
from keras.applications.vgg16 import preprocess_input
# prepare the image for the VGG model
image = preprocess_input(image)
# predict the probability across all output classes
yhat = model.predict(image)
from keras.applications.vgg16 import decode_predictions
# convert the probabilities to class labels
label = decode_predictions(yhat)
# retrieve the most likely result, e.g. highest probability
label = label[0][0]
# print the classification
print('分类结果:%s (%.2f%%)' % (label[1], label[2]*100))
3.4 点击“运行”执行VGG卷积神经图像分类
(注:图像存储路径默认在:C:\Users\To Kill a MockinBird\dots.jpg)