<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>hye_ju.log</title>
        <link>https://velog.io/</link>
        <description>🍮</description>
        <lastBuildDate>Thu, 02 Jan 2025 16:02:40 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <image>
            <title>hye_ju.log</title>
            <url>https://velog.velcdn.com/images/hye_ju/profile/d830e5a0-3f64-4d0e-801b-b9d26d6c2e70/image.jpg</url>
            <link>https://velog.io/</link>
        </image>
        <copyright>Copyright (C) 2019. hye_ju.log. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/hye_ju" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[[Paper Review] How Contextual are Contextualized Word Representations? Comparing the Geometry of BERT, ELMo, and GPT-2 Embeddings (Contextual Embedding)]]></title>
            <link>https://velog.io/@hye_ju/Paper-Review-How-Contextual-are-Contextualized-Word-Representations-Comparing-the-Geometry-of-BERT-ELMo-and-GPT-2-Embeddings-Contextual-Embedding</link>
            <guid>https://velog.io/@hye_ju/Paper-Review-How-Contextual-are-Contextualized-Word-Representations-Comparing-the-Geometry-of-BERT-ELMo-and-GPT-2-Embeddings-Contextual-Embedding</guid>
            <pubDate>Thu, 02 Jan 2025 16:02:40 GMT</pubDate>
            <description><![CDATA[<h2 id="1-anisotropy">1. Anisotropy</h2>
<blockquote>
<p>Contextualized representations are anisotropic in all non-input layers. If word representations from a particular layer were isotropic(i.e., directionally uniform), then the average cosine similarity between uniformly randomly sampled words would be 0(Arora et al., 2017). The closer this average is to 1, the more anistropic the representations.</p>
</blockquote>
<ul>
<li><p>isotropic: 등방성(좌), anisotropic: 이방성, 비등방성(우)
<img src="https://velog.velcdn.com/images/hye_ju/post/9b2b323b-1dbb-4e08-b7fc-975133fe88bc/image.png" alt="">-&gt; 임베딩에서 isotropic은 주어진 vocab의 임베딩 벡터들이 사방으로 향함, anisotropic은 벡터가 주어진 공간에서 특정 방향으로 향해 일종의 cone 형태 이룸. </p>
</li>
<li><p>GPT-2의 마지막 층에서는 두 무작위 단어의 코사인 유사도가 거의 1에 가까울 정도로 극단적 anisotropy 
<img
src="https://velog.velcdn.com/images/hye_ju/post/d75177eb-2ce2-47cf-aeb9-63c4787d9b31/image.png" width=500 height=500></p>
<blockquote>
<p>In almost all layers of BERT, ELMo, and GPT-2, the word representations are anisotropic(i.e., not directionally uniform): the average cosine similarity between uniformly randomly sampled word is non-zero. The one exception is ELMo&#39;s input layer; this is not surprising given that it generates character-level embeddings without using context. Representations in higher layers are generally more anisotropic than those in lower ones.</p>
</blockquote>
</li>
</ul>
<h2 id="2-문맥에-따른-단어-표현context-specificity">2. 문맥에 따른 단어 표현(Context-Specificity)</h2>
<h3 id="1-self-similarity">(1) Self-Similarity</h3>
<p>: 평균 코사인 유사도로 계산됨, 특정 레이어에서 단어 표현의 문맥 특이성 측정 지표
(1-&gt;0으로 값이 변할수록 문맥 특이성이 최대가 됨)</p>
<ul>
<li>높은 레이어일수록 문맥 특이성 강해짐(self-similarity 감소로)</li>
<li>GPT-2의 마지막 레이어는 거의 최대의 문맥 특이성</li>
<li>ELMo의 입력 레이어는 self-similarity가 1(정적 임베딩을 사용하므로)</li>
</ul>
<h3 id="2-stopwords">(2) stopwords</h3>
<ul>
<li>‘the’, ‘of’, ‘to’ 등의 stopwords-&gt; 문맥 특이성이 가장 큼 (self-similarity가 낮음)</li>
<li>다의어 아니어도 문맥에 따라 다양한 표현적 특성 나타냄</li>
</ul>
<h3 id="3-문장-내-단어-유사도intra-sentence-similarity">(3) 문장 내 단어 유사도(Intra-Sentence Similarity)</h3>
<p><img
src="https://velog.velcdn.com/images/hye_ju/post/738574e1-f37a-4215-a766-17a7ce1f1549/image.png" width=500 height=500> </p>
<ul>
<li>문장 내 단어 표현은 문맥화가 잘 되어 있더라도 서로 유사하지 않을 수 있음</li>
</ul>
<h2 id="3-정적-vs-문맥화된-표현">3. 정적 vs. 문맥화된 표현</h2>
<h3 id="1-maximum-explainable-variancemev">(1) Maximum Explainable Variance(MEV)</h3>
<p>: 단어의 문맥화된 표현 중 정적 임베딩으로 설명 가능한 분산의 비율</p>
<ul>
<li>정적 임베딩이 단어의 문맥화된 표현을 얼마나 잘 대체할 수 있는지에 대한 상한선 제공</li>
<li>adjusted MEV<ul>
<li>문맥화된 표현의 anisotropy 조정을 위해 무작위로 샘플링 된 단어 표현의 첫 번째 주성분으로         설명되는 분산 비율을 차감하여 계산</li>
</ul>
</li>
</ul>
<h3 id="2-관찰-결과">(2) 관찰 결과</h3>
<ul>
<li>ELMo, BERT, 또는GPT-2의 어떤 레이어에서도 단어의 문맥 분산이 단어의 문맥적 표현에서 5% 이상의 분산을 평균적으로 정적 임베딩으로 설명할 수 없음-&gt; 정적 임베딩이 문맥화된 표현을 대체하기에 매우 제한적(GPT-2의 2~11 레이어는 높은 anisotropy로 인해 raw MEV가 약 30%로 나타남) </li>
<li>단어 표현의 문맥화 모델은 단순히 한정된 개수의 단어 의미 표현 중 하나를 할당하지 않음(그렇지 않았다면 MEV 비율 더 높음)</li>
</ul>
<h3 id="3-principal-components">(3) Principal Components</h3>
<ul>
<li>낮은 레이어(예: BERT Layer 1)의 문맥화된 표현은 GloVe 및 FastText보다 여러 벤치마크에서 더 우수한 성능이 나타남<blockquote>
<p> Principal components of contextualized representations in lower layers outperform GloVe and FastText on many benchmarks.</p>
</blockquote>
</li>
</ul>
<h3 id="reviewed-paper">[Reviewed Paper]</h3>
<p><a href="https://arxiv.org/abs/1909.00512">https://arxiv.org/abs/1909.00512</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Paper Review] Low-Rank Adaptation of Large Language Models (LoRA)]]></title>
            <link>https://velog.io/@hye_ju/Paper-Review-Low-Rank-Adaptation-of-Large-Language-Models-LoRA</link>
            <guid>https://velog.io/@hye_ju/Paper-Review-Low-Rank-Adaptation-of-Large-Language-Models-LoRA</guid>
            <pubDate>Fri, 27 Dec 2024 14:56:52 GMT</pubDate>
            <description><![CDATA[<h2 id="1-overall-summary-of-the-whole-content">1. Overall Summary of the whole content</h2>
<p>LoRA는 사전학습된 모델의 가중치를 고정하고, 각 트랜스포머 레이어에 학습 가능한 low-rank 행렬을 추가하여 다운스트림 작업에 적응하도록 한다. 논문에서는 LLM을 효율적으로 fine-tuning하기 위한 새로운 방법인 LoRA를 제안한다.</p>
<h2 id="2-details">2. Details</h2>
<h3 id="1-low-rank-행렬을-통한-효육적인-fine-tuning">1) Low-Rank 행렬을 통한 효육적인 fine-tuning</h3>
<ul>
<li>Pre-trained된 LLM의 모든 가중치를 업데이트하는 대신, 특정 레이어에서 가중치 행렬을 low-rank approximation 으로 분해하여 fine-tuning.</li>
<li>기존 모델과 유사하거나 더 나은 성능을 제공</li>
<li>학습해야 할 파라미터의 수를 많이 줄일 수 있음.<ul>
<li>계산 효율성 증가</li>
<li>메모리 사용량 감소</li>
</ul>
</li>
</ul>
<h3 id="2-gpt-3-175b-모델에서-lora의-성능">2) GPT-3 175B 모델에서 LoRA의 성능</h3>
<p><img src="https://velog.velcdn.com/images/hye_ju/post/21fba88a-4bfd-4949-80a2-65d442bd904c/image.png" alt=""></p>
<ul>
<li>GPT-3 175B 모델을 대상으로 실험한 결과, LoRA는 1/10,000 수준의 적은 파라미터로 학습하지만 전체 모델을 업데이트한 것과 비슷한 성능을 달성</li>
<li>GPU 메모리 사용량을 기존보다 약 3배 감소시키면서 추론 속도는 유지 </li>
</ul>
<h3 id="3-pytorch-통합-패키지">3) Pytorch 통합 패키지</h3>
<ul>
<li>pre-trained된 가중치와 LoRA가 적용된 새로운 모델의 체크포인트 제공</li>
<li>RoBERTa, DeBERTa, GPT-2 등 주요 사전 학습 모델에 LoRA를 통합하는 방법 설명</li>
</ul>
<h3 id="4-기존의-어댑터-기반-접근-방식의-추론-지연-문제-해결">4) 기존의 어댑터 기반 접근 방식의 추론 지연 문제 해결</h3>
<ul>
<li>LoRA는 low-rank 행렬을 활용하여 추론 지연 시간 없이 높은 효율성 달성</li>
<li>추론 할 때에도 원래의 가중치 W에 ΔW=A를 더하는 방식으로 동작하여 지연 시간이 발생하지 않음</li>
<li>학습 처리량 증가로 대규모 모델에서도 활용 가능</li>
</ul>
<h2 id="3-conclusion">3. Conclusion</h2>
<p>논문과 같은 접근방식을 통해 LLM의 미세 조정 시 발생하는 효율성 문제 및 자원 소모 등을 해결하는 데 큰 기여를 할 수 있다. 특히 LoRA는 메모리 제약이 있는 환경에서 유용하며, LLM을 더 적은 자원으로 더 많은 작업에 적용가능하게 한다. 따라서 추론, 학습, 메모리 사용의 전반적인 최적화를 달성하는 데 굉장히 효과적인 방법으로 평가받고 있다.</p>
<h3 id="reviewed-paper">[Reviewed Paper]</h3>
<p><a href="https://arxiv.org/pdf/2106.09685">https://arxiv.org/pdf/2106.09685</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Naive Bayes - Count vectorization, TF-IDF]]></title>
            <link>https://velog.io/@hye_ju/Naive-Bayes-Count-vectorization-TF-IDF</link>
            <guid>https://velog.io/@hye_ju/Naive-Bayes-Count-vectorization-TF-IDF</guid>
            <pubDate>Fri, 20 Dec 2024 14:32:04 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p> Using raw string text for Machine Learning models<br>= &quot;Natural Language Processing&quot; : Supervised learning text tasks</p>
