2、mobilenet

linux下面

1、

git clone https://github.com/AIWintermuteAI/transfer_learning_sipeed

2、安裝對應的keras最新版本

pip3 install keras

3、在transfer_learning_sipeed目錄下

python3 test.py

4、在images目錄的yourclass1和yourclass2下各放置數百某類型張照片

python3 mbnet_keras.py

5、在

pip3 install matplotlib

6、測試

import keras
import numpy as np
from keras import backend as K
from keras.callbacks import Callback
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing import image
from keras.models import Model
from keras.applications import imagenet_utils
from keras.layers import Dense, GlobalAveragePooling2D, Dropout
from keras.applications import MobileNet
from keras.applications.mobilenet import preprocess_input
import matplotlib.pyplot as plt
import argparse
import os

def prepare_image(file, show=False, predictions=None):
    img_path = ''
    img = image.load_img(img_path + file, target_size=(128, 128))
    img_array = image.img_to_array(img)
    img_array_expanded_dims = np.expand_dims(img_array, axis=0)
    if show:
        plt.imshow(img)   
        plt.text(0.2, 0.2, predictions, bbox=dict(facecolor='red', alpha=0.5))                        
        plt.axis('off')
        plt.show(block=False)
        plt.pause(2)
        plt.close()
    return keras.applications.mobilenet.preprocess_input(img_array_expanded_dims)



	
base_model=keras.applications.mobilenet.MobileNet(input_shape=(128, 128, 3), alpha = 0.75,depth_multiplier = 1, dropout = 0.001,include_top = False, weights = "imagenet", classes = 2)


x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(100,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dropout(0.5)(x)
x=Dense(50,activation='relu')(x) #dense layer 3
preds=Dense(2,activation='softmax')(x) #final layer with softmax activation

train_datagen=ImageDataGenerator(preprocessing_function=preprocess_input, validation_split=0.1) #included in our dependencies
train_generator=train_datagen.flow_from_directory('/home/chenub/trainimages',
                                                 target_size=(128,128),
                                                 color_mode='rgb',
                                                 batch_size=32,
                                                 class_mode='categorical', 
						 shuffle=True,   							 							 subset='training')

labels = (train_generator.class_indices)
labels = dict((v,k) for k,v in labels.items())
fo = open("labels_101.txt", "w")
for k,v in labels.items():
    print(v)
    fo.write(v+"\n")
fo.close()

model=Model(inputs=base_model.input,outputs=preds)
#specify the inputs
#specify the outputs
#now a model has been created based on our architecture




print("Load model mode")
model.load_weights('my_model.h5')


print("Testing on the images model hasn't seen in training")
for filename in os.listdir('/home/chenub/testimage'):
    preprocessed_image = prepare_image(os.path.join('/home/chenub/testimage',filename),show=False)
    pred = model.predict(preprocessed_image)
    predicted_class_indices=np.argmax(pred,axis=1)
    predictions = [labels[k] for k in predicted_class_indices]
    print(predictions)
    preprocessed_image = prepare_image(os.path.join('/home/chenub/testimage',filename),show=True,predictions=predictions)




最後測試

python3 mbnet_keraschen.py

6、拷貝my_model.h5到Maix_Toolbox目錄下

tflite_convert  --output_file=model.tflite \   --keras_model_file=my_model.h5

7、而後

./tflite2kmodel.sh model.tflite

這個時候得到 model.kmodel文件

 

---------------------------------------------

2、anaconda 轉換爲python3.6

python --version

查看版本

cmd使用命令:

conda create -n py36 python=3.6 anaconda

安裝好後,會有提示:
To activate this environment, use:
# > activate py36
#
# To deactivate an active environment, use:
# > deactivate
#
# * for power-users using bash, you must source

即想激活python3.6版本,使用命令:

conda activate py36

退出python3.6,使用命令:

deactivate

 

conda install keras==2.1.5

 

發佈了116 篇原創文章 · 獲贊 33 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章