반응형
05-15 00:00
Today
Total
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
관리 메뉴

개발하는 고라니

[Tensorflow.js] 모델 Save & Load 본문

Programming/Tensorflow.js

[Tensorflow.js] 모델 Save & Load

조용한고라니 2021. 1. 9. 17:12
반응형

이전에 데이터를 가지고 비어있는 모델에게 여러 번 반복 학습을 시키며 원하는 모델을 만들었다. 이 모델을 만드는데 많은 리소스가 필요했다. 힘들게 모델을 만들었는데 다른 웹 페이지를 갖다가 다시 돌아오면 어떻게 될까? 만들어 놓은 모델은 사라졌으므로 다시 만드는 작업을 진행할 것이다. 이와 같은 이유로 모델의 생성과 사용은 분리되야한다.

 

만들어진 모델은 file, upload, localstorage, indexedDB 등과 같은 곳에 보관할 수 있다.


www.tensorflow.org/js/guide/save_load

 

모델 저장 및로드  |  TensorFlow.js

TensorFlow.js는 Layers API로 생성되었거나 기존 TensorFlow 모델에서 변환 된 모델을 저장하고로드하는 기능을 제공합니다. 이것은 여러분이 직접 훈련 한 모델이거나 다른 사람들이 훈련 한 모델 일 수

www.tensorflow.org

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
    <script>
        let temperature = [20, 21, 22, 23, 24, 25, 26, 27];
        let product = [40, 42, 44, 46, 48, 50, 52, 54];

        let cause = tf.tensor(temperature);
        let result = tf.tensor(product);

        let X = tf.input({shape: [1]}); //원인이 1개(온도) 이므로 []안의 값이 1
        let Y = tf.layers.dense({units: 1}).apply(X); //결과가 1개(음료) 이므로 값이 1

        let model = tf.model({inputs: X, outputs: Y});
        let compileParam = {optimizer: tf.train.adam(), loss: tf.losses.meanSquaredError}
        model.compile(compileParam);


        let fitParam = {epochs:3000
                        , callbacks:{
                            onEpochEnd: function(epoch, logs) {
                                console.log('epoch', epoch, 'RMSE =>', Math.sqrt(logs.loss));
                            }
                        }};
        model.fit(cause, result, fitParam).then(function(data) {

            //모델 이용하기
            let nextTemperature = [15, 16, 17, 18, 19];                              //다음 주 온도
            let nextCause = tf.tensor(nextTemperature, [nextTemperature.length, 1]); //다음 주 원인
            let nextResult = model.predict(nextCause);                               //다음 주 결과
            
            nextResult.print(); //console에 출력
        });
    </script>

이전의 코드에 추가하는 식으로 한다.

# 저장

  • 로컬 저장소(Browser only)
  • IndexedDB(Browser only)
  • 파일 다운로드(Browser only)
  • HTTP(s) 요청
  • 네이티브 파일 시스템(Node.js only)

 

> 파일 다운로드

await 명령어는 현재 코드에서는 작동하지 않으므로 제거하고 model.save()를 해보자.

model.fit(cause, result, fitParam).then(function(data) {

    //모델 이용하기
    let nextTemperature = [15, 16, 17, 18, 19];                              //다음 주 온도
    let nextCause = tf.tensor(nextTemperature, [nextTemperature.length, 1]); //다음 주 원인
    let nextResult = model.predict(nextCause);                               //다음 주 결과

    nextResult.print(); //console에 출력

    model.save('downloads://gorany');
});

위 코드가 실행이 되면 모델이 만들어진 후 ['gorany.weights.bin', 'gorany.json'] 2개의 파일이 다운로드 된다. 이 파일에 우리가 학습시킨 모델이 들어있다.

 

> 로컬 저장소

페이지가 리로드되거나, 다른 웹 페이지에서도 같은 도메인이라면 이 모델을 읽어들일 수 있다.

model.fit(cause, result, fitParam).then(function(data) {

    //모델 이용하기
    let nextTemperature = [15, 16, 17, 18, 19];                              //다음 주 온도
    let nextCause = tf.tensor(nextTemperature, [nextTemperature.length, 1]); //다음 주 원인
    let nextResult = model.predict(nextCause);                               //다음 주 결과

    nextResult.print(); //console에 출력

    //model.save('downloads://gorany'); //파일 다운로드
    model.save('localstorage://gorany'); //로컬 저장소
});

위 코드가 실행되면 모델을 학습시킨 후 F12(개발자도구) - Application - Storage - Local Storage에서 확인할 수 있다.

 

 

# 로드

  • 로컬 저장소(Browser only)
  • IndexedDB(Browser only)
  • HTTP(s) 요청
  • 네이티브 파일 시스템(Node.js only)

> 로컬 저장소

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
<script>
  tf.loadLayersModel('localstorage://gorany').then(function(model) {
  	model.predict(tf.tensor([25])).print();
  })
</script>

모델을 변수로써 사용하지 않을 것이기에 모델을 로드 후 함수를 실행시키는데 함수의 인자로 model을 주어 '25'를 줘서 실행시킨다.

 

<본 포스팅은 '생활코딩'의 Tensorflow.js 수업을 진행하며 작성됩니다.>

opentutorials.org/course/4628/29773

반응형

'Programming > Tensorflow.js' 카테고리의 다른 글

[Tensorflow.js] 모델 만들기  (0) 2021.01.09
[Tensorflow.js] 선행 학습된 Model  (0) 2021.01.09
Comments