</blockquote>
<h2 id="1-bayes-theorem">1. Bayes&#39; Theorem</h2>
<p>Naive Bayes -&gt; Bayes&#39; Theorem으로 supervised learning classify 
<img
src="https://velog.velcdn.com/images/hye_ju/post/6e42e70e-8f6c-44b0-a669-8efda657b42f/image.png" width="60%" height="50%"></p>
<h2 id="2-nlp-classification---joint-probability">2. NLP Classification - Joint probability</h2>
<p>Bayes&#39; Theorem을 Machine Learning Model로 conversion이 가능하다.
<img src="https://velog.velcdn.com/images/hye_ju/post/6239909a-d7e0-452c-903b-a5b9911d3aed/image.png" alt=""><img src="https://velog.velcdn.com/images/hye_ju/post/7dfbb536-54d5-4b90-9dfd-f6d78e2ab0cf/image.png" alt=""></p>
<ul>
<li>여기서 Numerator: Equal to joint probability model -&gt; chain rule에 의해 product of conditional probabilities로 표현 가능 (물론, 모든 x feature가 independent하다는 가정하에)</li>
</ul>
<p>따라서, 최종 joint model(the full Naive Bayes Model)은 아래와 같이 적을 수 있음. <img src="https://velog.velcdn.com/images/hye_ju/post/4c35c91d-3f0e-485a-9c2d-7a74ee1ee908/image.png" alt=""></p>
<h2 id="3-variation-of-naive-bayes-model">3. Variation of Naive Bayes Model</h2>
<p>Naive Bayes Model의 variation으로는 Multinomial/Gaussian/Complement/Categorical/Bernoulli 등으로 다양함.
이 중 가장 잘 이용되는 모델은 Multinomial Naive Bayes Model.</p>
<h2 id="4-two-main-methods-of-extracting-features-from-text-data">4. Two main methods of extracting features from text data</h2>
<h3 id="1-count-vectorization">1) Count Vectorization</h3>
<ul>
<li><p>각 document에 있는 가능한 모든 단어들을 겹치지 않게 펼치고 frequency count vector를 생성한다.</p>
</li>
<li><p>Document Term Matrix(DTM) 예시 <img
src="https://velog.velcdn.com/images/hye_ju/post/183727a6-4b48-4f68-adf4-a1c84c6dd7b9/image.png" width=60% height=60%></p>
</li>
<li><p>most value: 0 (sparse함) -&gt; document가 클수록 더 sparse해짐</p>
</li>
<li><p>표에서 [단어들: feature, 빈도수 백터: strength of feature]</p>
</li>
</ul>
<h3 id="2-tf-idf-term-frequency-inverse-document-frequency">2) TF-IDF (Term Frequency-Inverse Document Frequency)</h3>
<ul>
<li>DFT 채우는 대신 Document Frequency issue 해결: common할 stop words들 처리</li>
<li>Inverse Document Frequency: non-stop words들이 common한 document 고려</li>
</ul>
<blockquote>
<p>희귀-&gt; weight 증가시킴
흔함-&gt; weight 감소시킴 (값이 0에 가까울수록 단어가 common)</p>
</blockquote>
<p><img
src="https://velog.velcdn.com/images/hye_ju/post/ef32f8b5-d356-4874-9416-742e1b5a0c04/image.png" width=60% height=60%></p>
<p>예를 들어, 100개 word에서 &#39;run&#39; 100개면 IDF는
-&gt; log 1 = 0</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Web-Crawling]]></title>
            <link>https://velog.io/@hye_ju/Web-Crawling</link>
            <guid>https://velog.io/@hye_ju/Web-Crawling</guid>
            <pubDate>Wed, 11 Dec 2024 14:16:55 GMT</pubDate>
            <description><![CDATA[<h2 id="1-crawling">1. Crawling</h2>
<ul>
<li>크롤러: 크롤링 과정을 수행하는 소프트웨어 -&gt; data mining, AI 언어 모델, 빅데이터 분석 등 다양한 IT 영역에서 필수적인 역할 수행</li>
</ul>
<blockquote>
<p>web crawling -&gt; 웹페이지를 그대로 가져와서 그 안에서 데이터를 추출하는 과정</p>
</blockquote>
<ul>
<li><p>주된 목적: 정보 수집 및 분류를 위해 다양한 웹 페이지를 방문하여 데이터를 모으고 이를 체계적으로 분류하고자 함.</p>
</li>
<li><p>Ex) ChatGPT -&gt; 웹크롤링 기반으로 학습할 데이터 가져옴.</p>
</li>
</ul>
<p><img src="https://velog.velcdn.com/images/hye_ju/post/06db8865-9acc-4177-a893-e0aa905036cb/image.png" alt=""></p>
<ul>
<li><p>웹 크롤링 vs 웹 스크래핑</p>
<ul>
<li>웹 크롤링(web-crawling): 정해진 링크를 따라 연결된 페이지를 가져오는 것 -&gt; 자동화 봇인 웹 크롤러가 정해진 규칙에 따라 웹페이지들을 브라우징하는 행위</li>
<li>웹 스크래핑(web-scraping): 웹 크롤러가 수집하는 페이지가 있을 때 추출하고자 하는 위치의 데이터를 가져오는 것 -&gt; 웹 사이트의 데이터를 수집하는 수집하는 모든 작업</li>
</ul>
</li>
</ul>
<h2 id="2-web-crawling-method---python">2. Web-Crawling Method - Python</h2>
<h3 id="1-requests-beautifulsoup-라이브러리-다운로드">(1) requests, beautifulsoup 라이브러리 다운로드</h3>
<ul>
<li>명령 프롬프트 CMD창에서 명령어 작성하여 다운로드<pre><code>pip install requests
pip install beautifulsoup4
</code></pre></li>
</ul>
<pre><code>- 각 라이브러리의 역할:

    - requests: 웹 서버에 정보를 요청하고 그 결과를 가져옴 -&gt; 원하는 웹 페이지에 HTTP 요청을 보내고, 그 응답을 쉽게 처리할 수 있도록 함. 
    - beautifulsoup: 가져온 HTML 문서에서 필요한 정보를 추출 -&gt; HTML을 파싱하고 원하는 태그, 클래스, 아이디 등을 기준으로 원하는 정보를 쉽게 찾을 수 있음.


### (2) 웹 크롤링 순서
1. 타깃 URL 선택 및 설정
크롤링할 웹사이트의 타깃 URL을 선정하고, 첫 번째 방문할 페이지의 URL을 설정

2. 웹 페이지 다운로드
- 설정된 URL로 HTTP 요청을 보내고, 응답으로 받은 HTML 데이터를 다운로드
- 일반적으로 Python에서는 requests 라이브러리를 사용

3. HTML 파싱
- 다운로드한 HTML 파일에서 원하는 데이터를 추출하기 위해 파싱 작업을 진행 (웹 파싱: 웹 상의 자연어, 컴퓨터 언어 등 일련의 문자열들을 분석하는 과정)
- 주로 BeautifulSoup 같은 라이브러리를 사용하여 DOM 구조를 분석

4. 데이터 추출 및 링크 수집
- HTML 파싱 과정에서 필요한 데이터를 추출
- 동시에 페이지 내에 포함된 다른 링크(URL)를 수집하여 다음에 방문할 대상 설정도 가능

5. 데이터 저장 및 활용
추출한 데이터를 원하는 형식(CSV, JSON 등)으로 저장하거나, 데이터 분석, 모델 학습 등 다양한 목적으로 활용

## 3. 웹 크롤링 예시
-melon top100 정보 가져오기-

### &lt;특정 URL로 부터 웹페이지에 있는 텍스트(멜론의 top100 차트 정보)를 가져오기&gt;</code></pre><p>url = &quot;<a href="https://www.melon.com/chart/&quot;">https://www.melon.com/chart/&quot;</a>
headers = {&#39;User-Agent&#39;: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36&#39;}
data = requests.get(url, headers=headers)
soup = BeautifulSoup(data.text, &#39;html.parser&#39;)</p>
<pre><code>위 코드에서...
- get 함수: 지정된 URL로 HTTP GET 요청을 보내는 함수 -&gt; 지정된 URL에서 정보를 가져오겠다고 웹페이지에 선언하는 것
- data의 text 인자에는 지정된 URL의 웹페이지의 모든 텍스트가 들어가있음 -&gt; 다음 행의 BeautifulSoup에서 HTML parser를 이용하여 내용들을 잘라주는 역할을 수행

### &lt;BeautifulSoup의 HTML parser을 이용하여 텍스트를 parsing&gt;</code></pre><p>trs = soup.select(&#39;table &gt; tbody &gt; tr&#39;)
for tr in trs[:1]:
    print(tr.select_one(&#39;.rank01 &gt; span &gt; a&#39;).text)
    print(tr.select_one(&#39;.rank02 &gt; a&#39;).text)
    print(tr.select_one(&#39;.rank03 &gt; a&#39;).text)
    print(tr.select_one(&#39;img&#39;)[&#39;src&#39;])</p>
<pre><code>위 코드에서...
- select, select_one 함수: CSS 선택자를 사용하여 HTML 문서에서 원하는 요소를 찾는 데 사용
- &quot;F12&quot;키를 눌러 개발자 도구를 사용하여 좌측 상단의 마우스 모양을 클릭하고 웹페이지의 요소에 가져가면 원하는 요소가 담겨있는 코드를 쉽게 찾을 수 있음(&#39;table&#39; 태그 안, &#39;tbody&#39; 태그 안, &#39;tr&#39;태그에 원하는 정보들이 있음을 알 수 있었음).
- 태그들을 타고 들어가면, 노래 제목은 &#39;rank01&#39;의 &#39;span&#39; 태그의 &#39;a&#39; 태그에 있고,  가수는 &#39;rank02&#39; 태그의 &#39;a&#39; 태그에 있고, 앨범 정보는 &#39;rank03&#39; 태그의 &#39;a&#39;태그에 있고, 앨범 커버 이미지의 정보는 &#39;img&#39;의 &#39;src&#39;인자에 있음을 알 수 있음.
&lt;img src=&quot;https://velog.velcdn.com/images/hye_ju/post/9b8f8834-221d-45ec-8a72-7ca369fe63e7/image.png&quot; width=&quot;55%&quot; height=&quot;55%&quot;&gt;

</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[[Paper Review] Training language models to follow instructions with human feedback (InstructGPT)]]></title>
            <link>https://velog.io/@hye_ju/Paper-Review-Training-language-models-to-follow-instructions-with-human-feedback-InstructGPT</link>
            <guid>https://velog.io/@hye_ju/Paper-Review-Training-language-models-to-follow-instructions-with-human-feedback-InstructGPT</guid>
            <pubDate>Thu, 28 Nov 2024 11:29:28 GMT</pubDate>
            <description><![CDATA[<h2 id="1-overall-summary-of-the-whole-content">1. Overall Summary of the whole content</h2>
<p>기존 GPT-3와 같은 LLM은 텍스트 생성 능력이 뛰어나지만, 사용자의 명령을 완벽하게 이해하고 따르는 능력에는 여전히 한계가 있으며, 사용자의 의도와 미묘하게 어긋나는 결과를 생성하는 경우가 많다. 해당 논문에서는 언어모델이 인간의 피드백을 잘 반영하여 작동하도록 강화학습을 사용하여 GPT-3모델을 개선한 InstructGPT를 다룬다. 또, LLM이 명령을 더 잘 이해하고 수행하도록하며, 모델의 성능과 안전성 및 신뢰성을 높이는 방법론을 제안한다.</p>
<h2 id="2-details">2. Details</h2>
<h3 id="1-rlhfreinforcement-learning-from-human-feedback---sft-rm-ppo">(1) RLHF(Reinforcement Learning from Human Feedback) - SFT, RM, PPO</h3>
<p>논문에서는 RLHF를 통해 InstructGPT를 훈련시키는 방법론을 제안한다. 이는 이용자의 선호도를 모델 훈련에 반영하는 과정으로, 이전의 지도 학습 기반 모델보다 사용자 친화적인 출력 생성이 가능하여 여러 분야에서 개선된 사용자 경험을 제공한다. </p>
<p>&lt;RLHF의 주요 3단계&gt;</p>
<ol>
<li>Supervised Fine-Tuning(SFT)</li>
</ol>
<ul>
<li>prompt(명령어)와 이에 대한 적절한 응답을 수집하여 모델이 초기 학습 방향을 설정하게 함.</li>
<li>labelers(인간 평가자)가 작성한 적절한 출력 예시들을 기반으로 기존 GPT-3 모델을 초기 fine-tuning함.</li>
</ul>
<ol start="2">
<li>Reward Model Training</li>
</ol>
<ul>
<li>인간 평가자가 여러가지 출력 결과들을 비교하여 &#39;선호도&#39;를 표기한 데이터를 수집.</li>
<li>수집한 데이터를 기반으로 보상 함수를 학습(선호도를 잘 반영하는 출력 -&gt; 높은 점수를 받도록 설계).
<img src="https://velog.velcdn.com/images/hye_ju/post/82af6391-2de7-40a8-9b63-55ce95747d68/image.png" alt=""></li>
</ul>
<ol start="3">
<li>Proximal Policy Optimization(PPO)</li>
</ol>
<ul>
<li>학습된 RM을 기반으로 GPT-3을 반복적으로 fine-tuning.</li>
<li>이 알고리즘 사용으로 RM의 점수를 극대화하도록 정책 최적화.
<img src="https://velog.velcdn.com/images/hye_ju/post/6b41c92d-2887-465f-91a6-7c45973b71c2/image.png" alt=""></li>
</ul>
<p>&lt;인간 피드백 데이터의 한계&gt;</p>
<ul>
<li>평가자 간 의견 불일치로 reward model 학습 시 잡음이 생길 수 있음.</li>
<li>평가자 개인의 선호도나 편향이 데이터에 포함될 가능성이 존재.</li>
<li>고품질 피드백 데이터를 얻으려면 많은 시간과 비용이 소요됨.</li>
</ul>
<h3 id="2-instructgpt---성능-개선">(2) InstructGPT - 성능 개선</h3>
<img src="https://velog.velcdn.com/images/hye_ju/post/72a6df2d-2436-4be8-b796-86877854343e/image.png" width="50%" height="50%">
기존의 GPT-3모델과 비교했을 때, InstructGPT는 사용자 선호도 및 명령 수행 정확도등의 지표들에서 큰 개선을 보였다. 특히 훈련 과정에서 사용자 피드백이 잘못된 출력을 보정하도록 유도하여 편향 및 오류를 감소시켰으며, 소규모의 피드백 데이터만으로도 모델의 성능을 크게 향상시켜 데이터의 효율성을 증폭시켰다.

<p>&lt;주요한 결과들을 정리해보면...&gt;</p>
<ul>
<li>동일한 파라미터 크기를 기준으로 비교했을 때, 더 뛰어난 명확성과 일관성.</li>
<li>핵심 내용 위주의 응답(불필요/과도한 정보 줄임).</li>
<li>입력 명령에 적합한 응답 비율이 2배 이상 향상.</li>
</ul>
<h3 id="3-소규모-모델의-효율적-활용">(3) 소규모 모델의 효율적 활용</h3>
<p>InstructGPT는 기존의 GPT-3과 같은 175B 파라미터 모델뿐만 아니라, 소규모 파라미터 모델에서도 성능 향상을 보여준다. RLHF를 적용한 소규모 모델은 동일 크기의 기존 GPT-3모델보다 높은 사용자 선호도를 보이는데, 이는 그저 모델 크기를 늘리는 것만으로는 해결되지 않는 품질 문제를 RLHF가 효과적으로 보완하였음을 의미한다. </p>
<p>&lt;결과적 효율성&gt;</p>
<ul>
<li>중소형 규모의 하드웨어에서도 고품질 언어 모델을 배포할 수 있는 가능성을 제시</li>
<li>모델 비용의 효율성 및 소규모 모델에서도 사용 가능한 응용 사례 증가</li>
</ul>
<p>&lt;의의&gt;</p>
<ul>
<li>자원이 제한된 환경에서도 사용자(인간) 친화적인 모델 활용 가능성을 열어줌.</li>
<li>소규모 모델의 실용적 사용 사례를 증가시켜 대규모 파라미터 모델의 독점적인 사용을 완화 -&gt; 다양한 규모의 AI 모델 개발에 기여.</li>
</ul>
<h3 id="4-편향-및-안전성-문제">(4) 편향 및 안전성 문제</h3>
<p>InstructGPT도 여전히 완벽하지는 못하며, &lt;인간 피드백 데이터의 한계&gt;에서 언급한 바와 같이, 훈련 데이터 및 평가자의 개인적인 편견을 반영할 위험이 있고 공격적인 언어를 생성할 수도 있다는 등의 몇몇 문제들이 남아있다. 이에 대비해 평가자들의 다양성을 높이고, 여러 관점을 반영하는 피드백 시스템 도입이 필요하다. 또, 유해한 응답이나 부정적인 발언에 낮은 점수를 주도록 학습시키는 등의 보상 구조 개선도 필요한 상황으로, 이에 대한 연구도 진행중이다.</p>
<h3 id="5-이론과-구현-현실-사이의-차이">(5) 이론과 구현 현실 사이의 차이</h3>
<ul>
<li>PPO 알고리즘을 활용하여 모델을 강화학습할 때 reward model의 점수를 극대화하는 방향으로 최적화를 수행한다고 하지만, PPO 알고리즘의 효율성은 모델의 복잡도나 크기에 따라 달라질 수 있다.</li>
<li>평가자 간의 의견 불일치나 데이터의 노이즈가 생길 수 있으며, 이는 reward model의 학습에 부정적인 영향을 미쳐서 최적화가 불안정해지거나 모델이 잘못 학습할 수 있다.</li>
</ul>
<p>&lt;PPO 알고리즘의 적용 코드 예시&gt;</p>
<pre><code>import gym
from stable_baselines3 import PPO

# OpenAI Gym 환경 불러오기
env = gym.make(&#39;CartPole-v1&#39;)

# PPO 모델 학습
model = PPO(&#39;MlpPolicy&#39;, env, verbose=1)
model.learn(total_timesteps=10000)

# 학습된 모델 저장
model.save(&quot;ppo_cartpole&quot;)

# 모델 테스트
obs = env.reset()
for _ in range(1000):
    action, _states = model.predict(obs, deterministic=True)
    obs, reward, done, info = env.step(action)
    if done:
        obs = env.reset()
</code></pre><h2 id="3-conclusion">3. Conclusion</h2>
<p>논문의 InstructGPT는 지도학습, 보상 모델 학습, 그리고 강화학습을 단계적으로 실행하여 기존 GPT-3 모델보다 사용자 선호도에 더 부합한 결과를 출력하는 것에 성공했다. 제안된 방법론은 언어모델의 신뢰성을 향상시킬 뿐만 아니라, 현실에서의 적용 가능성도 실질적으로 입증했다. 
향후에는 데이터의 편향 문제를 완화하고, 다양한 배경을 포괄할 수 있는 확장된 피드백 시스템 도입이 필요하다. 이 논문에서 진행된 연구는 모델의 성능을 높이는 것에 그치지 않고, AI 시스템이 인간과 더욱 조화롭게 협력할 수 있는 방향성까지 나아가 제시했다는 점에서 큰 의의를 지닌다. </p>
<h3 id="reviewed-paper">[Reviewed Paper]</h3>
<p><a href="https://arxiv.org/pdf/2203.02155">https://arxiv.org/pdf/2203.02155</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Paper Review] Improving Language Understanding
 by Generative Pre-Training (GPT-1)]]></title>
            <link>https://velog.io/@hye_ju/Paper-Review-Improving-Language-Understanding-by-Generative-Pre-Training-GPT-1</link>
            <guid>https://velog.io/@hye_ju/Paper-Review-Improving-Language-Understanding-by-Generative-Pre-Training-GPT-1</guid>
            <pubDate>Thu, 21 Nov 2024 15:49:55 GMT</pubDate>
            <description><![CDATA[<h2 id="1-overall-summary-of-the-whole-content">1. Overall Summary of the whole content</h2>
<p>이 페이퍼는 Generative Pre-Training(GPT) 방식으로 자연어처리 성능을 개선하는 방법을 제안한다. (그 결과, 이전의 지도학습 기반 모델보다 더 적은 label data로 높은 성능을 달성.)</p>
<h3 id="제안된-방법론">&lt;제안된 방법론&gt;</h3>
<ul>
<li><p>Generative Pre-Training: 대량의 비지도 데이터를 활용한 사전 학습 수행
<img src="https://velog.velcdn.com/images/hye_ju/post/5ea56078-bed0-4d1a-9d9b-f3e8072fd120/image.png" alt=""><img src="https://velog.velcdn.com/images/hye_ju/post/1b3fccf9-90c7-4904-a324-f2a943bf8ca0/image.png" alt=""></p>
</li>
<li><p>Fine-tuning(미세 조정): 사전 학습된 모델을 task별로 적은 label data로 조정
<img src="https://velog.velcdn.com/images/hye_ju/post/c0791f29-e60e-4d4d-bd96-dca048c56d57/image.png" alt=""><img src="https://velog.velcdn.com/images/hye_ju/post/4fec71d7-5c7c-41fa-8fea-a1677f4d1eaf/image.png" alt=""><img src="https://velog.velcdn.com/images/hye_ju/post/a93fcb98-aaf9-4769-85b8-6950e12b58e7/image.png" alt=""></p>
</li>
</ul>
<ul>
<li>아키텍처: Transformer 구조를 기반으로, 기존의 RNN, LSTM보다 병렬화 및 성능에서 이점이 있음.</li>
</ul>
<blockquote>
<p>... we explore a semi-supervised approach for language understanding tasks using a combination of unsupervised pre-training and supervised fine-tuning.
... (생략) ...
For our model architecture, we use the Transformer, which has been shown to perform strongly on various tasks such as machine translation, document generation, and syntactic parsing. This model choice provides us with a more structured memory for handling long-term dependencies in text, compared to alternatives like recurrent networks, resulting in robust transfer performance across diverse tasks.</p>
</blockquote>
<h2 id="2-details">2. Details</h2>
<h3 id="1-사전-학습-기반-언어-모델의-필요성과-새로운-접근">(1) 사전 학습 기반 언어 모델의 필요성과 새로운 접근</h3>
<ul>
<li><p>기존의 NLP모델: task별로 훈련되었고, label data를 많이 필요로 함 
  -&gt; task간의 일반화 어려움 + task별로 모델을 따로 학습이 필요하다는 비효율성 + 데이터 부족 문제 + 학습 비용 증가 </p>
</li>
<li><p>논문에서 제안된 방법: 비지도(사전)학습을 통해 언어모델의 일반적 언어 이해 능력 학습, 이를 다양한 task에 적용가능하게 하여 학습 데이터 요구량 감소</p>
</li>
</ul>
<h3 id="2-제안된-방법의-한계와-향후-연구-방향">(2) 제안된 방법의 한계와 향후 연구 방향</h3>
<ul>
<li>한계: task와 사전 학습 데이터 사이의 도메일 불일치가 있으면 성능이 저하되고, 모델 크기가 제한적이므로 대규모 데이터 활용에는 한계가 있다.</li>
<li>후속 연구: 다양한 task에서 성능 개선을 위한 사전 학습 방법 개선, 더 큰 규모의 모델과 데이터로 실험 확장(실제로도 GPT-2, GPT-3 등으로 연구가 이어짐).</li>
</ul>
<h3 id="3-연구에-대한-의문과-이에-대한-잠정적-답변">(3) 연구에 대한 의문과 이에 대한 잠정적 답변</h3>
<ul>
<li>의문: 미세 조정 이전에 사전 학습 과정을 거치는 것이 어떠한 영향을 주는가?</li>
<li>잠정적 답변: Fine-tuning전에 사전 학습을 하지 않으면, 성능이 태스크 복잡도나 데이터의 양 등에 크게 의존하게 되므로, 미세 조정 이전 단계인 사전 학습이 초기 성능을 높이는 데 중요한 역할을 한다.</li>
</ul>
<h3 id="4-이론과-현실-간의-간극과-코드-구현-방법">(4) 이론과 현실 간의 간극과 코드 구현 방법</h3>
<ul>
<li>이론과 현실의 괴리: 실제로는 메모리,GPU와 같은 하드웨어 자원과 모델 크기 등에 따라 제한을 받아 논문에서처럼 사전학습과 미세 조정을 모두 효율적으로 수행하기 어려워질 수 있다.</li>
<li>코드 구현: 딥러닝 프레임워크(pytorch, tensorflow 등)를 사용하여 Transformer구조를 구현할 수 있다.</li>
</ul>
<h3 id="5-아직-해결-못한-의문">(5) 아직 해결 못한 의문..</h3>
<p>사전 학습 데이터가 특정 도메인에 대해 편향이 있으면 모델의 성능에 영향을 줄 것 같은데, 이후에 별다른 처리 없이 바로 미세 조정 단계로 넘어가도 특정 도메인에 대한 편중이 해결되는지, 아니면 그 영향이 미미해서 무시해도 되는건지 의문이 든다.</p>
<h2 id="3-conclusion">3. Conclusion</h2>
<p>특정 task를 수행하기 위해 task별로 많은 레이블 데이터를 필요로 했던 기존의 NLP모델은 task간의 일반화를 잘 못했고, 데이터 수집 비용이 높았다. 하지만 언어 모델링 목표를 사용하여 신경망을 사전 학습한 후 감독을 통해 대상 작업에 맞게 미세 조정하는 방법을 통해 다양한 NLP task(natural language inference, text classification 등)에서 높은 성능을 달성하였다.</p>
<h3 id="reviewed-paper">[Reviewed Paper]</h3>
<p><a href="https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf">https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Paper Review] Sequence to Sequence Learning
with Neural Networks]]></title>
            <link>https://velog.io/@hye_ju/Paper-Review-Sequence-to-Sequence-Learningwith-Neural-Networks</link>
            <guid>https://velog.io/@hye_ju/Paper-Review-Sequence-to-Sequence-Learningwith-Neural-Networks</guid>
            <pubDate>Sat, 09 Nov 2024 15:46:54 GMT</pubDate>
            <description><![CDATA[<h2 id="1-overall-summary-of-the-whole-content">1. Overall Summary of the whole content</h2>
<p>위 논문은 LSTM(Long Short-Term Memory) 기반 모델을 활용한 sequence to sequence(Seq2Seq) 학습 방법을 제안한다.
<img src="https://velog.velcdn.com/images/hye_ju/post/5ccf0b38-a7f6-4efd-a68b-d423faf8772b/image.png" alt="">
(이 페이퍼에서는 4개의 layer로 이뤄진 2개의 LSTM을 사용)
<img src="https://velog.velcdn.com/images/hye_ju/post/b7ea0087-78d6-4340-bf2f-a3fc019cd56c/image.png" alt=""></p>
<p>성능을 개선하기 위해 모델에 조금씩 변주를 주며 영어-프랑스어 기계 번역 작업을 수행하고 BLEU점수를 측정한다.</p>
<h2 id="2-details">2. Details</h2>
<h3 id="1-seq2seq모델-구성---인코더디코더-아키텍처">(1) Seq2Seq모델 구성 - 인코더,디코더 아키텍처</h3>
<p>Seq2Seq모델은 입력 시퀀스를 고정된 차원의 백터로 인코딩하고, 이를 다시 목표 시퀀스로 디코딩하는 방식으로 2개의 LSTM 네트워크를 사용한다. 인코더-디코더 아키텍처가 사용되기 이전의 딥러닝 모델들은 고정된 차원의 벡터로 시퀀스를 표현하였기 때문에 입력 및 출력 시퀀스의 길이가 같거나 단순한 패턴일 때만 효과적이었다.</p>
<blockquote>
<p>&lt;Encoder-Decoder architecture 이전 딥러닝 모델들의 시퀀스 처리 방식&gt;</p>
</blockquote>
<ul>
<li>RNN : 시퀀스의 이전 상태를 다음 상태로 전달하여 데이터 처리</li>
<li><blockquote>
<p>한계: 입출력 시퀀스 길이가 동일하거나 간단한 관계여야함.</p>
</blockquote>
</li>
<li>고정된 차원의 벡터 사용</li>
<li><blockquote>
<p>한계: 문장을 고정된 차원의 벡터로 변환하여 단어의 순서 정보 유실 가능</p>
</blockquote>
</li>
</ul>
<p>-&gt; 이전 모델의 한계: 입력과 출력 시퀀스 사이의 complex mapping 처리의 어려움</p>
<h3 id="2-모델의-성능-향상---입력-시퀀스-반전하기">(2) 모델의 성능 향상 - 입력 시퀀스 반전하기</h3>
<p>이 페이퍼에서 또 한가지 주목할 부분은 source sentence들을 반전(reverse) 시켜서(target sentence는 반전시키지 않음) 성능을 향상시켰다는 점이다.</p>
<blockquote>
<p>Reversing the order of words makes it easy for SGD to &quot;establish communication&quot; between the input and the output.</p>
</blockquote>
<p>반전시킨 결과, LSTM의 test perplexity는 5.8에서 4.7로 감소했고, test BLEU 점수는 25.9에서 30.6으로 증가했다. </p>
<p>기존의 순서대로 학습(시퀀스 반전x) : &#39;문장의 맨 앞 단어&#39;&lt;-&gt;&#39;출력의 첫 단어&#39; 사이에 긴 거리가 생겨서 모델이 장기 의존성을 학습하는 데 어려움.</p>
<p>&lt;해결 방안: 입력 시퀀스를 반전시키기&gt;
입력 시퀀스를 반전시키면 시퀀스 내 단어들 사이의 단기 의존성을 강화하여 모델이 더 쉽게 학습할 수 있게 함.</p>
<blockquote>
<p>While we do not have a complete explanation to this phenomenon, we believe that it is caused by the introduction of many short term dependencies to the dataset. Normally, when we concatenate a source sentence with a target sentence, each word in the source sentence is far from its corresponding word in the target sentence. As a result, the problem has a large “minimal time lag”. (...생략)
Thus, backpropagation has an easier time “establishing communication” between the source sentence and the target sentence, which in turn results in substantially improved overall performance.</p>
</blockquote>
<h2 id="3-conclusion">3. Conclusion</h2>
<p>이 논문은 encoder-decoder 구조를 통해 가변 길이의 입력 시퀀스를 고정된 벡터로 인코딩하고 이를 디코더가 target sequence로 변환하여 예측을 수행하는 방식이 효과적임을 확인하며, Seq2Seq 모델이 sequence to sequence 학습에 좋은 성능을 보인다는 결론을 제시한다. 특히 &#39;2. Details&#39; 부분에서도 다룬 것처럼 입력 시퀀스의 반전 기법은 모델의 장기 의존성 학습을 용이하게 만들어 성능 향상에 기여하고, 이는 시퀀스 간의 거리 감소로 모델의 학습을 돕는 중요한 발견으로 해석된다.</p>
<p>따라서 Seq2Seq 모델은 시퀀스 길이에 무관하게 다양한 입력과 출력 간의 복잡한 매핑 처리가 가능하여 여러 NLP 문제에 적용가능하다는 점을 시사한다.</p>
<h3 id="reviewed-paper">[Reviewed Paper]</h3>
<p><a href="https://archive.org/details/arxiv-1409.3215">https://archive.org/details/arxiv-1409.3215</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Evaluation steps during the implementation of an ECG classification paper]]></title>
            <link>https://velog.io/@hye_ju/Evaluation-steps-during-the-implementation-of-an-ECG-classification-paper</link>
            <guid>https://velog.io/@hye_ju/Evaluation-steps-during-the-implementation-of-an-ECG-classification-paper</guid>
            <pubDate>Thu, 20 Jun 2024 09:09:16 GMT</pubDate>
            <description><![CDATA[<h2 id="1-introduction">1. Introduction</h2>
<p>논문 구현 프로젝트의 코드 작성 단계들 중 대략적인 전처리 과정과 마지막에 여러 지표들을 계산하여 평가를 하는 과정을 중점적으로 맡게 되어서, 평가지표 관련된 내용에 대해 공부하며 예전에 학습했던 기억이 있는 내용들을 상기시켜봤다. 진행한 프로젝트의 목적은 1D CNN 모델을 활용하여 ECG 데이터를 자동으로 분류하고 심장 질환을 예측하는 것이었고, 연구 범위는 ECG 신호의 전처리, 특징 추출, 그리고 분류 및 예측 모델 개발까지 포함하였다.</p>
<h2 id="2-evaluation-metrics">2. Evaluation metrics</h2>
<p><img src="https://velog.velcdn.com/images/hye_ju/post/a0a2ac2f-567e-4f2c-9a5c-8aadfb4fc2d6/image.png" alt=""></p>
<p>평가지표는 분류(classification), 회귀(regression), 랭킹, 군집화(clustering), 토픽모델링(topic modeling) 등 다양하고 각각의 모델마다 적절한 평가지표는 상이하지만, Precision-recall과 같이 통상적으로 유용하게 사용되는 지표들도 있다. 
프로젝트에서 재현하는 논문은 ECG signal을 분류하는 것으로 평가지표로는 accuracy, loss function(based on the binary cross-entropy function), precision, recall, F1-score등을 다룬다.  </p>
<h3 id="2-1-calculating-performance-indicators---accuracy-precision-recall-f1-score">2-1. Calculating performance indicators - Accuracy, Precision, Recall, F1-score</h3>
<p><img
src="https://velog.velcdn.com/images/hye_ju/post/a7494614-19ef-4efa-ba49-3bb14da59bf1/image.png" width=70% height=70%>
Accuracy, Precision, Recall 등의 지표들 계산은 위 confusion matrix의 수식들과 같다. </p>
<p>F1 score는 Precision과 Recall의 조화평균으로 아래와 같은 수식으로 구한다. 
<img src="https://velog.velcdn.com/images/hye_ju/post/f69f9fa3-b5e9-43a4-b024-df054e875426/image.png" alt=""> 이때 조화평균이 이용되는 이유는 Precision과 Recall중 더 작은 값에 영향을 많이 받게 하기 위함이다. 예를 들어 Precision = 0.9 Recall = 0.1 인 경우 F1-score = 0.18이지만 Precision = 0.6 Recall = 0.4라면 F1_score = 0.48이 된다.</p>
<h3 id="2-2-roc-curve-auc">2-2. ROC curve, AUC</h3>
<p>ROC(수용자 반응 특성, Receiver Operating Characteristic) curve는 분류기의 분류 능력을 그래프 좌표로 표현하는 방법으로 FPR ( False Positive Rate = FP/(FP+TN) )에 대한 TPR ( True Positive Rate = TP/(TP+FN) )을 여러 threshold로 조정하여 표로 그려서 표현한다.
<img src="https://velog.velcdn.com/images/hye_ju/post/c8c07249-23e1-428c-a76f-7ac4363e891c/image.png" alt="">
ROC 퍼포먼스 수치를 모델의 예상 성능을 나타내는 단일 스칼라값으로 정리하여 보고자 할 때는 ROC곡선 아래 면적 계산한 것을 이용한다. 이를  AUC(Area Under the ROC Curve)라고 한다.</p>
<h2 id="3-result">3. Result</h2>
<p>위와 같은 개념들을 활용하여 코드로 구현해본 결과, MIT-BIH dataset과 PTB-DB dataset 각각에서 논문과 유사한 결과를 얻을 수 있었다. 
(MIT-BIH - Precision: 0.9214, Recall: 0.9062, F1-score: 0.9129
 PTB-DB - Precision: 0.9812, Recall: 0.9886, F1-score: 0.9849)</p>
<p><img
src="https://velog.velcdn.com/images/hye_ju/post/1e9c6517-a83f-40db-afe5-56cb2de7e774/image.png" width=50% height=50%> <img       src="https://velog.velcdn.com/images/hye_ju/post/dfeb261b-1b1b-4c3f-a5fd-0126df0d4e74/image.png" width=50% height=50%></p>
<p><img src="https://velog.velcdn.com/images/hye_ju/post/ac8c4743-bd3e-438d-81ea-642d0231c399/image.png" alt=""></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Developing a Deep Learning  Model Trainer Using PyTorch]]></title>
            <link>https://velog.io/@hye_ju/Developing-a-Deep-Learning-Model-Trainer-Using-PyTorch</link>
            <guid>https://velog.io/@hye_ju/Developing-a-Deep-Learning-Model-Trainer-Using-PyTorch</guid>
            <pubDate>Fri, 07 Jun 2024 07:37:54 GMT</pubDate>
            <description><![CDATA[<h2 id="1-introduction">1. Introduction</h2>
<p>딥러닝 모델을 활용한 문제 해결을 위해서는 해당하는 기능을 수행할 수 있도록 구성된 학습기가 필요하다. 따라서 지도학습과 딥러닝의 관계를 정리하며 모델 학습에 대한 분류를 해봤고, 지도학습을 위한 학습기가 동작하기 위해 필요한 구성 요소들을 살펴봤다. 또, 일부 필수 구성 요소들에 대해서는 프로젝트 때 사용할 PyTorch 프레임워크를 활용한 코드도 작성하였다.</p>
<h2 id="2-모델-학습-분류">2. 모델 학습 분류</h2>
<h3 id="2-1-지도학습-supervised-learning">2-1. 지도학습 (Supervised Learning)</h3>
<p>지도학습은 간단히 말해 정답을 알려주며 학습시키는 것으로 <strong>분류 (classification: kNN, Navie Bayes, Support Vector, Machine Decision)</strong>와 <strong>회귀 (regression: Linear Regression, Locally Weighted Linear, Ridge, Lasso)</strong>가 이에 해당한다.</p>
<h3 id="2-2-비지도학습">2-2. 비지도학습</h3>
<p>비지도학습은 label이 없으며, 라벨링 되어있지 않은 데이터로부터 패턴이나 형태를 찾아 비슷한 데이터들을 군집화하는 것으로 <strong>Clustering, Dimensionality Reduction, Hidden Markov Model</strong>등이 있다.</p>
<h3 id="2-3-강화학습">2-3. 강화학습</h3>
<p>강화학습은 분류할 수 있는 데이터가 있는 것도 아니고, 데이터가 있어도 정답이 따로 정해져 있지 않으며, 자신이 한 행동에 대해 보상(reward)을 받으며 학습하는 것이다. 알파고 또한 이 강화학습 모델로 만들어졌다.</p>
<h3 id="2-4-딥러닝과의-관계-정리">2-4. 딥러닝과의 관계 정리</h3>
<p><img src="https://velog.velcdn.com/images/hye_ju/post/4c42a216-e869-4b2d-9043-dc8e399ff527/image.png" alt=""></p>
<blockquote>
<p>딥러닝은 기계를 학습시켜 AI를 만드는 것이라는 점에서는 머신러닝과 동일하지만, 보다 더 세부적이고 깊은 심층학습이 이루어진다. 이때 신경망(Neural Network)을 Deep하게 쌓아서 인공지능(인공신경망)을 만든다.</p>
</blockquote>
<p>따라서, 딥러닝은 머신러닝의 한 부분으로 볼 수 있으며, 머신러닝이 포함하는 여러 방법 중 하나가 딥러닝인 것이다. </p>
<p>딥러닝도 머신러닝의 지도학습을 사용할 수 있다. 즉, 딥러닝 모델도 입력 데이터와 해당하는 정답을 이용해 학습할 수 있다. 이 경우, 딥러닝 모델은 매우 복잡한 패턴을 학습할 수 있어서(feature들을 사람이 직접 설계해야했던 전통적인 머신러닝 기법들과 달리 자동으로 특징을 학습할 수 있으므로) 이미지 인식, 음성 인식, 자연어 처리 등에서 뛰어난 성능을 보이게 된다.</p>
<h2 id="3-model-trainer---필수-구성-요소들">3. Model Trainer - 필수 구성 요소들</h2>
<p>진행하는 프로젝트와 관련(MIT-BIH, PTB-DB database)하여 전체 코드를 블로그에 기재할 수는 없어서 필수 구성 요소들 중 일부에 대한 코드들만 아래 항목에 작성했다. </p>
<h3 id="3-1-dataset-data_loader">3-1. DataSet, data_loader</h3>
<p>: 학습 &amp; 평가를 위한 (입력, 정답) 쌍으로 구성된 학습용 dataset</p>
<pre><code># DATASET

import os
import csv
import pywt
import numpy as np
import pandas as pd
from scipy import stats
import torch
from torch.utils.data import Dataset
import matplotlib.pyplot as plt
from sklearn.utils import resample

def denoise(data, wavelet=&#39;sym4&#39;, threshold=0.04):
    w = pywt.Wavelet(wavelet)
    maxlev = pywt.dwt_max_level(len(data), w.dec_len)
    coeffs = pywt.wavedec(data, wavelet, level=maxlev)
    for i in range(1, len(coeffs)):
        coeffs[i] = pywt.threshold(coeffs[i], threshold * max(coeffs[i]))
    return pywt.waverec(coeffs, wavelet)

class ECGDataset(Dataset):
    def __init__(self, data_dir, window_size=93, max_count=10000):
        self.data_dir = data_dir
        self.window_size = window_size
        self.max_count = max_count
        self.classes = [&#39;N&#39;, &#39;L&#39;, &#39;R&#39;, &#39;A&#39;, &#39;V&#39;]
        self.X, self.y = self.load_data()
        self.X, self.y = self.balance_classes(self.X, self.y)

    def load_data(self):
        X, y = [], []
        records, annotations = self.get_files()
        for r in range(len(records)):
            signals = self.load_signals(records[r])
            annotations_data = self.load_annotations(annotations[r])
            X, y = self.extract_features(signals, annotations_data, X, y)
        return np.array(X), np.array(y)

    def get_files(self):
        records, annotations = [], []
        for root, _, files in os.walk(self.data_dir):
            records.extend([os.path.join(root, f) for f in files if f.endswith(&#39;.csv&#39;)])
            annotations.extend([os.path.join(root, f) for f in files if f.endswith(&#39;.txt&#39;)])
        records.sort(), annotations.sort()
        return records, annotations

    def load_signals(self, file_path):
        signals = []
        with open(file_path, &#39;rt&#39;) as csvfile:
            reader = csv.reader(csvfile)
            for row_index, row in enumerate(reader):
                if row_index &gt; 0:
                    signals.append(int(row[1]))
        return stats.zscore(denoise(signals))

    def load_annotations(self, file_path):
        with open(file_path, &#39;r&#39;) as file:
            return file.readlines()

    def extract_features(self, signals, annotations, X, y):
        for d in range(1, len(annotations)):
            pos, arrhythmia_type = map(int, annotations[d].split()[1:3])
            if arrhythmia_type in self.classes:
                arrhythmia_index = self.classes.index(arrhythmia_type)
                if self.window_size &lt;= pos &lt; (len(signals) - self.window_size):
                    start_idx, end_idx = pos - self.window_size, pos + self.window_size + 1
                    X.append(signals[start_idx:end_idx])
                    y.append(arrhythmia_index)
        return X, y

    def balance_classes(self, X, y):
        df = pd.DataFrame(X)
        df[&#39;label&#39;] = y
        balanced_dfs = [resample(df[df[&#39;label&#39;] == i], n_samples=5000, random_state=42+i, replace=True)
                        for i in range(len(self.classes))]
        df_balanced = pd.concat(balanced_dfs)
        return df_balanced.drop(&#39;label&#39;, axis=1).values, df_balanced[&#39;label&#39;].values

    def plot_class_distribution(self, y, title=&quot;Class Distribution&quot;):
        plt.figure(figsize=(8, 6))
        values, counts = np.unique(y, return_counts=True)
        labels = [self.classes[v] for v in values]
        plt.pie(counts, labels=labels, autopct=&#39;%1.1f%%&#39;, startangle=90)
        plt.title(title)
        plt.axis(&#39;equal&#39;)
        plt.show()

    def __len__(self):
        return len(self.X)

    def __getitem__(self, idx):
        return torch.tensor(self.X[idx], dtype=torch.float32).unsqueeze(0), torch.tensor(self.y[idx], dtype=torch.long)</code></pre><pre><code># DATA LOADER

import torch

from base import BaseDataLoader
from dataset.dataset import ECGDataset


class ECGDataLoader(BaseDataLoader):
    def __init__(self, data_dir, batch_size=8, shuffle=True, validation_split=0.2, num_workers=1, training=True):
        self.data_dir = data_dir
        dataset = ECGDataset(data_dir)
        print(len(dataset))
        super().__init__(dataset, batch_size, shuffle, validation_split, num_workers)</code></pre><h3 id="3-2-model">3-2. Model</h3>
<p>: 추론을 위한 딥러닝 모델</p>
<pre><code>import torch
import torch.nn as nn
import torch.nn.functional as F
from base import BaseModel

class ECGModel(BaseModel):
    def __init__(self, num_classes=5):
        super().__init__()
        self.conv1 = nn.Conv1d(1, 32, kernel_size=5)
        self.conv_layers = nn.ModuleList([nn.Conv1d(32, 32, kernel_size=5, padding=2) for _ in range(10)])
        self.pool = nn.MaxPool1d(kernel_size=5, stride=2)
        self.flatten = nn.Flatten()
        self.fc_layers = nn.Sequential(
            nn.Linear(64, 32),
            nn.ReLU(),
            nn.Linear(32, 32),
            nn.ReLU(),
            nn.Linear(32, num_classes),
            nn.Softmax(dim=1)
        )
        self.leaky_relu = nn.LeakyReLU()

    def forward(self, x):
        x = self.conv1(x)
        for i in range(0, len(self.conv_layers), 2):
            x1 = self.leaky_relu(self.conv_layers[i](x))
            x1 = self.conv_layers[i + 1](x1)
            x = F.relu(x1 + x)
            x = self.pool(x)
        x = self.flatten(x)
        return self.fc_layers(x)

class ECGModel2(BaseModel):
    def __init__(self, num_classes=5):
        super().__init__()
        self.conv_layers = nn.Sequential(
            nn.Conv1d(1, 16, kernel_size=5),
            nn.ReLU(),
            nn.MaxPool1d(2),
            nn.Conv1d(16, 32, kernel_size=5),
            nn.ReLU(),
            nn.MaxPool1d(2)
        )
        self.fc_layers = nn.Sequential(
            nn.Linear(1376, 120),
            nn.ReLU(),
            nn.Dropout(),
            nn.Linear(120, num_classes),
            nn.LogSoftmax(dim=1)
        )

    def forward(self, x):
        x = self.conv_layers(x)
        x = x.view(x.size(0), -1)
        return self.fc_layers(x)</code></pre><h3 id="3-3-criterion">3-3. Criterion</h3>
<p>: loss 연산을 위한 함수</p>
<pre><code>import torch.nn as nn


def ce_loss(output, target):
    criterion = nn.CrossEntropyLoss()
    return criterion(output, target)</code></pre><h3 id="3-4-other-elements--learning-process-using-the-elements">3-4. Other elements &amp; Learning process using the elements</h3>
<p>: 이외에도, 코드를 이곳에 작성하지는 않겠지만, <strong>Optimizer</strong>(학습을 위함), <strong>Train Iterator</strong>(학습을 위한 train step), <strong>Evaluation Logic</strong>(모델의 학습정도를 확인하기 위한 평가) 등의 요소들도 있다.</p>
<p><strong>&lt;학습과정&gt;</strong></p>
<blockquote>
<p>지도학습에서는 입력된 데이터를 바탕으로 모델이 정답을 추론하도록 하며, 모델이 추론한 결과와 실제 값을 비교하여 손실(loss)을 계산하고, 이를 역전파하여 모델을 학습시킨다. 위 요소들(3-1 ~ 3-4)을 통해 이러한 과정이 이루어지며, 이 과정을 반복함으로써 모델이 점차적으로 정답을 정확하게 추론할 수 있게 된다.</p>
</blockquote>
]]></description>
        </item>
        <item>
            <title><![CDATA[Data Preprocessing : One-hot-encoding]]></title>
            <link>https://velog.io/@hye_ju/Data-preprocessing-One-hot-encoding</link>
            <guid>https://velog.io/@hye_ju/Data-preprocessing-One-hot-encoding</guid>
            <pubDate>Thu, 30 May 2024 10:26:04 GMT</pubDate>
            <description><![CDATA[<h2 id="1-introduction">1. Introduction</h2>
<p>프로젝트에서 구현하기로 한 논문(<a href="https://www.sciencedirect.com/science/article/pii/S2666521222000333?via%3Dihub#abs0015)%EC%9D%80">https://www.sciencedirect.com/science/article/pii/S2666521222000333?via%3Dihub#abs0015)은</a> 데이터(MIT-BIH database, PTB-DB dataseet) 로드 후 전처리가 진행된다. 위 논문에서 데이터 전처리는 대략적으로 &#39;Annotation,Visualization -&gt; QRS complex detection -&gt; Data augmentation -&gt; Data subdivision&#39;의 단계들을 거친다.</p>
<p>이 중 Data augmentation 과정에서는 &#39;One-hot-encoding&#39;이라는 encoding method가 사용되는데, 전처리 코드를 작성하다가 논문 리뷰때 이 부분은 간단하게만 보고 넘어갔던 기억이 나서 해당 부분을 공부해보고 정리하였다.</p>
<h2 id="2-encoding-method">2. Encoding Method</h2>
<p>우선 인코딩이란 사람의 언어를 약속된 규칙에 따라 컴퓨터가 이해하는(0과 1로 이루어진) 언어로 바꾸는 것을 통틀어 일컫는다. 즉, 일정한 규칙에 따라 &#39;암호화, 부호화, 코드화&#39; 하는 것을 말한다. (반대로 디코딩은 이와 반대되는 개념으로 &#39;역코드화&#39;의 의미를 지닌다.)</p>
<p>인코딩의 종류는 다양하며 아래 사진처럼 분류해 볼 수도 있다.
프로젝트를 진행 때 구현할 논문(&#39;A new vision of a simple 1D Convolutional Neural Networks (1D-CNN) with Leaky-ReLU function for ECG abnormalities classification&#39;)에서는 이 중 원-핫-인코딩 방식을 다루고 있어 그에 대해 더 알아봤다.
<img src="https://velog.velcdn.com/images/hye_ju/post/54297cb1-9f02-47df-b21c-60a1cef66f65/image.png" alt=""></p>
<h2 id="3-one-hot-encoding">3. One-hot-encoding</h2>
<h3 id="3-1-definition"><strong>3-1. Definition</strong></h3>
<blockquote>
<p>feature값의 유형에 따라 새로운 feature를 추가하고, 고유 값에 해당하는 column에만 1을 표시하고 나머지 값들은 모두 0을 갖게하는 방식으로 범주형 데이터를 수치형 데이터로 변환하는 방법 중 하나이다.</p>
</blockquote>
<h3 id="3-2-necessity"><strong>3-2. Necessity</strong></h3>
<p>범주형 데이터를 수치형 데이터로 변환하는 방법들 중 원-핫-인코딩의 필요성에 대해 알아보았다.
예를 들어 &#39;컴퓨터=1, 키보드=2, 마우스=3&#39;으로 하여 범주형 데이터를 각각 숫자에 대응시킨다고 해보자. 이 방식을 통해 각 데이터들을 숫자로 대응시키고 프로젝트를 진행하게 되면 문제가 생긴다.</p>
<p>대표적으로 키보드(2)를 컴퓨터(1)와 마우스(3)의 중간이라고 할 수 있을까? 또, 만약 모델이 &#39;2.7&#39;이라는 결과를 출력했을 경우, 이 데이터에 대해 &#39;키보드와 마우스 사이의 어떤 값인데 마우스에 더 가깝다&#39;와 같은 해석이 가능한 것인가와 같은 한계점들도 생긴다.</p>
<blockquote>
<p>결론적으로 범주형 데이터들을 임의의 숫자들에 각각 대응시키다보면, 연속적이지 않으며 순서가 없는 범주형 데이터의 특성에 의해 데이터 해석에 문제가 생긴다.</p>
</blockquote>
<p>이에 대한 해결책으로 이용될 수 있는 one-hot-encoding은 하나의 값만 1을 가지고 나머지 값들은 모두 0을 가지는 데이터로, 1값의 위치가 해당 데이터가 어떤 범주에 속하는지를 의미하게 된다.
<img src="https://velog.velcdn.com/images/hye_ju/post/19de8ccb-00bb-4793-b7bb-113b328bcd5d/image.png" alt=""></p>
<h3 id="3-3-one-hot-encoding-코드-구현"><strong>3-3. One-hot-encoding 코드 구현</strong></h3>
<p>(1) sklearn</p>
<ul>
<li>사이킷런의 OneHotEncoder 클래스로 가능</li>
<li>2차원 데이터가 입력값으로 필요</li>
<li>변환값을 다시 &#39;toarray()&#39; method를 이용해 밀집행렬로 변환해야함.(변환값이 희소행렬 형태이므로)</li>
</ul>
<p>(2) pandas</p>
<ul>
<li>sklearn에서 하는 변환하는 과정을 거칠 필요 없음</li>
<li>&#39;get_dummies()&#39; method 사용</li>
<li>문자열 카테고리 값을 바로 변환 가능(숫자형으로 변환할 필요 없음)<pre><code>import pandas as pd
</code></pre></li>
</ul>
<p>df = pd.Dataframe({&#39;item&#39;:[&#39;컴퓨터&#39;, &#39;키보드&#39;, &#39;마우스&#39;]})
pd.get_dummies(df)</p>
<pre><code>

</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[PyTorch Fundamentals - In connection with Tensor]]></title>
            <link>https://velog.io/@hye_ju/PyTorch-%EC%A0%95%EB%A6%AC-Tensor-%EA%B4%80%EB%A0%A8</link>
            <guid>https://velog.io/@hye_ju/PyTorch-%EC%A0%95%EB%A6%AC-Tensor-%EA%B4%80%EB%A0%A8</guid>
            <pubDate>Fri, 24 May 2024 10:35:19 GMT</pubDate>
            <description><![CDATA[<h2 id="1-introduction"><strong>1. Introduction</strong></h2>
<h3 id="1-1-pytorch는"><strong>1-1. Pytorch는...</strong></h3>
<blockquote>
<p>GPU와 CPU를 사용하는 딥 러닝에 최적화된 텐서 라이브러리</p>
</blockquote>
<p>-&gt; 최신 연구 환경에서 지배적, 커뮤니티에서 널리 채택되고 대부분의 출판물/사용 가능한 모델에서 사용</p>
<h3 id="1-2-colab-사용시-import-코드"><strong>1-2. colab 사용시 import 코드</strong></h3>
<pre><code>!pip install torch

import numpy as np
import torch</code></pre><h2 id="2-tensor"><strong>2. Tensor</strong></h2>
<h3 id="2-1-tensor란"><strong>2-1. Tensor란?</strong></h3>
<blockquote>
<p>Numpy의 배열과 유사한 자료형으로 다차원의 행렬. (=n차원의 행렬)</p>
</blockquote>
<p><img src="https://velog.velcdn.com/images/hye_ju/post/b369d92b-999a-4009-ba37-9a911120e958/image.png" alt=""></p>
<p>ex) 0D Tensor(Scalar), 1D Tensor(Vector), 2D Tensor(Matrix), 3D부터는 주로 그냥 Tensor라 칭함.</p>
<h3 id="2-2-tensor생성-코드들"><strong>2-2. Tensor생성 코드들</strong></h3>
<pre><code>torch.ones()    ## 각 element가 1인 tensor를 만들어줌
torch.zeros()    ## 각 element가 0인 tensor를 만들어줌

torch.arange()    ## 주어진 범위 내의 정수를 순서대로 생성
torch.rand()    ## 0과 1사이의 uniform dist에서 난수를 생성해서 tensor로 만들어줌

torch.ones_like()    ## 기존의 tensor와 같은 모양의 원소가 1인 tensor를 만들어줌
torch.zeros_like()    ## 기존의 tensor와 같은 모양의 원소가 0인 tensor를 만들어줌
-&gt; &#39;ones&#39;나 &#39;zeros&#39;대신 다른 들어가도 적용되어 기존의 tensor와 같은 모양의 입력된 숫자를 원소로 갖는 tensor를 만들어줌
</code></pre><h3 id="2-3-tensordevice"><strong>2-3. Tensor.device</strong></h3>
<pre><code>## 현재 해당 tensor가 어느 device에 있는지 확인
a = torch.tensor([1,2,3])
a.device

## 현재 GPU를 사용할 수 있는 환경인지 확인
torch.cuda.is_available()

## GPU 이름 체크(cuda: 0에 연결된 그래픽 카드 기준)
torch.cuda.get_device_name(device=0)

## 사용 가능한 GPU의 개수 체크
torch.cuda.device_count()

## tensor를 GPU에 할당(2가지 방법 존재)
a = torch.tensor([1., 2., 3.]).cuda()
b = torch.tensor([1., 2., 3.]).to(&quot;cuda&quot;)

이후 &#39;a.device&#39;나 &#39;b.device&#39;코드를 실행하면 첫 번째 GPU에 올라간 것을 확인할 수 있음. (코드 실행했을 때 결과: device(type=&#39;cuda&#39;, index=0 )</code></pre><p>CUDA(Compute Unified Device Architecture): GPU(그래픽 처리 장치)에서 수행하는 병렬처리 알고리즘을 산업 표준언어를 사용하여 작성할 수 있게 하는 GPGPU기술. </p>
<h3 id="2-4-nnmodule---neural-network-class-생성"><strong>2-4. nn.Module() - Neural Network Class 생성</strong></h3>
<blockquote>
<p>&#39;nn.Module()&#39; -&gt; 모든 neural network 모형의 기본이 되며, 각 layer의 함수와 신경망 구조를 정의할 때 사용한다.</p>
</blockquote>
<pre><code>## &#39;torch.nn&#39; : neural network 설계할 때 필요한 대부분의 기본적인 layer 구조를 제공해줌
import torch.nn as nn

class MyLinear(nn.Module):
    def __init__(self, input_dim, output_dim):
        super().__init__()
        self.input_dim = input_dim
        self.output_dim = output_dim

        self.W = torch.FloatTensor(input_dim, output_dim)
        self.b = torch.FloatTensor(output_dim)

    def forward(self,x):        ## input으로 x받음

      ## matmul: input으로 받은 x와 위에 선언해놓은 weight matrix를 matrix multiplication 해줌
        y = torch.matmul(x, self.W) + self.b    
</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[[Paper Review] Classifying ECG abnormalities using 1D Convolutional Neural Networks(1D-CNN) with Leaky-ReLU function]]></title>
            <link>https://velog.io/@hye_ju/Week2-WIL-a-paper-review-Classifying-ECG-abnormalities-using-1D-Convolutional-Neural-Networks1D-CNN-with-Leaky-ReLU-function</link>
            <guid>https://velog.io/@hye_ju/Week2-WIL-a-paper-review-Classifying-ECG-abnormalities-using-1D-Convolutional-Neural-Networks1D-CNN-with-Leaky-ReLU-function</guid>
            <pubDate>Tue, 14 May 2024 15:41:21 GMT</pubDate>
            <description><![CDATA[<h2 id="1-summary-of-this-paper"><strong>1. Summary of this paper</strong></h2>
<p>The steps of preprocessing(followed by QRS complex detection, data augmentation, data subdivision) and modeling have a significant impact on the overall performance of the classification model. Also the choice of the activation function (Leaky-ReLU in this paper) and the number&amp;type of layers influences the result.
High-quality classification leads to detect ECG abnormalities with a very high precision, recall and accuracy remaining the same on the test dataset. 
All of these processes and their accompanying consequences show that it has the potential to handle more cardiac abnormalities (because features can be learned automatically based on the provided dataset).</p>
<p>The comprehensive structure of the implementation process is outlined below. (I&#39;ve encapsulated the particulars of certain processes delineated in the paper.)
<img src="https://velog.velcdn.com/images/hye_ju/post/a373b4ff-d95c-44f6-810e-3271a242c0d5/image.png" alt=""></p>
<h2 id="2-details"><strong>2. Details</strong></h2>
<h3 id="2-1-used-database"><strong>2-1. Used database</strong></h3>
<p>(1) MIT-BIH </p>
<ul>
<li>Contains..
: recordings of the two-channel ambulatory ECG signals from 47 people</li>
<li>Represents the classes of..
: normal ECG, premature contractions(arterial &amp; ventricular), bundle branch block(right and left), signal at an accelerated rate</li>
</ul>
<p>(2) PTB-DB</p>
<ul>
<li>Contains..
: archives of ECG signals from 290 mixed population(age-17~87, rate of 1-5 recordings per person)</li>
<li>Can be summarized into two main classes of..
: healthy people &amp; people with a variety of coronary heart disease</li>
</ul>
<h3 id="2-2-qrs-complex-detection"><strong>2-2. QRS complex detection</strong></h3>
<p><img
src="https://velog.velcdn.com/images/hye_ju/post/28884db8-fbbf-4979-94fe-26237defb4dc/image.png" width=60% height=60%></p>
<ul>
<li>Necessity
: The heterogenity of database needs to be augmented(&#39;one-hot-encoder: location of &quot;1&quot; differentiating each vector from the others&#39; method is used for encoding in data augmentation step in this paper) and preprocessed. The data augmentation step regularizes the amount of data in each class to be equal(&lt;- this step only possible after detecting the QRS complex in the ECG signals).</li>
<li>Denotes..<blockquote>
<p>: either the peak or the highest point of the signal standing out as a crucial feature of the ECG</p>
</blockquote>
</li>
</ul>
<h3 id="2-3-used-activation-function"><strong>2-3. Used activation function</strong></h3>
<p><img
src="https://velog.velcdn.com/images/hye_ju/post/30bcf014-0211-4183-8583-f375002da55e/image.png" width=60% height=60%></p>
<p>Leaky-ReLU function is used in this paper considering that it assigns a variant to negative values to reserve the neurons and keeps the valuable data in the end. </p>
<p>However, for the smaller PTB-DB dataset, the activation function was changed to the standard &quot;ReLU&quot; instead of &quot;Leaky ReLU&quot; to prevent the dying ReLU issue. The model was trained for 30 epochs, demonstrating strong learning and generalization abilities across various cardiac datasets.
<img
src="https://velog.velcdn.com/images/hye_ju/post/93359ee6-0032-4826-8b30-09e39e6a0397/image.png" width=50% height=48%> Outlined above is the architecture of the 1D-CNN model proposed within this paper.</p>
<h2 id="3-conclusion"><strong>3. Conclusion</strong></h2>
<p>Various factors, including data quality, preprocessing and regularization steps, choice of activation function, and the number and type of layers, are crucial in enhancing the overall performance of the classification model. Moreover, this approach has led to algorithms that achieve very high precision, recall, and accuracy. With its capability for automatic learning, this model shows promise for further development to address more heart abnormalities in the future.</p>
<h3 id="link-to-the-paper-reviewed">[Link to the paper reviewed]</h3>
<p><a href="https://www.sciencedirect.com/science/article/pii/S2666521222000333?via%3Dihub#abs0015">https://www.sciencedirect.com/science/article/pii/S2666521222000333?via%3Dihub#abs0015</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Paper Review]
ECG Arrhythmia Classification using RNN]]></title>
            <link>https://velog.io/@hye_ju/Week1-WIL-a-paper-review-ECG-Arrhythmia-Classification-using-RNN</link>
            <guid>https://velog.io/@hye_ju/Week1-WIL-a-paper-review-ECG-Arrhythmia-Classification-using-RNN</guid>
            <pubDate>Thu, 09 May 2024 09:52:09 GMT</pubDate>
            <description><![CDATA[<h2 id="1-summary-of-this-paper"><strong>1. Summary of this paper</strong></h2>
<p>The primary aim of this paper is to enable automatic seperation applying RNN(Recurrent Neural Networks) to classify the normal and abnormal beats in an ECG(Electrocardiography). </p>
<h2 id="2-details"><strong>2. Details</strong></h2>
<p>Recurrent Neural Network(RNN), Gated Recurrent Unit(GRU), Long Short Term Memory Network(LSTM) are the methodology used, and the performance is evaluated based on three measurements (accuracy, specificity, sensitivity).</p>
<h3 id="2-1-reccurent-neural-networkrnn"><strong>2-1. Reccurent Neural Network(RNN)</strong></h3>
<p><img src="https://velog.velcdn.com/images/hye_ju/post/65b94e42-7da2-4967-a302-477766d95784/image.png" alt="">
RNN has an architecture consisting of an input layer, hidden layer, and an output layer. It stores the past state along with the input, enabling processing of inputs that change over time, and the output also affects the next input.</p>
<h3 id="2-2-gated-recurrent-unitgru--long-short-term-memory-networklstm"><strong>2-2. Gated Recurrent Unit(GRU) &amp; Long Short Term Memory Network(LSTM)</strong></h3>
<p><img src="https://velog.velcdn.com/images/hye_ju/post/ce33c94f-5961-4c0b-af47-65e3564054cd/image.png" alt=""></p>
<ul>
<li>GRU consists of two gates (A reset gate: determines how to combine the new input &amp; An update gate: determines how much the memory should be used to keep around). </li>
<li>LSTM is a specific type of RNN and it is applied after pre-processing.</li>
</ul>
<h3 id="2-3-performance-measurement"><strong>2-3. Performance Measurement</strong></h3>
<p>Since the goal was to classify the normal and abnormal(&lt;- it is a binary classification) beats in an ECG, the measurements are described by confusion matrix. 
(Below is the confusion matrix and ECG Arrhythmia classification results of this study. Also I added an image with a formula to obtain each measurement value including &#39;accuracy, specificity, and sensitivity&#39; using the confusion matrix.)
<img src="https://velog.velcdn.com/images/hye_ju/post/6ec679af-529b-4119-984f-383c4227ca52/image.png" alt="">
<img src="https://velog.velcdn.com/images/hye_ju/post/b4fbfad0-2cb8-43e4-b672-9f7cd7e247d9/image.png" alt=""></p>
<h2 id="3-conclusion"><strong>3. Conclusion</strong></h2>
<p>LSTM networks offer a valuable tool for real-time monitoring and classification of ECG signals in the field. This study proposes further exploration into optimizing these models for a wider range of arrhythmia conditions and effectively integrating them into clinical operations.</p>
<h3 id="link-to-the-paper-reviewed">[Link to the paper reviewed]</h3>
<p><a href="https://www.sciencedirect.com/science/article/pii/S1877050918307774">https://www.sciencedirect.com/science/article/pii/S1877050918307774</a></p>
]]></description>
        </item>
    </channel>
</rss>