깊이 학습 프레임 워크 -Tensorflow 기반 학습

Tensorflow 프로필

프로그래밍 시스템은 컴퓨팅 작업도를 나타내는 데 사용된다 Tensorflow 1. 도면을 나타내는도 컴퓨팅 태스크 노드라고 연산 (동작의 약어) 등으로 구성된다. 연산은 0 이상의 구 Tensor, 계산을 수행하는 제로 이상 발생 Tensor텐서의 각 유형을 다차원이고 어레이. TensorFlow 프로그램은 일반적으로 위상 및 빌드의 실행 단계로 구성된다. 빌드 단계 동안, 연산 단계는 그래프로 설명한다. 구현 단계에서 연산도 세션 실행을 사용.
2. Tensorflow 역할
  • 도는 컴퓨팅 작업을 나타내는
  • 세션은도 2의 환경에서 수행 하였다.
  • 텐서를 사용하여 데이터를 표현
  • 상태에 의해 변수 유지 보수
  • 사료의 사용 및 작업을 가져 임의로 할당하거나 데이터를 검색 할 수 있습니다
작동 원리 (3)
  • inference()예측은 텐서의 결과 (출력 예측)를 반환 있도록 가능한 한 많은 기능, 차트를 만들 수 있습니다. 이 한 쌍의 연결 (레이어)으로 구성 ReLu (정류 선형 단위)의 활성화 작용에 의해이 기초에, 입력 화상 틀로서 받아들이고, 10 노드 (노드)와, 상기 선형 모델 층 출력 logtis를 나타낸다 .

  • 입력 틀 (입 나타내지는) placeholder_inputs()함수는 두 생성 tf.placeholder동작 차트 전달 형상 파라미터를 정의 형상 파라미터는 상기 batch_size값.

    후속 단계 들어오는 태그 전체 이미지 데이터 세트의 트레이닝 사이클 (트레이닝 루프) 동작 설정의 각각에 맞게 분리되는 batch_size값을, 조작이 충족하는 자리 채울 batch_size값. 이어서 사용 feed_dict매개 변수, 수신 데이터 sess.run()기능.

  • 건설 차트 (그래프를 구축)

변수 : 생성, 초기화, 저장 및로드

훈련 할 때, 저장 및 업데이트 매개 변수를 사용합니다. 변수 메모리 버퍼에 저장된 텐서 (텐서)를 포함한다.

만들기
  • tf.Variable

    import tensorflow as tf
    weights = tf.Variable(tf.random_normal([784,200], stddev=0.35), name = "weights") # 权重
초기화
  • 때때로 당신은, 현재의 변수 초기화에 또 다른 변수의 값을 초기화 할 필요가 tf.initialize_all_variables()이러한 요구 상황이주의 요구에, 그래서 모든 변수를 초기화하는 평행! 새로운 변수의 다른 변수, 다른 변수의 값으로 초기화하는 경우 initialized_value()속성입니다. 직접 새로운 변수의 초기 값으로 값을 초기화하거나 새 변수에 할당 된 텐서 계산 된 값으로 생각할 수 있습니다.

    # 承接上面创建的变量weights
    w2 = tf.Variable(weights.initialized_value(), name = 'w2')
  • 사용자 초기화. tf.initialized_all_variables()모든 변수는 변수 연산 모델을 초기화하는 기능을 추가합니다.

저장 및로드

저장하고 모델을 복원하는 가장 쉬운 방법은 사용하는 tf.train.Saver객체. 생성자리스트에 정의 된 모든 변수 또는 변수를 추가하는 그래프 saverestoreOPS. 보호기 객체는이 작전 정의 검사 점 파일을 실행 경로를 읽고 쓰는 방법을 제공합니다.

  • 검사 점 파일

    변수는 텐서 값으로 변수 이름의 기본 매핑을 포함, 이진 파일에 저장됩니다. 당신이 절약 객체를 만들 때 기본적으로 각 변수 Variables.name 속성 값을 정의합니다.

  • 저장 변수

    tf.train.Saver()모든 변수를 관리 할 수있는 보호기 객체를 생성

    # Create all variables
    v1 = tf.Variable(..., name= 'v1')
    v2 = tf.Variable(..., name='v2')
    # Add an op to initialize the variables
    init_op = initialized_all_variables()
    # Add ops to save and restore all the variables
    saver() = tf.train.Saver()
    # Later, launch the model, initialize the variables, do some work,save the variables to disk.
    with tf.Session() as sess:
        sess.run()
        #..do some work with the model..
        save_path = saver.save(sess, '/tmp/model.ckpt')
        print('Model saved in file:', save_path)
  • 변수 복구

    같은 보호기 개체 개체를 복구하는 데 사용되는 변수를 복원합니다. saver.restore()복구 변수.

