欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

keras导入weights方式

程序员文章站 2022-03-10 19:47:08
keras源码engine中toplogy.py定义了加载权重的函数:load_weights(self, filepath, by_name=false)其中默认by_name为false,这时候加...

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方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。