StoryCode

docker-compose, models.config, http 테스트 호출

인공지능,AI,학습,ML,Tensorflow, Cafee2,MLFlow/Tensorflow
반응형

docker-compose.yml

    tfsservice:
        build:
            context: .
            dockerfile: Dockerfile.tfs
        image: tensorflow/serving
        container_name: tfs
        hostname: tfs
        command:
            - '--model_config_file=/models/models.config'
            - '--model_config_file_poll_wait_seconds=60'
        volumes:
            - ./volume.tfs/models:/models/
        ports:
            - 8500:8500
            - 8501:8501
        networks:
            - backend

 

models.config

git clone https://github.com/tensorflow/serving


model_config_list:
{
    config:
    {
        name:"serving"
        base_path:"/models/serving/tensorflow_serving/servables/tensorflow/testdata/saved_model_half_plus_two_cpu"
        model_platform: "tensorflow"
    }
}

 

command line >

curl -d '{"instances": [1.0, 2.0, 5.0]}' -X POST http://localhost:8501/v1/models/serving:predict 
{ 
    "predictions": [2.5, 3.0, 4.5 
    ] 
}


v1/models 는 디폴트로 입력
serving 은 models.config 의 name

 

반응형

AttributeError: 'module' object has no attribute 'pack'

인공지능,AI,학습,ML,Tensorflow, Cafee2,MLFlow/Tensorflow
반응형

Attribute tf.pack 이 tf.stack 으로 변경됨.

반응형

NotFoundError: Key ... not found in checkpoint

인공지능,AI,학습,ML,Tensorflow, Cafee2,MLFlow/Tensorflow
반응형

오류 상황) 변수를 저장후 출력해보면, 변수명 끝에 _1 이 붙는다.

실행을 한 번더 하면 _2 가 된다.


해결) 커널 리스타트 를 해야 한다. 중간부터 다시 실행하면 "오류상황" 과 같은 문제가 발생한다.

쥬피터에서는 동그란 화살표의 Restart 버튼을 클릭하면 된다.

반응형

Saver 에서 save 후, CheckpointVariables 변수 보기

인공지능,AI,학습,ML,Tensorflow, Cafee2,MLFlow/Tensorflow
반응형

1) 아래 소스 추가


inspect_checkpoint.py


2) Traine 소스에서, 


임포트후,

from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file


저장하고,

ckpt_path = saver.save(sess, 'saved1/train1')


출력하면

print_tensors_in_checkpoint_file(ckpt_path, all_tensors=True, tensor_name='', all_tensor_names=False)


결과가 나온다.

tensor_name:  b_h1_3

[ 1.5395054e-03  0.0000000e+00  1.7294792e-02 -1.9801984e-05

 -3.9077952e-04  1.9007076e-07  2.1687772e-02  1.2043750e-05

  2.5410240e-04  0.0000000e+00]











PS) print_tensors_in_checkpoint_file 파라미터 설명


file_name: not a physical file, just the prefix of filenames

If no tensor_name is provided, prints the tensor names and shapes in the checkpoint file. If tensor_name is provided, prints the content of the tensor.(inspect_checkpoint.py)

If all_tensor_names is True, Prints all the tensor names

If all_tensor is 'True`, Prints all the tensor names and the corresponding content.

N.B. all_tensor and all_tensor_names will override tensor_name

반응형

Linear regresision, Logistic

인공지능,AI,학습,ML,Tensorflow, Cafee2,MLFlow/Tensorflow
반응형

1) Linear regression



2) Logistic regression



반응형

MNST-input data 로 기본적 트레이닝 테스트

인공지능,AI,학습,ML,Tensorflow, Cafee2,MLFlow/Tensorflow
반응형

[ 참조 : MNST ] 


import tensorflow as tf


# input_data 가 [ 0, 0, 0, 1, 0 ] 가 [0, 0, 0, 1, 0] 이 다섯클래스다라는 것을 트레이닝

# 추후에 input_data 를 data set 으로 확장하면 됨.

input_data = [1, 5, 3, 7, 8 ,10, 12]

lable_data = [0, 0, 0, 1, 0] // 5 class




INPUT_SIZE = 7

HIDDEN1_SIZE = 10

HIDDEN2_SIZE = 8

CLASSES = 5




# input_data 와 lable_data 를 텐서로 바꾸기.

