<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>bona-park.log</title>
        <link>https://velog.io/</link>
        <description>읏차 웃자</description>
        <lastBuildDate>Mon, 28 Nov 2022 00:58:06 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <image>
            <title>bona-park.log</title>
            <url>https://velog.velcdn.com/images/bona-park/profile/97d2aa17-aa8f-4cf2-bbd2-146f0ea07f0d/image.jpg</url>
            <link>https://velog.io/</link>
        </image>
        <copyright>Copyright (C) 2019. bona-park.log. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/bona-park" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[[Docker] Let me like you, Docker : part 1]]></title>
            <link>https://velog.io/@bona-park/Docker-Let-me-like-you-Docker-part-1</link>
            <guid>https://velog.io/@bona-park/Docker-Let-me-like-you-Docker-part-1</guid>
            <pubDate>Mon, 28 Nov 2022 00:58:06 GMT</pubDate>
            <description><![CDATA[<h3 id="problem">Problem</h3>
<p>A python file(&quot;hw1.py&quot;) runs well on my laptop.
But what if it does not on my friend&#39;s?
➡ <em>ModuleNotFoundError: No Module named &#39;xgboost&#39;</em>
➡ The module isn&#39;t installed in his laptob</p>
<p>Plus, what if there&#39;s a one who hasn&#39;t installed a Python?
What if there&#39;s a one with Python 2.10 ..?</p>
<p>It is a headache to configure your environment for different versions of software a on single machine. </p>
<h3 id="solve">Solve</h3>
<p><em><strong>&quot;Let&#39;s make our program run on every environtment!&quot;</strong></em></p>
<hr>
<h2 id="✅-virtualization">✅ Virtualization</h2>
<p>Virtualization, as the name implies, is the creation of a virtual version of something, such as an OS, a server or a storage device.</p>
<p>It creates a simulated computing environment that is abstracted from the physical computing hardware. </p>
<p>Then the software simulates hardware functionallity.</p>
<p>There are 2 types of virtualization. Let&#39;s see what are the differences.</p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/0e594d76-9090-4b88-b6af-157ea2db9a04/image.png" alt=""></p>
<h3 id="1-virtual-machines">1. Virtual Machines</h3>
<p>✌ Hardware-level virtualization</p>
<p>A virtual machine is a system which acts exactly like a computer.</p>
<p>Each virtual machine requires its <strong>own underlying operating system</strong>, and then the hardware is virtualized. </p>
<p>Virtual mahicne takes up a lot of resouces because each VM runs a virtual copy of all the HW that the OS needs to run. </p>
<p><strong>Hypervisor</strong>: 
A layer that runs on the physical host and interacts with both the host machine and the VM. 
It abstracts the host computer&#39;s resources to VM.
Thanks to the hypervisor, the hardware resources are virtualized and each VM is isolated from each other.</p>
<h3 id="2-container">2. Container</h3>
<p>✌ OS-level virtualizaition</p>
<p>Containers are a layer of abstraction <strong>above</strong> both pyhiscal machines and VMs. It sits on top of them.</p>
<p>While a VM abstracts a complete machine, a container only abstracts an application and its dependences. </p>
<p>While a VM has its own guest OS above the host OS, which makes VM heavy, a container share the host OS.</p>
<hr>
<h2 id="✅-docker">✅ Docker</h2>
<h3 id="what-is-docker">What is Docker?</h3>
<p><img src="https://velog.velcdn.com/images/bona-park/post/5d822b9a-40c7-4e3d-b8af-e353bb3c8e18/image.png" alt=""></p>
<p>Docker is a <strong>OS-level virtualization software</strong>.
It is designed to make it easier for developers to develop, ship, and run applications by using containers. </p>
<h3 id="container">Container</h3>
<p>As we mentioned above, containers are <strong>isolated</strong> from one another and <strong>bundle</strong> their own software, libraries and configuration files.
They can communicate with each other through well-defined channels.</p>
<h4 id="❔-then-how-they-are-isolated">❔ Then how they are isolated?</h4>
<p>Thanks to 2 isolation techonologies on linux kernel.</p>
<p>1) Namespace: a feature for partitioning kernel resources 
2) Control group(cgroup):  a feature for limiting and isolating resource usage(CPU, memorym, network ..) of a collection of processes.
<img src="https://velog.velcdn.com/images/bona-park/post/b9a741f8-1f58-4c9c-bb2b-c786367fbdee/image.png" alt=""></p>
<h3 id="docker-image">Docker Image</h3>
<p>Docker Image is a read-only templates containing instructions for creating a container.
Then a docker <strong>container</strong> is a running <strong>image instance</strong>. You can create many containers from same image, each with its own unique data and state.
<img src="https://velog.velcdn.com/images/bona-park/post/177dfdb2-d589-4821-816d-1461d8487219/image.png" width="30%" height="30%">
(You can think of the left as an Image and the right as a Container! yummy Boongeobbang ;-))</p>
<p>image)
<a href="https://en.wikipedia.org/wiki/Docker_(software)">https://en.wikipedia.org/wiki/Docker_(software)</a>
<a href="https://bikramat.medium.com/namespace-vs-cgroup-60c832c6b8c8">https://bikramat.medium.com/namespace-vs-cgroup-60c832c6b8c8</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Ubunut] Brew command not found]]></title>
            <link>https://velog.io/@bona-park/Ubunut-Brew-command-not-found</link>
            <guid>https://velog.io/@bona-park/Ubunut-Brew-command-not-found</guid>
            <pubDate>Sun, 27 Nov 2022 00:41:24 GMT</pubDate>
            <description><![CDATA[<pre><code class="language-shell">eval $(/home/linuxbrew/.linuxbrew/bin/brew shellenv) </code></pre>
<p>must be add into you file .bashrc at the end</p>
<pre><code class="language-shell">vi ~/bashrc
source ~/.bashrc</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Paper Review] Attention is all you need]]></title>
            <link>https://velog.io/@bona-park/Attention-is-all-you-need</link>
            <guid>https://velog.io/@bona-park/Attention-is-all-you-need</guid>
            <pubDate>Thu, 17 Nov 2022 11:31:43 GMT</pubDate>
            <description><![CDATA[<p><img src="https://velog.velcdn.com/images/bona-park/post/370315ca-11bc-42b4-808f-10b25a74fe26/image.png" alt=""></p>
<h3 id="before">Before..</h3>
<ol>
<li>RNN</li>
<li>LSTM
: slow to train</li>
</ol>
<p>Can we parallelize sequential data?</p>
<h2 id="transformers">Transformers</h2>
<p>Input sequence can be transmitted *<em>parallel 
*</em></p>
<p>No concept of time step</p>
<p>Pass all the words simultaneously and determine the word embedding simultaneously</p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/91239c2a-b289-493b-ba85-b589449b0010/image.png" alt=""></p>
<p>(RNN passes input word one after another)</p>
<h3 id="input-embedding">Input Embedding</h3>
<p><img src="https://velog.velcdn.com/images/bona-park/post/cd0b7e77-637d-4307-a9fb-a6494cc13b46/image.png" alt=""></p>
<p>In embedding space, close-meaning words locates close to each other
There&#39;re already pretrained embedding spaces.</p>
<p>But, same word in a different sentence has a different meaning!</p>
<h3 id="positional-encoder">Positional Encoder</h3>
<p>: vector that gives context <strong>information based on position of word in a sentence</strong></p>
<p>Can use sin/cos function to generate PE, but any reasonable function is ok
<img src="https://velog.velcdn.com/images/bona-park/post/60fff74c-35c2-4c14-b899-5e671858a803/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/9f18a7b2-bb2b-4035-9216-f9320a522370/image.png" alt=""></p>
<hr>
<h2 id="structure-of-encoder">Structure of Encoder</h2>
<h3 id="1-attention">1. Attention</h3>
<p>: What part of the input should we focus?</p>
<p>How much the word &#39;The&#39; is relevant to other words(big, red, dog) in the same sentence?
<img src="https://velog.velcdn.com/images/bona-park/post/c3d5188e-f3a2-4519-960b-7f968342baad/image.png" alt=""></p>
<p>Attention Vetors(of English) contain <strong>contextual relationships betweeen the words</strong> in the sentence. </p>
<h3 id="2-feed-forward">2. Feed Forward</h3>
<p>Simple feed forward network is applied to every one of the attention vectors! 
<img src="https://velog.velcdn.com/images/bona-park/post/3073a473-797c-44a7-85d1-60dee8dde2a9/image.png" alt=""></p>
<h4 id="problem-of-attention-vector">Problem of Attention vector</h4>
<p>Focuses to much on itself..
We want to know the interactions and relationships between words!</p>
<p>➡ <strong>Use mulitple attention vector</strong> for the same word and average them: Multi Head Attention Block
(Q. vectors from different sentence..?)</p>
<p>Attention vectors are feeded to Feed Forward Network one vector at a time 
Each of the attention vector of different word is <strong>independent</strong> each other 
➡ can Parallize Feed Forwared Network! 
➡ All words can be passed to the encoder block at the same time and output is a set of encoded vectors for every word
<img src="https://velog.velcdn.com/images/bona-park/post/ab12a845-d55f-4651-b225-7ae6eef9fc96/image.png" alt=""></p>
<hr>
<h2 id="structure-of-decoder">Structure of Decoder</h2>
<p>In English -&gt; French task, we feed output French to the decoder</p>
<h3 id="1-self-attention-block">1. Self attention block</h3>
<p>Generates attention vectors(of French) showing how much each word is related to another
<img src="https://velog.velcdn.com/images/bona-park/post/ffed0005-23fa-4636-aa95-1e94218adc45/image.png" alt=""></p>
<p>Attention vectors from both Encoder(English) and Decoder(French) are passed to another <strong>Encoder-Decoder Attention block</strong>.
➡ output of this block: Attention vector of all words(English+French) 
➡ Each attention vector shows the realtionship of other words including both languages
➡ English to French word <strong>mapping</strong> happens!
<img src="https://velog.velcdn.com/images/bona-park/post/59049a25-d23b-48f1-9b47-a89346648bac/image.png" alt=""></p>
<h4 id="multi-headed-attention">Multi-headed Attention</h4>
<p>If we use all the words in the French sentence, there&#39;d be no learning, just spitting out the next word
➡ <strong>mask input</strong>: observe only previous and itself
<img src="https://velog.velcdn.com/images/bona-park/post/cba1f00b-ca34-4d97-8771-d13b79ef3e16/image.png" alt=""></p>
<h4 id="single-headed-attention-vs-multi-headed-attention">Single-headed attention vs Multi-headed attention</h4>
<h5 id="1-single-headed-attention">1) Single-headed attention</h5>
<p>V,K,Q: abstract vector that extracts different components of input words
We have V,K,Q vectors for every single word
➡ create attention vector for every word using V, K, Q
<img src="https://velog.velcdn.com/images/bona-park/post/631640ae-a02d-42da-8c1d-5d0967fe3551/image.png" alt=""></p>
<h5 id="2-multi-headed-attention">2) Multi-headed attention</h5>
<p>Have multiple weight matrices(Wv, Wk, Wq) 
➡ multiple attention vectors for every word
➡ another weighted matrices(Wz)
➡ now feed forward nn can be fed only one attention vector per word
<img src="https://velog.velcdn.com/images/bona-park/post/7198cdb9-7090-45da-9eab-fe5649839f67/image.png" alt=""></p>
<h3 id="2-feed-forward-unit">2. Feed forward unit</h3>
<p>Pass each attention vector to feed forward unit</p>
<h3 id="3-linear-layer">3. Linear layer</h3>
<p>: another Feed Forward Layer</p>
<p>Used to expand the dimension to the number of words in French</p>
<h3 id="4-softmax-layer">4. Softmax layer</h3>
<p>Transforms it into Probability Distribution</p>
<p>Output: The word with the highest probability to come next
<img src="https://velog.velcdn.com/images/bona-park/post/6cf1dc97-0d5b-4d62-b5c9-1c5794faefe7/image.png" alt=""></p>
<hr>
<h3 id="codes">Codes</h3>
<p>Reference to <a href="https://github.com/hyunwoongko/transformer">https://github.com/hyunwoongko/transformer</a></p>
<blockquote>
<p>Scale Dot Production Attention
<img src="https://velog.velcdn.com/images/bona-park/post/db8c4c73-bc54-4bd8-b981-78f9fca298a0/image.png" alt=""></p>
</blockquote>
<pre><code class="language-python">class ScaleDotProductAttention(nn.Module):
    &quot;&quot;&quot;
    compute scale dot product attention

    Query : given sentence that we focused on (decoder)
    Key : every sentence to check relationship with Qeury(encoder)
    Value : every sentence same with Key (encoder)
    &quot;&quot;&quot;

    def __init__(self):
        super(ScaleDotProductAttention, self).__init__()
        self.softmax = nn.Softmax(dim=-1)

    def forward(self, q, k, v, mask=None, e=1e-12):
        # input is 4 dimension tensor
        # [batch_size, head, length, d_tensor]
        batch_size, head, length, d_tensor = k.size()

        # 1. dot product Query with Key^T to compute similarity
        k_t = k.transpose(2, 3)  # transpose
        score = (q @ k_t) / math.sqrt(d_tensor)  # scaled dot product

        # 2. apply masking (opt)
        if mask is not None:
            score = score.masked_fill(mask == 0, -e)

        # 3. pass them softmax to make [0, 1] range
        score = self.softmax(score)

        # 4. multiply with Value
        v = score @ v

        return v, score</code></pre>
