2017-11-14 7 views
0

Windows 7을 사용하고 있습니다. 공식 retraining 예제를 사용하여 mobilenet을 교육 시켰습니다.Tensorflow : tensorflow 예제의 label_image.py에있는 "input_mean"및 "input_std"는 무엇입니까?

python ../tensorflow-master/tensorflow/examples/image_retraining/retrain.py --image_dir test/ --learning_rate=0.0001 --testing_percentage=20 --validation_percentage=20 --train_batch_size=32 --validation_batch_size=-1 --flip_left_right True --random_scale=30 --random_brightness=30 --eval_step_interval=100 --how_many_training_steps=2000 --architecture mobilenet_0.25_128 

를 내가 얻을 훈련을 그래프 및 레이블 파일 "output_graph.pb"와 "output_labels.txt"

https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/image_retraining

I는 다음과 같이 명령을 실행했다.

이제 위의 생성 된 그래프를 사용하여 분류를 수행하고자하므로 tensorflow github에 제공된 label_image.py를 사용했습니다.

from __future__ import absolute_import 
from __future__ import division 
from __future__ import print_function 

import argparse 
import sys 

import numpy as np 
import tensorflow as tf 

def load_graph(model_file): 
    graph = tf.Graph() 
    graph_def = tf.GraphDef() 

    with open(model_file, "rb") as f: 
    graph_def.ParseFromString(f.read()) 
    with graph.as_default(): 
    tf.import_graph_def(graph_def) 

    return graph 

def read_tensor_from_image_file(file_name, input_height=299, input_width=299, 
       input_mean=0, input_std=255): 
    input_name = "file_reader" 
    output_name = "normalized" 
    file_reader = tf.read_file(file_name, input_name) 
    if file_name.endswith(".png"): 
    image_reader = tf.image.decode_png(file_reader, channels = 3, 
             name='png_reader') 
    elif file_name.endswith(".gif"): 
    image_reader = tf.squeeze(tf.image.decode_gif(file_reader, 
                name='gif_reader')) 
    elif file_name.endswith(".bmp"): 
    image_reader = tf.image.decode_bmp(file_reader, name='bmp_reader') 
    else: 
    image_reader = tf.image.decode_jpeg(file_reader, channels = 3, 
             name='jpeg_reader') 
    float_caster = tf.cast(image_reader, tf.float32) 
    dims_expander = tf.expand_dims(float_caster, 0); 
    resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width]) 
    normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std]) 
    sess = tf.Session() 
    result = sess.run(normalized) 

    return result 

def load_labels(label_file): 
    label = [] 
    proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines() 
    for l in proto_as_ascii_lines: 
    label.append(l.rstrip()) 
    return label 

if __name__ == "__main__": 
    file_name = "tensorflow/examples/label_image/data/grace_hopper.jpg" 
    model_file = \ 
    "tensorflow/examples/label_image/data/inception_v3_2016_08_28_frozen.pb" 
    label_file = "tensorflow/examples/label_image/data/imagenet_slim_labels.txt" 
    input_height = 299 
    input_width = 299 
    input_mean = 0 
    input_std = 255 
    input_layer = "input" 
    output_layer = "InceptionV3/Predictions/Reshape_1" 

    parser = argparse.ArgumentParser() 
    parser.add_argument("--image", help="image to be processed") 
    parser.add_argument("--graph", help="graph/model to be executed") 
    parser.add_argument("--labels", help="name of file containing labels") 
    parser.add_argument("--input_height", type=int, help="input height") 
    parser.add_argument("--input_width", type=int, help="input width") 
    parser.add_argument("--input_mean", type=int, help="input mean") 
    parser.add_argument("--input_std", type=int, help="input std") 
    parser.add_argument("--input_layer", help="name of input layer") 
    parser.add_argument("--output_layer", help="name of output layer") 
    args = parser.parse_args() 

    if args.graph: 
    model_file = args.graph 
    if args.image: 
    file_name = args.image 
    if args.labels: 
    label_file = args.labels 
    if args.input_height: 
    input_height = args.input_height 
    if args.input_width: 
    input_width = args.input_width 
    if args.input_mean: 
    input_mean = args.input_mean 
    if args.input_std: 
    input_std = args.input_std 
    if args.input_layer: 
    input_layer = args.input_layer 
    if args.output_layer: 
    output_layer = args.output_layer 

    graph = load_graph(model_file) 
    t = read_tensor_from_image_file(file_name, 
            input_height=input_height, 
            input_width=input_width, 
            input_mean=input_mean, 
            input_std=input_std) 

    input_name = "import/" + input_layer 
    output_name = "import/" + output_layer 
    input_operation = graph.get_operation_by_name(input_name); 
    output_operation = graph.get_operation_by_name(output_name); 

    with tf.Session(graph=graph) as sess: 
    results = sess.run(output_operation.outputs[0], 
         {input_operation.outputs[0]: t}) 
    results = np.squeeze(results) 

    top_k = results.argsort()[-5:][::-1] 
    labels = load_labels(label_file) 
    for i in top_k: 
    print(labels[i], results[i]) 