데이터 읽기

수유 데이터

Tensorflow 공급기구는 계산지도 데이터 텐서 임의 주입 tensorflow 허용 할 것이다. 저자 run()또는 eval()함수 입력 feed_dict파라미터

with tf.Session() as tf:
    input = tf.placeholder(tf.float32)
    classifer = ...
    print(classifer.eval(feed_dict={input:my_python_preprocessing_fn()}))
파일에서 데이터를 읽는 단계
    1. 파일 이름 목록 : 당신은 (예 : 문자열 텐서를 사용하여 ["file0", "file1"], [("file%d" % i) for i in range(2)], [("file%d" % i) for i in range(2)]또는) tf.train.match_filenames_once기능 파일 이름의 목록을 생성 할 수 있습니다.
    1. 순서 (셔플) 중 구성 파일 이름 : string_input_producer주문 및 훈련 반복의 최대 수에서 파일 이름을 설정하는 구성 매개 변수를 제공 QueueRunner, 모든 파일 이름이 대기열에서 파일 이름에 추가 된 각 반복 (시대)입니다을 제공 할 것입니다 경우 shuffle=True단어 파일 이름은 주문 처리의 주요 요인이 될 수 있습니다. 이 균형 파일명 큐를 생성 할 수 있도록이 프로세스는 상대적으로 균일하다.
    2. 구성 훈련 반복의 최대 수 (신기원 제한)
    3. 파일 이름 큐
    4. 입력 파일 포맷 독자
    5. 파서
    6. 구성 처리기
    7. 의 코호트
다른 파일 형식의 데이터 읽기

다른 파일 형식은 다른 파일 리더를 선택하고 큐 판독기 () 메서드에 읽기 파일 이름을 제공합니다.

  • CSV 파일

    우리는 사용할 필요 textLineReader(),decode_csv()

    때마다 read실행 파일에서 한 줄을 읽는 decode_csv작업이이 라인의 컨텐츠를 해결하고 텐서리스트로 변환됩니다. 입력 파라미터 삭제하는 경우, record_default파라미터는 디폴트 값 유형 텐서에 따라 설정 될 수있다.

    전화에서 run또는 eval수행하기 read전에, 당신은 호출해야 tf.train.start_queue_runners큐에 파일 이름을 입력 할 수 있습니다. 그렇지 않으면, read조작은 큐의 파일 이름 값을 가지고에 차단됩니다.

    # 使用string_input_producer来生成一个先入先出的队列
    filename_queue = tf.train.string_input_producer(['file0.csv', 'file1.csv'])
    # 使用阅读器读取
    reader = tf.TextLineReader()
    key,value = reader.read(filename_queue)
    # decord result
    recorde_defaults = [[1], [1], [1], [1], [1]]
    col1,col2,col3,col4,col5 = tf.decode_csv(value, record_defaults=record_defaults)
    features = tf.concat(0, [col1,col2,col3,col4])
    # start popularing the filename queue
    with tf.Session() as sess:
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
      for i in range(1200):
            example,label = sess.run([features, cols])
        coord.request_stop()
        coord.join(threads) # join the queue
  • 고정 길이 이진 데이터에서 읽기

    고정 길이 이진 파일에서 데이터를 읽기, 당신은 사용할 수 있습니다 tf.FixedLengthRecordReader에서 tf.decode_raw동작을 제어한다. decode_raw작동이 unit8 텐서의 문자열로 변환 할 수 있습니다.

    같은 파일 포맷이 정의되어있는 경우, 각 레코드의 길이를, 라벨 바이트 고정되고, 후자는 3072의 화상 데이터이다. UINT8 텐서는 사진을 도출하고 필요에 따라 재 조립 할 수 있습니다.

  • TFRecode 표준 형식

    이 방법은 더 쉽게 TensorFlow 데이터 세트는 네트워크 애플리케이션 아키텍처와 일치하는이 방법은 할 수있다, 당신은 형식으로 임의의 데이터가 TensorFlow를 지원 말할 수있다. 이 제안 방법은 TFRecords 파일을 사용하는 것입니다.

    TFRecode 파일에 포함 된 tf.train.Example프로토콜 메모리 블록 (프로토콜 버퍼)는, 상기 메모리 블록을 상기 프로토콜 필드는 고유 특징 포함한다. 코드를 획득하는 단계, 및 기록 된 데이터에 의해, 메모리 블록 프로토콜 예 및 문자열로의 메모리 블록의 순서로 데이터가 될 수 tf.python_io_TFRecordWriterTFRecords 파일 클래스를 작성.

    파일에서 데이터를 읽을 TFRecords, 당신은 사용할 수 있습니다 파서를. 동작 할 수있다 프로토콜 메모리 블록 (프로토콜 버퍼) 텐서를 해결한다.tf.TFRecordReadertf.parse_single_exampleparse_single_exampleExample

