keras导入weights方式

keras源码engine中toplogy.py定义了加载权重的函数:

load_weights(self, filepath, by_name=False)

其中默认by_name为False,这时候加载权重按照网络拓扑结构加载,适合直接使用keras中自带的网络模型,如VGG16

VGG19/resnet50等,源码描述如下:

If `by_name` is False (default) weights are loaded
based on the network's topology, meaning the architecture
should be the same as when the weights were saved.
Note that layers that don't have weights are not taken
into account in the topological ordering, so adding or
removing layers is fine as long as they don't have weights.

若将by_name改为True则加载权重按照layer的name进行,layer的name相同时加载权重,适合用于改变了

模型的相关结构或增加了节点但利用了原网络的主体结构情况下使用,源码描述如下:

If `by_name` is True, weights are loaded into layers
only if they share the same name. This is useful
for fine-tuning or transfer-learning models where
some of the layers have changed.

在进行边缘检测时,利用VGG网络的主体结构,网络中增加反卷积层,这时加载权重应该使用

model.load_weights(filepath,by_name=True)

补充知识:Keras下实现mnist手写数字

之前一直在用tensorflow,被同学推荐来用keras了,把之前文档中的mnist手写数字数据集拿来练手,

代码如下。

import struct
import numpy as np
import os

import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD

def load_mnist(path, kind):
  labels_path = os.path.join(path, '%s-labels.idx1-ubyte' % kind)
  images_path = os.path.join(path, '%s-images.idx3-ubyte' % kind)
  with open(labels_path, 'rb') as lbpath:
    magic, n = struct.unpack('>II', lbpath.read(8))
    labels = np.fromfile(lbpath, dtype=np.uint8)
  with open(images_path, 'rb') as imgpath:
    magic, num, rows, cols = struct.unpack(">IIII", imgpath.read(16))
    images = np.fromfile(imgpath, dtype=np.uint8).reshape(len(labels), 784) #28*28=784
  return images, labels

#loading train and test data
X_train, Y_train = load_mnist('.\\data', kind='train')
X_test, Y_test = load_mnist('.\\data', kind='t10k')

#turn labels to one_hot code
Y_train_ohe = keras.utils.to_categorical(Y_train, num_classes=10)

#define models
model = Sequential()

model.add(Dense(input_dim=X_train.shape[1],output_dim=50,init='uniform',activation='tanh'))
model.add(Dense(input_dim=50,output_dim=50,init='uniform',activation='tanh'))
model.add(Dense(input_dim=50,output_dim=Y_train_ohe.shape[1],init='uniform',activation='softmax')) 

sgd = SGD(lr=0.001, decay=1e-7, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=["accuracy"])

#start training
model.fit(X_train,Y_train_ohe,epochs=50,batch_size=300,shuffle=True,verbose=1,validation_split=0.3)

#count accuracy
y_train_pred = model.predict_classes(X_train, verbose=0)

train_acc = np.sum(Y_train == y_train_pred, axis=0) / X_train.shape[0]
print('Training accuracy: %.2f%%' % (train_acc * 100))

y_test_pred = model.predict_classes(X_test, verbose=0)
test_acc = np.sum(Y_test == y_test_pred, axis=0) / X_test.shape[0]
print('Test accuracy: %.2f%%' % (test_acc * 100))

训练结果如下:

Epoch 45/50
42000/42000 [==============================] - 1s 17us/step - loss: 0.2174 - acc: 0.9380 - val_loss: 0.2341 - val_acc: 0.9323
Epoch 46/50
42000/42000 [==============================] - 1s 17us/step - loss: 0.2061 - acc: 0.9404 - val_loss: 0.2244 - val_acc: 0.9358
Epoch 47/50
42000/42000 [==============================] - 1s 17us/step - loss: 0.1994 - acc: 0.9413 - val_loss: 0.2295 - val_acc: 0.9347
Epoch 48/50
42000/42000 [==============================] - 1s 17us/step - loss: 0.2003 - acc: 0.9413 - val_loss: 0.2224 - val_acc: 0.9350
Epoch 49/50
42000/42000 [==============================] - 1s 18us/step - loss: 0.2013 - acc: 0.9417 - val_loss: 0.2248 - val_acc: 0.9359
Epoch 50/50
42000/42000 [==============================] - 1s 17us/step - loss: 0.1960 - acc: 0.9433 - val_loss: 0.2300 - val_acc: 0.9346
Training accuracy: 94.11%
Test accuracy: 93.61%