# shape=[X, Y], 

#           X = input_data set 의 개수, set이 100개면 100, 하지만 보통은 모르기때문에 None

#           Y = input_data 의 class 개수, 7

x = tf.placeholder(tf.float32, shape=[1, INPUT_SIZE])

y_ = tf.placeholder(tf.float32, shape=[1, CLASSES])





# 모델설계

# 신경망은 매트릭스연산 => Weight Matrix 설계 => Input data X Weight= 결과노드 => 결과 X Weight =결과노드 의 반복

# Weight 설계는 Variable로 제작

# truncated_normal = normal distribution,  디폴트평균 mean = 0.0, stddev = 1.0 사용 https://www.tensorflow.org/api_docs/python/tf/truncated_normal

# matmul : Matrix 곱셈


feed_dict = {x : input_data, y_ : lable_data}

W_h1 = tf.Variable(tf.truncated_normal(shape=[INPUT_SIZE, HIDDEN1_SIZE]), dtype=tf.float32)

b_h1 = tf.Variable(tf.zeros(shape=[HIDDEN1_SIZE]), dtype=tf.float32)



hidden1 = tf.matmul(x, W_h1) + b_h1


# 한번 더 반복

W_h2 = tf.Variable(tf.truncated_normal(shape=[HIDDEN1_SIZE, HIDDEN2_SIZE]), dtype=tf.float32)

b_h2 = tf.Variable(tf.zeros(shape=[HIDDEN2_SIZE]), dtype=tf.float32)

hidden2 = tf.matmul(hidden1, W_h2) + b_h2



# Output Layer


W_o = tf.Variable(tf.truncated_normal(shape=[HIDDEN2_SIZE, CLASSES]), dtype=tf.float32)

b_o = tf.Variable(tf.zeros(shape=[CLASSES]), dtype=tf.float32)


# Output 까지 아래와 같은 레이어로 그려진것.

# Hidden Layer 는 바꿔가며 트레이닝 테스트해야 함.

# 그래프는 아래와 같다.




# 트레이닝을 시키지 위해서는 Cost Function을 작성해야 한다.




반응형

트레이닝 샘플

인공지능,AI,학습,ML,Tensorflow, Cafee2,MLFlow/Tensorflow
반응형

import tensorflow as tf

import numpy as np


input_data = [1, 5, 3, 7,8, 10, 12]

lable_data = [0, 0, 0, 1, 0] // "input_data 로 들어온 데이타는 00010 이다." 라고 학습 트레이닝 시킨다.

//데이타가 하나뿐이라 오버피팅은 발생한다.



반응형

Constant, Variable, Placeholder 의 차이점.

인공지능,AI,학습,ML,Tensorflow, Cafee2,MLFlow/Tensorflow
반응형

Constant)

이전 예제에서 Constant 로 그래프 세션을 그리고 디바이스로 실행하는 샘플을 보았다.

우선, Constant 는 그 자체로서 그래프 세션이 된다.

( 잘 사용되지는 않음. )



Variable)

뉴럴 네트워크에서 weight 정의시 담아두는 공간으로 주로 사용.

Consant 와 다르게 아래와 같이 Constant 와 동일한 방식으로 Variable 을 실행하면 오류가 나타난다.

var1 = tf.Variable([5])

var2 = tf.Variable([3])

var3 = tf.Variable([2])

var4 = var1 + var2 + var3

sess = tf.Session()

result = sess.run(var4)

print result


오류가 나타나는 이유는 Variable 은 초기화가 필요하기 때문이다.

초기화 함수는 tf.initialize_all_variables() 이다.

즉,

var1 = tf.Variable([5])

var2 = tf.Variable([3])

var3 = tf.Variable([2])

var4 = var1 + var2 + var3

sess = tf.Session()

init = tf.initialize_all_variables()

sess.run( init )

result = sess.run(var4)

print result


여기서

init = tf.initialize_all_variables()

sess.run( init )

는 그래프를 생성하지만 값은 배정되지 않은 상태( 마치 데이타베이스 옵티마이저의 플랜만 떠진 상태) 라고 보면 된다.


이후

result = sess.run(var4)

에서 빈 그래프에 값을 배정해서 디바이스에서 실행하게 된다.


참고로, initialize_all_variables global_variables_initializer 로 변경