전처리

넌 수 tensorflow/models/image/cifar10/cifar10.py데이터의 임의의 일부를 추출하고, 정규화 된 미리 처리 된 데이터의 일례를 찾아, 따라서 노이즈 또는 왜곡을 증가시킨다.

일괄

데이터 입력 라인의 끝에서, 우리는 교육, 평가, 추론을 수행하는 또 다른 샘플 입력 큐가 있어야합니다. 따라서, 우리는 사용하는 tf.train.shuffle_batch기능을 큐에 스크램블 샘플을 처리 할 수 있습니다.

def read_file(filename_queue):
    reader = tf.SomeReader()
    key,record_string = reader.read(filename_queue)
    example,label = tf.some_decoder(record_string) # 解码器
    processed_example = some_processing(example)
return processed_example,label

def input_pipeline(filenames, batch_size, num_epochs=None):
    filename_queue = tf.train.string_input_producer(
        filenames,num_epochs=num_epochs,shuffle=True
    )
    example,label = read_file(filename_queue)
    # min_after_dequeue defines how big a buffer we will randomly sample
  #   from -- bigger means better shuffling but slower start up and more
  #   memory used.
  # capacity must be larger than min_after_dequeue and the amount larger
  #   determines the maximum we will prefetch.  Recommendation:
  #   min_after_dequeue + (num_threads + a small safety margin) * batch_size
  min_after_dequeue = 10000
    capacity = min_after_dequeue + 3*batch_size
    example_batch, label_batch = tf.train.shuffle_batch(
        [example, label], batch_size = batch_size,capacity=capacity,
        min_after_dequeue=min_after_dequeue
    )
    return example_batch,label_batch

당신은 순서와 다른 파일의 병렬 처리, 당신이 사용할 수있는 방법 중 더 필요한 경우 tf.train.shuffle_batch_join기능의 예 :

def read_my_file_format(filename_queue):
  # Same as above

def input_pipeline(filenames, batch_size, read_threads, num_epochs=None):
  filename_queue = tf.train.string_input_producer(
      filenames, num_epochs=num_epochs, shuffle=True)
  example_list = [read_my_file_format(filename_queue)
                  for _ in range(read_threads)]
  min_after_dequeue = 10000
  capacity = min_after_dequeue + 3 * batch_size
  example_batch, label_batch = tf.train.shuffle_batch_join(
      example_list, batch_size=batch_size, capacity=capacity,
      min_after_dequeue=min_after_dequeue)
  return example_batch, label_batch

또 다른 대안이다 : 사용 tf.train.shuffle_batch하는 기능을 설정 num_threads1보다 큰 값. 이 제도는 이전이 아니라, 동시에 여러 파일을 읽을 수있는 (단일 스레드 읽기 속도보다 여전히 더 나은하지만) 같은 문서 읽기 동작 시간을 보장 할 수 있습니다. 이 솔루션의 장점은 다음과 같습니다

  • 같은 파일에서 동일한 샘플을 읽기 위해 두 개의 서로 다른 스레드를 피하십시오.
  • 과도한 디스크 검색 작업을 피하십시오.