<blockquote>
<p>Multi-head Attention 
<img src="https://velog.velcdn.com/images/bona-park/post/738c7575-2b8e-4b8e-a089-3db5ca45f032/image.png" alt=""></p>
</blockquote>
<pre><code class="language-python">  class MultiHeadAttention(nn.Module):

      def __init__(self, d_model, n_head):
          super(MultiHeadAttention, self).__init__()
          self.n_head = n_head
          self.attention = ScaleDotProductAttention()
          self.w_q = nn.Linear(d_model, d_model)
          self.w_k = nn.Linear(d_model, d_model)
          self.w_v = nn.Linear(d_model, d_model)
          self.w_concat = nn.Linear(d_model, d_model)

      def forward(self, q, k, v, mask=None):
          # 1. dot product with weight matrices
          q, k, v = self.w_q(q), self.w_k(k), self.w_v(v)

          # 2. split tensor by number of heads
          q, k, v = self.split(q), self.split(k), self.split(v)

          # 3. do scale dot product to compute similarity
          out, attention = self.attention(q, k, v, mask=mask)

          # 4. concat and pass to linear layer
          out = self.concat(out)
          out = self.w_concat(out)

          # 5. visualize attention map
          # TODO : we should implement visualization

          return out

      def split(self, tensor):
          &quot;&quot;&quot;
          split tensor by number of head

          :param tensor: [batch_size, length, d_model]
          :return: [batch_size, head, length, d_tensor]
          &quot;&quot;&quot;
          batch_size, length, d_model = tensor.size()

          d_tensor = d_model // self.n_head
          tensor = tensor.view(batch_size, length, self.n_head, d_tensor).transpose(1, 2)
          # it is similar with group convolution (split by number of heads)

          return tensor

      def concat(self, tensor):
          &quot;&quot;&quot;
          inverse function of self.split(tensor : torch.Tensor)

          :param tensor: [batch_size, head, length, d_tensor]
          :return: [batch_size, length, d_model]
          &quot;&quot;&quot;
          batch_size, head, length, d_tensor = tensor.size()
          d_model = head * d_tensor

          tensor = tensor.transpose(1, 2).contiguous().view(batch_size, length, d_model)
          return tensor
