TensorFlow.js는 Google이 개발한 오픈 소스 머신 러닝 라이브러리 TensorFlow의 JavaScript 버전입니다. 웹 브라우저나 Node.js 환경에서 머신 러닝 모델을 훈련시키고 실행할 수 있게 해주며, 프론트엔드 개발자들이 브라우저 내에서 직접 머신 러닝 모델을 구현하고 사용할 수 있게 합니다.
웹 애플리케이션의 사용자는 텍스트 영역(textarea
)에 자신의 감정이나 생각을 표현하는 문장을 입력합니다. 예를 들어, 사용자가 "I feel very happy today because I received some great news!"라고 입력할 수 있습니다.
입력된 텍스트를 분석한 결과, 감정 분석 모델은 감정 점수를 계산하여 사용자에게 제공합니다. 이 점수는 텍스트의 긍정성을 나타내며, 예를 들어 0.8
(80% 긍정적)과 같은 형태로 출력될 수 있습니다. 웹 페이지에는 "Sentiment Score: 80%"라고 표시됩니다.
<template>
<div>
<!-- 입력 필드: 사용자로부터 텍스트 입력 받음 -->
<textarea v-model="userInput" placeholder="Type something..."></textarea>
<!-- 버튼 클릭 시 감정 분석 함수 호출 -->
<button @click="analyzeSentiment">Analyze</button>
<!-- 분석 결과 표시 -->
<p v-if="sentiment">Sentiment Score: {{ sentiment }}</p>
</div>
</template>
<script>
import * as tf from '@tensorflow/tfjs';
export default {
data() {
return {
userInput: '', // 사용자 입력을 저장하는 변수
sentiment: null // 감정 분석 결과를 저장하는 변수
};
},
methods: {
// 모델 로드
async loadModel() {
// TensorFlow.js를 사용하여 사전 훈련된 모델 로드
const model = await tf.loadLayersModel('/path/to/sentiment_model/model.json');
this.model = model;
},
// 감정 분석 실행
async analyzeSentiment() {
// 사용자 입력을 모델에 전달하여 예측 실행
const prediction = await this.model.predict([this.userInput]);
this.sentiment = prediction.dataSync()[0];
}
},
// 컴포넌트 마운트 시 모델 로드
mounted() {
this.loadModel();
}
};
</script>
이 예시에서는 사용자가 이미지를 업로드하고, 웹 페이지에서 실시간으로 이미지를 분류하는 모델을 사용하여 결과를 표시합니다. TensorFlow.js를 활용하여 Svelte 애플리케이션 내에서 모델을 실행합니다.
사용자는 웹 인터페이스를 통해 이미지 파일을 업로드합니다. 예를 들어, 사용자가 자신의 강아지의 사진을 업로드할 수 있습니다.
업로드된 이미지는 모델에 의해 분석되고, 결과로 강아지의 종류와 분류에 대한 확신도(예: 95% 확률로 "래브라도 리트리버")가 표시됩니다. 웹 페이지에는 "Detected breed: Labrador Retriever with 95% confidence"라고 표시됩니다.
<script>
import * as tf from '@tensorflow/tfjs';
let imageFile; // 사용자가 업로드한 이미지 파일을 저장할 변수
let classificationResult; // 이미지 분류 결과를 저장할 변수
// 이미지 파일 처리 및 모델을 사용한 분류 함수
function handleFileChange(event) {
const fileReader = new FileReader();
fileReader.readAsDataURL(event.target.files[0]);
fileReader.onload = async (e) => {
const imgElement = document.createElement('img');
imgElement.src = e.target.result;
imgElement.onload = async () => {
const processedImage = tf.browser.fromPixels(imgElement);
const model = await tf.loadLayersModel('/path/to/model.json');
const prediction = await model.predict(processedImage);
classificationResult = `Detected breed: ${prediction.className} with ${Math.round(prediction.probability * 100)}% confidence`;
};
};
fileReader.readAsDataURL(imageFile);
}
</script>
<main>
<!-- 이미지 파일을 업로드할 input 요소 -->
<input type="file" bind:files={imageFile} on:change={handleFileChange}>
<!-- 분류 결과 표시 -->
<p>{classificationResult}</p>
</main>
이 Svelte 컴포넌트는 사용자가 이미지를 업로드할 때마다 해당 이미지를 분석하고 객체를 식별합니다. TensorFlow.js를 활용하여 브라우저 내에서 모델을 실행하고 결과를 실시간으로 표시합니다. 이는 MLOps 원칙에 따라 모델의 성능을 모니터링하고 필요에 따라 업데이트하여 최적의 사용자 경험을 제공합니다.