스레드를 생성하고 프리 페치 객체를 사용 QueueRunner

위에 나열된 많은 사용 tf.train기능을 추가 QueueRunner하여 데이터 흐름 그래프. 당신이 어떤 교육 단계를 실행하기 전에 호출 할 필요가 tf.train.start_queue_runners기능을, 또는 데이터 흐름 다이어그램은 항상 중단됩니다. tf.train.start_queue_runners실 공급 라인을 시작합니다이 기능은, 샘플 대기열에서 샘플을 얻을 수 디큐 작업에 대한 대기열에 가득 차 있습니다. 이 경우는 바람직하게는 함께 사용되어 tf.train.Coordinator, 스레드 에러의 경우에 적절히 근접 할 수 있도록. 당신이 훈련 반복의 수를 제한 할 경우, 당신은 카운터 훈련의 반복 수를 사용해야하고, 초기화 할 필요가있다.

권장 사항 :

# Create the graph, etc.
init_op = tf.initialize_all_variables()

# Create a session for running operations in the Graph.
sess = tf.Session()

# Initialize the variables (like the epoch counter).
sess.run(init_op)

# Start input enqueue threads.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)

try:
    while not coord.should_stop():
        # Run training steps or whatever
        sess.run(train_op)

except tf.errors.OutOfRangeError:
    print 'Done training -- epoch limit reached'
finally:
    # When done, ask the threads to stop.
    coord.request_stop()

# Wait for threads to finish.
coord.join(threads)
sess.close()

스레드와 큐

비동기 TensorFlow 계산 큐 사용시 것은 강력한 메커니즘이다.

  • 코디네이터 다음과 같이 공동 작업을위한 복수의 스레드는 동기화가 종료, 주요 방법은 다음과 같습니다

    should_stop():如果线程应该停止则返回True。
    request_stop(<exception>): 请求该线程停止。
    join(<list of threads>):等待被指定的线程终止。
    
    # 线程体:循环执行,直到`Coordinator`收到了停止请求。
    # 如果某些条件为真,请求`Coordinator`去停止其他线程。
    def MyLoop(coord):
      while not coord.should_stop():
        ...do something...
        if ...some condition...:
          coord.request_stop()
    
    # Main code: create a coordinator.
    coord = Coordinator()
    
    # Create 10 threads that run 'MyLoop()'
    threads = [threading.Thread(target=MyLoop, args=(coord)) for i in xrange(10)]
    
    # Start the threads and wait for all of them to stop.
    for t in threads: t.start()
    coord.join(threads)
  • QueueRunner는 : QueueRunner는 함께 같은 코디네이터에 엔큐 동작을 실행할 수있는 스레드들의 세트를 생성한다.

    # Create a queue runner that will run 4 threads in parallel to enqueue
    # examples.
    qr = tf.train.QueueRunner(queue, [enqueue_op] * 4)
    
    # Launch the graph.
    sess = tf.Session()
    # Create a coordinator, launch the queue runner threads.
    coord = tf.train.Coordinator()
    enqueue_threads = qr.create_threads(sess, coord=coord, start=True)
    # Run the training loop, controlling termination with the coordinator.
    for step in xrange(1000000):
        if coord.should_stop():
            break
        sess.run(train_op)
    # When done, ask the threads to stop.
    coord.request_stop()
    # And wait for them to actually do it.
    coord.join(threads)

영업 이익 인터페이스

OP-정의 된 인터페이스

이익은, 등록시 인터페이스 TensorFlow 시스템을 정의하는 레지스터 연산, 입력 (타입 명) 및 출력 (타입 및 이름)를 지정하고, 필요한 특성을 설명.

 #include "tensorflow/core/framework/op.h"
REGISTER_OP("ZeroOut")
    .Input("to_zero: int32")
    .Output("zeroed: int32");
연산 커널은 달성하기 위해

인터페이스를 정의한 후, 또는 OP 복수 달성했다. 이러한 커널 상속의 각각에 대응하는 클래스를 만들고 OpKernel, 피복 Compute방법. Compute이 방법은 제공 유형 OpKernelContext*파라미터를 context유용한 정보에 대한 액세스.