</code></pre>
<p>REF
<a href="https://github.com/hyunwoongko/transformer">https://github.com/hyunwoongko/transformer</a>
<a href="https://www.youtube.com/watch?v=TQQlZhbC5ps">https://www.youtube.com/watch?v=TQQlZhbC5ps</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Algorithms] 다익스트라(Dijkstra)]]></title>
            <link>https://velog.io/@bona-park/Algorithms-%EB%8B%A4%EC%9D%B5%EC%8A%A4%ED%8A%B8%EB%9D%BCDijkstra</link>
            <guid>https://velog.io/@bona-park/Algorithms-%EB%8B%A4%EC%9D%B5%EC%8A%A4%ED%8A%B8%EB%9D%BCDijkstra</guid>
            <pubDate>Sat, 05 Nov 2022 02:20:28 GMT</pubDate>
            <description><![CDATA[<h2 id="다익스트라dijkstra">다익스트라(Dijkstra)</h2>
<ul>
<li><p>문제 상황</p>
<ol>
<li>Va -&gt; Vb까지의 최단경로</li>
<li>Va -&gt; 모든 노드 의 최단경로</li>
<li>모든 노드 -&gt; 다른 모든 지점 의 최단 경로</li>
</ol>
</li>
<li><p>그리디 알고리즘으로 분류됨</p>
</li>
<li><p>매 상황에서 가장 비용이 적은 노드를 선택해서 임의의 과정을 반복</p>
</li>
<li><p>동작 단계</p>
<ol>
<li>출발노드 설정</li>
<li>최단거리 테이블 초기화</li>
<li>현재 위치한 노드의 인접 노드들 중 방문하지 않은 노드들 중에서 가장 거리가 짧은 노드 선택. 그 노드를 방문 처리.</li>
<li>cost를 계산하고 최단거리 테이블 업데이트</li>
<li>(3)(4) 과정 반복</li>
</ol>
</li>
</ul>
<h3 id="다익스트라-구현-방법">다익스트라 구현 방법</h3>
<ul>
<li><p><strong>힙(Heap)</strong> 자료구조 이용
<img src="https://velog.velcdn.com/images/bona-park/post/de74da86-723c-4f06-b69e-03679d5832a7/image.png" alt=""></p>
</li>
<li><h4 id="cf-힙heap">cf) 힙(Heap)</h4>
<ul>
<li><strong>우선순위 큐</strong>(Priority Queue)를 구현하기 위해 사용하는 자료구조</li>
<li>Max Heap, Min Heap의 종류가 있음<ul>
<li>최대 힙을 최소 힙으로 쓰려면 저장되는 값에 -를 붙여 음수로 만들면 된다.</li>
</ul>
</li>
<li>삽입시간, 삭제시간: <strong>O(logN)</strong>
<img src="https://velog.velcdn.com/images/bona-park/post/68d2f3a5-c6a2-4c78-8449-55a93e007370/image.png" alt=""><pre><code class="language-python">import heapq
heapq.heappush(myHeap, value)
heapq.heappop(myHeap)</code></pre>
</li>
</ul>
</li>
</ul>
<h3 id="다익스트라-예제-백준-1238번-파티-파이썬">다익스트라 예제: 백준 1238번 파티 (파이썬)</h3>
<p><img src="https://velog.velcdn.com/images/bona-park/post/f056e172-abe5-46e0-8354-5c205097c918/image.png" alt=""></p>
<pre><code class="language-python">import heapq
import sys

def dijkstra(start):
    distance = [INF] * (V+1)
    q = [] # 우선순위 큐
           # 현재 노드의 이웃들이 거리가 짧은 순으로 우선순위가 높게 담겨있음

    distance[start] = 0 # 시작점은 최단거리 0
    heapq.heappush(q, (0, start))

    while q: 
        # 큐에서 가장 최단거리가 짧은 노드 꺼내기
        dist, now = heapq.heappop(q)
        # 현재 노드가 이미 처리된 적이 있는 노드라면(더 짧은 최단거리가 이미 구해졌다면) 무시
        if distance[now] &lt; dist:
            continue
        # 현재 노드와 연결된 다른 인접한 노드들을 확인
        for next in graph[now]:
            cost = dist + next[1]
            # 현재 노드를 거쳐서, 다음 노드로 이동하는 거리가 더 짧은 경우
            if cost &lt; distance[next[0]]:
                distance[next[0]] = cost # 거리테이블 업데이트
                heapq.heappush(q, (cost, next[0]))
    return distance

input = sys.stdin.readline
INF = int(1e9) # 무한값(10억)

V, E, X= map(int, input().split())
graph = [[] for _ in range(V+1)]


# 모든 엣지값 입력받기
for _ in range(E):
    u, v, w = map(int, input().split())
    # u에서 v로 가는 가중치 w인 간선이 존재
    graph[u].append((v, w))


max_dist = 0
for i in range(1 ,V+1):
    # 다익스트라 i -&gt; x
    d_0 = dijkstra(i)[X]
    # 다익스트라 x -&gt; i
    d_1 = dijkstra(X)[i]
    max_dist = max(max_dist, d_0 + d_1)

print(max_dist)</code></pre>
<p>(ref)
<a href="https://freedeveloper.tistory.com/277">https://freedeveloper.tistory.com/277</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Paper Review] CoCa: Contrastive Captioners are Image-Text
Foundation Models]]></title>
            <link>https://velog.io/@bona-park/Paper-Review-CoCa-Contrastive-Captioners-are-Image-TextFoundation-Models</link>
            <guid>https://velog.io/@bona-park/Paper-Review-CoCa-Contrastive-Captioners-are-Image-TextFoundation-Models</guid>
            <pubDate>Thu, 03 Nov 2022 10:15:55 GMT</pubDate>
            <description><![CDATA[<h2 id="coca-contrastive-captioners-are-image-text-foundation-models"><em>&quot;CoCa: Contrastive Captioners are Image-Text Foundation Models&quot;</em></h2>
<p><img src="https://velog.velcdn.com/images/bona-park/post/af69fe3b-4374-4a80-b3c7-72f7cbccb86b/image.png" alt=""></p>
<h2 id="history-of-vision-and-language-training">History of Vision and Language training</h2>
<ol>
<li>Vision pretraining</li>
</ol>
<ul>
<li>pretrain ConvNets or Transformers on large-scale data such as ImageNet, Instagram to solve visual recognition problem </li>
<li>these models only learn modes for the vision modality-&gt; not applicable to joint reasoning task over both image and text inputs</li>
</ul>
<ol start="2">
<li>Vision-Language Pretraining(VLP)</li>
</ol>
<ul>
<li>Early work: relying on pretrained object detection modules such as Faster R-CNN to extract visual representations</li>
<li>Later work: <strong>unifying vision and language transformers</strong>, and training multimodal transformer from scratch</li>
</ul>
<ol start="3">
<li>Image-Text Foundation models</li>
</ol>
<ul>
<li>recent works subsume both vision and vision-language pretrianing</li>
<li>adaptable for a wide range of vision and image-text benchmarks</li>
</ul>
<h2 id="previous-models-for-vision-and-vison-language-problems-3-training-paradigms">Previous models for vision and vison-language problems: 3 training paradigms</h2>
<p><img src="https://velog.velcdn.com/images/bona-park/post/e7f93f88-4b5a-410a-a35c-a1b6a0e3e3dc/image.png" alt=""></p>
<ol>
<li>Single-encoder models</li>
</ol>
<ul>
<li>provides generic visual represantations that can be adapted for various downstream tasks including image and video understanding</li>
<li>rely heavily on <strong>image annotains as labeled vectors</strong></li>
<li>cannot deal a free-form human natural language</li>
</ul>
<ol start="2">
<li>Dual-encoder models</li>
</ol>
<ul>
<li>pretrains two parallel encoders wit a contrastive loss on web-scale noisy image-text pairs</li>
<li><strong>encode textual embeddings to the same latent space</strong>, enabling new crossmodal alignment
capabilities such as zero-shot image classification and image-text retrieval</li>
<li>misses joint componenets to learn fuesed image and text representations </li>
<li><blockquote>
<p>not applicable for joint vision-language understanding tasks such as visual question answering</p>
</blockquote>
</li>
<li>learns an aligned text encoder that enables ** crossmodal alignment applications ** such as image-text retrieval and zero-shot image classification</li>
</ul>
<ol start="3">
<li>Encoder-decoder models</li>
</ol>
<ul>
<li>During training, it takes images on the encoder side and applies Language Modeling loss on the decoder outputs </li>
<li>decoder outputs can be used as joint representations for mulitodal understanding tasks</li>
<li>the image <strong>encoder</strong>: provides latent encoded features using Vision Transformers</li>
<li>Text <strong>decoder</strong>: learns to maximize the likelihood of the paird text under the forward autoregressive factorization</li>
</ul>
<h2 id="coca">CoCa</h2>
<ul>
<li>focus on training an image-text foundation model from scratch in a single pretraining stage to unify image and text</li>
<li>performs <strong>one</strong> forward and backward propagation for a batch of image-textpairs while ALBEF requires two (one on corrupted inputs and another without corruption)</li>
<li>trained from scratch on the** two objectives** only while ALBEF is initialized from pretrained visual and textual encoders with additional training signals including momentum modules</li>
<li>The <strong>decoder architecture with generative loss is preferred</strong> for natural language generation and thus directly enables image captioning and zero-shot learning</li>
</ul>
<p><img src="https://velog.velcdn.com/images/bona-park/post/22fe0cbf-b1c2-46b5-9e3b-bb89d015ab12/image.png" alt=""></p>
<h3 id="architecture">Architecture</h3>
<ol>
<li>Image Encoder
Enocdes imgaes to latent representations by a neural network encoder</li>
<li>Decoupled Decoder
Simultaneously produces both unimdoal and multimodal text representations for both contrastive and generative objectives</li>
</ol>
<p><strong>1) Unimodal Text Decoder</strong>
 - for Contrastive objective for learning global representations
 - append learnable token[CLS] at the end of the input sentence 
<strong>2) Multimodal Text Decoder</strong>
- for Captioning objective for fine-grained region-level features</p>
<ul>
<li>Benefits of <ul>
<li>Can compute two training losses efficiently</li>
<li>Induces minimal overhead</li>
</ul>
</li>
</ul>
<h3 id="basic"><strong>Basic</strong></h3>
<p><strong>Captioning approcah</strong>: optimies the conditional likelihood of text
<strong>Contrastive approach:</strong> uses an unconditional text representation</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Spark] Practice: RDD]]></title>
            <link>https://velog.io/@bona-park/Spark-Practice-RDD</link>
            <guid>https://velog.io/@bona-park/Spark-Practice-RDD</guid>
            <pubDate>Tue, 18 Oct 2022 07:23:45 GMT</pubDate>
            <description><![CDATA[<blockquote>
<pre><code class="language-python">sc = SparkContext(&#39;local&#39;, &#39;assignment&#39;)
baserdd = sc.textFile(&#39;file:///home/ec2-user/RDD/grade.txt&#39;) # 경로 설정 유의
baserdd.collect()</code></pre>
</blockquote>
<pre><code>
```text
[&#39;Mathew, science, grade-3, 45&#39;,
 &#39;Mathew, history, grade-2, 55&#39;,
 &#39;Mark, maths, grade-2, 23&#39;,
 &#39;Mark, science, grade-1, 76&#39;,
 &#39;John, history, grade-1, 14&#39;,
 &#39;John, maths, grade-2, 74&#39;,
 &#39;Lisa, science, grade-1, 24&#39;,
 &#39;Lisa, history, grade-3, 86&#39;,
 &#39;Andrew, maths, grade-1, 34&#39;,
 &#39;Andrew, science, grade-3, 26&#39;,
 &#39;Andrew, history, grade-1, 74&#39;,
 &#39;Mathew, science, grade-2, 55&#39;,
 &#39;Mathew, history, grade-2, 87&#39;,
 &#39;Mark, maths, grade-1, 92&#39;,
 &#39;Mark, science, grade-2, 12&#39;,
 &#39;John, history, grade-1, 67&#39;,
 &#39;John, maths, grade-1, 35&#39;,
 &#39;Lisa, science, grade-2, 24&#39;,
 &#39;Lisa, history, grade-2, 98&#39;,
 &#39;Andrew, maths, grade-1, 26&#39;,
 &#39;Andrew, science, grade-3, 44&#39;,
 &#39;Andrew, history, grade-2, 77&#39;]</code></pre><h3 id="읽어온-line을--를-기준으로-나눈-후-list로-저장">읽어온 line을 &quot;, &quot;를 기준으로 나눈 후, list로 저장</h3>
<p>(단, 점수는 int형으로)</p>
<blockquote>
<pre><code class="language-python">b0 = baserdd.map(lambda line: line.split(&quot;, &quot;))
#erdd = baserdd.map(lambda line[3]: int(line[3]) )
b0.collect()</code></pre>
</blockquote>
<pre><code></code></pre><p>[[&#39;Mathew&#39;, &#39;science&#39;, &#39;grade-3&#39;, &#39;45&#39;],
 [&#39;Mathew&#39;, &#39;history&#39;, &#39;grade-2&#39;, &#39;55&#39;],
 [&#39;Mark&#39;, &#39;maths&#39;, &#39;grade-2&#39;, &#39;23&#39;],
 [&#39;Mark&#39;, &#39;science&#39;, &#39;grade-1&#39;, &#39;76&#39;],
 [&#39;John&#39;, &#39;history&#39;, &#39;grade-1&#39;, &#39;14&#39;],</p>
<pre><code>

&gt;```python
b1 = b0.map(lambda line: line[:-1] + [int(line[-1])])
b1.collect()</code></pre><pre><code>[[&#39;Mathew&#39;, &#39;science&#39;, &#39;grade-3&#39;, 45],
 [&#39;Mathew&#39;, &#39;history&#39;, &#39;grade-2&#39;, 55],
 [&#39;Mark&#39;, &#39;maths&#39;, &#39;grade-2&#39;, 23],
 [&#39;Mark&#39;, &#39;science&#39;, &#39;grade-1&#39;, 76],
 [&#39;John&#39;, &#39;history&#39;, &#39;grade-1&#39;, 14],</code></pre><h3 id="과목별-등장-횟수를-과목명-등장-횟수로">과목별 등장 횟수를 (과목명, 등장 횟수)로</h3>
<blockquote>
<pre><code class="language-python">b2 = b1.map(lambda x: (x[1],1))
b2.collect()</code></pre>
</blockquote>
<pre><code></code></pre><p>[(&#39;science&#39;, 1),
 (&#39;history&#39;, 1),
 (&#39;maths&#39;, 1),
 (&#39;science&#39;, 1),</p>
<pre><code>
&gt;```python
b2 = b2.reduceByKey(lambda x, y: x+y)
b2.collect()</code></pre><pre><code>[(&#39;science&#39;, 8), (&#39;history&#39;, 8), (&#39;maths&#39;, 6)]</code></pre><h3 id="학생별-평균-점수-구하기">학생별 평균 점수 구하기</h3>
<p>이름이 같아도 학년이 다르면 다른 사람임</p>
<blockquote>
<pre><code class="language-python">b5 = b1.map(lambda x: ((x[0], x[2]), (x[3], 1)))
b5.collect()</code></pre>
</blockquote>
<pre><code></code></pre><p>[((&#39;Mathew&#39;, &#39;grade-3&#39;), (45, 1)),
 ((&#39;Mathew&#39;, &#39;grade-2&#39;), (55, 1)),
 ((&#39;Mark&#39;, &#39;grade-2&#39;), (23, 1)),
 ((&#39;Mark&#39;, &#39;grade-1&#39;), (76, 1)),
 ((&#39;John&#39;, &#39;grade-1&#39;), (14, 1)),
 ((&#39;John&#39;, &#39;grade-2&#39;), (74, 1)),
 ((&#39;Lisa&#39;, &#39;grade-1&#39;), (24, 1)),
 ((&#39;Lisa&#39;, &#39;grade-3&#39;), (86, 1)),
 ((&#39;Andrew&#39;, &#39;grade-1&#39;), (34, 1)),
 ((&#39;Andrew&#39;, &#39;grade-3&#39;), (26, 1)),
 ((&#39;Andrew&#39;, &#39;grade-1&#39;), (74, 1)),
 ((&#39;Mathew&#39;, &#39;grade-2&#39;), (55, 1)),
 ((&#39;Mathew&#39;, &#39;grade-2&#39;), (87, 1)),
 ((&#39;Mark&#39;, &#39;grade-1&#39;), (92, 1)),
 ((&#39;Mark&#39;, &#39;grade-2&#39;), (12, 1)),
 ((&#39;John&#39;, &#39;grade-1&#39;), (67, 1)),
 ((&#39;John&#39;, &#39;grade-1&#39;), (35, 1)),
 ((&#39;Lisa&#39;, &#39;grade-2&#39;), (24, 1)),
 ((&#39;Lisa&#39;, &#39;grade-2&#39;), (98, 1)),
 ((&#39;Andrew&#39;, &#39;grade-1&#39;), (26, 1)),
 ((&#39;Andrew&#39;, &#39;grade-3&#39;), (44, 1)),
 ((&#39;Andrew&#39;, &#39;grade-2&#39;), (77, 1))]</p>
<pre><code>
&gt;```python
totalByName = b5.reduceByKey(lambda x, y: (x[0]+y[0], x[1]+y[1]))
totalByName.collect()</code></pre><pre><code>[((&#39;Mathew&#39;, &#39;grade-3&#39;), (45, 1)),
 ((&#39;Mathew&#39;, &#39;grade-2&#39;), (197, 3)),
 ((&#39;Mark&#39;, &#39;grade-2&#39;), (35, 2)),
 ((&#39;Mark&#39;, &#39;grade-1&#39;), (168, 2)),
 ((&#39;John&#39;, &#39;grade-1&#39;), (116, 3)),
 ((&#39;John&#39;, &#39;grade-2&#39;), (74, 1)),
 ((&#39;Lisa&#39;, &#39;grade-1&#39;), (24, 1)),
 ((&#39;Lisa&#39;, &#39;grade-3&#39;), (86, 1)),
 ((&#39;Andrew&#39;, &#39;grade-1&#39;), (134, 3)),
 ((&#39;Andrew&#39;, &#39;grade-3&#39;), (70, 2)),
 ((&#39;Lisa&#39;, &#39;grade-2&#39;), (122, 2)),
 ((&#39;Andrew&#39;, &#39;grade-2&#39;), (77, 1))]</code></pre><blockquote>
<pre><code class="language-python">averageByName = totalByName.mapValues(lambda x: x[0] / x[1])
averageByName.collect()</code></pre>
</blockquote>
<pre><code></code></pre><p>[((&#39;Mathew&#39;, &#39;grade-3&#39;), 45.0),
 ((&#39;Mathew&#39;, &#39;grade-2&#39;), 65.66666666666667),
 ((&#39;Mark&#39;, &#39;grade-2&#39;), 17.5),
 ((&#39;Mark&#39;, &#39;grade-1&#39;), 84.0),
 ((&#39;John&#39;, &#39;grade-1&#39;), 38.666666666666664),
 ((&#39;John&#39;, &#39;grade-2&#39;), 74.0),
 ((&#39;Lisa&#39;, &#39;grade-1&#39;), 24.0),
 ((&#39;Lisa&#39;, &#39;grade-3&#39;), 86.0),
 ((&#39;Andrew&#39;, &#39;grade-1&#39;), 44.666666666666664),
 ((&#39;Andrew&#39;, &#39;grade-3&#39;), 35.0),
 ((&#39;Lisa&#39;, &#39;grade-2&#39;), 61.0),
 ((&#39;Andrew&#39;, &#39;grade-2&#39;), 77.0)]</p>
<pre><code>





</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[[파이썬 머신러닝 완벽가이드] 8장: Text Analysis]]></title>
            <link>https://velog.io/@bona-park/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D-%EC%99%84%EB%B2%BD%EA%B0%80%EC%9D%B4%EB%93%9C-8%EC%9E%A5-Text-Analysis-lkbs137k</link>
            <guid>https://velog.io/@bona-park/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D-%EC%99%84%EB%B2%BD%EA%B0%80%EC%9D%B4%EB%93%9C-8%EC%9E%A5-Text-Analysis-lkbs137k</guid>
            <pubDate>Tue, 18 Oct 2022 07:18:08 GMT</pubDate>
            <description><![CDATA[<ul>
<li><p>NLP vs 텍스트 분석</p>
</li>
<li><p>텍스트 분석 주요 영역
  텍스트 분류(어떤 카테고리에 속하나)
  감성 분석(텍스트에서 나타나는 주관적인 기분 등의 요소를 분석)
  텍스트 요약
  텍스트 군집화와 유사도 측정</p>
</li>
<li><p>텍스트 문석 머신러닝 수행 프로세스
  데이터 사전가공-&gt; Feature Vectorization -&gt; ML 학습/예측/평가
<img src="https://velog.velcdn.com/images/bona-park/post/9b97dfc5-8729-43b7-9f79-90dcb178e7e9/image.png" alt=""></p>
</li>
</ul>
<p><a href="https://www.researchgate.net/figure/Text-mining-process-Source-Chakraborty-Pagolu-and-Garla-2013_fig1_262413948">https://www.researchgate.net/figure/Text-mining-process-Source-Chakraborty-Pagolu-and-Garla-2013_fig1_262413948</a></p>
<ul>
<li><p>파이썬 기반의 NLP, 텍스트 분석 패키지
  NLTK, Gensim(토픽모델링), SpaCy</p>
</li>
<li><p>텍스트 전처리: 텍스트 정규화
  클렌징: html, xml 태그나 특정 기호 제거
  토큰화: 문장/ 단어 토큰화
  필터링/ 스톱워드 제거/ 철자 수정: 관사 제거
  Stemming/ Lemmatization: 단어 원형 추출</p>
</li>
<li><p>N-Gram
  문장을 개별 단어로 토큰화 하면 문맥적인 의미가 무시됨
  -&gt; n개의 단어를 하나의 토큰화 단위로 분리하는 것
  n개 단어 크기의 윈도우를 만들어 토큰화 수행</p>
</li>
</ul>
<ul>
<li><p>텍스트의 피처 벡터화 유형
  BOW(Bag of Words)</p>
<pre><code>  Document Term Matrix
  단어들의 등장 횟수를 매트릭스로</code></pre><p>  Word Embedding</p>
<pre><code>  개별 단어를 문맥을 기준으로 N차원 공간에 벡터로 표현</code></pre></li>
<li><p>BOW 
  문맥이나 순서를 무시하고
  일괄적으로 단어에 대해 빈도 값을 부여해 피처 값을 추출하는 모델
  (문서 내 모든 단어를 bag아넹 넣고 흔들어서 섞는다는 의미)</p>
</li>
<li><p>BOW 구조
  column은 단어로, row는 문장을 기준으로 각 column의 단어들이 몇번 등장했는지름 적음</p>
<p>  장점: 쉽고 빠른 구축 </p>
<pre><code>      예상보다 문서의 특징을 잘 나타내서 전통적으로 여러분야에 활용도가 높음</code></pre><p>  단점: 문맥 의미 반영을 못함</p>
<pre><code>      희소 행렬 문제(값의 없는 null이 너무 많다)</code></pre></li>
<li><p>BOW 피처 벡터화</p>
<ol>
<li><p>단순 카운트 기반의 벡터화
 각 문서에서 해당 단어가 나타나는 횟수를 부여</p>
</li>
<li><p>TF-IDF 벡터화
 단어에 가중치를 주어서, 모든 문서에서 많이 나타나는 단어에는 패널티를 줌</p>
<p> 특정 문서에만 나타나는 단어를 해당 문서를 잘 특징짓는 중요 단어일 가능성이 높다고 여김.</p>
<p> TF(Term Frequency): 그 문서에서 몇번 나왔니
 DF(Document Frequency): 그 단어가 전체 몇개의 문서에서 나왔는지
 IDF: 전체문체수/DF</p>
</li>
</ol>
</li>
</ul>
<ul>
<li><p>CountVectorizer를 이용한 피처 벡터화
  사전데이터가공-&gt;토큰화-&gt;텍스트정규화-&gt;피처 벡터화</p>
</li>
<li><p>희소행렬의 저장 변환 방식
  COO형식: 0이 아닌 데이터만 별도의 배열에 저장
  CSR형식: COO형식이 위치 배열값을 중복적으로 가지는 문제를 해결한 방식</p>
</li>
<li><p>20 Newsgroup 분류하기 *
  18846개의 뉴스 문서를 20개의 카테고리로 분류하기</p>
<p>  텍스트정규화 -&gt; 피처벡터화 -&gt; 머신러닝 -&gt; pipline 적용 -&gt; GridSearchCV최적화</p>
</li>
</ul>
<ul>
<li><p>감성분석
  지도학습 기반의 분석</p>
<p>  감성 어휘 사전을 이용한 분석</p>
<pre><code>  SentiWordNet: Synset별로 3가지 감성지수(긍정감성지수, 부정감성지수, 객관성지수)
  CADER: 소셜미디어의 텍스트에 대한 감성분석
  Pattern</code></pre><ul>
<li>IMDB의 영화 review에 대한 긍부정 예측</li>
</ul>
</li>
<li><p>SentiWordNet의 감성지수<br>  가로: 긍정부정, 세로: 객관성 정도</p>
<p>  문서를 문장단위로 분해
  -&gt; 단어를 토큰화, 품사 태깅
  -&gt; synset객체, senti_synset객체 생성
  -&gt; senti_synset에서 긍정 부정 감성지수 구하고 역치값 기준으로 판별</p>
</li>
<li><p>VADER
  SentiIntensityAnalyzer 클래스 사용</p>
</li>
</ul>
<ul>
<li><p>토픽 모델링
  문서들에 잠재돼 있는 공통된 토픽들을 추출해 내는 기법</p>
<ol>
<li><p>행렬 분해 기반 토픽 모델링(LSA. NMF)</p>
</li>
<li><p>확률 기반의 토픽 모델링</p>
</li>
</ol>
</li>
<li><p>LDA(Latent Dirichelt Allocation)
  문서내의 단어들을 이용해 베이즈 추론을 통해
  잠재된 문서내 토픽분포와 토픽별 단어분포를 추론하는 방식</p>
</li>
<li><p>베이즈 추론 켤레 사전 분포
  이항 분포 -&gt; 베타 분포
  다항 분포 -&gt; 디리클레 분포</p>
</li>
<li><p>LDA 구성요소</p>
</li>
<li><p>LDA 수행 프로세스 
  count 기반 행렬
  토픽의 개수 설정
  임의 주제를 최초할당 후, 문서별 토픽분포, 토픽별 단어분포가 결정됨
  특정 단어를 추출.제외 하고 두 분포를 재계산
  모든 단어들의 토픽 할당분포를 재계산</p>
</li>
</ul>
<ul>
<li>문섭 군집화</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[[파이썬 머신러닝 완벽가이드] 5장: Regression]]></title>
            <link>https://velog.io/@bona-park/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D-%EC%99%84%EB%B2%BD%EA%B0%80%EC%9D%B4%EB%93%9C-5%EC%9E%A5-Regression</link>
            <guid>https://velog.io/@bona-park/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D-%EC%99%84%EB%B2%BD%EA%B0%80%EC%9D%B4%EB%93%9C-5%EC%9E%A5-Regression</guid>
            <pubDate>Tue, 18 Oct 2022 07:14:52 GMT</pubDate>
            <description><![CDATA[<ul>
<li><p>회귀 
  데이터의 값이 평균과 같은 일정한 값으로 돌아가려는 경향
  (아무리 키가 큰 집안의 아이도 무한정 키가 커지지는 x)</p>
<p>  회귀: 여러개의 독립변수와 종속변수 간의 상관관계를 모델링하는 기법을 통칭</p>
<p>  머신러닝에서 회귀의 핵심:</p>
<pre><code>  최적의 회귀 계수를 찾아내는 것! (W1, W2, ..)</code></pre><p>  선형회귀 vs 비선형회귀: 회귀계수의 제곱여부! (독립변수 x**2는 상관없음!)</p>
</li>
<li><p>분류 vs 회귀
  분류: 결과 값이 category값(이산적인 값으로)</p>
<p>  회귀: 숫자값(연속값)</p>
</li>
</ul>
<p><img src="https://velog.velcdn.com/images/bona-park/post/c3c0171f-9a93-4c3b-9085-76e7d078ac9a/image.png" alt=""></p>
<p><a href="https://miro.medium.com/max/1400/1*kcBsTJsIiDEC9XcizmnmYg.png">https://miro.medium.com/max/1400/1*kcBsTJsIiDEC9XcizmnmYg.png</a></p>
<p>[지도학습]</p>
<p>정답이 있는 데이터를 활용해 데이터를 학습시키는 것</p>
<p>대표적으로 분류(결과가 카테고리로 나뉠 때), 회귀(결과값이 실수)</p>
<p>[비지도학습]</p>
<p>정답 라벨이 없는 데이터를 비슷한 특징끼리 군집화하여 새로운 데이터에 대한 결과를 예측하는 법</p>
<p>대표적으로 클러스터링, K Means</p>
<p>[강화학습]</p>
<p>자신이 한 행동에 대한 보상(reward)를 받으며 높은 점수를 얻는 방법을 찾아가는 것</p>
<p>특정 학습 횟수 이후에, 높은 점수(reward)를 획득할 수 있는 전략이 형성됨</p>
<p>(행동을 위한 행동 목록은 사전에 정의 되어 있음)</p>
<ul>
<li>선형 회귀의 종류
  일반선형회귀
  릿지, 라쏘, 엘라스틱넷
  로지스틱회귀(사실은 분류에 사용되는 선형 모델)</li>
</ul>
<p><img src="https://velog.velcdn.com/images/bona-park/post/c913d708-9def-4eb8-9bed-b62b640bd0ca/image.png" alt=""></p>
<p><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fdevopedia.org%2Ftypes-of-regression&amp;psig=AOvVaw2_T3lABcpo_xoUkj-OpLXx&amp;ust=1651009003135000&amp;source=images&amp;cd=vfe&amp;ved=0CAwQjRxqFwoTCLDV1uWWsPcCFQAAAAAdAAAAABAP">https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fdevopedia.org%2Ftypes-of-regression&amp;psig=AOvVaw2_T3lABcpo_xoUkj-OpLXx&amp;ust=1651009003135000&amp;source=images&amp;cd=vfe&amp;ved=0CAwQjRxqFwoTCLDV1uWWsPcCFQAAAAAdAAAAABAP</a></p>
<ul>
<li><p>단순 선형 회귀(SR): 피처가 1개
  y = w0 + w1*x</p>
</li>
<li><p>RSS 기반의 회귀 오류 측정
  RSS: 회귀의 비용함수(오류값의 제곱의 합)</p>
<p>  단순선형회귀에서, RSS식에는 w0과 w1만 남는다.</p>
<p>  회귀 알고리즘에서는 RSS(비용함수)를 최소로 만들어야 한다</p>
</li>
<li><p>비용 최소화하기: 경사하강법(Gradient Descent)
  점진적으로 반복적인 계산을 통해 w를 업데이트 시키기</p>
</li>
<li><p>R(w)의 편미분</p>
</li>
<li><p>사이킷런 LinearRegression 클래스</p>
</li>
<li><p>선형회귀의 다중 공선성 문제
  피처간의 상관관계가 높으면, 분산이 커져서, 오류에 매우 민감해진다
  상관관계가 높은 피처들 중에 중요한 피처만 남겨야 한다!</p>
</li>
<li><p>회귀 평가 지표
  MSE: mean squared error
  MSLE: MSE에 로그를 적용한 것</p>
</li>
<li><p>Scoring 함수에 회귀 평가 적용 시 유의사항</p>
</li>
<li><p>다항회귀
  독립변수(x)의 식이 단항식이 아닌 2차, 3차 방적식과 같은 다항식으로 표현되는 것</p>
</li>
<li><p>PolynomialFeatures
  다항식을 하나의 단항식으로 바꾼 다음에 LinearRegression학습을 시킨다</p>
<pre><code>  ex) x1**3 = z1 으로 변환</code></pre></li>
</ul>
<ul>
<li><p>규제선형회귀
  다항회귀에서 회귀계수가 기하급수적으로 커지는 것을 제어해야한다</p>
<p>  최적모델을 위한 cost함수 구성요소 </p>
<pre><code>  = 학습데이터 잔차 오류 최소화 + 회귀계수 크기 제어</code></pre><p>  규제: aplpha값으로 페널티를 부여해, 회귀 계수 값의 크기를 감소시킴</p>
<p>  릿지회귀: w의 제곱에 대해 패널티 부여
  라쏘회귀: W의 절댓값에 대해 패널티 부여</p>
</li>
<li><p>릿지 회귀
  회귀계수의 크기를 주기적으로 감소시킴</p>
</li>
<li><p>라쏘회귀<br>  불필요한 회귀 계수를 급격하게 감소시켜 0으로 만들고 제거</p>
</li>
<li><p>엘라스틱넷 회귀: L2+L1
  alpha:  = L1의 alpha + L2의 aplha</p>
</li>
</ul>
<ul>
<li><p>선형회귀모델을 위한 데이터 변환</p>
<p>  타깃값변환: 타깃값을 반드시 정규 분포로 만들어야 함(주로 로그 변환 적용)</p>
<p>  피처값 변환:    </p>
<pre><code>  StandardScaler
  MinMaxScaler</code></pre><p>  데이터 인코딩은 원-핫 인코딩 적용</p>
</li>
<li><p>피처 데이터 변환에 따른 예측 성능 비교
  원본 vs 표준정규분호 vs 표준정규분포+2차다항식 vs 최소최대정규화 vs 로그변환</p>
</li>
</ul>
<ul>
<li><p>로지스틱 회귀
  시그모이드 함수 최적선을 찾고, 이 시그모이드 함수의 반환 값을 확률로 간주해 확률에 따른 분류를 결정한다</p>
<p>  주로 이진 분류에 사용됨.
  예측확률은 시그모이드 함수의 출력값
  예측확률이 0.5이상이면 예측값을 1로.</p>
</li>
<li><p>회귀트리
  CART: Classification and regression trees</p>
<ol>
<li>RSS를 최소화하는 규칙 기준에 따라 분할</li>
<li>최종 분할된 영역에 있는 데이터들의 평균값들로 학습/예측</li>
</ol>
</li>
<li><p>회귀트리의 오버비팅
  트리크기, 노드 개수 제한 등의 방법 통해 오버피팅 개선.</p>
</li>
</ul>
<p>ref: &quot;파이썬 머신러닝 완벽가이드&quot;,  권철민, 위키북스</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Bioinformatics] Presentation: ShRec3D]]></title>
            <link>https://velog.io/@bona-park/Bioinformatics-Presentation-ShRec3D</link>
            <guid>https://velog.io/@bona-park/Bioinformatics-Presentation-ShRec3D</guid>
            <pubDate>Tue, 18 Oct 2022 04:30:09 GMT</pubDate>
            <description><![CDATA[<p>   I gave a 40-minute presentation in the Introduction to Bioinformatics class at the University of Miami. It was reviewing the paper &quot;3D Genome Reconstruction from chromosol contacts&quot; by Annick Lense. It was the first in-person presentation in my university life. 40-minute was a long presentation but I ended up performing well.</p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/240a96e4-78b7-4e2c-81f8-3659165c2976/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/d3ccbfb4-9d10-4d68-81de-95ca227f4832/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/f447d654-a301-46f0-bb28-ebc43e835040/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/61c224cc-52d1-4124-ac1a-04ac0ed23ef4/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/5aca0c61-83f4-44af-89df-c7a37ac2fcb8/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/8329ff2c-b610-4501-abb0-cf3667c2c890/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/7b407568-3a96-4fc0-a873-0e27eaf048c5/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/615766f8-24fe-4f2d-b532-178dece0761f/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/7c79eb4e-f30b-49d0-a018-6114f52d2e1c/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/2ecb1f7f-1b81-42b3-ad69-ced67ec24d6b/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/3dacc5b4-af5d-4e88-9633-311a64166629/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/dd8da089-7e87-4c6f-8670-7ebe8f4b9bc8/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/d79ba6ef-cb0c-4b90-bc33-a258533b3e8b/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/6c360536-b394-4fd6-846f-08f01495b679/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/0afd3cd5-d9bc-494d-9410-f7a8ccc97878/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/5a8e197b-7bc4-45de-9c1f-c12f3273a7ba/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/41996aba-7a01-4fe1-be5b-8bd2316e30aa/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/4e6debcc-fd99-4b94-8126-82fcb6cd0ec9/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/68db0419-2392-47b6-90f2-58018a5e6f89/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/3ddbda76-ffbd-49ea-a9d7-f14ce7a786d8/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/4f5e94b3-56e7-40f3-badd-fb60b461df3e/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/5ce5dffb-9732-4ae3-89af-1b00ec6925a8/image.jpg" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/503402fd-ea1d-4c32-997a-633815096197/image.jpg" alt=""></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Bioinformatics] Paper Review: Hi-C]]></title>
            <link>https://velog.io/@bona-park/Bioinformatics-Paper-Review-Hi-C</link>
            <guid>https://velog.io/@bona-park/Bioinformatics-Paper-Review-Hi-C</guid>
            <pubDate>Tue, 18 Oct 2022 03:46:14 GMT</pubDate>
            <description><![CDATA[<h2 id="comprehensive-mapping-of-long-range-interactions-reveals-folding-principles-of-the-human-genome"><a href="https://www.science.org/doi/10.1126/science.1181369"><em>Comprehensive Mapping of Long-Range Interactions Reveals Folding Principles of the Human Genome</em></a></h2>
<div style="text-align: right"> Bona Park </div>




<p>Chromosome conformation capture is a way that enables researchers to observe interactions between loci. These loci are in close contact in the 3-dimnesional structure of a chromosome, but they can be apart in the linear sequence. It is important to understand how chromosomes fold that it is relevant to complicated relationships between chromatic structure, gene activity, and the cell’s functional state. There are many different ways to look into the 3-D structure of chromatin. Chromosome conformation capture, as know as 3C, was the first chromatin structure assay. It uses spatially constrained ligation. 3C has been adapted into several ways such as 4C(inverse PCR) and 5C(multiplexed ligation-meditated amplification). But those methods have to overcome that they require choosing a set of target loci and they cannot be applied to unbiased genomwide analysis. Therefore, researchers in this paper suggest a new method called Hi-C. It also has been developed from above methods but can identify chromatin interactions genomwidely. Hi-C starts with the cross-linking and DNA digestion steps. While the 5’ overhang is filled, biotinylated residue incorporates it. The biotin tag is at the center of the ligation junction in the DNA strand. It results in fragments in close spatial proximity in the nucleus compost of the ligation products.</p>
<p>The researchers divide the genome into loci 1Mb of which comprise one genome and make a genomwide contact matrix(M) .The matrix entry m(ij) means the number of ligation products between locus I and j. This expresses the combined meaning of the interactions in the cells.</p>
<p>They validated the Hi-C model with several ways. First, they repeated the experiment with the same restriction enzyme and with a different one and checked whether it reproduces same results every time. It was validated by extracting similar contact matrices from the different experiments. Furthermore, they checked whether there is corresponds to the known features of genome organization such as patterns in subnuclear positioning or chromosome territories.</p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/6fc16726-fc93-4e59-a277-bd9957841a78/image.png" alt=""></p>
<p>From a genomic distance in base pairs along the nucleotide sequence, they computed the average contact probability. It can be expressed as In(s), where n stands for the sequence number of chromosome and s for the distance. As 3D distance between loci increases, In(s) decreases on every chromosome. These is also supported by 3C and fluorescence in situ hybridization(FISH). In terms of interchromosomal contact probabilities, some small and gene-rich chromosomes preferentially showed strong interact with each other. On the other hand, small but gene-poor chromosomes don’t interact that much with other small chromosomes. This is also supported by FISH. They were also curious about whether there are specific regions on individual chromosomes that preferentially associate with each other. They defined a normalized contact matrix M*. This entry of the matrix is by dividing each entry in the contact matrix by the genomwide average probability for loci. Interestingly, it makes a plaid pattern that has many blocks of enriched and depleted interactions. Then they defined a correlation matrix C from the assumption that spatially neighboring loci would have a correlated interaction profile. The entry c(ij) of correlation matrix C is the Pearson correlation between the ith row and jth column of M*. It even improves the plaid pattern composed of label A and B. Furthermore, the plaid patterns of intra-chromosome were similar within that of inter-chromosome. This leads to the fact that the whole genome can be divided into two compartments in 3-dimensional where the interactions within each compartment is bigger than across compartments. The Hi-C data shows that regions corresponding to the same compartment are likely to be spatially closer. They tested this by 3D-Fish method with investigating four loci on one chromosome locating in the two compartments. The result validated the compartmentalization in the space. They also examined the density of regions. They found out that the pairs of loci in the compartment B had a higher interaction frequency than the pairs in compartment A which means that B is denser and more packed.</p>
<p>The researchers compared the known genetic and epigenetic features between two spatial compartments. Compartment A is relevant to stronger presence of genes, higher expression through genomwide mRNA expression, and more accessible chromatin. It concludes that the compartment A is more with actively transcribed, open, and accessible chromatin. They do this experiment again with K562 cells, and gained similar result from in GM06990 cells. Even though both K562 and GM06990 showed similar compartment patterns, the loci alternated the compartment. They concluded that even a highly rearranged genome, spatial compartmentalization is relevant with the open or closed status.</p>
<p>Last but not least, they correlated chromatin structure to compartments. They calculated contact probability within chromosome scaling as s^(-1). So far, the chromosol regions have been modeled as an “equilibrium globule”. In it chromatin is pictured as being in a compact and densely knotted configuration. On the other hand “fractal globule” is formed by an unentangled polymer like a “beads-on-a-string” configuration. Because of lacking knots and availability to enfold and refold during the cell cycle, the latter is more attractive structure for chromatin segments than the former. Two globule models make very different predictions about the 3D distance between pairs of loci and the scaling of contact probability with genomic distance s. The researchers created ensemble models by implementing Monte Carlo simulations. The ensemble was tested and showed consistent to theoretically derived results for contact probability and 3D distance.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[파이썬 머신러닝 완벽가이드] 4장ㅣ 분류]]></title>
            <link>https://velog.io/@bona-park/hki8wkqn</link>
            <guid>https://velog.io/@bona-park/hki8wkqn</guid>
            <pubDate>Mon, 17 Oct 2022 14:59:55 GMT</pubDate>
            <description><![CDATA[<h2 id="4장-분류">[4장: 분류]</h2>
<h4 id="균일도-기반-규칙-조건">균일도 기반 규칙 조건</h4>
<h4 id="정보-균일도-측정-방법">정보 균일도 측정 방법</h4>
<p>1) 정보 이득
        ..앤트로피 개념
        정보이득 지수 = 1-엔트로피 지수</p>
<p>2) 지니계수: 불평등 지수
지니계수 낮을수록 균일한 데이터</p>
<h4 id="결정트리의-규칙노드-생성-프로세스">결정트리의 규칙노드 생성 프로세스</h4>
<pre><code>If true/ else</code></pre><h4 id="결정트리-장점">결정트리 장점</h4>
<p>   쉽고 직관적</p>
<h4 id="결정트리-단점">결정트리 단점</h4>
<p>과적합(overfitting)<br>    sol) 트리크기를 사전에 제한</p>
<h4 id="결정트리-주요-hyperparameter">결정트리 주요 hyperparameter</h4>
<pre><code>- max_depth, max_features..</code></pre><h4 id="graphviz이용한-결정트리-모델의-시각화실제-나무-모양-그림으로">Graphviz이용한 결정트리 모델의 시각화(실제 나무 모양 그림으로)</h4>
<ul>
<li>각 노드에는피처의 규칙 조건 gini samples: 현 규칙에 해당하는 데이터 건수 value: 클래스 값 기반의 데이터 건수
ex) [41,4,10] 이면 해당 조건을 만족하는 a품종은 41개 b품종은 4개<pre><code>class: value리스트 내에 가장 많은 건수를 가진 결정값</code></pre></li>
</ul>
<h4 id="결정트리의-feture-선택-중요도">결정트리의 feture 선택 중요도</h4>
<p>중요한 feature들만 선택해서 학습,예측하는게 나을 수도
    - feature_importance: 중요한 feature 찾아내기</p>
<h4 id="결정트리-실습-사용자-행동-인식-데이터-세트">결정트리 실습: 사용자 행동 인식 데이터 세트</h4>
<p>* 스마트 워치끼고 어떤 행동을 하는지 찾아낸다 </p>
<h4 id="앙상블-학습">앙상블 학습</h4>
<p>다양한 분류기의 예측 결과를 도합
    이질적인 모델들을 섞는 게 전체 성능에 도움이 될 수 ㅇ</p>
<p><strong>1. 보팅</strong>
        하드 보팅: 다수의 classifier 간 다수결
        소프트보팅: class별 확률 결정 by predict_proba()</p>
<p>* 위스콘신 유방암 데이터 예측
        (cf) kNeighborsClassifier에서 n_neighbors는 내 주변의 몇개의 이웃들을 참조해서 이 데이터를 예측할 건지</p>
<p align="center"><img src="https://velog.velcdn.com/images/bona-park/post/76126451-b183-48b7-a699-7c11eb74cc6c/image.png" width="400px"></p>      

<p><span style="font-size: 11px; color:
             #008000" >
  <a href="https://velog.velcdn.com/images%2Fjiselectric%2Fpost%2F49803ffd-d915-403f-8c78-9fe5ee26ad1d%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202021-01-14%20%E1%84%8B%E1%85%A9%E1%84%8C%E1%85%A5%E1%86%AB%201.02.01.png">https://velog.velcdn.com/images%2Fjiselectric%2Fpost%2F49803ffd-d915-403f-8c78-9fe5ee26ad1d%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202021-01-14%20%E1%84%8B%E1%85%A9%E1%84%8C%E1%85%A5%E1%86%AB%201.02.01.png</a></br>
</span></p>
<p> <strong>2.</strong> <strong>배깅</strong> | 랜덤 포레스트가 대표적
        여러개의 결정트리 분류기가 전체 데이터에서 배깅방식으로 각자 데이터를 샘플링해 개별적으로 학습 수행
        -&gt; 이후 모든 분류기를 보팅으로 예측 결정
        비교적 빠른 수행속도</p>
<p> bootstrapping: 전체 데이터 세트를 중첩되게 분리하는 것
            한 서브세트에 [1233346889]와 같이 한 데이터가 여러개씩 들어있음</p>
<pre><code>  * 사용자 행동인지 데이터 예측
        (cf) 개별 피쳐들의 중요도 시각화    
            Random forest의 feature_importances_: 중요도 순서로 ndarray로 반환
            -&gt; series로 변환</code></pre><p>** 3. 부스팅**    
        여러개의 학습기를 &quot;순차적&quot;으로 학습,예측하면서 &quot;잘못 에측한 데이터&quot;에 가중치 부여해 오류를 개선해나가며 학습시키기<br>                            -&gt; 수행시간 오래걸림</p>
<ul>
<li><p><strong>GBM</strong> (Gradient Boost Machine)
   가중치 업데이트에 경사하강법을 이용
   GradientBoostingClassifier 클래스</p>
<p>   learning_rate: GBM 학습 진행시에 적용되는 학습률
   n_estimators: weak learner의 개수
   subsample: weak learner가 학습에 사용하는 데이터 샘플링 비율</p>
</li>
<li><p><strong>XGBoost</strong>(extra gradient boost)
   빠른 수행시간
   다양한 성능향상기능: 규제, tree pruning(가지치기)<br>   다양한 편의기능: 조기 중단, 자체 내장된 교차검증, 결손값 자체 처리</p>
<ul>
<li>조기중단기능
  더이상 비용함수가 감소하지 않으면, 수행을 종료
  early_stopping_rounds(더이상 비용평가지표가 감소하지않는 최대 반복횟수), eval_metric, eval_set</li>
</ul>
</li>
<li><p><strong>LightGBM</strong>
   더 빠르고 더 작은 메모리 사용
   카테고리형 feature의 자동변환, 최적분활</p>
<p>   leaf 중심트리 분할 방식(leaf wise(&lt;-&gt;균형트리분할방식))</p>
</li>
</ul>
<p><a href="https://miro.medium.com/max/2590/1*5gY5IdU6PO4JCqQoEDtdMA.png">https://miro.medium.com/max/2590/1*5gY5IdU6PO4JCqQoEDtdMA.png</a></p>
</br>

<h4 id="-분류-실습1-캐글경연대회의-산탄데르-은행-고객-만족-예측">* 분류 실습1: 캐글경연대회의 산탄데르 은행 고객 만족 예측</h4>
<h4 id="-분류-실습2-신용카드-사기-예측-실습">* 분류 실습2: 신용카드 사기 예측 실습</h4>
<h4 id="iqr과-박스플롯">IQR과 박스플롯</h4>
<h4 id="언더샘플링-오버샘플링">언더샘플링, 오버샘플링</h4>
<pre><code>    언더샘플링: 많은 레이블을 가진 데이터 세트를
                적은 레이블을 가진 데이터 세트 수준으로 감소 샘플링 </code></pre><h4 id="smote">SMOTE</h4>
<pre><code>    원본데이터-&gt; k최근접 이웃으로 데이터 신규증식 -&gt; 신규증식하여 오버샘플링 완료</code></pre><h4 id="정리">정리</h4>
<pre><code>    데이터 로그 변환: 약간식 성능 좋아짐
    이상치 데이터 제거: 정밀도 up, 재현율 up
    SMOTE 오버 샘플링: 정밀도 down, 재현율 up</code></pre><h4 id="stacking-model">Stacking Model</h4>
<pre><code>기반 모델들이 예측한 값들을 Stacking 형태로 만들어서
메타 모달들이 이를 학습하고 예측하는 모델</code></pre><h4 id="교차-검증-세트-기반의-스태킹">교차 검증 세트 기반의 스태킹</h4>
<p>step1: 각 기반 모델 별로 학습하고, 학습/테스트 데이터를 예측한 결과값을 기반으로
            메타 모델을 위한 학습용/테스트용 데이터를 생성한다
    step2: 스텝1에서 </p>
<h4 id="신규">(신규)</h4>
<h5 id="feature-selection">Feature Selection</h5>
<pre><code>모델을 구성하는 주요 피처들을 선택
불필요한 다수의 피처들로 인해 모델 성능을 떨어뜨릴 가능성을 제거
설명가능한 모델이 될 수 있도록 피처들을 선별

피처값의 분포, Null의 개수, 피처간 높은 상관도(겹치는거 제거), 결정값과의 독립성 등을 고려
모델의 피처중요도 기반</code></pre><h5 id="사이킷런-feature-selection-지원">사이킷런 Feature Selection 지원</h5>
<h4 id="rfe">RFE</h4>
<p>모델의 최초학습 후 feature 중요도 선정
            feature중요도가 낮은 속성들을 차례대로 제거, 반복적으로 학습.평가 수행하여
                최적의 feature추출
            수행시간이 너무 오래걸린다..</p>
<h4 id="selectfrommodel">SelectFromModel</h4>
<p>모델 최초 학습 후 선정된 피처 중요도에 따라 평균.중앙값의 특정 비율 이상인 피처들을 선택</p>
<p><em>ref: &quot;파이썬 머신러닝 완벽가이드&quot;,  권철민, 위키북스</em></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[GDSC-ML] Practice: Improve accuracy of ImageNet Classification project]]></title>
            <link>https://velog.io/@bona-park/GDSC-ML-Practice-Improve-accuracy-of-ImageNet-Classification-project</link>
            <guid>https://velog.io/@bona-park/GDSC-ML-Practice-Improve-accuracy-of-ImageNet-Classification-project</guid>
            <pubDate>Thu, 13 Oct 2022 09:32:16 GMT</pubDate>
            <description><![CDATA[<h4 id="--models">- Models</h4>
<p><img src="https://velog.velcdn.com/images/bona-park/post/75d3136e-79a2-4b0a-bd87-4c175f70b1ee/image.png" alt=""></p>
<h4 id="1-initial-mymodelyaml">1. Initial “mymodel.yaml”</h4>
<pre><code>```powershell
epochs: 10
resume: None
learning_rate: **0.001**
weight_decay: 10e-6
inference_device: &quot;cuda&quot;

train:
  batch_size: 4
  num_workers: 4
  valid_size: 0.3
  train_path: &quot;./2_data/train&quot;

test:
  batch_size: 4
  num_workers: 4
  test_path: &quot;./2_data/val&quot;

model:
  base_model: &quot;convnext_base&quot;
```</code></pre><p>   <img src="https://velog.velcdn.com/images/bona-park/post/4431ed03-ba91-4576-a265-23a1b5b4207b/image.png" alt=""></p>
<h4 id="2-convnext_baseyaml">2. “convnext_base.yaml”</h4>
<p>   I follwed the hyperparamters same as <strong><a href="https://huggingface.co/ImageIN/convnext-base-224_finetuned_on_ImageIn_annotations">convnext-base-224_finetuned_on_ImageIn_annotations</a></strong>
    Learning rate decreased.</p>
<p>  <img src="https://velog.velcdn.com/images/bona-park/post/255beb99-9af8-4484-a0f7-2e132214b619/image.png" alt=""></p>
<pre><code class="language-powershell">      epochs: 10
      resume: None
      learning_rate: **2e-05**
      weight_decay: 10e-6
      inference_device: &quot;cuda&quot;

      train:
        batch_size: 16
        num_workers: 4
        valid_size: 0.3
        train_path: &quot;./2_data/train&quot;

      test:
        batch_size: 16
        num_workers: 4
        test_path: &quot;./2_data/val&quot;

      model:
        base_model: &quot;convnext_base&quot;</code></pre>
<p>  <img src="https://velog.velcdn.com/images/bona-park/post/11f1103f-70c5-41ba-a8eb-4a1dc0813d78/image.png" alt=""></p>
<p>   valid_loss: 2.0629</p>
<h4 id="3-convnext_base_1yaml">3. “convnext_base_1.yaml”</h4>
<p><img src="https://velog.velcdn.com/images/bona-park/post/fbd94957-e93e-40e7-930f-084ac6586953/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/e0179f95-cfc8-487a-a866-1f91f2e9446c/image.png" alt=""></p>
<pre><code class="language-powershell">epochs: 10
resume: None
learning_rate: **4e-3**
weight_decay: 10e-6
inference_device: &quot;cuda&quot;

train:
  batch_size: 16
  num_workers: 4
  valid_size: 0.3
  train_path: &quot;./2_data/train&quot;

test:
  batch_size: 16
  num_workers: 4
  test_path: &quot;./2_data/val&quot;

model:
  base_model: &quot;convnext_base&quot;</code></pre>
<p><img src="https://velog.velcdn.com/images/bona-park/post/e945e237-04b9-4440-a540-eecb6276bc43/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/6151b217-ec58-4bda-b4d7-b2526af95fda/image.png" alt=""></p>
<h4 id="4-restnet50yaml">4. “RestNet50.yaml”</h4>
<p>   learning_rate: 2e-05, batch size: 16</p>
<p>   <img src="https://velog.velcdn.com/images/bona-park/post/837d8f37-63eb-4131-a466-0dda14cc7522/image.png" alt=""></p>
<h4 id="5-resnet50_batch256yaml">5. “ResNet50_batch256.yaml”</h4>
<p>   learning_rate: 0.001, batch size: 256
   <img src="https://velog.velcdn.com/images/bona-park/post/3b40ab2c-a60e-49c1-92dd-4938b53de2a6/image.png" alt=""></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[ML] Hyperparameter Tuning: Learning rate and Batch size]]></title>
            <link>https://velog.io/@bona-park/ML-Hyperparameter-Tuning-Learning-rate-and-Batch-size</link>
            <guid>https://velog.io/@bona-park/ML-Hyperparameter-Tuning-Learning-rate-and-Batch-size</guid>
            <pubDate>Thu, 13 Oct 2022 09:25:15 GMT</pubDate>
            <description><![CDATA[<h3 id="batch-size-and-learning-rate">Batch size and Learning rate</h3>
<p><img src="https://velog.velcdn.com/images/bona-park/post/d58c03f7-b3ed-4175-8be1-abc48892136c/image.png" alt=""></p>
<p><a href="https://openreview.net/pdf?id=B1Yy1BxCZ">https://openreview.net/pdf?id=B1Yy1BxCZ</a></p>
<h4 id="1-batch-size">1. Batch Size</h4>
<p><img src="https://velog.velcdn.com/images/bona-park/post/56461999-3a80-4cc8-a845-aaf0aefd44a8/image.png" alt=""></p>
<ul>
<li>small: converges quickly at the cost of noise in the training process</li>
<li>large: converges slowly with accurate estimates of the error gradient</li>
</ul>
<h4 id="2-learning-rate">2. Learning Rate</h4>
<p>   <img src="https://velog.velcdn.com/images/bona-park/post/6c02d1fa-91be-423e-8053-47f057385e04/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/708a1bfe-28d1-4f6b-823e-b6e304dcf30c/image.png" alt=""></p>
<p>The most popular form of learning rate annealing is a <em>step decay</em>
 where the learning rate is reduced by some percentage after a set number of training epochs.</p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/b3a5afba-8e27-4339-bf62-5b8f085ec9d7/image.png" alt=""></p>
<p><a href="https://www.jeremyjordan.me/nn-learning-rate/">https://www.jeremyjordan.me/nn-learning-rate/</a></p>
<p><a href="https://www.baeldung.com/cs/learning-rate-batch-size">https://www.baeldung.com/cs/learning-rate-batch-size</a></p>
<p><a href="https://inhovation97.tistory.com/32">https://inhovation97.tistory.com/32</a></p>
<h3 id="bag-of-tricks-for-image-classification-with-convolutional-neural-networks"><em><strong>Bag of Tricks for Image Classification with Convolutional Neural Networks</strong></em></h3>
<p><a href="https://arxiv.org/abs/1812.01187">https://arxiv.org/abs/1812.01187</a></p>
<ul>
<li><p><strong>Increase Batch size</strong></p>
</li>
<li><p><strong>Linear scaling learning rate</strong></p>
</li>
<li><p><strong>Model Architecture Tweaks</strong></p>
<blockquote>
<p>“A model tweak is a minor adjustment to the network architecture, such as changing the stride of a particular convolution layer. Such a tweak often barely changes the computational complexity but might have a non-negligible effect on the model accuracy.”</p>
</blockquote>
</li>
</ul>
<p><img src="https://velog.velcdn.com/images/bona-park/post/a7f91d58-baa4-4c93-88cf-d28ad6a99b96/image.png" alt=""></p>
<ul>
<li><p><strong>Training Refinements</strong></p>
<ul>
<li><p>Cosine Learning rate Decay</p>
</li>
<li><p>Label smoothing</p>
</li>
<li><p>Mixup training</p>
<p>  <img src="https://velog.velcdn.com/images/bona-park/post/205ed119-c1f6-4486-9b90-45df20595fc3/image.png" alt=""></p>
</li>
</ul>
</li>
</ul>
<p><a href="https://norman3.github.io/papers/docs/bag_of_tricks_for_image_classification.html">https://norman3.github.io/papers/docs/bag_of_tricks_for_image_classification.html</a></p>
<p><a href="https://medium.com/analytics-vidhya/bag-of-tricks-for-image-classification-with-convolutional-neural-networks-99f00a9b9565">https://medium.com/analytics-vidhya/bag-of-tricks-for-image-classification-with-convolutional-neural-networks-99f00a9b9565</a></p>
<p><a href="https://phil-baek.tistory.com/entry/CNN-%EA%BF%80%ED%8C%81-Bag-of-Tricks-for-Image-Classification-with-Convolutional-Neural-Networks-%EB%85%BC%EB%AC%B8-%EB%A6%AC%EB%B7%B0">https://phil-baek.tistory.com/entry/CNN-꿀팁-Bag-of-Tricks-for-Image-Classification-with-Convolutional-Neural-Networks-논문-리뷰</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[ML] Various ways for Hyperparameter Tuning in Machine Learning]]></title>
            <link>https://velog.io/@bona-park/Hyperparameter-Tuning-in-Machine-Learning</link>
            <guid>https://velog.io/@bona-park/Hyperparameter-Tuning-in-Machine-Learning</guid>
            <pubDate>Thu, 13 Oct 2022 09:21:33 GMT</pubDate>
            <description><![CDATA[<h3 id="hyperparameter-tuning">Hyperparameter Tuning</h3>
<p>The process of finding the right combination of hyperparameters to maximize the model performance</p>
<h3 id="hyperparameter-tuning-methods">Hyperparameter tuning methods</h3>
<ul>
<li><p>Random Search</p>
</li>
<li><p>Grid Search</p>
<ul>
<li><p>Each iteration tries a combination of hyperparameters in a specific order.</p>
<p>  It fits the model on each combination, records the model performance, and returns the best model with the best hyperparameters.</p>
</li>
</ul>
</li>
<li><p>Bayesian Optimization</p>
</li>
<li><p>Tree-structured Parzen estimators(TPE)</p>
</li>
</ul>
<h3 id="hyperparameter-tuning-algorithms">Hyperparameter tuning algorithms</h3>
<ul>
<li>Hyperband</li>
<li>Population-based Training(PBT)<ul>
<li>a hybrid of Random Search and manual tuning</li>
<li>Many neural networks run in parallel but they are not fully independent of each other.</li>
<li>It uses the information from the rest of the networks to refine the hyperparameters and determine which hyperparameter to use based on the rests</li>
</ul>
</li>
</ul>
<h3 id="useful-libraries-for-hyperparameter-optimization">Useful libraries for hyperparameter optimization</h3>
<ul>
<li><p>Optuma</p>
<ul>
<li>Efficiently search large spaces and prune unpromising trials for faster results</li>
</ul>
</li>
<li><p>Ray Tune</p>
<blockquote>
<p>Tune is a Python library for experiment execution and hyperparameter tuning at any scale. You can tune your favorite machine learning framework (<a href="https://docs.ray.io/en/latest/tune/examples/tune-pytorch-cifar.html#tune-pytorch-cifar-ref">PyTorch</a>
  , <a href="https://docs.ray.io/en/latest/tune/examples/tune-xgboost.html#tune-xgboost-ref">XGBoost</a>, <a href="https://docs.ray.io/en/latest/tune/examples/tune-sklearn.html">Scikit-Learn</a>, <a href="https://docs.ray.io/en/latest/tune/examples/tune_mnist_keras.html">TensorFlow and Keras</a>, and <a href="https://docs.ray.io/en/latest/tune/examples/index.html">more</a>) by running state of the art algorithms such as <a href="https://docs.ray.io/en/latest/tune/api_docs/schedulers.html#tune-scheduler-pbt">Population Based Training (PBT)</a>  and <a href="https://docs.ray.io/en/latest/tune/api_docs/schedulers.html#tune-scheduler-hyperband">HyperBand/ASHA</a>.</p>
</blockquote>
<blockquote>
<p><strong>Two Benefits</strong></p>
<ul>
<li><strong>They maximize model performance</strong>: e.g., DeepMind uses PBT to <a href="https://www.reddit.com/r/MachineLearning/comments/ajgzoc/we_are_oriol_vinyals_and_david_silver_from/">achieve superhuman performance on StarCraft</a>; Waymo uses <a href="https://www.technologyreview.com/s/614004/deepmind-is-helping-waymo-evolve-better-self-driving-ai-algorithms/">PBT to enable self-driving cars</a>.</li>
<li><strong>They minimize training costs</strong>: <a href="https://determined.ai/blog/addressing-challenges-parallel-hyperparameter-optimization/">HyperBand and ASHA converge to high-quality configurations</a> in half the time taken by previous approaches; <a href="https://arxiv.org/abs/1905.05393">population-based data augmentation algorithms</a> cut costs by orders of magnitude.</li>
</ul>
<p>cf) ASHA: one of the popular early stopping algorithm</p>
</blockquote>
<p>  <img src="https://velog.velcdn.com/images/bona-park/post/f7e9f1a4-8ae5-4616-aa1b-7084f18aefc5/image.png" alt=""></p>
<p>  To be brief, Ray Tune scales your training from a single machine to a large distributed cluster without changing your code.</p>
<ol>
<li>Simplifies scaling<ul>
<li>It allows to use all of the cores and GPUs on the machine</li>
<li>So it makes it perform parallel asynchronous hyperparameter tuning.</li>
</ul>
<ol start="2">
<li>Flexible<ul>
<li>Supports any ML framework(PyTorch, TensorFlow ..)</li>
<li>It provides a flexible interface for optimization algorithms,</li>
<li>We can visualize with MLFlow and TensorBoard.</li>
</ul>
</li>
</ol>
</li>
</ol>
</li>
</ul>
<p>ref) <a href="https://neptune.ai/blog/hyperparameter-tuning-in-python-complete-guide">https://neptune.ai/blog/hyperparameter-tuning-in-python-complete-guide</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Spark] Spark DataFrame / SQL]]></title>
            <link>https://velog.io/@bona-park/Spark-DataFrame-SQL</link>
            <guid>https://velog.io/@bona-park/Spark-DataFrame-SQL</guid>
            <pubDate>Sat, 08 Oct 2022 06:53:10 GMT</pubDate>
            <description><![CDATA[<ul>
<li><p>목표</p>
<ol>
<li>정형 데이터를 쉽게 다룰 수 있는 Spark Dataframe, Dataset에 대해 이해한다</li>
<li>Spark DataFrame, DataSet 에 대해 SQL 연산을 수행해본다</li>
</ol>
</li>
<li><p>Spark SQL 특징</p>
<ol>
<li>Integrated<ul>
<li>spark와 sql 쿼리를 원활하게 결합</li>
<li>Spark SQL은 Spark 내에 RDD 형태로 저장돼있는 정형 데이터를 통합된 API로 Qeury할 수 있게 한다</li>
</ul>
</li>
<li>Unified Data Access<ul>
<li>다양한 소스로부터 데이터를 load, query할 수 있다</li>
</ul>
</li>
<li>Standard Connectivity</li>
</ol>
</li>
<li><p>DataFrame</p>
<ul>
<li>RDD+Schema</li>
<li>관계형 데이터베이스의 테이블</li>
<li>대량의 데이터를 처리하기 용이하게 디자인됨</li>
</ul>
</li>
<li><p>RDD vs DataFrame</p>
<ul>
<li>RDD:  데이터에 대한 설명이 안들어가 있음</li>
<li>DataFrame: 데이터에 대한 설명이 있음</li>
</ul>
</li>
<li><p>Programming Interface</p>
<ul>
<li>중간과정 Spark SQL에서 통합적으로 사용하는 DF API를 사용하고, 우리가 볼 수 있는 상태로 보여줌</li>
<li>Catalyst: 연산최적화 해줌(?)</li>
</ul>
</li>
<li><p>DataSet</p>
<ul>
<li>DataFrame과 거의 비슷한데, DF API가 DataSet API에 통합됐다. DataSet이 더 큰 개념</li>
<li>DF는 Row로 이루어진 DataSet임. DF = DataSet[Row]</li>
<li>DataSet은 Row 이외에도 다양한 형식을 가질 수 있음</li>
</ul>
</li>
<li><p>차이: 스키마의 추정이 언제 일어나는 가? 의 차이</p>
<ul>
<li>DF: 런타임에 Schema 추정(데이터를 받아온 시점)</li>
<li>DataSet: 컴파일 타임에 Schema를 정함. 에러를 쉽게 찾고, 최적화가 잘됨. 컴파일 기반의 언어에서만 사용가능(파이썬에서 no)</li>
</ul>
</li>
<li><p>RDD vs Spark SQL</p>
</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[[파이썬 머신러닝 완벽가이드] 8장: Text Analysis]]></title>
            <link>https://velog.io/@bona-park/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D-%EC%99%84%EB%B2%BD%EA%B0%80%EC%9D%B4%EB%93%9C-8%EC%9E%A5-Text-Analysis</link>
            <guid>https://velog.io/@bona-park/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D-%EC%99%84%EB%B2%BD%EA%B0%80%EC%9D%B4%EB%93%9C-8%EC%9E%A5-Text-Analysis</guid>
            <pubDate>Fri, 07 Oct 2022 13:55:48 GMT</pubDate>
            <description><![CDATA[<br>

<ul>
<li><p>NLP vs 텍스트 분석</p>
</li>
<li><p>텍스트 분석 주요 영역
  텍스트 분류(어떤 카테고리에 속하나)
  감성 분석(텍스트에서 나타나는 주관적인 기분 등의 요소를 분석)
  텍스트 요약
  텍스트 군집화와 유사도 측정</p>
</li>
<li><p>텍스트 문석 머신러닝 수행 프로세스
  데이터 사전가공-&gt; Feature Vectorization -&gt; ML 학습/예측/평가</p>
</li>
</ul>
<p><a href="https://www.researchgate.net/figure/Text-mining-process-Source-Chakraborty-Pagolu-and-Garla-2013_fig1_262413948"><img src="https://velog.velcdn.com/images/bona-park/post/9ffab14c-d08b-4859-85ac-0819dfb51034/image.png" alt=""></a></p>
<ul>
<li><p>파이썬 기반의 NLP, 텍스트 분석 패키지
  NLTK, Gensim(토픽모델링), SpaCy</p>
</li>
<li><p>텍스트 전처리: 텍스트 정규화
  클렌징: html, xml 태그나 특정 기호 제거
  토큰화: 문장/ 단어 토큰화
  필터링/ 스톱워드 제거/ 철자 수정: 관사 제거
  Stemming/ Lemmatization: 단어 원형 추출</p>
</li>
<li><p>N-Gram
  문장을 개별 단어로 토큰화 하면 문맥적인 의미가 무시됨
  -&gt; n개의 단어를 하나의 토큰화 단위로 분리하는 것
  n개 단어 크기의 윈도우를 만들어 토큰화 수행</p>
</li>
</ul>
<ul>
<li><p>텍스트의 피처 벡터화 유형
  BOW(Bag of Words)</p>
<pre><code>  Document Term Matrix
  단어들의 등장 횟수를 매트릭스로</code></pre><p>  Word Embedding</p>
<pre><code>  개별 단어를 문맥을 기준으로 N차원 공간에 벡터로 표현</code></pre></li>
<li><p>BOW 
  문맥이나 순서를 무시하고
  일괄적으로 단어에 대해 빈도 값을 부여해 피처 값을 추출하는 모델
  (문서 내 모든 단어를 bag아넹 넣고 흔들어서 섞는다는 의미)</p>
</li>
<li><p>BOW 구조
  column은 단어로, row는 문장을 기준으로 각 column의 단어들이 몇번 등장했는지름 적음</p>
<p>  장점: 쉽고 빠른 구축 </p>
<pre><code>      예상보다 문서의 특징을 잘 나타내서 전통적으로 여러분야에 활용도가 높음</code></pre><p>  단점: 문맥 의미 반영을 못함</p>
<pre><code>      희소 행렬 문제(값의 없는 null이 너무 많다)</code></pre></li>
<li><p>BOW 피처 벡터화</p>
<ol>
<li><p>단순 카운트 기반의 벡터화
 각 문서에서 해당 단어가 나타나는 횟수를 부여</p>
</li>
<li><p>TF-IDF 벡터화
 단어에 가중치를 주어서, 모든 문서에서 많이 나타나는 단어에는 패널티를 줌</p>
<p> 특정 문서에만 나타나는 단어를 해당 문서를 잘 특징짓는 중요 단어일 가능성이 높다고 여김.</p>
<p> TF(Term Frequency): 그 문서에서 몇번 나왔니
 DF(Document Frequency): 그 단어가 전체 몇개의 문서에서 나왔는지
 IDF: 전체문체수/DF</p>
</li>
</ol>
</li>
</ul>
<ul>
<li><p>CountVectorizer를 이용한 피처 벡터화
  사전데이터가공-&gt;토큰화-&gt;텍스트정규화-&gt;피처 벡터화</p>
</li>
<li><p>희소행렬의 저장 변환 방식
  COO형식: 0이 아닌 데이터만 별도의 배열에 저장
  CSR형식: COO형식이 위치 배열값을 중복적으로 가지는 문제를 해결한 방식</p>
</li>
<li><p>20 Newsgroup 분류하기 *
  18846개의 뉴스 문서를 20개의 카테고리로 분류하기</p>
<p>  텍스트정규화 -&gt; 피처벡터화 -&gt; 머신러닝 -&gt; pipline 적용 -&gt; GridSearchCV최적화</p>
</li>
</ul>
<ul>
<li><p>감성분석
  지도학습 기반의 분석</p>
<p>  감성 어휘 사전을 이용한 분석</p>
<pre><code>  SentiWordNet: Synset별로 3가지 감성지수(긍정감성지수, 부정감성지수, 객관성지수)
  CADER: 소셜미디어의 텍스트에 대한 감성분석
  Pattern</code></pre><ul>
<li>IMDB의 영화 review에 대한 긍부정 예측</li>
</ul>
</li>
<li><p>SentiWordNet의 감성지수<br>  가로: 긍정부정, 세로: 객관성 정도</p>
<p>  문서를 문장단위로 분해
  -&gt; 단어를 토큰화, 품사 태깅
  -&gt; synset객체, senti_synset객체 생성
  -&gt; senti_synset에서 긍정 부정 감성지수 구하고 역치값 기준으로 판별</p>
</li>
<li><p>VADER
  SentiIntensityAnalyzer 클래스 사용</p>
</li>
</ul>
<ul>
<li><p>토픽 모델링
  문서들에 잠재돼 있는 공통된 토픽들을 추출해 내는 기법</p>
<ol>
<li><p>행렬 분해 기반 토픽 모델링(LSA. NMF)</p>
</li>
<li><p>확률 기반의 토픽 모델링</p>
</li>
</ol>
</li>
<li><p>LDA(Latent Dirichelt Allocation)
  문서내의 단어들을 이용해 베이즈 추론을 통해
  잠재된 문서내 토픽분포와 토픽별 단어분포를 추론하는 방식</p>
</li>
<li><p>베이즈 추론 켤레 사전 분포
  이항 분포 -&gt; 베타 분포
  다항 분포 -&gt; 디리클레 분포</p>
</li>
<li><p>LDA 구성요소</p>
</li>
<li><p>LDA 수행 프로세스 
  count 기반 행렬
  토픽의 개수 설정
  임의 주제를 최초할당 후, 문서별 토픽분포, 토픽별 단어분포가 결정됨
  특정 단어를 추출.제외 하고 두 분포를 재계산
  모든 단어들의 토픽 할당분포를 재계산</p>
</li>
</ul>
<ul>
<li>문섭 군집화</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[[GDSC-ML] Apply PyTorch template to  Mnist classification]]></title>
            <link>https://velog.io/@bona-park/GDSC-ML-Apply-PyTorch-template-to-Mnist-classification</link>
            <guid>https://velog.io/@bona-park/GDSC-ML-Apply-PyTorch-template-to-Mnist-classification</guid>
            <pubDate>Thu, 06 Oct 2022 05:31:01 GMT</pubDate>
            <description><![CDATA[<p><img src="https://velog.velcdn.com/images/bona-park/post/4f375675-188d-435b-adbb-a6ca8cae84a8/image.png" alt=""></p>
<p>The second GDSC-ML session was to convert Jupyter Notebook of MNIST CNN model into Python scripts.</p>
<p>Like most people, I was used to do ML projects through Jupyter notebook. It had a big advangtage that I can validate and check the code easily by just typing (Shift + Enter).</p>
<p>But there are some fallbacks of Jupyter Notbooks in data science projects</p>
<ul>
<li>Unorganized<ul>
<li>hard to keep track of what I write</li>
</ul>
</li>
<li>Not ideal for reproducibility<ul>
<li>if there&#39;s a slight data change, hard to identify a source error</li>
</ul>
</li>
<li>Not ideal for production<ul>
<li>hard to run Jupyter Notebook while using other tools</li>
</ul>
</li>
</ul>
<p>This time I used<a href="https://github.com/victoresque/pytorch-template"> @victoresque &#39;s <em>Pytorch-Template</em>.</a>
It provides a clear folder structure suitable for many Deep Learning Projects.</p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/f2ca8a6b-d1a1-4ca6-b926-d7e5a2d3e5b3/image.png" alt=""></p>
<h3 id="previous-mnist_examleipynb-outline">previous <em>mnist_examle.ipynb</em> outline</h3>
<ul>
<li>set device</li>
<li>hyperparmeter setting</li>
<li>load dataset</li>
<li>see dataset(we don&#39;t need it)</li>
<li>use torch dataloader to divide dataset into mini-batch<ul>
<li>define 2 Dataloaders: <code>train_loader</code> <code>test_loader</code></li>
</ul>
</li>
<li>define Basic CNN class</li>
<li>create model instance with preconifigured class</li>
<li>define optimizer -&gt; <em>mutate in &#39;config.json&#39;</em></li>
<li>choose <strong>Loss function</strong></li>
<li><strong>train</strong> the model </li>
<li>update gradient in each training steps</li>
<li><strong>evaluate</strong> the model</li>
</ul>
<br>

<p>Because both projects are dealing with MNIST, there weren&#39;t that many things to change from the template.</p>
<p>We only need to change some parameters in <em>config.json</em> file and change the model structure in <em>model.py</em></p>
<h3 id="new-python-scripts-using-a-template">New Python Scripts using a template</h3>
<blockquote>
<h4 id="configjson">config.json</h4>
</blockquote>
<pre><code class="language-json">{
  &quot;name&quot;: &quot;Mnist_LeNet&quot;,
  &quot;n_gpu&quot;: 1,

  &quot;arch&quot;: {
    &quot;type&quot;: &quot;MnistModel&quot;,
    &quot;args&quot;: {}
  },
  &quot;data_loader&quot;: {
    &quot;type&quot;: &quot;MnistDataLoader&quot;,
    &quot;args&quot;: {
      &quot;data_dir&quot;: &quot;data/&quot;,
      &quot;batch_size&quot;: 50,
      &quot;shuffle&quot;: true,
      &quot;validation_split&quot;: 0.1,
      &quot;num_workers&quot;: 2
    }
  },
  &quot;optimizer&quot;: {
    &quot;type&quot;: &quot;Adam&quot;,
    &quot;args&quot;: {
      &quot;lr&quot;: 0.0001,
      &quot;weight_decay&quot;: 0,
      &quot;amsgrad&quot;: true
    }
  },
  &quot;loss&quot;: &quot;nll_loss&quot;,
  &quot;metrics&quot;: [&quot;accuracy&quot;, &quot;top_k_acc&quot;],
  &quot;lr_scheduler&quot;: {
    &quot;type&quot;: &quot;StepLR&quot;,
    &quot;args&quot;: {
      &quot;step_size&quot;: 50,
      &quot;gamma&quot;: 0.1
    }
  },
  &quot;trainer&quot;: {
    &quot;epochs&quot;: 100,

    &quot;save_dir&quot;: &quot;saved/&quot;,
    &quot;save_period&quot;: 1,
    &quot;verbosity&quot;: 2,

    &quot;monitor&quot;: &quot;min val_loss&quot;,
    &quot;early_stop&quot;: 10,

    &quot;tensorboard&quot;: true
  }
}
</code></pre>
<br>


<blockquote>
<h4 id="modelpy">model.py</h4>
</blockquote>
<pre><code class="language-python">class MnistModel(BaseModel):
        def __init__(self): ..
        def forward(self, x): ..</code></pre>
<blockquote>
<h4 id="basemodelpy">BaseModel.py</h4>
</blockquote>
<pre><code class="language-python">class BaseModel(nn.Module):
    &quot;&quot;&quot;
    Base class for all models
    &quot;&quot;&quot;
    @abstractmethod
    def forward(self, *inputs):
        &quot;&quot;&quot;
        Forward pass logic
        :return: Model output
        &quot;&quot;&quot;
        raise NotImplementedError</code></pre>
<br>

<blockquote>
<h4 id="trainpy">train.py</h4>
</blockquote>
<pre><code class="language-python"># setup data_loader instances with following conditions in config.json
data_loader = config.init_obj(&quot;data_loader&quot;, module_data)
valid_data_loader = data_loader.split_validation()

# build model architecture, then print to console
model = config.init_obj(&quot;arch&quot;, module_arch)
logger.info(model)

# prepare for (multi-device) GPU training
device, device_ids = prepare_device(config[&quot;n_gpu&quot;])
model = model.to(device)
if len(device_ids) &gt; 1:
model = torch.nn.DataParallel(model, device_ids=device_ids)

# get function handles of loss and metrics
criterion = getattr(module_loss, config[&quot;loss&quot;])
metrics = [getattr(module_metric, met) for met in config[&quot;metrics&quot;]]

# build optimizer, learning rate scheduler. delete every lines containing lr_scheduler for disabling scheduler
trainable_params = filter(lambda p: p.requires_grad, model.parameters())
optimizer = config.init_obj(&quot;optimizer&quot;, torch.optim, trainable_params)
lr_scheduler = config.init_obj(&quot;lr_scheduler&quot;, torch.optim.lr_scheduler, optimizer) 

trainer = Trainer(
        model,
        criterion,
        metrics,
        optimizer,
        config=config,
        device=device,
        data_loader=data_loader,
        valid_data_loader=valid_data_loader,
        lr_scheduler=lr_scheduler,
    )
trainer.train()</code></pre>
<br>

<blockquote>
<blockquote>
<h4 id="load_state_dictstate_dict-stricttrue">load_state_dict(state_dict, strict=True)</h4>
<p>Copies parameters and buffers from state_dict into this module and its descendants. If strict is True, then the keys of state_dict must exactly match the keys returned by this module’s state_dict() function.
<a href="https://pytorch.org/tutorials/beginner/saving_loading_models.html">more: saving_loading_models</a></p>
</blockquote>
</blockquote>
<p><img src="https://velog.velcdn.com/images/bona-park/post/53d57b0f-0539-4476-a08b-7089ac42fd47/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/d5d3d7a3-e756-46d9-9506-f81f5affc9c5/image.png" alt=""></p>
<p>&ensp;&ensp;&ensp;&ensp;&ensp;&ensp; <em>path: ./saved/models/Mnist_LeNet/1006_133305/model_best.pth</em></p>
<br>

<blockquote>
<h4 id="testpy">test.py</h4>
</blockquote>
<pre><code class="language-python">    data_loader = getattr(module_data, config[&quot;data_loader&quot;][&quot;type&quot;])(
        config[&quot;data_loader&quot;][&quot;args&quot;][&quot;data_dir&quot;],
        batch_size=50,  #
        shuffle=True,  #
        validation_split=0.0,
        training=False,
        num_workers=2,
    )

    # build model architecture
    model = config.init_obj(&quot;arch&quot;, module_arch)
    logger.info(model)

    # get function handles of loss and metrics
    loss_fn = getattr(module_loss, config[&quot;loss&quot;])
    metric_fns = [getattr(module_metric, met) for met in config[&quot;metrics&quot;]]

    logger.info(&quot;Loading checkpoint: {} ...&quot;.format(config.resume))
    checkpoint = torch.load(config.resume)
    state_dict = checkpoint[&quot;state_dict&quot;]
    if config[&quot;n_gpu&quot;] &gt; 1:
        model = torch.nn.DataParallel(model)
    model.load_state_dict(state_dict)

    # prepare model for testing
    device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)
    model = model.to(device)
    model.eval()

    total_loss = 0.0
    total_metrics = torch.zeros(len(metric_fns))

    with torch.no_grad():
        for i, (data, target) in enumerate(tqdm(data_loader)):
            data, target = data.to(device), target.to(device)
            output = model(data)

            #
            # save sample images, or do something with output here
            #

            # computing loss, metrics on test set
            loss = loss_fn(output, target)
            batch_size = data.shape[0]
            total_loss += loss.item() * batch_size
            for i, metric in enumerate(metric_fns):
                total_metrics[i] += metric(output, target) * batch_size

    n_samples = len(data_loader.sampler)
    log = {&quot;loss&quot;: total_loss / n_samples}
    log.update(
        {met.__name__: total_metrics[i].item() / n_samples for i, met in enumerate(metric_fns)}
    )
    logger.info(log)</code></pre>
<p>Running Command: <code>python test.py --resume ./saved/models/Mnist_LeNet/1006_133305/model_best.pth</code></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/1b7c76da-0997-49db-9cf1-059fda6d68fd/image.png" alt=""></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Processing] how to enable auto-complete in Processing]]></title>
            <link>https://velog.io/@bona-park/Processing-auto-complete</link>
            <guid>https://velog.io/@bona-park/Processing-auto-complete</guid>
            <pubDate>Sat, 01 Oct 2022 14:47:58 GMT</pubDate>
            <description><![CDATA[<h4 id="❔-how-to-enable-auto-complete-in-processing">❔ how to enable auto-complete in Processing?</h4>
<p><img src="https://velog.velcdn.com/images/bona-park/post/35f364b0-9f71-4f20-b39a-6fcb46243dd6/image.png" alt=""></p>
<h4 id="✅solution">✅solution</h4>
<ol>
<li><p>check <em>code completion with CTRL+space</em>
<img src="https://velog.velcdn.com/images/bona-park/post/4d5853a2-6452-419f-819d-a0ced8f32298/image.png" alt=""></p>
</li>
<li><p>find &quot;preferences.txt&quot; and change <code>pdex.completion.trigger=true</code></p>
</li>
</ol>
<p><img src="https://velog.velcdn.com/images/bona-park/post/f24ee7ea-ef4a-4870-b18f-656793bdf276/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/bona-park/post/7cd6b8f5-ad8e-4041-a556-fa604b35a58a/image.png" alt=""></p>
<ol start="3">
<li>Autocomplete works</li>
</ol>
<p><img src="https://velog.velcdn.com/images/bona-park/post/d2f884da-7513-4968-87b1-01b95349b0df/image.png" alt=""></p>
<p>▶Processing version: processing-4.0.1</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Spark RDD]]></title>
            <link>https://velog.io/@bona-park/Spark-RDD</link>
            <guid>https://velog.io/@bona-park/Spark-RDD</guid>
            <pubDate>Sat, 01 Oct 2022 05:20:47 GMT</pubDate>
            <description><![CDATA[<ul>
<li><p>RDD: resilient distributed data</p>
<ul>
<li>스파크에서 in-memory 기반으로 분산환경에서 대용량 데이터를 처리하기 위해 만든 일종의 자료구조</li>
<li>목적: 뷴산 컬랙션의 성질과 장애 내성을 추상화 -&gt; 직관적이고 효율적인 대규모 데이터 셋 처리</li>
</ul>
</li>
<li><p>RDD 연산 : Lazy execution</p>
<ul>
<li>연산을 즉시 처리하지 않고, 계산의 결과값이 필요할때까지 계산을 늦추는 기법</li>
</ul>
</li>
<li><p>Spark는 연산들을 바로하지 않고, 계산과정을 Lineage에 저장한 뒤, 마지막에 결과를 보여주거나 반환할 때 계산을 실행한다. </p>
<ol>
<li><p>변환 연산자들의 연산과정을 RDD lineage에 <strong>저장</strong></p>
<ol start="2">
<li>행동 연산자가 호출되면 lineage를 토대로 최적화된 실행과정을 만듦</li>
<li>이를 토대로 최적화된 연산 실행</li>
</ol>
<ul>
<li><p><strong>행동 연산자</strong>: count, collect와 같이 결과를 반환하는 연산</p>
<ul>
<li>최종 결과 값을 반환하거나 외부 저장소에 값을 기록하는 연산</li>
<li>호출 시 최적화된 경로로 계산을 진행한 뒤, 최종 결과를 return =&gt; &quot; RDD in, Other out &quot; </li>
</ul>
</li>
<li><p><strong>변환 연산자</strong>: map, filter와 같이 결과를 바로 안 보여줘도 되는 연산</p>
<ul>
<li>불변성을 가지는 RDD의 형태를 변형하는 연산</li>
<li>기존의 RDD를 입력받아서, 새로운 RDD를 return =&gt; &quot; RDD in, RDD out &quot; </li>
<li>Action연산이 호출될 때까지는 실제로 수행되지 않음(Lazy execution)</li>
</ul>
</li>
</ul>
</li>
</ol>
</li>
<li><p>RDD 연산</p>
<ol>
<li>Map <pre><code>rdd.map(lambda x : x + 1)
# (1, 2, 3, 3) 을 가지고 있는 Rdd에 대해 연산 시 return: (2, 3, 4, 4)</code></pre></li>
</ol>
</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Hadoop & Spark] Hadoop의 map/reduce와 spark의 RDD연산의 차이]]></title>
            <link>https://velog.io/@bona-park/Hadoop%EC%9D%98-mapreduce%EC%99%80-spark%EC%9D%98-RDD%EC%97%B0%EC%82%B0%EC%9D%80-%EC%96%B4%EB%96%A4-%EC%A0%90%EC%97%90%EC%84%9C-%EB%8B%A4%EB%A5%B8%EC%A7%80</link>
            <guid>https://velog.io/@bona-park/Hadoop%EC%9D%98-mapreduce%EC%99%80-spark%EC%9D%98-RDD%EC%97%B0%EC%82%B0%EC%9D%80-%EC%96%B4%EB%96%A4-%EC%A0%90%EC%97%90%EC%84%9C-%EB%8B%A4%EB%A5%B8%EC%A7%80</guid>
            <pubDate>Fri, 30 Sep 2022 15:25:51 GMT</pubDate>
            <description><![CDATA[<p> ❔ Hadoop의 map/reduce와 spark의 RDD연산의 차이는 무엇일까?</p>
<p><img src = "https://velog.velcdn.com/images/bona-park/post/47c99e84-8aba-4396-be9b-04c34694e87c/image.png
" width = "50%" height = "50%">  </p>
<ul>
<li><p>Hadoop은 mapreduce 방식으로 데이터를 분산 처리한다. 여러 곳에 분산 저장된 데이터를 처리 하기 위해 mapreduce 방식으로 데이터를 처리한다.</p>
</li>
<li><p>spark 역시 mapreduce 방식의 데이터처리 구조를 지원한다. spark도 여러 곳에 저장된 데이터를 처리 하기 위해 mapreduce 방식으로 데이터를 처리 할 수 있다.</p>
<ul>
<li>하지만 둘의 차이는, 데이터를 메모리에 놓고 하느냐, 디스크에 놓고 하느냐.</li>
</ul>
</li>
<li><p><strong>Hadoop은 기본적으로 디스크로부터</strong> map/reduce할 데이터를 불러오고, 처리 결과를 디스크로 쓴다. 따라서, 데이터의 읽기/쓰기 속도는 느린 반면, 디스크 용량 만큼의 데이터를 한번에 처리 할 수 있다.</p>
</li>
<li><p>반면, <strong>spark는 메모리로부터</strong> map/reduce할 데이터를 불러오고, 처리 결과를 메모리로 쓴다. 따라서, 데이터의 읽기/쓰기 속도는 빠른 반면, 메모리 용량만큼의 데이터만 한번에 처리 할 수 있다.
결론은, spark나 hadoop이나 모두 mapreduce 방식을 지원하지만, hadoop은 디스크 기반의 mapreduce 인것이고, spark는 메모리 기반의 mapreduce 인것이다.</p>
</li>
<li><p>Map Reduce를 사용하면 좋을 때
1) 거대한 데이터 세트의 선형처리: Hadoop Mapreduce를 사용하면 방대한 양의 데이터를 병렬로 처리 가능. 결과 데이터 세트가 사용 가능한 RAM보다 큰 경우 Hadoop MapReduce가 Spark를 능가할 수 있음.<br>
2)    즉각적으로 결과가 필요하지 않는 경우 경제적인 솔루션이다. </p>
</li>
<li><p>Spark를 사용하면 좋을 때: 
1)    빠른 데이터 처리<br>
2)    반복 처리 <br>
3)    Spark의 RDD(Resilient Distributed Datasets)는 메모리에서 여러 맵 작업을 가능하게 하는 반면 Hadoop MapReduce는 중간 결과를 디스크에 기록해야 함.<br>
4)    기계 학습.  Spark에는 내장된 기계 학습 라이브러리인 MLlib가 있으며, MLlib에는 메모리에서도 실행되는 즉시 사용 가능한 알고리즘이 있음.</p>
</li>
</ul>
<p>_ref) _</p>
<p><a href="https://wooono.tistory.com/50">https://wooono.tistory.com/50</a>
        <a href="https://sunrise-min.tistory.com/entry/MapReduce-vs-Spark-%EB%A7%B5%EB%A6%AC%EB%93%80%EC%8A%A4%EC%99%80-%EC%8A%A4%ED%8C%8C%ED%81%AC%EC%9D%98-%EC%B0%A8%EC%9D%B4%EC%A0%90">https://sunrise-min.tistory.com/entry/MapReduce-vs-Spark-%EB%A7%B5%EB%A6%AC%EB%93%80%EC%8A%A4%EC%99%80-%EC%8A%A4%ED%8C%8C%ED%81%AC%EC%9D%98-%EC%B0%A8%EC%9D%B4%EC%A0%90</a>
        <a href="https://3months.tistory.com/5__11">https://3months.tistory.com/5__11</a></p>
]]></description>
        </item>
    </channel>
</rss>