以上这篇keras导入weights方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 使用Keras 实现查看model weights .h5 文件的内容

    Keras的模型是用hdf5存储的,如果想要查看模型,keras提供了get_weights的函数可以查看: for layer in model.layers: weights = layer.get_weights() # list of numpy array 而通过hdf5模块也可以读取:hdf5的数据结构主要是File - Group - Dataset三级,具体操作API可以看官方文档.weights的tensor保存在Dataset的value中,而每一集都会有attrs保存各网络

  • keras 权重保存和权重载入方式

    如果需要全部权重载入,直接使用权重载入方式 model.save_weights('./weigths.h5') model2.load_weights('./weigths.h5') 但是有时候你只需要载入部分权重 所以你可以这样操作 首先,为所有层命名,在层中直接加入方法 name='layer1' 第二,使用,将你不需要载入权重的值更改名字. 最后,载入权重. x=BatchNormalization(axis=channel_axis,name='layer2')(x) model2.l

  • keras中模型训练class_weight,sample_weight区别说明

    keras 中fit(self, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None) 官方文档

  • keras导入weights方式

    keras源码engine中toplogy.py定义了加载权重的函数: load_weights(self, filepath, by_name=False) 其中默认by_name为False,这时候加载权重按照网络拓扑结构加载,适合直接使用keras中自带的网络模型,如VGG16 VGG19/resnet50等,源码描述如下: If `by_name` is False (default) weights are loaded based on the network's topology,

  • keras实现VGG16方式(预测一张图片)

    我就废话不多说了,大家还是直接看代码吧~ from keras.applications.vgg16 import VGG16#直接导入已经训练好的VGG16网络 from keras.preprocessing.image import load_img#load_image作用是载入图片 from keras.preprocessing.image import img_to_array from keras.applications.vgg16 import preprocess_inpu

  • pycharm中keras导入报错无法自动补全cannot find reference分析

    目录 引言 分析 解决方法 理论解释 1. 直接导入keras 2. 从tensorflow里导入keras 3. 从tensorflow.python里导入keras: 4. 不导入keras 总结 引言 目前无论是中文还是国外网站对于如何正确的导入keras,如何从tensorflow中导入keras,如何在pycharm中从tensorflow里导入keras,这几个问题都众说纷纭,往往是互相借鉴给出一个可用的解决方法,但没有更进一步的解释了.常见因为keras导入引发的问题有以下几个:

  • Django import export实现数据库导入导出方式

    使用django-import-export库,导入导出数据,支持csv.xls.json.html等格式 官网:http://django-import-export.readthedocs.io/en/latest/installation.html 1.安装django-import-export pip install django-import-export 2.配置settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'djan

  • 详解Typescript 内置的模块导入兼容方式

    一.前言 前端的模块化规范包括 commonJS.AMD.CMD 和 ES6.其中 AMD 和 CMD 可以说是过渡期的产物,目前较为常见的是commonJS 和 ES6.在 TS 中这两种模块化方案的混用,往往会出现一些意想不到的问题. 二.import * as 考虑到兼容性,我们一般会将代码编译为 es5 标准,于是 tsconfig.json 会有以下配置: { "compilerOptions": { "module": "commonjs&qu

  • matlab、python中矩阵的互相导入导出方式

    还有一种最流行的h5py.. 过几天更新 ------------在python中导出矩阵至matlab------------ 如果矩阵是mxn维的. 那么可以用 : np.savetxt('dev_ivector.csv', dev_ivector, delimiter = ',') 对应matlab读取为: dev_ivec = csvread('dev_ivector.csv') ###csv格式其实就内定了结构体 如果矩阵是(n,)这种格式.['aagj' 'aagy' 'aann'

  • Keras自定义IOU方式

    我就废话不多说了,大家还是直接看代码吧! def iou(y_true, y_pred, label: int): """ Return the Intersection over Union (IoU) for a given label. Args: y_true: the expected y values as a one-hot y_pred: the predicted y values as a one-hot or softmax output label:

  • Keras 切换后端方式(Theano和TensorFlow)

    实验室新装了keras,发现keras默认后端是tensorflow,想换回theano,看了官方文档也没搞懂,最终搞定,很简单. 中文文档的描述:keras中文文档,切换后端 其实就是在C:\Users\75538(75538是我的windos用户名字,找你对应的用户名就行)下有个文件夹.keras,里面有keras.json文件,改一下里面的内容就好了,如果没有文件夹和文件,手动创建就行. 用theano的话,keras.json写入 { "image_dim_ordering":

  • maven实现jar包导入+导出方式

    普通 jar 包的导出 1.点击 file 中的project.structor=>选择Artifacts=>+=>选择 jar+=>选择from modules with dependencies 2.如果你的 jar 包具有主函数main,即为可执行jar包则需要在下图所示处,输入主函数位置,点击右边文件夹,选择主函数即可 3.选择好后点击OK,切记下一步需要先应用在OK 4.导出成功后点击Builder=>build artifacts=>build/rebuil

  • SpringBoot使用@PostConstruct注解导入配置方式

    目录 使用@PostConstruct注解导入配置 使用@PostConstruct注解,完成静态对象注入 为什么static对象不可直接使用@Autowired注入? @PostConstruct和@PreDestroy 使用@PostConstruct注解导入配置 通过@PostConstruct注解能够通过一种更友好的方式将配置进行导入 代码如下: /** * 引导类 * * @author zhangzhixiang * @date 2018/09/18 14:51:39 */ @Con

随机推荐