https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/label_image 그리고 난 다음 명령을 실행

python ../tensorflow-master/tensorflow/examples/label_image/label_image.py --graph=output_graph.pb --labels=output_labels.txt --image=test.jpg --input_layer=input --output_layer=final_result --input_mean=128 --input_std=128 --input_width=128 --input_height=128 

그리고 이미지 "test.jpg를"를 분류 할 수있다.

그러나 "input_mean"및 "input_std"에 다른 값을 사용하면 결과가 변경됩니다.

"input_mean"및 "input_std"는 무엇에 사용됩니까? 그리고이 두 매개 변수에 대한 올바른 값을 얻으려면 어떻게해야합니까?

+0

사용중인 코드를 입력하십시오. – Lescurel

+0

@Lescurel 내가 사용했던 .py 파일을 포함하는 관련 링크를 추가했습니다. – Season

+0

미래에 링크가 변경 될 수 있으므로 질문에 코드를 포함해야합니다. – Lescurel

답변

0

데이터 세트를 정규화하는 데이 두 변수를 사용합니다. 결과에서 개선 된 점을 관찰 할 수 있습니다.
input_mean은 데이터 집합의 채널 당 평균이며 input_std은 관련된 표준 편차입니다. 네트워크에서 전달하는 데이터 집합을 제어 할 때 평균과 표준을 계산할 수 있어야합니다.

정규화는 2 가지 의미

  • () 우리의 경우에 0 주위 (센터링) (스케일링) 포인트 주위의 데이터를 분산
  • 동일한 크기의 데이터를 퍼팅

우리가 그렇게하는 이유에 대해서는 Crossvalidated answer에서 읽을 수 있습니다 : https://stats.stackexchange.com/a/220970

"Su 데이터 세트 평균을 버리는 것은 데이터를 "센터링"하는 역할을합니다. 또한 각 기능 값 을 z- 점수로 정규화하려면 해당 기능 또는 픽셀의 sttdev로 나누고 싶을 것입니다.

의 과정이 우리의 네트워크를 훈련에서, 우리가 정품 인증을 을 야기하기 위해 이러한 초기 입력 (편견)에 추가 (무게) 및 을 곱 될 것하고 있기 때문에 우리가 그 일을 모두 할 그 이유는 우리는 그라디언트로 백 프로 페 게이트하여 모델을 훈련시킵니다.

이 과정에서 각 기능이 비슷한 범위를 가지므로 그라디언트가 제어 불능 상태가 아니며 전체 학습 속도 배율은 만 필요합니다."

편집 : 3 개 픽셀의 정말 간단한 이미지는 이미지를 상상 예를됩니다 제공하는 것은 :

img = [[[1,2,3],[4,5,6],[7,8,9]]] 

당신은 쉽게 채널

mean = [4,5,6] 

그리고 쉽게 당 평균을 계산할 수 있습니다 채널 당 std :

std = [2.45,2.45,2.45] 

tensorflow는 요소 별 뺄셈을 수행 한 다음 요소 별 나누기를 수행하므로 이미지의 각 채널을 개별적으로 표준화합니다.

코드에서 tf.image 함수를 준수하는 차원을 추가 한 것처럼 보입니다. 첫 번째 차원은 일괄 처리이므로 배열 앞에 0을 붙여야합니다. ([0,4,5,6])

+0

즉,이 경우 모든 채널의 이미지 색상의 평균 및 표준을 계산해야한다는 의미입니까? – Season

+0

채널 별 평균 옵션을 사용하면 최상의 결과를 얻을 수 있습니다. int 대신에 평균 및 표준 배열을 전달하십시오. 나는 예를 제공하기 위해 나의 대답을 업데이트 할 것이다. – Lescurel