首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用于keras的Mobilenet

用于keras的Mobilenet
EN

Stack Overflow用户
提问于 2017-08-09 13:16:32
回答 2查看 6.6K关注 0票数 1

以下是我的模型的架构。

代码语言:javascript
复制
# %%
# Defining the model
input_shape = img_data[0].shape

model = Sequential()

model.add(Convolution2D(32, 3, 3, border_mode='same', input_shape=input_shape))
model.add(Activation('relu'))

model.add(Convolution2D(32, 3, 3))
model.add(Activation('relu'))

model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.75))

model.add(Convolution2D(64, 3, 3))
model.add(Activation('relu'))
# model.add(Convolution2D(64, 3, 3))
# model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.75))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.75))
model.add(Dense(num_classes))
model.add(Activation('softmax'))

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

精确度有点低。所以我想把架构改造成mobilenet。是否有任何基于keras的实现来使用mobilenet对图像进行分类?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-09 18:24:10

Keras有一组用于图像分类的预训练模型。您可以查看列表和使用here

您还可以将架构的实现复制到github存储库here the link

票数 1
EN

Stack Overflow用户

发布于 2018-12-07 19:15:44

也许这个代码片段会对你有所帮助

代码语言:javascript
复制
from keras.applications.mobilenet import MobileNet
from keras.applications.mobilenetv2 import MobileNetV2
from  keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing import image
from keras import Sequential
from keras.layers import Dense
from keras.optimizers import Adam, RMSprop, SGD
import keras
from tensorflow import confusion_matrix
from matplotlib import pyplot as plt

import config
import numpy as np

train_path = 'data/train'
val_batch = 'data/val'
test_batch = 'data/test'

train_batches = ImageDataGenerator(preprocessing_function=keras.applications.mobilenet.preprocess_input).flow_from_directory(train_path, target_size=(config.IMAGE_SIZE, config.IMAGE_SIZE),
                                                         class_mode='categorical', batch_size=20)
val_batches = ImageDataGenerator(preprocessing_function=keras.applications.mobilenet.preprocess_input).flow_from_directory(val_batch, target_size=(config.IMAGE_SIZE, config.IMAGE_SIZE),
                                                         class_mode='categorical', batch_size=20)

def prepare_image(file):
    img = image.load_img(file, target_size=(config.IMAGE_SIZE, config.IMAGE_SIZE))
    img_array = image.img_to_array(img)
    img_expanded_dims = np.expand_dims(img_array, axis=0)
    return keras.applications.mobilenet.preprocess_input(img_expanded_dims)

mobilenet = MobileNetV2()

# x =  mobilenet.layers[-6].output
x =  mobilenet.layers[-2].output
predictions =  Dense(8, activation='softmax')(x)
from keras import Model
model = Model(inputs= mobilenet.input, outputs=predictions)

print(model.summary())



# for layer in model.layers[:-5]:
#     layer.trainable = False


# for layer in model.layers[:-1]:
#     layer.trainable = False

print(model.summary())

# exit(0)


model.compile(SGD(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])

history = model.fit_generator(train_batches, steps_per_epoch=10,
                    validation_data=val_batches, validation_steps=10, epochs=300, verbose=2)

acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(len(acc))

plt.plot(epochs, acc, 'b', label='Training acc')
plt.plot(epochs, val_acc, 'r', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()

plt.figure()

plt.plot(epochs, loss, 'b', label='Training loss')
plt.plot(epochs, val_loss, 'r', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()

plt.show()

# Get the ground truth from generator
ground_truth = train_batches.classes

# Get the label to class mapping from the generator
label2index = train_batches.class_indices

# Getting the mapping from class index to class label
idx2label = dict((v, k) for k, v in label2index.items())

print(idx2label)


# _, val_labels =  next(val_batches)
#
# predictions = model.predict_generator(val_batches, steps=1, verbose=0)
#
# cm = confusion_matrix(val_batches, np.round(predictions[:,0]))
# cm_plot_labels = []
#
# for k, v in label2index.items():
#     cm_plot_labels.append(v)
#
# print(cm)



# serialize model to JSON
model_json = model.to_json()
with open("mobilenet.json", "w") as json_file:
    json_file.write(model_json)

from keras.models import save_model
save_model(model, 'mobilenet.h5')


import tensorflow as tf
# from tensorflow.contrib import lite
# tf.lite.TocoConverter

converter = tf.lite.TocoConverter.from_keras_model_file("mobilenet.h5")
tflite_model = converter.convert()
open("model/mobilenet.tflite", "wb").write(tflite_model)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45582157

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档