程式碼筆記:caffereid利用訓練好的模型提取特徵
set -e
if [ ! -n "$1" ] ;then
echo "\$1 is empty, default is 0"
gpu=0
else
echo "use $1-th gpu"
gpu=$1
fi
#base_model=caffenet
base_model=vgg_reduce
#base_model=googlenet
#base_model=res50
feature_name=fc7
#feature_name=pool5/7x7_s1
#feature_name=pool5
model_file=./models/market1501/$base_model /snapshot/${base_model}.full_iter_18000.caffemodel
python examples/market1501/testing/extract_feature.py \
examples/market1501/lists/test.lst \
examples/market1501/datamat/test.lst.fc7.mat \
examples/market1501/datamat/test.lst.score.mat \
--gpu $gpu \
--model_def ./models/market1501/$base_model/dev.proto \
--feature_name $feature_name \
--pretrained_model $model_file \
--mean_value 97.8286,99.0468,105.606
python examples/market1501/testing/extract_feature.py \
examples/market1501/lists/query.lst \
examples/market1501/datamat/query.lst.fc7.mat \
examples/market1501/datamat/query.lst.score.mat \
--gpu $gpu \
--model_def ./models/market1501/$base_model /dev.proto \
--feature_name $feature_name \
--pretrained_model $model_file \
--mean_value 97.8286,99.0468,105.606
extract_feature.py
內容如下:
import numpy as np
import os
import sys
import argparse
import glob
import time
import _init_paths
from units import SClassifier
import caffe
import scipy.io as sio
def load_txt(xfile):
img_files = []
labels = []
for line in open(xfile):
line = line.strip('\n').split(' ')
assert(len(line) == 2)
img_files.append(line[0])
labels.append(int(float(line[1])))
return img_files, labels
def main(argv):·
parser = argparse.ArgumentParser()
# Required arguments: input and output files.
#由於沒有設定default,因此這些引數在命令列中是必須的,否則會報錯
parser.add_argument(
"input_file",
help="Input image, directory"
)
parser.add_argument(
"feature_file",
help="Feature mat filename."
)
parser.add_argument(
"score_file",
help="Score Output mat filename."
)
# Optional arguments.
# 由於設定了default,因此這些引數在命令列中是可選的
parser.add_argument(
"--model_def",
default=os.path.join(
"./models/market1501/caffenet/feature.proto"),
help="Model definition file."
)
parser.add_argument(
"--pretrained_model",
default=os.path.join(
"./models/market1501/caffenet/caffenet_iter_17000.caffemodel"),
help="Trained model weights file."
)
parser.add_argument(
"--gpu",
type=int,
default=-1,
help="Switch for gpu computation."
)
parser.add_argument(
//action='store_true'的意思是說,如果指令碼有傳遞--center_only的引數則將該值center_only取值為true
//由於指令碼沒有傳遞center_only,則其值為false
"--center_only",
action='store_true',
help="Switch for prediction from center crop alone instead of " +
"averaging predictions across crops (default)."
)
parser.add_argument(
"--images_dim",
default='256,256',
help="Canonical 'height,width' dimensions of input images."
)
parser.add_argument(
"--mean_value",
default=os.path.join(
'examples/market1501/market1501_mean.binaryproto'),
help="Data set image mean of [Channels x Height x Width] dimensions " +
"(numpy array). Set to '' for no mean subtraction."
)
parser.add_argument(
"--input_scale",
type=float,
help="Multiply input features by this scale to finish preprocessing."
)
parser.add_argument(
"--raw_scale",
type=float,
default=255.0,
help="Multiply raw input by this scale before preprocessing."
)
parser.add_argument(
"--channel_swap",
default='2,1,0',
help="Order to permute input channels. The default converts " +
"RGB -> BGR since BGR is the Caffe default by way of OpenCV."
)
parser.add_argument(
"--ext",
default='jpg',
help="Image file extension to take as input when a directory " +
"is given as the input file."
)
parser.add_argument(
"--feature_name",
default="fc7",
help="feature blob name."
)
parser.add_argument(
"--score_name",
default="prediction",
help="prediction score blob name."
)
args = parser.parse_args()
//image_dims = [256,256]
image_dims = [int(s) for s in args.images_dim.split(',')]
channel_swap=[2,1,0]
channel_swap = None
if args.channel_swap:
channel_swap = [int(s) for s in args.channel_swap.split(',')]
mean_value= [97.8,99.0,105.6]
mean_value = None
if args.mean_value:
mean_value = [float(s) for s in args.mean_value.split(',')]
mean_value = np.array(mean_value)
if args.gpu >= 0:
caffe.set_mode_gpu()
caffe.set_device(args.gpu)
print("GPU mode, device : {}".format(args.gpu))
else:
caffe.set_mode_cpu()
print("CPU mode")
//這句話的意思是根據訓練好的模型,使用dev.proto前向一遍,得到分類的結果
//同時,前向網路也計算了fc7,這正是我們需要的特徵
--model_def = ./models/market1501/caffenet/dev.proto
args.pretrained_model在命令列中存在
input_scale為空,無預設值
raw_scale=255
channel_swap=[2,1,0]
# Make classifier.
classifier = SClassifier(args.model_def, args.pretrained_model,
image_dims=image_dims, mean_value=mean_value,
input_scale=args.input_scale, raw_scale=args.raw_scale,
channel_swap=channel_swap)
# Load numpy, directory glob (*.jpg), or image file.
//將符號路徑擴充套件成完整路徑
args.input_file = os.path.expanduser(args.input_file)
//args.ext='jpg'
//args.input_file以lst結尾
if args.input_file.endswith(args.ext):
print("Loading file: %s" % args.input_file)
inputs = [caffe.io.load_image(args.input_file)]
labels = [-1]
//lst也不是資料夾
elif os.path.isdir(args.input_file):
print("Loading folder: %s" % args.input_file)
inputs =[caffe.io.load_image(im_f)
for im_f in glob.glob(args.input_file + '/*.' + args.ext)]
labels = [-1 for _ in xrange(len(inputs))]
else:
## Image List Files
print("Loading file: %s" % args.input_file)
//按列讀取
img_files, labels = load_txt(args.input_file)
//對於lst中的每一個地址,就讀取一次,放入到input中
inputs = [caffe.io.load_image(im_f)
for im_f in img_files]
print("Classifying %d inputs." % len(inputs))
# Classify.
ok = 0.0
save_feature = None
save_score = None
//由於指令碼沒有傳遞center_only,則其值為false
for idx, _input in enumerate(inputs):
start = time.time()
//_input是每一張圖,後面的引數說明是否要對影象進行crop
//本例中是對影象進行了crop,四個角+一箇中心,水平翻轉之後再來一次,總計10張。否則我們僅僅需要中心的那張就可以
//返回的是一張N*C的numpy.ndarry,代表每張圖片有可能對應的C個類別
_ = classifier.predict([_input], not args.center_only)
//提取fc7層的特徵
feature = classifier.get_blob_data(args.feature_name)
//獲取使用softmax後的結果
score = classifier.get_blob_data(args.score_name)
//都是一維的資料
assert (feature.shape[0] == 1 and score.shape[0] == 1)
feature_shape = feature.shape
score_shape = score.shape
//列印結果
if save_feature is None:
args.feature_name feature fc7 feature_shape(1,4096)
print('feature : {} : {}'.format(args.feature_name, feature_shape))
save_feature = np.zeros((len(inputs), feature.size),dtype=np.float32)
save_feature[idx, :] = feature.reshape(1, feature.size)
if save_score is None:
args.score_name score prediction (1,751)
print('score : {} : {}'.format(args.score_name, score_shape))
save_score = np.zeros((len(inputs), score.size),dtype=np.float32)
save_score[idx, :] = score.reshape(1, score.size)
//找到得分中最大的一項
mx_idx = np.argmax(score.view())
ok = ok + int(int(mx_idx) == int(labels[idx]))
print("{:5d} / {:5d} images predict done in {:.2f} s. [PRED: {:3d}] vs [OK: {:3d}] accuracy: {:.4f} = good: {:5d} bad: {:5d}".format( \
idx+1, len(inputs), time.time() - start, mx_idx, labels[idx], ok/(idx+1), int(ok), idx+1-int(ok)))
# Save
if (args.feature_file):
print("Saving feature into %s" % args.feature_file)
sio.savemat(args.feature_file, {'feature':save_feature})
else:
print("Without saving feature")
if (args.score_file):
print("Saving score into %s" % args.score_file)
sio.savemat(args.score_file, {'feature':save_score})
else:
print("Without saving score")
if __name__ == '__main__':
main(sys.argv)
相關推薦
程式碼筆記:caffereid利用訓練好的模型提取特徵
set -e if [ ! -n "$1" ] ;then echo "\$1 is empty, default is 0" gpu=0 else echo "use $1-th gpu" gpu=$1 fi #base_mod
tensorflow學習筆記十一:用別人訓練好的模型來進行影象分類
谷歌在大型影象資料庫ImageNet上訓練好了一個Inception-v3模型,這個模型我們可以直接用來進來影象分類。下載完解壓後,得到幾個檔案:其中的classify_image_graph_def.pb 檔案就是訓練好的Inception-v3模型。imagenet_sy
Caffe:利用訓練好的模型進行分類
以大神訓練好的模型為基礎,利用自己的資料進行了finetune之後,下一步就可以真正使用模型來進行分類操作了。具體步驟如下: 1. 編輯分類網路的配置檔案deploy.prototxt deploy檔案是真正使用模型時候用的,其結構與train_v
tensorflow 1.0 學習:用別人訓練好的模型來進行圖像分類
ima ppi gin 什麽 dir targe spl flow blog 谷歌在大型圖像數據庫ImageNet上訓練好了一個Inception-v3模型,這個模型我們可以直接用來進來圖像分類。 下載地址:https://storage.googleapis.com/d
Keras 使用:載入已經訓練好的模型進行預測
使用Keras訓練好的模型用來直接進行預測,這個時候我們該怎麼做呢?【我這裡使用的就是一個圖片分類網路】 現在讓我來說說怎麼樣使用已經訓練好的模型來進行預測判定把 首先,我們已經又有了model模型,這個模型被儲存為model.h5檔案 然後我們需要在程式碼裡面進行載入 mode
Tensorflow學習教程------利用卷積神經網路對mnist資料集進行分類_利用訓練好的模型進行分類
#coding:utf-8 import tensorflow as tf from PIL import Image,ImageFilter from tensorflow.examples.tutorials.mnist import input_data def imageprepare(ar
Tensorflow如何儲存、讀取model (即利用訓練好的模型測試新資料的準確度)
目標: cnn2d.py cnn2d_test.py 訓練網路,並儲存網路模型 讀取網路,用測試集測試準確度 直接貼程式碼:(只貼了相關部分,瀏覽完整程式碼請到GitHub) 1. cnn2
TensorFlowLite:將TensorFlow訓練好的模型遷移到Android APP上
在Android Studio中配置TensorFlowLite 把訓練好的 TensorFlow的 pb模型 移植到Android Studio上,TensorFlow Lite官方的例子中已經給我們展示了,我們其實只需要兩個檔案: libandroid_tensor
TensorFlow實現人臉識別(5)-------利用訓練好的模型實時進行人臉檢測
經過前面複雜的操作,訓練出來對於某一個人的識別模型。本文將利用該模型對於開啟的視訊或者攝像頭實時的識別該人。 讀取視訊 ==> 識別人臉 ==> 繪製標誌 程式碼如下: #-*- coding:UTF-8 -*- import tensor
tensorflow 1.0 學習:用Google訓練好的模型來進行影象分類
谷歌在大型影象資料庫ImageNet上訓練好了一個Inception-v3模型,這個模型我們可以直接用來進來影象分類。下載地址:github:https://github.com/taey16/tf/tree/master/imagenet下載完解壓後,得到幾個檔案:其中的c
tensorflow 1.0 學習:用別人訓練好的模型來進行影象分類
谷歌在大型影象資料庫ImageNet上訓練好了一個Inception-v3模型,這個模型我們可以直接用來進來影象分類。 下載完解壓後,得到幾個檔案: 其中的classify_image_graph_def.pb 檔案就是訓練好的Inception-v3模型。 imagenet_synset_to_h
caffe利用訓練好的模型進行實際測試
官方版demo import numpy as np import os import sys import cv2 caffe_root = 'your caffe root' sys.path.insert(0, caffe_root + '/py
Caffe學習:4. 使用訓練好的caffemodel(python)
在嘗試過 mnist 資料集進行測試後,想要對任意一張圖片進行識別測試,所以將目光瞄準了GoogleNet。在Caffe安裝好後就會有GoogleNet的example,在model種就可以找到。 ————————————————————————————————————
Tensorflow學習筆記:變數作用域、模型的載入與儲存、執行緒與佇列實現多執行緒讀取樣本
# tensorflow變數作用域 用上下文語句規定作用域 with tf.variable_scope("作用域_name") ......
程式碼筆記:wordpress後臺新增選單的幾種方式比較
在日常的主題及外掛開發中,嚐嚐需要將外掛/主題的想要選單放在wordpress後臺對應的位置,比如:使用者管理外掛的管理選單放在“使用者”選單下會比較方便,具體怎麼實現的呢? 後臺增加主選單 add_menu_pageadd_menu_page( $page_title
matlab利用訓練好的BP神經網路來預測新資料(先儲存網路,再使用網路)
1,儲存網路。 save ('net') % net為已訓練好的網路,這裡把他從workspace儲存到工作目錄,顯示為net.mat文件。 2,使用網路。 load ('net')
周志華《機器學習》筆記:第3章 線性模型
本章概括 從最簡單但也是最基礎的線性模型開始研究。線性模型雖然簡單,但卻是基礎。先研究線性、單屬性的線性迴歸問題,在此基礎上研究非線性、多屬性的迴歸和分類問題。 第3章 線性模型 所謂線性模型,也即是: 1. 假定示例有d個屬性,x
深度學習tensorflow實戰筆記(4)利用儲存的VGG-16CNN網路模型提取特徵
前幾篇部落格寫了如何處理資料,如何把用自己的資料訓練VGG-16,如何把訓練好的模型儲存。而在實際應用中,並不是所有的操作都是為了分類的,有時候需要提取影象的特徵,那麼怎麼利用已經儲存的模型提取特徵呢? “桃葉兒尖上尖,柳葉兒就遮滿了天” 測試資料轉換成tf
tensorflow學習系列六:mnist從訓練儲存模型再到載入模型測試
通過前面幾個系列的學習對tensorflow有了一個漸漸親切的感覺,本文主要是從tensorflow模型訓練與驗證的模型進行實踐一遍,以至於我們能夠通過tensorflow的訓練有一個整體的概念。下面主要是從訓練到儲存模型,然後載入模型進行預測。# -*- codin
機器學習筆記:最大熵(模型,推導,與似然函式關係的推導,求解)
1、最大熵模型 最大熵原理:最大熵原理認為在學習概率模型時,在所有可能的概率模型中,熵最大的模型是最少的模型。 該原理認為要選擇的概率模型首先得承認已有的現實(約束條件),對未來無偏(即不確定的部分是等可能的)。比如隨機變數取值有A,B,C,另外已知