예를 들면 :

#include "tensorflow/core/framework/op_kernel.h"
using namespace tensorflow;
class ZeroOutOp : public OpKernel {
 public:
  explicit ZeroOutOp(OpKernelConstruction* context) : OpKernel(context) {}
  void Compute(OpKernelContext* context) override {
    // 获取输入 tensor.
    const Tensor& input_tensor = context->input(0);
    auto input = input_tensor.flat<int32>();
   // 创建一个输出 tensor.
    Tensor* output_tensor = NULL;
    OP_REQUIRES_OK(context, context->allocate_output(0, input_tensor.shape(),
                                                     &output_tensor));
    auto output = output_tensor->template flat<int32>();
    // 设置 tensor 除第一个之外的元素均设为 0.
    const int N = input.size();
    for (int i = 1; i < N; i++) {
      output(i) = 0;
    }
    // 尽可能地保留第一个元素的值.
    if (N > 0) output(0) = input(0);
  }
};

시스템에 등록 된 커널 실현 후 TensorFlow. 등록, 커널 런타임 인스턴스를 지정할 수 있습니다 제약의 복수의 GPU에서 실행, 다른 CPU에서 실행하는 커널을 지정할 수 있습니다.

# 将下列代码加入到 zero_out.cc 中, 注册 ZeroOut op:
REGISTER_KERNEL_BUILDER(Name("ZeroOut").Device(DEVICE_CPU), ZeroOutOp);

사용자 지정 데이터 읽기

파일 형식 리더를 작성

1.Reader은 파일 읽기에 기록하도록 설계되었습니다. TensorFlow 내장 된 리더 연산의 예 :