Placeholder)

다른 자료형을 매핑해서 텐서로 변경주는 역할.

placeholder 는 그래프를 생성시키지 않는다.

그래서 feeding 이라는 단계가 필요하다.


아래에서


value1 = 5 // 데이타를 만들고

value2 = 3

value3 = 2


ph1 = tf.placeholder( dtype=tf.float32 ) // shape은 선택사항

ph2 = tf.placeholder( dtype=tf.float32 )

ph3 = tf.placeholder( dtype=tf.float32 )

result_value = ph1 * ph2 + ph3 // value 는 없이, 껍데기 placeholder 로 그래프 생성


feed_dict = {ph1: value1, ph2: value2, ph3: value3} // feeding 단계, result_value 는 feed_dict 이전/ 이후 어디에 써도 상관없다. Session 전에만 있으면 됨.


sess = tf.Session()

result = sess.run(result_value, feed_dict=feed_dict)

print (result)




이미지로 트레이닝 샘플)

image = [[1, 2, 3, 4, 5],

             [5, 4, 3, 2, 1],

             [10, 20, 30, 40, 50] // list 일수도 있고, num file array 일수도 있고...

label = [10, 20, 30, 40, 50]


ph_image = tf.placeholder(dtype=tf.float32)

ph_label = tf.placeholder(dtype=tf.float32)


feed_dict = {ph_image: image, ph_label: label}


result_tensor = ph_image + ph_label


이후 image 에 데이타 불러오는 방법 (opencv, pandas.DataFrame... ) 은 쉽다.




기타)

- True/ Flase, And/Or

tf.Variable([True, True, False, False, True], dtype=bool)

tf.constant([10, 20, 30, 40, 50], dtype=bool)


- tensorflow 의 특징 : 디바이스에 올려서 도는 중에 데이터 매트릭스 모델오류를 발견하는 게 아니라, 돌기전에 데이타 매트릭스 모델을 먼저 체크하고 디바이스에 올려서, 디바이스 올린이후에 오류걱정은 할 필요가 없어진다.

반응형

graph 및 기본 연산 샘플

인공지능,AI,학습,ML,Tensorflow, Cafee2,MLFlow/Tensorflow
반응형

[ 베스트 참조 ] https://www.youtube.com/channel/UCRyIQSBvSybbaNY_JCyg_vA



ex> 5 x 4 x 3 x 2 x 1 = ? 을 그래프로 정의



ex> 2(5 + 4) + 3(1 + 2) = ? 을 그래프로 정의

1) 그래프의 (?) 을 실행하면, 그래프 (텐서플로에서는 session 이라 부름) 를 device (cpu or gpu) 에서 심음.


2) 동작구조



3) 세션은 File 로 I/O handle 된다.


4) 그래프의 (?) = sess.run() 이다.


5) 단일 const 그래프를 연산하는 샘플

import tensorflow as tf

const = tf.constant([10, 20, 30, 40, 50], dtype=tf.float32)

sess = tf.Session()

result = sess.run (const)

print (result)


6) 다중 const 그래프를 생성하는 샘플 (디바이스로 보내기전)

import tensorflow as tf

a =tf.constant([5]);

b =tf.constant([10]);

c =tf.constant([2]);

d = a * b + c // 여기까지가 "모델을 만들었다" 고 표현함.


7) 6)세션을 디바이스로 보내 실행.

sess = tf.Session()

result = sess.run(d)

print (result)


52


반응형

데이타 타입

인공지능,AI,학습,ML,Tensorflow, Cafee2,MLFlow/Tensorflow
반응형

[ 참조 ] www.tensorflow.org


- tensorflow.placeholder(dtype, shape, name)

   : Method

   : input data 를 담아두고 tensor 매핑.

   : graph 를 만들지 않는다.


   dtype : tf.float32

   shape : input data shape


- variables

   : Object

   : 생성자 __init__(initial_value, trainable.트레이닝할거냐?, ...)

   weight matrix 가 variables 로 만들어진다.


- tensorflow.constant

   : 상수


- Sample Code


import tensorflow as tf

ph =tf.placeholder(tf.float32, shape=[3,3])

var = tf.variable([1,2,3,4,5], dtype.float32)

const = tf.constant([10, 20, 30, 40, 50], dtype=tf.float32)

print ph

print var

print var

































반응형