机器学习环境配置系列五之keras2
keras一个大坑就是配置文件的问题,网上会给很多的误导,让我走了很多弯路。
1、安装keras2
conda install keras
2、环境配置
echo ‘{
"epsilon": 1e-07,
"floatx": "float32",
"image_data_format": "channels_last",
"backend": "theano"
}’> ~/.keras/keras.json
如果用的tensorflow,backend要更换为tensorflow这个变量
3、问题说明
关于环境配置网上大多是1.几的版本,这个与2点几的版本有很大的区别,请大家一定注意。并且keras上了2这个版本后,代码也出现了很多的变化。下面就是对vgg16.py代码关于python2.7+keras2的代码更新
from __future__ import division, print_function import os, json
from glob import glob
import numpy as np
from scipy import misc, ndimage
from scipy.ndimage.interpolation import zoom from keras import backend as K
from keras.layers.normalization import BatchNormalization
from keras.utils.data_utils import get_file
from keras.models import Sequential
from keras.layers.core import Flatten, Dense, Dropout, Lambda
#from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.layers.convolutional import Conv2D, MaxPooling2D, ZeroPadding2D # Conv2D: Keras2
from keras.layers.pooling import GlobalAveragePooling2D
from keras.optimizers import SGD, RMSprop, Adam
from keras.preprocessing import image # In case we are going to use the TensorFlow backend we need to explicitly set the Theano image ordering
from keras import backend as K
K.set_image_dim_ordering('th') vgg_mean = np.array([123.68, 116.779, 103.939], dtype=np.float32).reshape((3,1,1))
def vgg_preprocess(x):
"""
Subtracts the mean RGB value, and transposes RGB to BGR.
The mean RGB was computed on the image set used to train the VGG model. Args:
x: Image array (height x width x channels)
Returns:
Image array (height x width x transposed_channels)
"""
x = x - vgg_mean
return x[:, ::-1] # reverse axis rgb->bgr class Vgg16():
"""
The VGG 16 Imagenet model
""" def __init__(self):
self.FILE_PATH = 'http://files.fast.ai/models/'
self.create()
self.get_classes() def get_classes(self):
"""
Downloads the Imagenet classes index file and loads it to self.classes.
The file is downloaded only if it not already in the cache.
"""
fname = 'imagenet_class_index.json'
fpath = get_file(fname, self.FILE_PATH+fname, cache_subdir='models')
with open(fpath) as f:
class_dict = json.load(f)
self.classes = [class_dict[str(i)][1] for i in range(len(class_dict))] def predict(self, imgs, details=False):
"""
Predict the labels of a set of images using the VGG16 model. Args:
imgs (ndarray) : An array of N images (size: N x width x height x channels).
details : ?? Returns:
preds (np.array) : Highest confidence value of the predictions for each image.
idxs (np.ndarray): Class index of the predictions with the max confidence.
classes (list) : Class labels of the predictions with the max confidence.
"""
# predict probability of each class for each image
all_preds = self.model.predict(imgs)
# for each image get the index of the class with max probability
idxs = np.argmax(all_preds, axis=1)
# get the values of the highest probability for each image
preds = [all_preds[i, idxs[i]] for i in range(len(idxs))]
# get the label of the class with the highest probability for each image
classes = [self.classes[idx] for idx in idxs]
return np.array(preds), idxs, classes def ConvBlock(self, layers, filters):
"""
Adds a specified number of ZeroPadding and Covolution layers
to the model, and a MaxPooling layer at the very end. Args:
layers (int): The number of zero padded convolution layers
to be added to the model.
filters (int): The number of convolution filters to be
created for each layer.
"""
model = self.model
for i in range(layers):
model.add(ZeroPadding2D((1, 1)))
# model.add(Convolution2D(filters, 3, 3, activation='relu'))
model.add(Conv2D(filters, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2))) def FCBlock(self):
"""
Adds a fully connected layer of 4096 neurons to the model with a
Dropout of 0.5 Args: None
Returns: None
"""
model = self.model
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5)) def create(self):
"""
Creates the VGG16 network achitecture and loads the pretrained weights. Args: None
Returns: None
"""
model = self.model = Sequential()
model.add(Lambda(vgg_preprocess, input_shape=(3,224,224), output_shape=(3,224,224))) self.ConvBlock(2, 64)
self.ConvBlock(2, 128)
self.ConvBlock(3, 256)
self.ConvBlock(3, 512)
self.ConvBlock(3, 512) model.add(Flatten())
self.FCBlock()
self.FCBlock()
model.add(Dense(1000, activation='softmax')) fname = 'vgg16.h5'
model.load_weights(get_file(fname, self.FILE_PATH+fname, cache_subdir='models')) def get_batches(self, path, gen=image.ImageDataGenerator(), shuffle=True, batch_size=8, class_mode='categorical'):
"""
Takes the path to a directory, and generates batches of augmented/normalized data. Yields batches indefinitely, in an infinite loop. See Keras documentation: https://keras.io/preprocessing/image/
"""
return gen.flow_from_directory(path, target_size=(224,224),
class_mode=class_mode, shuffle=shuffle, batch_size=batch_size) def ft(self, num):
"""
Replace the last layer of the model with a Dense (fully connected) layer of num neurons.
Will also lock the weights of all layers except the new layer so that we only learn
weights for the last layer in subsequent training. Args:
num (int) : Number of neurons in the Dense layer
Returns:
None
"""
model = self.model
model.pop()
for layer in model.layers: layer.trainable=False
model.add(Dense(num, activation='softmax'))
self.compile() def finetune(self, batches): self.ft(batches.num_classes)
classes = list(iter(batches.class_indices)) # get a list of all the class labels # batches.class_indices is a dict with the class name as key and an index as value
# eg. {'cats': 0, 'dogs': 1} # sort the class labels by index according to batches.class_indices and update model.classes
for c in batches.class_indices:
classes[batches.class_indices[c]] = c
self.classes = classes def compile(self, lr=0.001):
"""
Configures the model for training.
See Keras documentation: https://keras.io/models/model/
"""
self.model.compile(optimizer=Adam(lr=lr),
loss='categorical_crossentropy', metrics=['accuracy']) def fit_data(self, trn, labels, val, val_labels, nb_epoch=1, batch_size=64):
"""
Trains the model for a fixed number of epochs (iterations on a dataset).
See Keras documentation: https://keras.io/models/model/
"""
#self.model.fit(trn, labels, nb_epoch=nb_epoch,
# validation_data=(val, val_labels), batch_size=batch_size)
self.model.fit(trn, labels, epochs=nb_epoch,
validation_data=(val, val_labels), batch_size=batch_size) #def fit(self, batches, val_batches, nb_epoch=1):
def fit(self, batches, val_batches, batch_size, nb_epoch=1):
"""
Fits the model on data yielded batch-by-batch by a Python generator.
See Keras documentation: https://keras.io/models/model/
"""
#self.model.fit_generator(batches, samples_per_epoch=batches.nb_sample, nb_epoch=nb_epoch,
# validation_data=val_batches, nb_val_samples=val_batches.nb_sample)
self.model.fit_generator(batches, steps_per_epoch=int(np.ceil(batches.samples/batch_size)), epochs=nb_epoch,
validation_data=val_batches, validation_steps=int(np.ceil(val_batches.samples/batch_size))) def test(self, path, batch_size=8):
"""
Predicts the classes using the trained model on data yielded batch-by-batch. Args:
path (string): Path to the target directory. It should contain one subdirectory
per class.
batch_size (int): The number of images to be considered in each batch. Returns:
test_batches, numpy array(s) of predictions for the test_batches. """
test_batches = self.get_batches(path, shuffle=False, batch_size=batch_size, class_mode=None)
#return test_batches, self.model.predict_generator(test_batches, test_batches.nb_sample)
return test_batches, self.model.predict_generator(test_batches, int(np.ceil(test_batches.samples/batch_size)))
机器学习环境配置系列五之keras2的更多相关文章
- 机器学习环境配置系列四之theano
决定撰写机器学习环境配置的主要原因就是因为theano的配置问题,为了能够用上gpu和cudnn加速,我是费劲了力气,因为theano1.0.0在配置方面出现了重大改变,而网上绝大多数都很老,无法解决 ...
- 机器学习环境配置系列三之Anaconda
1.下载Anaconda文件 进入anaconda的官网 选择对应的系统 选择希望下载的版本(本人下载的是Anaconda 5.3 For Linux Installer Python 3.7 ver ...
- 机器学习环境配置系列一之CUDA
本文配置的环境为redhat6.9+cuda10.0+cudnn7.3.1+anaonda6.7+theano1.0.0+keras2.2.0+jupyter远程,其中cuda的版本为10.0. 第一 ...
- 机器学习环境配置系列二之cuDNN
1.下载cuDNN 前往: NVIDIA cuDNN home page. 进入下载 勾选Nvidia的协议复选框(流氓的选择,不勾选不能下载) 选择与安装的cuda版本一致的cudnn进行下载. 2 ...
- 机器学习环境配置系列六之jupyter notebook远程访问
jupyter运行后只能在本机运行,如果部署在服务器上,大家都希望可以远程录入地址进行访问,这篇文章就是解决这个远程访问的问题.几个基本的命令就可以搞定,然后就可以愉快的玩耍了. 1.安装jupyte ...
- java web开发环境配置系列(二)安装tomcat
在今天,读书有时是件“麻烦”事.它需要你付出时间,付出精力,还要付出一份心境.--仅以<java web开发环境配置系列>来祭奠那逝去的…… 1.下载tomcat压缩包,进入官网http: ...
- java web开发环境配置系列(一)安装JDK
在今天,读书有时是件“麻烦”事.它需要你付出时间,付出精力,还要付出一份心境.--仅以<java web开发环境配置系列>来祭奠那逝去的…… 1.下载JDK文件(http://www.or ...
- PHP开发环境配置系列(四)-XAMPP常用信息
PHP开发环境配置系列(四)-XAMPP常用信息 博客分类: PHP开发环境配置系列 xamppphp 完成了前面三篇后(<PHP开发环境配置系列(一)-Apache无法启动(SSL冲突)> ...
- python数据分析&挖掘,机器学习环境配置
目录 一.什么是数据分析 1.这里引用网上的定义: 2.数据分析发展与组成 3.特点 二.python数据分析环境及各类常用分析包配置 1.处理的数据类型 2.为什么选择python 三.python ...
随机推荐
- 网上做题随笔--MySql
网上写写题 提高下自己的能力. Mysql平时写的是真的很少,所以训练一下下. 1.查找重复的电子邮箱 https://leetcode-cn.com/problems/duplicate-email ...
- Vue学习笔记-目录结构
1.采用脚手架构建的项目基本目录结构 可能会有些许差别,但是大致基本目录都差不多 2.项目入口(index.html,main.js,App.vue) 一般情况下,我们都习惯性将 index.html ...
- Oracle Net Manager 的使用方法(监听的配置方法)
一,在服务端配置oracle端口 win+R 输入netca 弹出如下窗口后 选择监听程序配置,点击下一步 二.配置端口后使用Telnet工具调试端口是否联通 在命令行输入telnet 服务器ip ...
- C++Review2_代码复用
C++的一个重要目的是实现代码重用. 有哪些机制可以实现这个目标呢? 1.公有继承——is a的关系 2.包含 (新的类包含另一个类的对象)——has a的关系 3.私有继承/保护继承——has a的 ...
- 常用数据库连接池 (DBCP、c3p0、Druid) 配置说明(转)
1. 引言 1.1 定义 数据库连接是一种关键的有限的昂贵的资源,这一点在多用户的网页应用程序中体现得尤为突出.对数据库连接的管理能显著影响到整个应用程序的伸缩性和健壮性,影响到程序的性能指标.数据库 ...
- 用VISA工具驱动继电器外设
1.驱动方式:TCP 2.开发过程 第一步:外设识别 TCP方式将继电器插上网线后,并不能像串口一样自动识别到这个外设,需要手动连接.打开NI MAX后,右击设备与接口,然后点击新建,双击VISA T ...
- 深入学习CSS中如何使用定位
CSS中定位介绍 position属性在英文单词中表示位置的意思,在CSS中主要作用设置元素的定位. CSS中一共有3种定位如下: 属性值 描述 fixed 设置固定定位. relative 设置相对 ...
- ELK学习实验007:Nginx的日志分析系统之Metribeat配置
一 Metricbeat 简介 1.1 系统级监控,更简洁将 Metricbeat 部署到您的所有 Linux.Windows 和 Mac 主机,并将它连接到 Elasticsearch 就大功告成了 ...
- 在Asp.Net Core中使用ModelConvention实现全局过滤器隔离
从何说起 这来自于我把项目迁移到Asp.Net Core的过程中碰到一个问题.在一个web程序中同时包含了MVC和WebAPI,现在需要给WebAPI部分单独添加一个接口验证过滤器IActionFil ...
- 1088 三人行 (20分)C语言
子曰:"三人行,必有我师焉.择其善者而从之,其不善者而改之." 本题给定甲.乙.丙三个人的能力值关系为:甲的能力值确定是 2 位正整数:把甲的能力值的 2 个数字调换位置就是乙的能 ...