리더의 인터페이스는 생성자 인 같은 유일한 차이이다. 가장 중요한 방법은 읽기된다. 언제든지 필요할 때 그것은 계급을 통해 줄 매개 변수, 매개 변수가 필요합니다, 당신은 파일 이름을 읽을 수 있습니다 (예 : 읽기 연산이 처음 실행할 때, 또는 파일에서 읽은 Read` 마지막 레코드 전). 키 문자열과 문자열 값 : 두 개의 스칼라 텐서를 생성합니다.

SomeReader라는 이름의 새로운 리더를 작성, 당신은 다음과 같은 단계가 필요합니다 :

  1. C ++에서의 정의에서 tensorflow :: ReaderBase의 "SomeReader"라는 이름의 서브 클래스.
  2. C ++에서 "SomeReader"라는 이름의 새로운 리더와 연산 커널을 등록합니다.
  3. 파이썬에서는 정의 tf.ReaderBase의 "SomeReader"라는 이름의 서브 클래스를.
    다음 방법을 수행 할 수 있습니다 :
  • OnWorkStartedLocked : 다음 파일을 엽니 다
  • ReadLocked : 기록이나 보고서 EOF / 오류를 읽고
  • OnWorkFinishedLocked : 현재 파일을 닫습니다
  • ResetLocked : 빈 기록, 예를 들면 : 기록 오류

2. 등록 작전. 호출 명령에 정의되어 사용이 필요 tensorflow / 코어 / 프레임 워크 / op.h의 에서 REGISTER_OP.

#include "tensorflow/core/framework/op.h"
REGISTER_OP("TextLineReader")
    .Output("reader_handle: Ref(string)")
    .Attr("skip_header_lines: int = 0")
    .Attr("container: string = ''")
    .Attr("shared_name: string = ''")
    .SetIsStateful()
    .Doc(R"doc(
A Reader that outputs the lines of a file delimited by '\n'.
)doc");

3. 정의하고 OpKernel를 등록합니다. OpKernel를 정의하려면, 독자 정의에 사용할 수 있습니다 tensorflow / 코어 / 프레임 워크 / reader_op_kernel.h 다운 바로 가기 ReaderOpKernel에서 실행 SetReaderFactory라는 생성자입니다. 클래스 정의 필요하면 REGISTER_KERNEL_BUILDER (...)에 의해 클래스를 등록해야합니다.

 #include "tensorflow/core/framework/reader_op_kernel.h"
class TextLineReaderOp : public ReaderOpKernel {
 public:
  explicit TextLineReaderOp(OpKernelConstruction* context)
      : ReaderOpKernel(context) {
    int skip_header_lines = -1;
    OP_REQUIRES_OK(context,
                   context->GetAttr("skip_header_lines", &skip_header_lines));
    OP_REQUIRES(context, skip_header_lines >= 0,
                errors::InvalidArgument("skip_header_lines must be >= 0 not ",
                                        skip_header_lines));
    Env* env = context->env();
    SetReaderFactory([this, skip_header_lines, env]() {
      return new TextLineReader(name(), skip_header_lines, env);
    });
  }
};
REGISTER_KERNEL_BUILDER(Name("TextLineReader").Device(DEVICE_CPU),
                        TextLineReaderOp);
  1. 파이썬 래퍼 추가, 당신은 tensorflow.python.ops.io_ops 가져와야 tensorflow / 파이썬 /는 user_ops / user_ops.py을 하고, 추가 io_ops.ReaderBase 파생 기능을.

    from tensorflow.python.framework import ops
    from tensorflow.python.ops import common_shapes
    from tensorflow.python.ops import io_ops
    class SomeReader(io_ops.ReaderBase):
        def __init__(self, name=None):
            rr = gen_user_ops.some_reader(name=name)
            super(SomeReader, self).__init__(rr)
    ops.NoGradient("SomeReader")
    ops.RegisterShape("SomeReader")(common_shapes.scalar_shape)

    당신은 할 수 io_ops.py / / 파이썬 / 작전을 tensorflow 몇 가지 예를 볼 수 있습니다.

    레코드 형식의 영업 이익을 기록

    연산 일반은 입력으로 기록 스칼라 문자열이 필요하므로 다음과 연산의 설명을 추가합니다 . 당신은 입력으로 스칼라 문자열을 선택하고 오류 메시지에 포맷 신고 잘못된 데이터를 구성 할 수 있습니다.

    기록 복호화 연산의 예 :

여러 연산의 사용이 특정 레코딩 형식이 유효 디코딩 할 수 있습니다. 예를 들어, 문자열 형식에 저장 한 tf.train.Example 프로토콜 버퍼 이미지 파일. 이미지의 형식, 당신은에서 할 수 있습니다 tf.parse_single_example의 반응과 읽기 연산 호출 출력 tf.decode_jpeg , tf.decode_png , 또는 tf.decode_raw을 . 판독 및 출력 tf.decode_raw에 대한 응답으로 사용 tf.slicetf.reshape을 데이터를 추출하는 일반적인 방법이다.

사용 GPU

  • "/cpu:0": 기계 CPU
  • "/gpu:0": 기계 GPU, 당신이 그 중 하나가 있다면.
  • "/gpu:1": 등등 기계 번째 GPU, 그리고 ...

오퍼레이터가이 디바이스에 할당되는 CPU 및 GPU 구현 모두에서 동작 TensorFlow은, GPU는 우선 순위를 갖는 경우, 예컨대 matmulCPU와 GPU 커널 함수 존재한다. 그렇게 cpu:0gpu:01, matmul동작에 할당된다 gpu:0.

실행을 수행하는 GPU를 할당합니다 :

# 新建一个 graph.
with tf.device('/gpu:2'):
  a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
  b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
  c = tf.matmul(a, b)
# 新建 session with log_device_placement 并设置为 True.
sess = tf.Session(config=tf.ConfigProto(
      allow_soft_placement=True, log_device_placement=True))
# 运行这个 op.
print sess.run(c)

공유 변수

공유 변수의 방법은 별도의 코드 블록과 그 기능을 만들도록 이용된다.

variables_dict = {
    "conv1_weights": tf.Variable(tf.random_normal([5,5,32,32]), name="conv1_weights"),
    "conv1_biases":tf.Variable(tf.zeros([32]), name="conv1_biases"),
    ...
}

def my_image_filter(input_images, variables_dict):
    conv1 = tf.nn.conv2d(input_images, variables_dict["conv1_weights"],
        strides=[1, 1, 1, 1], padding='SAME')
    relu1 = tf.nn.relu(conv1 + variables_dict["conv1_biases"])

    conv2 = tf.nn.conv2d(relu1, variables_dict["conv2_weights"],
        strides=[1, 1, 1, 1], padding='SAME')
    return tf.nn.relu(conv2 + variables_dict["conv2_biases"])

# The 2 calls to my_image_filter() now use the same variables
result1 = my_image_filter(image1, variables_dict)
result2 = my_image_filter(image2, variables_dict)

상기 방법은, 편리하지만,이 외에 있지만 모듈 코드의 변수를 사용하여 생성되지만 그 밀봉 훼손 :

  • 코드에서 변수 이름, 유형 구축을 위해 노력 나타냅니다, 모양이 만들어집니다.
  • 코드가 변경되면, 시외 전화는 아마 더 많거나 적은 또는 변수의 서로 다른 유형의 생산 것이다.

이 문제를 해결하는 한 가지 방법은 클래스의 사용은 신중하게 그들이 필요로하는 변수를 관리하는 데 필요한 모듈을 만들 클래스를 사용하는 것입니다. 더 현명한 방법은 클래스를 호출하지 않지만, TensorFlow를 사용하는 것은 제공 변수 범위 지정 메커니즘을 뷰를 구성 할 때, 이전에 변수 이름을 쉽게 공유 할 수 있습니다.

변수 범위

변수 범위 지정 메커니즘은 주로에서 TensorFlow의 두 부분으로 구성되어 있습니다 :

  • tf.get_variable(<name>, <shape>, <initializer>): 변수를 만들거나 주어진 이름으로 돌아왔다.
  • tf.variable_scope(<scope_name>)다음 tf.get_variable()네임 스페이스 변수 이름.

메소드 tf.get_variable()를 호출하는 대신, 구 또는 변수를 생성하는 데 사용되는 tf.Variable것이이 (가) 초기의 형상을 작성하는 방법이며, 이러한 형상에 대해 텐서를 제공 초기화하는데 사용 등을들 수있다. 이러한 방법은 직접 tf.Variable '의 값을 구하는 것은 아니다. 여기에 일부에 TensorFlow에 사용되는 변수를 초기화 할 수 있습니다 :

  • tf.constant_initializer(value) 모든 초기화 값 제공

  • tf.random_uniform_initializer(a, b)균일 A에서 B로 초기화

  • tf.random_normal_initializer(mean, stddev) 주어진 평균 및 표준 편차 균일 초기화와.

    # 单独创建一个卷积的函数,共享变量权重和偏置封装
    def conv_relu(input, kernel_shape, bias_shape):
        # Create variable named "weights".
        weights = tf.get_variable("weights", kernel_shape,
            initializer=tf.random_normal_initializer())
        # Create variable named "biases".
        biases = tf.get_variable("biases", bias_shape,
            initializer=tf.constant_intializer(0.0))
        conv = tf.nn.conv2d(input, weights,
            strides=[1, 1, 1, 1], padding='SAME')
        return tf.nn.relu(conv + biases)

    tf.variable_scope() 변수는 해당 네임 스페이스를 지정합니다.

    def my_image_filter(input_images):
        with tf.variable_scope("conv1"):
            # Variables created here will be named "conv1/weights", "conv1/biases".
            relu1 = conv_relu(input_images, [5, 5, 32, 32], [32])
        with tf.variable_scope("conv2"):
            # Variables created here will be named "conv2/weights", "conv2/biases".
            return conv_relu(relu1, [5, 5, 32, 32], [32])
    # 开始调用
    result1 = my_image_filter(image1)
    result2 = my_image_filter(image2)
    # Raises ValueError(... conv1/weights already exists ...)

    당신은 같이 볼 수 있듯이 tf.get_variable()변수가 기존 공유를 감지되었는지 여부. 당신은 당신이에 의해, 다음을 사용할 필요가 같이 공유 할 경우 reuse_variables()이 방법을 지정.

    with tf.variable_scope("image_filters") as scope:
        result1 = my_image_filter(image1)
        scope.reuse_variables()
        result2 = my_image_filter(image2)

특정 메커니즘을 참조하십시오 Tensorflow 자습서

추천

출처www.cnblogs.com/cecilia-2019/p/11368278.html