<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.0">Jekyll</generator><link href="https://nt-thuhang.github.io/ntth/feed.xml" rel="self" type="application/atom+xml" /><link href="https://nt-thuhang.github.io/ntth/" rel="alternate" type="text/html" /><updated>2022-04-08T06:27:41+00:00</updated><id>https://nt-thuhang.github.io/ntth/feed.xml</id><title type="html">NTTH</title><subtitle>Trên đây là blog cá nhân của mình, mình dùng nó để chia sẻ nhiều thứ về cuộc sống cũng như học thuật của mình. Mục đích chính của blog này mình sẽ chia sẻ những gì mình học, những gì mình biết được.
</subtitle><author><name>NT-ThuHang</name><email>thuhang.fit.hcmus@gmail.com</email></author><entry><title type="html">Array Manipulation</title><link href="https://nt-thuhang.github.io/ntth/Hackerrank_Array-Manipulation" rel="alternate" type="text/html" title="Array Manipulation" /><published>2022-04-08T00:00:00+00:00</published><updated>2022-04-08T00:00:00+00:00</updated><id>https://nt-thuhang.github.io/ntth/Hackerrank_Array-Manipulation</id><content type="html" xml:base="https://nt-thuhang.github.io/ntth/Hackerrank_Array-Manipulation">&lt;h2 id=&quot;problem&quot;&gt;&lt;a href=&quot;https://www.hackerrank.com/challenges/crush/problem?isFullScreen=true&amp;amp;h_l=interview&amp;amp;playlist_slugs%5B%5D=interview-preparation-kit&amp;amp;playlist_slugs%5B%5D=arrays&quot;&gt;Problem&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array.&lt;/p&gt;

&lt;h4 id=&quot;example&quot;&gt;Example&lt;/h4&gt;

&lt;p&gt;Queries are interpreted as follows:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;a b k
1 5 3
4 8 7
6 9 1 Add the values of  between the indices  and  inclusive: ``` index-&amp;gt;	 1 2 3  4  5 6 7 8 9 10
[0,0,0, 0, 0,0,0,0,0, 0]
[3,3,3, 3, 3,0,0,0,0, 0]
[3,3,3,10,10,7,7,7,0, 0]
[3,3,3,10,10,8,8,8,1, 0] ```
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The largest value is  after all operations are performed.&lt;/p&gt;

&lt;h4 id=&quot;function-description&quot;&gt;Function Description&lt;/h4&gt;

&lt;p&gt;Complete the function arrayManipulation in the editor below.&lt;/p&gt;

&lt;p&gt;arrayManipulation has the following parameters:&lt;/p&gt;

&lt;p&gt;int n - the number of elements in the array
int queries[q][3] - a two dimensional array of queries where each queries[i] contains three integers, a, b, and k.&lt;/p&gt;
&lt;h4 id=&quot;returns&quot;&gt;Returns&lt;/h4&gt;

&lt;p&gt;int - the maximum value in the resultant array&lt;/p&gt;
&lt;h4 id=&quot;input-format&quot;&gt;Input Format&lt;/h4&gt;

&lt;p&gt;The first line contains two space-separated integers  and , the size of the array and the number of operations.
Each of the next  lines contains three space-separated integers ,  and , the left index, right index and summand.&lt;/p&gt;

&lt;h4 id=&quot;constraints&quot;&gt;Constraints&lt;/h4&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;!-- $3 \leq n \leq 10^7$ --&gt;
    &lt;p&gt;&lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=3%20%5Cleq%20n%20%5Cleq%2010%5E7&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;!-- $1 \leq m \leq 2*10^5$ --&gt;
    &lt;p&gt;&lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=1%20%5Cleq%20m%20%5Cleq%202*10%5E5&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;!-- $1 \leq a \leq b \leq n$ --&gt;
    &lt;p&gt;&lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=1%20%5Cleq%20a%20%5Cleq%20b%20%5Cleq%20n&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;!-- $0 \leq k \leq 10^9$ --&gt;
    &lt;p&gt;&lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=0%20%5Cleq%20k%20%5Cleq%2010%5E9&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;sample-input&quot;&gt;Sample Input&lt;/h4&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;5 3
1 2 100
2 5 100
3 4 100
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h4 id=&quot;sample-output&quot;&gt;Sample Output&lt;/h4&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;200
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h4 id=&quot;explanation&quot;&gt;Explanation&lt;/h4&gt;

&lt;p&gt;After the first update the list is 100 100 0 0 0.&lt;/p&gt;

&lt;p&gt;After the second update list is 100 200 100 100 100.&lt;/p&gt;

&lt;p&gt;After the third update list is 100 200 200 200 100.&lt;/p&gt;

&lt;p&gt;The maximum value is &lt;strong&gt;200&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;solution&quot;&gt;Solution&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Assign the array value at position a is k and position b+1 is -k, this we can simply understand that when we go on the segment [a,b] the value will be k and if we get out of it will subtract k.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;After that, we only need to find the segment with the largest sum in the sequence with n elements.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;example-1&quot;&gt;Example:&lt;/h4&gt;
&lt;h5 id=&quot;input&quot;&gt;Input:&lt;/h5&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;10 3
1 5 3
4 8 7
6 9 1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h5 id=&quot;output&quot;&gt;Output:&lt;/h5&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;10
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h5 id=&quot;solve&quot;&gt;Solve:&lt;/h5&gt;
&lt;ul&gt;
  &lt;li&gt;Begin:
    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;arr[10] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;With query 0: the segment [a,b] is [1,5] and k is 3
    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;arr[10] = [3, 0, 0, 0, 0, -3, 0, 0, 0, 0]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;With query 0: the segment [a,b] is [4,8] and k is 7
    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;arr[10] = [3, 0, 0, 7, 0, -3, 0, 0, -7, 0]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;With query 0: the segment [a,b] is [6,9] and k is 1
    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;arr[10] = [3, 0, 0, 7, 0, -2, 0, 0, 0, -1]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;End: the result is the largest sum of array.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;code&quot;&gt;&lt;a href=&quot;https://github.com/NT-ThuHang/Practice-Coding-Skill/blob/main/HackerRank/Array%20Manipulation/Array_Manipulation.cpp&quot;&gt;Code&lt;/a&gt;&lt;/h2&gt;

&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;long&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cin&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;long&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;queries&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;long&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;long&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;res&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;long&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cin&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;long&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tmp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;//cout &amp;lt;&amp;lt; arr[i] &amp;lt;&amp;lt; &quot; &quot;;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;tmp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;res&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tmp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;</content><author><name>[&quot;Nguyễn Thị Thu Hằng&quot;]</name></author><category term="programming" /><summary type="html">Problem Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array.</summary></entry><entry><title type="html">Minimum Swaps 2</title><link href="https://nt-thuhang.github.io/ntth/Hackerrank_Minimum-Swaps-2" rel="alternate" type="text/html" title="Minimum Swaps 2" /><published>2022-04-08T00:00:00+00:00</published><updated>2022-04-08T00:00:00+00:00</updated><id>https://nt-thuhang.github.io/ntth/Hackerrank_Minimum-Swaps-2</id><content type="html" xml:base="https://nt-thuhang.github.io/ntth/Hackerrank_Minimum-Swaps-2">&lt;h2 id=&quot;problem&quot;&gt;&lt;a href=&quot;https://www.hackerrank.com/challenges/minimum-swaps-2/problem?isFullScreen=true&amp;amp;h_l=interview&amp;amp;playlist_slugs%5B%5D=interview-preparation-kit&amp;amp;playlist_slugs%5B%5D=arrays&quot;&gt;Problem&lt;/a&gt;&lt;/h2&gt;

&lt;p&gt;You are given an unordered array consisting of consecutive integers  [1, 2, 3, …, n] without any duplicates. You are allowed to swap any two elements. Find the minimum number of swaps required to sort the array in ascending order.&lt;/p&gt;

&lt;h4 id=&quot;example&quot;&gt;Example&lt;/h4&gt;
&lt;!-- $arr = [7, 1, 3, 2, 4, 5, 6]$ --&gt;
&lt;p&gt;&lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=arr%20%3D%20%5B7%2C%201%2C%203%2C%202%2C%204%2C%205%2C%206%5D&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Perform the following steps:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;i   arr                         swap (indices)
0   [7, 1, 3, 2, 4, 5, 6]   swap (0,3)
1   [2, 1, 3, 7, 4, 5, 6]   swap (0,1)
2   [1, 2, 3, 7, 4, 5, 6]   swap (3,4)
3   [1, 2, 3, 4, 7, 5, 6]   swap (4,5)
4   [1, 2, 3, 4, 5, 7, 6]   swap (5,6)
5   [1, 2, 3, 4, 5, 6, 7]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;It took 5 swaps to sort the array.&lt;/p&gt;

&lt;h4 id=&quot;function-description&quot;&gt;Function Description&lt;/h4&gt;

&lt;p&gt;Complete the function minimumSwaps in the editor below.&lt;/p&gt;

&lt;p&gt;minimumSwaps has the following parameter(s):&lt;/p&gt;

&lt;p&gt;int arr[n]: an unordered array of integers&lt;/p&gt;
&lt;h4 id=&quot;returns&quot;&gt;Returns&lt;/h4&gt;

&lt;p&gt;int: the minimum number of swaps to sort the array
Input Format&lt;/p&gt;

&lt;p&gt;The first line contains an integer n, the size of arr.
The second line contains n space-separated integers arr[i].&lt;/p&gt;

&lt;h4 id=&quot;constraints&quot;&gt;Constraints&lt;/h4&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;!-- $1 \leq n \leq 10^5$ --&gt;
    &lt;p&gt;&lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=1%20%5Cleq%20n%20%5Cleq%2010%5E5&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;!-- $1 \leq arr[i] \leq n$ --&gt;
    &lt;p&gt;&lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=1%20%5Cleq%20arr%5Bi%5D%20%5Cleq%20n&quot; /&gt;&lt;/p&gt;
    &lt;h4 id=&quot;sample-input-0&quot;&gt;Sample Input 0&lt;/h4&gt;
    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;4
4 3 1 2
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
    &lt;h4 id=&quot;sample-output-0&quot;&gt;Sample Output 0&lt;/h4&gt;
    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
    &lt;h4 id=&quot;explanation-0&quot;&gt;Explanation 0&lt;/h4&gt;
    &lt;p&gt;Given array &lt;!-- $arr = [4,3,1,2]$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=arr%20%3D%20%5B4%2C3%2C1%2C2%5D&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After swapping (0,2) we get &lt;!-- $arr = [1,3,4,2]$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=arr%20%3D%20%5B1%2C3%2C4%2C2%5D&quot; /&gt;&lt;/p&gt;

&lt;p&gt;After swapping (1,2) we get &lt;!-- $arr = [1,4,3,2]$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=arr%20%3D%20%5B1%2C4%2C3%2C2%5D&quot; /&gt;&lt;/p&gt;

&lt;p&gt;After swapping (1,3) we get &lt;!-- $arr = [1,2,3,4]$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=arr%20%3D%20%5B1%2C2%2C3%2C4%5D&quot; /&gt;&lt;/p&gt;

&lt;p&gt;So, we need a minimum of 3 swaps to sort the array in ascending order.&lt;/p&gt;

&lt;h4 id=&quot;sample-input-1&quot;&gt;Sample Input 1&lt;/h4&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;5
2 3 4 1 5
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h4 id=&quot;sample-output-1&quot;&gt;Sample Output 1&lt;/h4&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;sample-input-2&quot;&gt;Sample Input 2&lt;/h4&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;7
1 3 5 2 4 6 7
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h4 id=&quot;sample-output-2&quot;&gt;Sample Output 2&lt;/h4&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;solution&quot;&gt;Solution&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;If the position of a[i] already coincides with i+1, then ignore&lt;/li&gt;
  &lt;li&gt;Otherwise change a[i] to the a[i]-1th position and stay in place until at position i-1 is a[i]&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;code&quot;&gt;Code&lt;/h2&gt;

&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;swap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;temp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;temp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// Complete the minimumSwaps function below.&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;minimumSwaps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;res&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;continue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;swap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]);&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;</content><author><name>[&quot;Nguyễn Thị Thu Hằng&quot;]</name></author><category term="programming" /><summary type="html">Problem</summary></entry><entry><title type="html">New Year Chaos</title><link href="https://nt-thuhang.github.io/ntth/Hackerrank_New-Year-Chaos" rel="alternate" type="text/html" title="New Year Chaos" /><published>2022-04-08T00:00:00+00:00</published><updated>2022-04-08T00:00:00+00:00</updated><id>https://nt-thuhang.github.io/ntth/Hackerrank_New-Year-Chaos</id><content type="html" xml:base="https://nt-thuhang.github.io/ntth/Hackerrank_New-Year-Chaos">&lt;h2 id=&quot;problem&quot;&gt;&lt;a href=&quot;https://www.hackerrank.com/challenges/new-year-chaos/problem?isFullScreen=true&amp;amp;h_l=interview&amp;amp;playlist_slugs%5B%5D=interview-preparation-kit&amp;amp;playlist_slugs%5B%5D=arrays&quot;&gt;Problem&lt;/a&gt;&lt;/h2&gt;

&lt;p&gt;It is New Year’s Day and people are in line for the Wonderland rollercoaster ride. Each person wears a sticker indicating their initial position in the queue from 1 to n . Any person can bribe the person directly in front of them to swap positions, but they still wear their original sticker. One person can bribe at most two others.&lt;/p&gt;

&lt;p&gt;Determine the minimum number of bribes that took place to get to a given queue order. Print the number of bribes, or, if anyone has bribed more than two people, print Too chaotic.&lt;/p&gt;

&lt;h4 id=&quot;example&quot;&gt;Example&lt;/h4&gt;
&lt;!-- $q = [1,2,3,5,4,6,7,8]$ --&gt;
&lt;p&gt;&lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=q%20%3D%20%5B1%2C2%2C3%2C5%2C4%2C6%2C7%2C8%5D&quot; /&gt;&lt;/p&gt;

&lt;p&gt;If person 5 bribes person 4, the queue will look like this: 1,,2,3,5,4,6,7,8 . Only 1 bribe is required. Print 1.&lt;/p&gt;

&lt;!-- $q = [4,1,2,3]$ --&gt;
&lt;p&gt;&lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=q%20%3D%20%5B4%2C1%2C2%2C3%5D&quot; /&gt;
Person 4 had to bribe 3 people to get to the current position. Print Too chaotic.&lt;/p&gt;

&lt;h4 id=&quot;function-description&quot;&gt;Function Description&lt;/h4&gt;

&lt;p&gt;Complete the function minimumBribes in the editor below.&lt;/p&gt;

&lt;p&gt;minimumBribes has the following parameter(s):&lt;/p&gt;

&lt;p&gt;int q[n]: the positions of the people after all bribes&lt;/p&gt;
&lt;h4 id=&quot;returns&quot;&gt;Returns&lt;/h4&gt;

&lt;p&gt;No value is returned. Print the minimum number of bribes necessary or Too chaotic if someone has bribed more than 2 people.&lt;/p&gt;
&lt;h4 id=&quot;input-format&quot;&gt;Input Format&lt;/h4&gt;

&lt;p&gt;The first line contains an integer t, the number of test cases.&lt;/p&gt;

&lt;p&gt;Each of the next t pairs of lines are as follows:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;The first line contains an integer t, the number of people in the queue&lt;/li&gt;
  &lt;li&gt;The second line has n space-separated integers describing the final state of the queue.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;constraints&quot;&gt;Constraints&lt;/h4&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;!-- $1 \leq t \leq 10$ --&gt;
    &lt;p&gt;&lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=1%20%5Cleq%20t%20%5Cleq%2010&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;!-- $1 \leq n \leq 10^5$ --&gt;
    &lt;p&gt;&lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=1%20%5Cleq%20n%20%5Cleq%2010%5E5&quot; /&gt;&lt;/p&gt;
    &lt;h4 id=&quot;subtasks&quot;&gt;Subtasks&lt;/h4&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For &lt;!-- $60\%$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=60%5C%25&quot; /&gt; score &lt;!-- $1 \leq n \leq 10^3$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=1%20%5Cleq%20n%20%5Cleq%2010%5E3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;For &lt;!-- $100\%$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=100%5C%25&quot; /&gt; score &amp;lt;!– s&lt;/p&gt;

&lt;p&gt;Sample Input&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;STDIN       Function
-----       --------
2           t = 2
5           n = 5
2 1 5 3 4   q = [2, 1, 5, 3, 4]
5           n = 5
2 5 1 3 4   q = [2, 5, 1, 3, 4]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;Sample Output&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;3
Too chaotic
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;solution&quot;&gt;Solution&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;For each element to the number of elements greater than it is in front of it, this is simply understood that the person in the back wants to move forward.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;If the position after shifting forward 3 units, the printout is too chaotic.&lt;/p&gt;
    &lt;h2 id=&quot;code&quot;&gt;&lt;a href=&quot;https://github.com/NT-ThuHang/Practice-Coding-Skill/blob/main/HackerRank/New%20Year%20Chaos/New_Year_Chaos.cpp&quot;&gt;Code&lt;/a&gt;&lt;/h2&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;minimumBribes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; 
&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;cout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Too chaotic &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;</content><author><name>[&quot;Nguyễn Thị Thu Hằng&quot;]</name></author><category term="programming" /><summary type="html">Problem</summary></entry><entry><title type="html">MAKETREE - Hierarchy</title><link href="https://nt-thuhang.github.io/ntth/MAKETREE-Hierarchy" rel="alternate" type="text/html" title="MAKETREE - Hierarchy" /><published>2022-04-08T00:00:00+00:00</published><updated>2022-04-08T00:00:00+00:00</updated><id>https://nt-thuhang.github.io/ntth/MAKETREE-Hierarchy</id><content type="html" xml:base="https://nt-thuhang.github.io/ntth/MAKETREE-Hierarchy">&lt;h2 id=&quot;problem&quot;&gt;&lt;a href=&quot;https://www.spoj.com/problems/MAKETREE/&quot;&gt;Problem&lt;/a&gt;&lt;/h2&gt;

&lt;p&gt;A group of graduated students decided to establish a company; however, they don’t agree on who is going to be who’s boss.&lt;/p&gt;

&lt;p&gt;Generally, one of the students will be the main boss, and each of the other students will have exactly one boss (and that boss, if he is not the main boss, will have a boss of his own too). Every boss will have a strictly greater salary than all of his subordinates - therefore, there are no cycles. Therefore, the hierarchy of the company can be represented as a rooted tree.&lt;/p&gt;

&lt;p&gt;In order to agree on who is going to be who’s boss, they’ve chosen K most successful students, and each of them has given a statement: I want to be the superior of him, him, and him (they could be successful or unsuccessful). And what does it mean to be a superior? It means to be the boss, or to be one of the boss’ superiors (therefore, a superior of a student is not necessary his direct boss).&lt;/p&gt;

&lt;p&gt;Help this immature company and create a hierarchy that will satisfy all of the successful students’ wishes. A solution, not necessary unique, will exist in all of the test data.&lt;/p&gt;

&lt;p&gt;Input Format
In the first line of input, read positive integers N (&lt;!-- $N \le 100000$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=N%20%5Cle%20100000&quot; /&gt;), total number of students, and KK (&lt;!-- $K &lt; N$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=K%20%3C%20N&quot; /&gt;), the number of successful students. All students are numbered 1..N, while the successful ones are numbered 1..K. Then follow K lines. In &lt;!-- $A^{th}$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=A%5E%7Bth%7D&quot; /&gt;
​​  of these lines, first read an integer W (the number of wishes of the student A, &lt;!-- $1 \le W \le 10$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=1%20%5Cle%20W%20%5Cle%2010&quot; /&gt;), and then W integers from the range [1, N] which denote students which student A wants to be superior to.&lt;/p&gt;

&lt;p&gt;Output Format
Output N integers. The &lt;!-- $A^{th}$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=A%5E%7Bth%7D&quot; /&gt;
​​  of these integers should be 0 if student A is the main boss, and else it should represent the boss of the student A.&lt;/p&gt;

&lt;h2 id=&quot;solution&quot;&gt;Solution&lt;/h2&gt;
&lt;p&gt;Xây dựng một đồ thị có hướng không trọng số tương ứng với các nguyện vọng của K người xuất sắc nhất: có cạnh nối &lt;!-- $u \rightarrow v$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=u%20%5Crightarrow%20v&quot; /&gt; khi người u muốn làm cấp trên của v. Đồ thị này không có chu trình nên có thể sắp xếp Topo được. Gọi T là thứ tự Topo của đồ thị vừa xây dựng. Theo định nghĩa thì nếu có cạnh nối &lt;!-- $u \rightarrow v$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=u%20%5Crightarrow%20v&quot; /&gt; thì u sẽ đứng trước v trong T. Điều này có nghĩa là với mỗi người u, tất cả những người cấp dưới mà u muốn đều nằm sau u trong T.&lt;/p&gt;

&lt;p&gt;Cách xây dựng cây phân cấp đơn giản nhất là xây dựng theo thứ tự T:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;!-- $T_1$ --&gt;
    &lt;p&gt;&lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=T_1&quot; /&gt; làm sếp tổng &lt;!-- $\leftrightarrow boss(T_1) = -1$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=%5Cleftrightarrow%20boss(T_1)%20%3D%20-1&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;Sếp của &lt;!-- $T_2$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=T_2&quot; /&gt; là &lt;!-- $T_1$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=T_1&quot; /&gt;
​&lt;!-- $\leftrightarrow boss(T_2) = T_1$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=%5Cleftrightarrow%20boss(T_2)%20%3D%20T_1&quot; /&gt;&lt;/li&gt;
  &lt;li&gt;Sếp của &lt;!-- $T_3$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=T_3&quot; /&gt; là &lt;!-- $T_2 \leftrightarrow boss(T_3) = T_2$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=T_2%20%5Cleftrightarrow%20boss(T_3)%20%3D%20T_2&quot; /&gt;&lt;/li&gt;
  &lt;li&gt;…&lt;/li&gt;
  &lt;li&gt;Sếp của &lt;!-- $T_N$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=T_N&quot; /&gt; là &lt;!-- $T_{N-1} \leftrightarrow boss(T_N) = T_{N-1}$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=T_%7BN-1%7D%20%5Cleftrightarrow%20boss(T_N)%20%3D%20T_%7BN-1%7D&quot; /&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cuối cùng mảng boss chính là kết quả cần xuất ra màn hình.&lt;/p&gt;

&lt;p&gt;Độ phức tạp: &lt;!-- $\mathcal{O} \left( N + sum({W_i}) \right)$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=%5Cmathcal%7BO%7D%20%5Cleft(%20N%20%2B%20sum(%7BW_i%7D)%20%5Cright)&quot; /&gt;. với &lt;!-- $N$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=N&quot; /&gt; là số người trong công ty và &lt;!-- $W_i$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=W_i&quot; /&gt; là số người cấp dưới mà người i chọn.&lt;/p&gt;

&lt;h2 id=&quot;code&quot;&gt;&lt;a href=&quot;https://github.com/NT-ThuHang/Practice-Coding-Skill/blob/main/BigO_Orange06/Topic%2001:%20Topological%20Sort/Hierarchy/Hierarchy.cpp&quot;&gt;Code&lt;/a&gt;&lt;/h2&gt;
&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cp&quot;&gt;#include &amp;lt;bits/stdc++.h&amp;gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;using&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;namespace&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;dfs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bool&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;visited&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;visited&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;visited&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;dfs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;visited&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;push_back&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;topologicalSort&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reserve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bool&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;visited&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;visited&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;dfs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;visited&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reverse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;begin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;());&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;scanf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;%d%d&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;u&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;u&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scanf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;%d&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;scanf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;%d&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;push_back&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;auto&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;topo_order&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;topologicalSort&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;boss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;boss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;topo_order&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;boss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;topo_order&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;topo_order&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;printf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;%d&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;boss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;</content><author><name>[&quot;Nguyễn Thị Thu Hằng&quot;]</name></author><category term="programming" /><summary type="html">Problem</summary></entry><entry><title type="html">TOPOSORT - Topological Sorting</title><link href="https://nt-thuhang.github.io/ntth/Topological_Sorting" rel="alternate" type="text/html" title="TOPOSORT - Topological Sorting" /><published>2022-04-08T00:00:00+00:00</published><updated>2022-04-08T00:00:00+00:00</updated><id>https://nt-thuhang.github.io/ntth/Topological_Sorting</id><content type="html" xml:base="https://nt-thuhang.github.io/ntth/Topological_Sorting">&lt;h2 id=&quot;problem&quot;&gt;&lt;a href=&quot;https://www.hackerrank.com/challenges/crush/problem?isFullScreen=true&amp;amp;h_l=interview&amp;amp;playlist_slugs%5B%5D=interview-prepa&quot;&gt;Problem&lt;/a&gt;&lt;/h2&gt;

&lt;p&gt;Sandro is a well organised person. Every day he makes a list of things which need to be done and enumerates them from 1 to n. However, some things need to be done before others. In this task you have to find out whether Sandro can solve all his duties and if so, print the correct order.&lt;/p&gt;

&lt;h4 id=&quot;input&quot;&gt;Input&lt;/h4&gt;

&lt;p&gt;In the first line you are given an integer n and m (1&amp;lt;=n&amp;lt;=10000, 1&amp;lt;=m&amp;lt;=1000000). On the next m lines there are two distinct integers x and y, (1&amp;lt;=x,y&amp;lt;=10000) describing that job x needs to be done before job y.&lt;/p&gt;

&lt;h4 id=&quot;output&quot;&gt;Output&lt;/h4&gt;

&lt;p&gt;Print “Sandro fails.” if Sandro cannot complete all his duties on the list. If there is a solution print the correct ordering, the jobs to be done separated by a whitespace. If there are multiple solutions print the one, whose first number is smallest, if there are still multiple solutions, print the one whose second number is smallest, and so on.&lt;/p&gt;

&lt;h4 id=&quot;example-1&quot;&gt;Example 1&lt;/h4&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input:
8 9
1 4
1 2
4 2
4 3
3 2
5 2
3 5
8 2
8 6
Output:
1 4 3 5 7 8 2 6 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;solution&quot;&gt;Solution&lt;/h2&gt;

&lt;p&gt;Ta xem N công việc là N đỉnh của đồ thị, còn M cặp công việc là M cạnh của đồ thị có hướng. Vì một số công việc sẽ thực hiện trước một vài công việc khác nên ta sẽ dùng Topological Sort để giải quyết bài toán này. Nhận xét :&lt;/p&gt;

&lt;p&gt;Sandro sẽ không thực hiện được tất cả công việc nếu xuất hiện chu trình trong đồ thị.
Do yêu cầu đặc biệt nếu có nhiều công việc có cùng thứ tự thực hiện thì ta chọn công việc có số nhỏ nhất. Vậy để luôn chọn được công việc có số thứ tự nhỏ nhất thực hiện lúc đó ta cần cấu trúc dữ liệu thích hợp, ở đây ta chọn thuật toán Kahn và min heap để lưu các đỉnh có thể được chọn tiếp.
Vậy với thuật toán Kahn, ta cần danh sách đỉnh kề, mảng đếm số bậc vào còn lại của mỗi đỉnh và min heap các đỉnh có bậc vào hiện tại bằng 0.&lt;/p&gt;

&lt;p&gt;Ta bắt đầu với việc xác định các đỉnh có số bậc vào bằng 0 và cho vào heap.
Khi mà heap vẫn còn các đỉnh chưa được xét, ta chọn đỉnh đầu tiên trong heap sẽ là đỉnh tiếp theo được in ra.
Đồng thời, khi đỉnh này được chọn ta giảm đi số bậc vào của các đỉnh kề từ đỉnh này. Nếu có bất kì đỉnh kề nào có bậc vào bằng 00 thì ta cho đỉnh này vào heap.
Kết quả cuối cùng sau khi kết thúc thuật Kahn sẽ là danh sách các công việc cần thực hiện theo thứ tự thỏa mãn.
Độ phức tạp: &lt;!-- $\mathcal{O} \left( N \cdot \log(N) + M \right)$ --&gt; &lt;img style=&quot;transform: translateY(0.1em); background: white;&quot; src=&quot;https://render.githubusercontent.com/render/math?math=%5Cmathcal%7BO%7D%20%5Cleft(%20N%20%5Ccdot%20%5Clog(N)%20%2B%20M%20%5Cright)&quot; /&gt; với N là số công việc cần thực hiện, M là số cặp công việc phải thực hiện theo đúng thứ tự.&lt;/p&gt;

&lt;h2 id=&quot;code&quot;&gt;&lt;a href=&quot;https://github.com/NT-ThuHang/Practice-Coding-Skill/blob/main/BigO_Orange06/Topic%2001:%20Topological%20Sort/Topological%20Sorting/Topo_Sort.cpp&quot;&gt;Code&lt;/a&gt;&lt;/h2&gt;

&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
&lt;span class=&quot;cp&quot;&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
#include &amp;lt;queue&amp;gt;
#include &amp;lt;set&amp;gt;
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;using&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;namespace&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;topoSort&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;priority_queue&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;greater&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zero_indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;topoSorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// vector&amp;lt;bool&amp;gt; avail(n, true);&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;zero_indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;push&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;// avail[i] = false;&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;


    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;zero_indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;empty&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()){&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;u&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zero_indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;top&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;zero_indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt;

        &lt;span class=&quot;n&quot;&gt;topoSorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;push_back&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;
            &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;zero_indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;push&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;topoSorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(){&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// n: number of vertices&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// m: number of edges&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;scanf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;%d %d&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;resize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;assign&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scanf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;%d %d&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;push_back&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;res&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;topoSort&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;indegree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;printf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Sandro fails.&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;printf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;%d &quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;printf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;</content><author><name>[&quot;Nguyễn Thị Thu Hằng&quot;]</name></author><category term="programming" /><summary type="html">Problem</summary></entry><entry><title type="html">[PYTORCH] BÀI 1: TENSOR</title><link href="https://nt-thuhang.github.io/ntth/DL-PYTORCH1" rel="alternate" type="text/html" title="[PYTORCH] BÀI 1: TENSOR" /><published>2021-06-24T00:00:00+00:00</published><updated>2021-06-24T00:00:00+00:00</updated><id>https://nt-thuhang.github.io/ntth/DL-PYTORCH1</id><content type="html" xml:base="https://nt-thuhang.github.io/ntth/DL-PYTORCH1">&lt;h1 id=&quot;1-tensor-là-gì&quot;&gt;&lt;strong&gt;1. Tensor là gì?&lt;/strong&gt;&lt;/h1&gt;

&lt;p&gt;Đa số các thuật toán ML, DL chỉ xử lí được data dưới dạng số thực nên các dữ liệu đưa vào mô hình phải được chuyển về dạng số.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Tensor là đơn vị tính cơ bản trong deep learning, nó chứa dữ liệu và dữ liệu này thường là numeric. Đó cũng là nguồn cảm hứng mà google đặt tên cho thư viện deep learning nổi tiếng của mình là tensorflow ( Các tensor được tính toán theo(flow) computation graph).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;các-dạng-tensor-thường-gặp&quot;&gt;&lt;strong&gt;Các dạng tensor thường gặp&lt;/strong&gt;&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1.&lt;/strong&gt; &lt;strong&gt;&lt;em&gt;Scalars (0D tensor)&lt;/em&gt;&lt;/strong&gt; : tensor chứa duy nhất một number. Vd : 0,1,2,3&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.&lt;/strong&gt; &lt;strong&gt;&lt;em&gt;Vector (1D tensor)&lt;/em&gt;&lt;/strong&gt; : một array number người ta gọi là vector hay 1D tensor. Vd : [1,2,3],[,3,1,2]&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.&lt;/strong&gt; &lt;strong&gt;&lt;em&gt;Matrix (2D tensor)&lt;/em&gt;&lt;/strong&gt; : 1 array vector được gọi là matrix, hay 2D tensor nó giống như 1 bảng tính gồm các column và row . vd : [[2,1,1],[1,2,3],[1,2,3]]&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4.&lt;/strong&gt; &lt;strong&gt;&lt;em&gt;Higher-dimension tensor (3D tensor)&lt;/em&gt;&lt;/strong&gt; : Tưởng tượng như là 1 khối (cubic) hình hộp chữ nhật chứa các number. Nó được tạo nên từ nhiều matrix (2D tensor).&lt;/p&gt;

&lt;h2 id=&quot;các-thuộc-tính-của-tensor&quot;&gt;&lt;strong&gt;Các thuộc tính của tensor&lt;/strong&gt;&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1.&lt;/strong&gt; &lt;strong&gt;&lt;em&gt;Number of axis&lt;/em&gt;&lt;/strong&gt; : số axis của tensor, hiểu đơn giản là số chiều không gian chứa tensor, vd : scalars 0 axis, vector 1 axis, matrix 2 axis…&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.&lt;/strong&gt; &lt;strong&gt;&lt;em&gt;Shape&lt;/em&gt;&lt;/strong&gt; : Số chiều tensor trên mỗi axis . Vd : matrix có shape (5,10) gồm 5 row (axis=0) và 10 column (axis=1)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.&lt;/strong&gt; &lt;strong&gt;&lt;em&gt;Data type&lt;/em&gt;&lt;/strong&gt; : thường gọi là dtype trong python, kiểu dữ liệu lưu trữ mỗi tensor thông thường là float32.&lt;/p&gt;

&lt;h2 id=&quot;một-số-tensor-data-thường-sử-dụng-trong-deep-learning-&quot;&gt;&lt;strong&gt;Một số tensor data thường sử dụng trong deep learning :&lt;/strong&gt;&lt;/h2&gt;

&lt;p&gt;Ảnh màu (rgb) được biểu diễn dưới dạng 1 tensor 3 chiều&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://i2.wp.com/nttuan8.com/wp-content/uploads/2019/03/tensor.jpg?resize=568%2C426&amp;amp;ssl=1&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Hay dữ liệu dạng chữ (tôi, yêu, hoa,..) cũng được chuyển về dạng vector trước khi cho vào các mô hình, ví dụ như mô hình word2vec.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://i1.wp.com/jalammar.github.io/images/word2vec/word2vec.png?resize=445%2C197&amp;amp;ssl=1&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Hay các bảng số liệu được ghi nhận dưới cấu trúc (sample, feature) thường được sử dụng để dự đoán trong các bài toán ML&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://scontent.fvca1-1.fna.fbcdn.net/v/t1.6435-9/35102787_836919946498534_8241202123946065920_n.jpg?_nc_cat=108&amp;amp;ccb=1-3&amp;amp;_nc_sid=32a93c&amp;amp;_nc_ohc=xxNmPRhdufMAX-PwBjE&amp;amp;_nc_ht=scontent.fvca1-1.fna&amp;amp;oh=d7006a5e61140f3e4fcf99da182c3f02&amp;amp;oe=60D7FAE9&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;h1 id=&quot;2numpy-arrays-vs-pytorch-tensors&quot;&gt;&lt;strong&gt;2.Numpy arrays vs PyTorch tensors&lt;/strong&gt;&lt;/h1&gt;
&lt;blockquote&gt;
  &lt;p&gt;Numpy là thư viện Python giúp lưu trữ và xử lý các phép tính với dữ liệu dạng số thực. Tuy nhiên, Numpy được viết bằng C/C++ nên tốc độ xử lý và tính toán rất nhanh.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;PyTorch tensors có chức năng và mục đích tương tự Numpy arrays nhưng có một vài ưu điểm hơn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Thực hiện tính toán nhanh trên GPU, vì các mô hình DL muốn tăng tốc thì cần xử lý qua các GPU nên tensors hỗ trợ tính toán nhanh trên GPU rất cần thiết.&lt;/li&gt;
  &lt;li&gt;Các Pytorch tensors có thể lưu lại được đồ thị tính toán nên có thể tính đạo hàm nhanh chóng, phục vụ cho thuật toán backpropagation trong Deep Learning.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;3-torch-tensors&quot;&gt;&lt;strong&gt;3. Torch Tensors&lt;/strong&gt;&lt;/h1&gt;

&lt;p&gt;Số thực là dữ liệu 0D, vector 1D, ma trận 2D còn dữ liệu từ 3D trở đi được gọi là tensor.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://i0.wp.com/nttuan8.com/wp-content/uploads/2021/03/image.png?w=1247&amp;amp;ssl=1&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;31-vector&quot;&gt;&lt;strong&gt;3.1 Vector&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;Để truy cập đến phần tử của vector và sửa phần tử của vector ta dùng chỉ số index. Index sẽ được đánh bắt đầu từ 0 đến phần tử cuối cùng của vector.
&lt;img src=&quot;https://i2.wp.com/nttuan8.com/wp-content/uploads/2021/03/image-1.png?w=532&amp;amp;ssl=1&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Để truy cập phần tử cuối cùng&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# Tương đương với x[x.shape[0] - 1], lấy phần tử cuối cùng
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Vậy có cách nào lấy được 1 số phần tử trong vector, ví dụ 3 phần tử cuối cùng, các phần tử index chẵn,..? Có, slicing sẽ giúp mọi người.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://i1.wp.com/nttuan8.com/wp-content/uploads/2021/03/image-4.png?w=1299&amp;amp;ssl=1&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Nếu mọi người không truyền gì thì mặc định start=0, stop=x.shape[0] và step=1. Ý tưởng slicing là sẽ lấy từ phần tử index start đến index (stop – 1) với bước nhảy là step.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[::]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# lấy tất các phần tử trong x
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Như ví dụ x[1:5:2] ở trên thì mình sẽ lấy phần tử đầu ở index 1, sau đó lấy phần tử ở index 3, tuy nhiên sẽ không lấy phần tử ở index 5 vì mình chỉ lấy từ index start đến (stop – 1) hay từ 1 -&amp;gt; 4.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# output: [2, 4]
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Torch tensors không hỗ trợ step âm như python list.&lt;/strong&gt;&lt;/p&gt;

&lt;h2 id=&quot;31-ma-trận&quot;&gt;&lt;strong&gt;3.1 Ma trận&lt;/strong&gt;&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;https://i0.wp.com/nttuan8.com/wp-content/uploads/2021/03/image-2.png?resize=768%2C261&amp;amp;ssl=1&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Ví dụ muốn ấy kích thước ta có thể dùng&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# torch.Size([3, 2])
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# 3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;&lt;img src=&quot;https://i0.wp.com/nttuan8.com/wp-content/uploads/2021/03/image-15.png?w=1355&amp;amp;ssl=1&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# Tương đương A[1:A.shape[0]:1, 0:1:1]
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;33-tensor-3d&quot;&gt;&lt;strong&gt;3.3 Tensor 3D&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;Với tensor 3D thì thuộc tính shape sẽ cho ra 3 giá trị, tương ứng độ sâu (depth), số hàng, số cột. Để truy cập phần tử thì mình cũng phải chỉ rõ index của depth, hàng và cột. Tương tự để slicing thì mình cũng phải slicing trên cả 3 chiều.&lt;/p&gt;

&lt;h1 id=&quot;4-torch-properties&quot;&gt;&lt;strong&gt;4. Torch Properties&lt;/strong&gt;&lt;/h1&gt;

&lt;p&gt;Gán giá trị cho tensor và torch sẽ tự động gán dtype bằng với dtype của giá trị có kiểu rộng hơn trong tensor.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;points&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;6.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;points&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# output: torch.float32
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Tuy nhiên mình cũng có thể khởi tạo kiểu dữ liệu cho tensor luôn&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;points&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;points&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# output: torch.int64
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Gán kiểu dữ liệu cho tensor
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;points&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;short&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;points&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# output: torch.int16
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Hoặc mình cũng có thể chuyển kiểu dữ liệu của tensor đã được khai báo&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;points&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]).&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;short&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;points&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]).&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;short&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Hàm to(dtype=…) sẽ kiểm tra kiểu dữ liệu của tensor và chuyển sang kiểu dữ liệu mới nếu cần thiết. Phần dưới mình sẽ dùng hàm to() để chuyển tensor từ CPU sang GPU.&lt;/p&gt;

&lt;h1 id=&quot;5-torch-transpose&quot;&gt;&lt;strong&gt;5. Torch transpose&lt;/strong&gt;&lt;/h1&gt;

&lt;p&gt;Hàm &lt;strong&gt;torch transpose(input, dim0, dim1)&lt;/strong&gt; : để tìm ma trận chuyển vị của tensor input (Cụ thể chuyển chiều dim0 với dim1)&lt;/p&gt;

&lt;p&gt;Với ma trận 2D
&lt;img src=&quot;https://i2.wp.com/nttuan8.com/wp-content/uploads/2021/03/image-6.png?resize=535%2C140&amp;amp;ssl=1&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Với ma trận 3D
&lt;img src=&quot;https://i2.wp.com/nttuan8.com/wp-content/uploads/2021/03/image-7.png?resize=768%2C261&amp;amp;ssl=1&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CÁC PHÉP TÍNH KHÁC CÁC BẠN CÓ THỂ THAM KHẢO&lt;/strong&gt; &lt;a href=&quot;https://pytorch.org/docs/stable/torch.html&quot;&gt;&lt;strong&gt;TẠI ĐÂY&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1 id=&quot;6-torch-gpu&quot;&gt;&lt;strong&gt;6. Torch GPU&lt;/strong&gt;&lt;/h1&gt;

&lt;p&gt;Torch storage thì mặc định sẽ lưu ở CPU, tuy nhiên Torch cho phép tensor lưu ở GPU để tính toán song song cũng như tăng tốc độ xử lý.&lt;/p&gt;

&lt;p&gt;Nếu 1 tensor được lưu ở GPU, thì các phép tính toán sẽ được thực hiện ở GPU.&lt;/p&gt;

&lt;p&gt;Để khởi tạo 1 tensor và lưu trên gpu thì mình dùng thuộc tính device.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x_gpu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'cuda'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Hoặc mình có thể copy 1 tensor từ CPU sang GPU&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_gpu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'cuda'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Mỗi tensor chỉ được lưu trên 1 GPU nhất định nên nếu có nhiều GPU thì phải chỉ rõ lưu trên GPU nào, index GPU cũng bắt đầu từ 0.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x_gpu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'cuda:0'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# hoặc
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_gpu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cuda&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_gpu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_gpu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# Thực hiện phép tính trên GPU
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Để chuyển ngược lại từ GPU về CPU thì mình dùng&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x_cpu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_gpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'cpu'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# hoặc
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_cpu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_gpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h1 id=&quot;7-torch-tensor-to-numpy-array&quot;&gt;&lt;strong&gt;7. Torch Tensor to Numpy Array&lt;/strong&gt;&lt;/h1&gt;
&lt;p&gt;Torch cho phép chuyển tensor sang Numpy array. Các thuộc tính về size, shape sẽ được giữ nguyên, type sẽ chuyển từ Torch sang Numpy.&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_np&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;Nếu tensor được lưu trên CPU, Torch tensor và Numpy array sẽ dùng chung vùng nhớ, nên thay đổi giá trị ở 1 biến thì giá trị biến còn lại cũng thay đổi.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# output: [1, 0, 3]
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# output: [1, 0, 3]
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Nếu &lt;strong&gt;&lt;em&gt;tensor được lưu trên GPU thì mọi người sẽ không thể chuyển trực tiếp tensor sang Numpy array được&lt;/em&gt;&lt;/strong&gt;, mà mình cần copy nội dung của tensor sang CPU trước rồi mới chuyển sang Numpy array. Do đó 2 biến trên gpu và np không dùng chung vùng nhớ và sửa 1 biến không ảnh hưởng biến còn lại.&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x_gpu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'cuda'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_np&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_gpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# Error
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_np&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_gpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# ok
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_gpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; 
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_gpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# output: [1, 0, 3]
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# output: [1, 2, 3]
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;Tương tự, mình có thể chuyển Numpy array sang Torch tensor. Torch tensor sẽ lưu ở CPU và 2 biến trên np và cpu sẽ dùng chung vùng nhớ.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x_np&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_cpu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;from_numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;</content><author><name>[&quot;Nguyễn Thị Thu Hằng&quot;]</name></author><category term="deep_learning" /><summary type="html">1. Tensor là gì? Đa số các thuật toán ML, DL chỉ xử lí được data dưới dạng số thực nên các dữ liệu đưa vào mô hình phải được chuyển về dạng số. Tensor là đơn vị tính cơ bản trong deep learning, nó chứa dữ liệu và dữ liệu này thường là numeric. Đó cũng là nguồn cảm hứng mà google đặt tên cho thư viện deep learning nổi tiếng của mình là tensorflow ( Các tensor được tính toán theo(flow) computation graph). Các dạng tensor thường gặp 1. Scalars (0D tensor) : tensor chứa duy nhất một number. Vd : 0,1,2,3 2. Vector (1D tensor) : một array number người ta gọi là vector hay 1D tensor. Vd : [1,2,3],[,3,1,2] 3. Matrix (2D tensor) : 1 array vector được gọi là matrix, hay 2D tensor nó giống như 1 bảng tính gồm các column và row . vd : [[2,1,1],[1,2,3],[1,2,3]] 4. Higher-dimension tensor (3D tensor) : Tưởng tượng như là 1 khối (cubic) hình hộp chữ nhật chứa các number. Nó được tạo nên từ nhiều matrix (2D tensor). Các thuộc tính của tensor 1. Number of axis : số axis của tensor, hiểu đơn giản là số chiều không gian chứa tensor, vd : scalars 0 axis, vector 1 axis, matrix 2 axis… 2. Shape : Số chiều tensor trên mỗi axis . Vd : matrix có shape (5,10) gồm 5 row (axis=0) và 10 column (axis=1) 3. Data type : thường gọi là dtype trong python, kiểu dữ liệu lưu trữ mỗi tensor thông thường là float32. Một số tensor data thường sử dụng trong deep learning : Ảnh màu (rgb) được biểu diễn dưới dạng 1 tensor 3 chiều Hay dữ liệu dạng chữ (tôi, yêu, hoa,..) cũng được chuyển về dạng vector trước khi cho vào các mô hình, ví dụ như mô hình word2vec. Hay các bảng số liệu được ghi nhận dưới cấu trúc (sample, feature) thường được sử dụng để dự đoán trong các bài toán ML 2.Numpy arrays vs PyTorch tensors Numpy là thư viện Python giúp lưu trữ và xử lý các phép tính với dữ liệu dạng số thực. Tuy nhiên, Numpy được viết bằng C/C++ nên tốc độ xử lý và tính toán rất nhanh. PyTorch tensors có chức năng và mục đích tương tự Numpy arrays nhưng có một vài ưu điểm hơn: Thực hiện tính toán nhanh trên GPU, vì các mô hình DL muốn tăng tốc thì cần xử lý qua các GPU nên tensors hỗ trợ tính toán nhanh trên GPU rất cần thiết. Các Pytorch tensors có thể lưu lại được đồ thị tính toán nên có thể tính đạo hàm nhanh chóng, phục vụ cho thuật toán backpropagation trong Deep Learning. 3. Torch Tensors Số thực là dữ liệu 0D, vector 1D, ma trận 2D còn dữ liệu từ 3D trở đi được gọi là tensor. 3.1 Vector Để truy cập đến phần tử của vector và sửa phần tử của vector ta dùng chỉ số index. Index sẽ được đánh bắt đầu từ 0 đến phần tử cuối cùng của vector. Để truy cập phần tử cuối cùng x[-1] # Tương đương với x[x.shape[0] - 1], lấy phần tử cuối cùng Vậy có cách nào lấy được 1 số phần tử trong vector, ví dụ 3 phần tử cuối cùng, các phần tử index chẵn,..? Có, slicing sẽ giúp mọi người. Nếu mọi người không truyền gì thì mặc định start=0, stop=x.shape[0] và step=1. Ý tưởng slicing là sẽ lấy từ phần tử index start đến index (stop – 1) với bước nhảy là step. x = x[:] = x[::] = x[0:x.shape[0]:1] # lấy tất các phần tử trong x Như ví dụ x[1:5:2] ở trên thì mình sẽ lấy phần tử đầu ở index 1, sau đó lấy phần tử ở index 3, tuy nhiên sẽ không lấy phần tử ở index 5 vì mình chỉ lấy từ index start đến (stop – 1) hay từ 1 -&amp;gt; 4. x[1:5:2] # output: [2, 4] Torch tensors không hỗ trợ step âm như python list. 3.1 Ma trận Ví dụ muốn ấy kích thước ta có thể dùng A.shape # torch.Size([3, 2]) A.shape[0] # 3 A[1:, :1] # Tương đương A[1:A.shape[0]:1, 0:1:1] 3.3 Tensor 3D Với tensor 3D thì thuộc tính shape sẽ cho ra 3 giá trị, tương ứng độ sâu (depth), số hàng, số cột. Để truy cập phần tử thì mình cũng phải chỉ rõ index của depth, hàng và cột. Tương tự để slicing thì mình cũng phải slicing trên cả 3 chiều. 4. Torch Properties Gán giá trị cho tensor và torch sẽ tự động gán dtype bằng với dtype của giá trị có kiểu rộng hơn trong tensor. points = torch.tensor([7, 8, 10, 6.5]) print(points.dtype) # output: torch.float32 Tuy nhiên mình cũng có thể khởi tạo kiểu dữ liệu cho tensor luôn points = torch.tensor([7, 8, 10, 6]) print(points.dtype) # output: torch.int64 # Gán kiểu dữ liệu cho tensor points = torch.tensor([7, 8, 10, 6], dtype=torch.short) print(points.dtype) # output: torch.int16 Hoặc mình cũng có thể chuyển kiểu dữ liệu của tensor đã được khai báo points = torch.tensor([7, 8, 10, 6]).short() points = torch.tensor([7, 8, 10, 6]).to(dtype=torch.short) Hàm to(dtype=…) sẽ kiểm tra kiểu dữ liệu của tensor và chuyển sang kiểu dữ liệu mới nếu cần thiết. Phần dưới mình sẽ dùng hàm to() để chuyển tensor từ CPU sang GPU. 5. Torch transpose Hàm torch transpose(input, dim0, dim1) : để tìm ma trận chuyển vị của tensor input (Cụ thể chuyển chiều dim0 với dim1) Với ma trận 2D Với ma trận 3D CÁC PHÉP TÍNH KHÁC CÁC BẠN CÓ THỂ THAM KHẢO TẠI ĐÂY 6. Torch GPU Torch storage thì mặc định sẽ lưu ở CPU, tuy nhiên Torch cho phép tensor lưu ở GPU để tính toán song song cũng như tăng tốc độ xử lý. Nếu 1 tensor được lưu ở GPU, thì các phép tính toán sẽ được thực hiện ở GPU. Để khởi tạo 1 tensor và lưu trên gpu thì mình dùng thuộc tính device. x_gpu = torch.tensor([[4.0, 1.0], [5.0, 3.0], [2.0, 1.0]], device='cuda') Hoặc mình có thể copy 1 tensor từ CPU sang GPU x = torch.tensor([[4.0, 1.0], [5.0, 3.0], [2.0, 1.0]]) x_gpu = x.to(device='cuda') Mỗi tensor chỉ được lưu trên 1 GPU nhất định nên nếu có nhiều GPU thì phải chỉ rõ lưu trên GPU nào, index GPU cũng bắt đầu từ 0. x_gpu = x.to(device='cuda:0') # hoặc x_gpu = x.cuda(0) x_gpu = x_gpu + 4 # Thực hiện phép tính trên GPU Để chuyển ngược lại từ GPU về CPU thì mình dùng x_cpu = x_gpu.to(device='cpu') # hoặc x_cpu = x_gpu.cpu() 7. Torch Tensor to Numpy Array Torch cho phép chuyển tensor sang Numpy array. Các thuộc tính về size, shape sẽ được giữ nguyên, type sẽ chuyển từ Torch sang Numpy. x = torch.tensor([1,2,3]) x_np = x.numpy() Nếu tensor được lưu trên CPU, Torch tensor và Numpy array sẽ dùng chung vùng nhớ, nên thay đổi giá trị ở 1 biến thì giá trị biến còn lại cũng thay đổi. x[1] = 0 print(x) # output: [1, 0, 3] print(x_np) # output: [1, 0, 3] Nếu tensor được lưu trên GPU thì mọi người sẽ không thể chuyển trực tiếp tensor sang Numpy array được, mà mình cần copy nội dung của tensor sang CPU trước rồi mới chuyển sang Numpy array. Do đó 2 biến trên gpu và np không dùng chung vùng nhớ và sửa 1 biến không ảnh hưởng biến còn lại. x_gpu = torch.tensor([1, 2, 3], device='cuda') x_np = x_gpu.numpy() # Error x_np = x_gpu.cpu().numpy() # ok x_gpu[1] = 0 print(x_gpu) # output: [1, 0, 3] print(x_np) # output: [1, 2, 3] Tương tự, mình có thể chuyển Numpy array sang Torch tensor. Torch tensor sẽ lưu ở CPU và 2 biến trên np và cpu sẽ dùng chung vùng nhớ. x_np = np.array([1, 2, 3]) x_cpu = torch.from_numpy(x_np)</summary></entry><entry><title type="html">[ML] BÀI 0: CÁC BƯỚC CƠ BẢN ĐỂ GIẢI QUYẾT MỘT BÀI TOÁN MACHINE LEARNING</title><link href="https://nt-thuhang.github.io/ntth/ML-BAI0-BASIC-STEP-TO-SOLVE-ML" rel="alternate" type="text/html" title="[ML] BÀI 0: CÁC BƯỚC CƠ BẢN ĐỂ GIẢI QUYẾT MỘT BÀI TOÁN MACHINE LEARNING" /><published>2021-06-24T00:00:00+00:00</published><updated>2021-06-24T00:00:00+00:00</updated><id>https://nt-thuhang.github.io/ntth/ML-BAI0-BASIC-STEP-TO-SOLVE-ML</id><content type="html" xml:base="https://nt-thuhang.github.io/ntth/ML-BAI0-BASIC-STEP-TO-SOLVE-ML">&lt;p&gt;&lt;img src=&quot;https://aiwithmisa.com/img/in-post/aml/ml-step.png&quot; alt=&quot;IMAGE&quot; /&gt;&lt;/p&gt;

&lt;h1 id=&quot;1-thu-thập-dữ-liệu-get-data&quot;&gt;&lt;strong&gt;1. THU THẬP DỮ LIỆU (GET DATA)&lt;/strong&gt;&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bản thân mình là một đứa ngô nghê về việc phải crawl dữ liệu về như thế nào, làm sao để đọc được dữ liệu nên mình phải đứng ở giai đoạn này khá lâu và cũng nhiều lần suýt từ bỏ. Chắc hẳn rất buồn cười nhỉ? Vì đây chỉ là bước gửi xe mà thôi.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Cũng dễ hiểu thôi mình muốn máy học thì mình phải cho nó dữ liệu để học chứ. Tất nhiên data càng lớn thì càng tốt(nguồn học càng nhiều càng biết rộng hiểu sâu).&lt;/p&gt;

&lt;p&gt;Để thực hành các kỹ năng ML, chúng ta có thể tận dụng những nguồn dữ liệu (dataset) dồi dào từ các nguồn nổi tiếng như Kaggle (Kaggle: Your Home for Data Science), UCI (UCI Machine Learning Repository).&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/NT-ThuHang/Machine-Learning-Tutorial/blob/main/%5BTH0%5DDownload_Dataset.ipynb&quot;&gt;&lt;strong&gt;THỰC HÀNH DOWNLOAD DATASET TẠI ĐÂY.&lt;/strong&gt;&lt;/a&gt; 
Trong bài thực hành trên mình thực hiện trên nền tảng của google colab.&lt;/p&gt;

&lt;h1 id=&quot;2-tiền-xử-lí-dữ-liệu-pre-processing&quot;&gt;&lt;strong&gt;2. TIỀN XỬ LÍ DỮ LIỆU (PRE-PROCESSING)&lt;/strong&gt;&lt;/h1&gt;
&lt;p&gt;Khi có được dữ liệu, chúng ta cần phải tiền xử lý (pre-processing) trước khi tiến hành training model. Đây là giai đoạn rất quan trọng, nó giống như việc chúng ta cần phải cắt, gọt, rửa rau, thịt, cá trước khi đưa vào nồi để nấu. Bước đầu tiên để tiền xử lý dữ liệu chúng ta cần phải khám phá và phân tích dữ liệu – Explory Data Analysis (EDA).&lt;/p&gt;

&lt;p&gt;Trong EDA chúng ta sẽ khám phá và phân tích những thông tin về tập dữ liệu (dataset) như số lượng cá thể (instance), số biến (variable), phân phối (distribution) giá trị của các biến, mối quan hệ giữa các biến không phụ thuộc (independent variable) và biến phụ thuộc (dependent variable) cũng như kiểm tra các vấn đề như dữ liệu trống (missing values), mất cân bằng dữ liệu (imbalanced dataset), kiểm tra các cá thể ngoại biên (outlier). Để có thể nhìn nhận một cách trực quan các vấn đề, khi thực hiện EDA chúng ta sẽ sử dũng các biểu đồ như biểu đồ cột, hộp (box-plot), phân phối (distribution).&lt;/p&gt;

&lt;h1 id=&quot;3-huấn-luyện-dữ-liệu&quot;&gt;&lt;strong&gt;3. HUẤN LUYỆN DỮ LIỆU&lt;/strong&gt;&lt;/h1&gt;
&lt;p&gt;Khi dữ liệu đã được thu thập và tiền xử lý (pre-process) xong, giờ chúng ta sẽ bắt đầu tiến hành huấn luyện (training) cho ML model. Chúng ta sẽ phải lựa chọn ML model phù hợp với yêu cầu của bài toán. Với bài toán regression chúng ta có thể lựa chọn các model: Linear Regression, Polynomial Regression, Decision Tree (DT), Support Vector Machine (SVM), Artificial Neural Network (ANN). Với bài toán classification chúng ta có thể lựa chọn các model: Naive Bayes, Logistic Regression, DT, SVM, ANN. Để có thể lựa chọn ML model chính xác chúng ta cần suy xét về phân phối (distribution) của các cá thể (instance) trong tập dữ liệu (dataset).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://aiwithmisa.com/img/in-post/aml/distribution.jpg&quot; alt=&quot;IMAGE&quot; /&gt;
Ở hình trên mô tả một tập dữ liệu (dataset) có 2 nhóm (class) được biểu thị bằng các ký hiệu vuông và cộng. ML model sau quá trình huấn luyện sẽ cho ra một đường phân định (decision boundary) giúp phân loại các cá thể (instance) trong tập dữ liệu (dataset). Trong trường hợp đơn giản như ở hình đầu tiên, đường phân định (decision boundary) của chúng ta chỉ cần là một đường thẳng tuyến tính (linear) đã có thể phân loại được hai nhóm (class) một cách chính xác. Nhưng ở hình ở giữa, mọi thứ đã phức tạp hơn một chút, chúng ta phải sử dụng tới 2 đường thẳng tuyến tính (linear) kết hợp mới phân định được các nhóm. Ở hình cuối cùng mọi thứ trở nên rất phức tạp, đường phân định (decision boundary) là một đường phi tuyến (nonlinear) để sinh ra được đường phân định (decision boundary) này cần phải sử dụng các nonlinear ML model.&lt;/p&gt;

&lt;p&gt;Để thuận tiện cho quá trình training, tập dữ liệu (dataset) sẽ được sẽ được chia ta thành 3 tập nhỏ hơn: tập dữ liệu huấn luyện (training set), tập dữ liệu xác nhận (validation set) và tập dữ liệu kiểm thử (testing set). Trong quá trình huấn luyện, ML model sẽ ‘học’ trên tập dữ liệu huấn luyện (training set) và sau đó kiểm tra trên tập dữ liệu xác nhận (validation set). Quá trình huấn luyện ML model cần đảm bảo sao cho ML model không bị thiếu vừa vặn (underfit) cũng như quá vừa vặn (overfit). Việc nhận biệt sẽ dựa vào chỉ số mất mát của việc huấn luyện (training loss) và chỉ số mất mát của việc xác nhận (validation loss). Chỉ số mất mát (loss) này sẽ cho biết lỗi (error) của ML model trong việc dự đoán. Nếu chỉ số mất mát ở cả quá trình huấn luyện (training loss) và xác nhận (validation loss) đều cao, đó là dấu hiệu của việc thiếu vừa vặn (underfit), lúc này chúng ta cần tiến hành huấn luyện (tranining) thêm cho ML model. Nếu chỉ số mất mát của việc huấn luyện (training loss) là thấp trong khi đó chỉ số mất mát của việc xác nhận (validation loss) lại rất cao, điều đó chứng tỏ ML model đã có dấu hiệu của việc quá vừa vặn (overfit) và cần dừng việc huấn luyện (training) cho ML model.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://aiwithmisa.com/img/in-post/aml/over-underfit.png&quot; alt=&quot;IAMGE&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://aiwithmisa.com/img/in-post/aml/training.png&quot; alt=&quot;IMAGE&quot; /&gt;&lt;/p&gt;
&lt;h1 id=&quot;4-kiểm-thử&quot;&gt;&lt;strong&gt;4. KIỂM THỬ&lt;/strong&gt;&lt;/h1&gt;
&lt;p&gt;Sau khi đã trải qua quá trình huấn luyện (training), model giờ có thể đưa ra dự đoán kết quả trên tập dữ liệu kiểm thử (testing set) và so sánh với giá trị thực của chúng. Để đánh giá hiệu năng (performance) của ML model một trong cách phổ biến đó là dựa vào ma trận nhầm lẫn (confusion matrix).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://aiwithmisa.com/img/in-post/aml/confusion-matrix.png&quot; alt=&quot;IMAGE&quot; /&gt;
Ma trận nhầm lẫn sẽ giúp chúng ta biết được có bao nhiêu cá thể (instance) được ML model dự đoán là khớp (match) với nhãn (label) của chúng và bao nhiêu bị dự đoán sai. Như hình trên chúng ta có 2 nhóm (class) 1 và 0, chúng ta sẽ ngầm hiểu nhóm 1 là dương tính (Positive) và nhóm 0 là âm tính (Negative). Từ đó sẽ có 4 giá trị trong ma trận nhầm lẫn (confusion matrix).&lt;/p&gt;

&lt;p&gt;True Positives (TPs): Số cá thể (instance) được dự đoán là dương tính (Positive) và nhãn (label) của chúng cũng là dương tính (Positive)
True Negatives (TNs): Số cá thể (instance) được dự đoán là âm tính (Negative) và nhãn (label) của chúng cũng là âm tính (Negative)
False Positives (FPs): Số cá thể (instance) được dự đoán là dương tính (Positive) nhưng nhãn (label) của chúng lại là âm tính (Negative)
False Negatives (FNs): Số cá thể (instance) được dự đoán là âm tính (Negative) nhưng nhãn (label) của chúng lại là dương tính (Positive)
Từ các con số TPs, TNs, FPs, FNs chúng ta sẽ tính được các chỉ số sau:
&lt;img src=&quot;https://2.bp.blogspot.com/-EvSXDotTOwc/XMfeOGZ-CVI/AAAAAAAAEiE/oePFfvhfOQM11dgRn9FkPxlegCXbgOF4QCLcBGAs/w1200-h630-p-k-no-nu/confusionMatrxiUpdated.jpg&quot; alt=&quot;&quot; /&gt;
Độ chính xác (accuracy) sẽ cho chúng ta biết tỉ lệ cá thể (instance) được dự đoán chính xác, nếu để ý chúng ta sẽ thấy tử số của accuracy chính là tổng giá trị ở các ô nằm trên đường chéo (diagonal) của ma trận nhầm lẫn (confusion matrix). Tuy nhiên độ chính xác (accuracy) đôi khi không nói lên hết được vấn đề, đặc biệt là nếu tập dữ liệu kiểm thử (testing set) có hiện tượng mất cân bằng (imbalanced dataset). Ví dụ trong bài toán phân loại gian lận (fraud) thẻ tín dụng, tập dữ liệu kiểm thử (testing dataset) của chúng ta có 100 cá thể (instance), trong đó 99 cá thể (instance) thuộc nhóm không gian lận và chỉ có 1 cá thể (instance) thuộc nhóm gian lận. ML model của chúng ta dự đoán 100 cá thể này đều thuộc nhóm không gian lận và theo cách tính độ chính xác (accuracy) sẽ là 0.99 hay 99%, wow một con số rất hoàn hảo đúng không, nhưng bạn có thấy có gì đó sai sai ?&lt;/p&gt;

&lt;p&gt;Vì lẽ đó mà chúng ta cần tính thêm các chỉ số như độ bao phủ (recall), độ chuẩn xác (precision). Độ bao phủ (recall) sẽ cho chúng ta biết trong tổng số các cá thể (instance) dương tính (positive) tỉ lệ được dự đoán chính xác là dương tính (positive) là bao nhiêu. Độ chuẩn xác (precision) sẽ cho chúng ta biết trong tổng số các cá thể (instance) được dự đoán là dương tính (positive) tỉ lệ các cá thể (instance) thực sự là dương tính (positive) là bao nhiêu. F1-score là chỉ số tổng hợp cân bằng giữa độ bao phủ (recall) và độ chuẩn xác (precision) . 
Dựa vào ma trận nhầm lẫn trên chúng ta có thể thấy, độ bao phủ (recall), độ chuẩn xác (precision) và F1-score của ML model sẽ đều là 0%. Như vậy độ bao phủ (recall) và độ chuẩn xác (precision) cho chúng ta thêm những cái nhìn toàn diện hơn về hiệu năng (peformance) của ML model.&lt;/p&gt;

&lt;p&gt;Ngoài việc sử dụng ma trận nhầm lẫn (confusion matrix) và tính các chỉ số trên, một phương pháp khác để kiểm tra hiệu năng hiệu năng (peformance) của ML model cũng khá phổ biến đó là dùng chỉ số AUC. AUC là viết tắt của Area Under Curve, hay diện tích dưới vòng cung. Để tính được AUC, chúng ta cần vẽ ra được vòng cung ROC (ROC curve), ROC là viết tắt của receiver operating characteristic curve. Vòng cung ROC sẽ cho chúng ta biết sự thay đổi của tỉ lệ dương tính đúng (True Positive Rate) và tỉ lệ dương tính sai (False Positive Rate) khi ngưỡng (threshold) của ML model thay đổi. Ngưỡng (threshold) của ML model thông thường sẽ là 0.5, khi output của ML model lớn hơn ngưỡng (threshold) thì sẽ được phân loại vào nhóm dương tính (Positive class) nếu nhỏ hơn ngưỡng (threshold) thì sẽ phân loại vào nhóm âm tính (Negative class). Chúng ta sẽ hiểu rõ hơn về ngưỡng khi đi sâu vào từng ML model.
&lt;img src=&quot;https://www.researchgate.net/profile/Andreas-Fallgatter/publication/230830197/figure/fig1/AS:267609178374146@1440814408186/Confusion-matrix-summarizing-the-errors-made-by-the-classifier-on-the-test-set.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://aiwithmisa.com/img/in-post/aml/roc-curve.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Vòng cung ROC ở hình trên chính là đường xanh kẻ gạch, và AUC sẽ là diện tích bao bởi hình cung đó. AUC sẽ giao động từ 0 cho đến 1, càng gần 1 thì ML model có hiệu năng (performance) càng tốt.&lt;/p&gt;
&lt;h1 id=&quot;5-một-số-khái-niệm-cơ-bản-khi-tìm-hiểu-machine-learning&quot;&gt;&lt;strong&gt;5. MỘT SỐ KHÁI NIỆM CƠ BẢN KHI TÌM HIỂU MACHINE LEARNING&lt;/strong&gt;&lt;/h1&gt;
&lt;p&gt;Có những khái niệm cơ bản cần nắm khi tìm hiểu về Machine learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Data&lt;/strong&gt;: dữ liệu đầu vào.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Label&lt;/strong&gt;: đầu ra (hay còn gọi là nhãn).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Model&lt;/strong&gt;: được tạo ra từ data và label, sử dụng model để dự đoán những data khác.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thư viện numpy&lt;/strong&gt;: một thư viện toán học phổ biến và mạnh mẽ của Python.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thư viện tensorflow&lt;/strong&gt;: thư viện mã nguồn mở hỗ trợ cho việc tính toán số học dựa trên biểu đồ mô tả sự thay đổi của dữ liệu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Loss&lt;/strong&gt;: hàm đánh giá độ chính xác của giá trị dự đoán.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optimizer&lt;/strong&gt;: hàm đưa ra giá trị dự đoán sao cho giá trị của hàm loss là nhỏ nhất.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Epochs&lt;/strong&gt;: Số lần lặp khi train model.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Neural network&lt;/strong&gt;: là một hệ thống tính toán lấy cảm hứng từ sự hoạt động của các neuron trong hệ thần kinh.&lt;/p&gt;</content><author><name>[&quot;Nguyễn Thị Thu Hằng&quot;]</name></author><category term="machine_learning" /><summary type="html">1. THU THẬP DỮ LIỆU (GET DATA) Bản thân mình là một đứa ngô nghê về việc phải crawl dữ liệu về như thế nào, làm sao để đọc được dữ liệu nên mình phải đứng ở giai đoạn này khá lâu và cũng nhiều lần suýt từ bỏ. Chắc hẳn rất buồn cười nhỉ? Vì đây chỉ là bước gửi xe mà thôi. Cũng dễ hiểu thôi mình muốn máy học thì mình phải cho nó dữ liệu để học chứ. Tất nhiên data càng lớn thì càng tốt(nguồn học càng nhiều càng biết rộng hiểu sâu). Để thực hành các kỹ năng ML, chúng ta có thể tận dụng những nguồn dữ liệu (dataset) dồi dào từ các nguồn nổi tiếng như Kaggle (Kaggle: Your Home for Data Science), UCI (UCI Machine Learning Repository). THỰC HÀNH DOWNLOAD DATASET TẠI ĐÂY. Trong bài thực hành trên mình thực hiện trên nền tảng của google colab. 2. TIỀN XỬ LÍ DỮ LIỆU (PRE-PROCESSING) Khi có được dữ liệu, chúng ta cần phải tiền xử lý (pre-processing) trước khi tiến hành training model. Đây là giai đoạn rất quan trọng, nó giống như việc chúng ta cần phải cắt, gọt, rửa rau, thịt, cá trước khi đưa vào nồi để nấu. Bước đầu tiên để tiền xử lý dữ liệu chúng ta cần phải khám phá và phân tích dữ liệu – Explory Data Analysis (EDA). Trong EDA chúng ta sẽ khám phá và phân tích những thông tin về tập dữ liệu (dataset) như số lượng cá thể (instance), số biến (variable), phân phối (distribution) giá trị của các biến, mối quan hệ giữa các biến không phụ thuộc (independent variable) và biến phụ thuộc (dependent variable) cũng như kiểm tra các vấn đề như dữ liệu trống (missing values), mất cân bằng dữ liệu (imbalanced dataset), kiểm tra các cá thể ngoại biên (outlier). Để có thể nhìn nhận một cách trực quan các vấn đề, khi thực hiện EDA chúng ta sẽ sử dũng các biểu đồ như biểu đồ cột, hộp (box-plot), phân phối (distribution). 3. HUẤN LUYỆN DỮ LIỆU Khi dữ liệu đã được thu thập và tiền xử lý (pre-process) xong, giờ chúng ta sẽ bắt đầu tiến hành huấn luyện (training) cho ML model. Chúng ta sẽ phải lựa chọn ML model phù hợp với yêu cầu của bài toán. Với bài toán regression chúng ta có thể lựa chọn các model: Linear Regression, Polynomial Regression, Decision Tree (DT), Support Vector Machine (SVM), Artificial Neural Network (ANN). Với bài toán classification chúng ta có thể lựa chọn các model: Naive Bayes, Logistic Regression, DT, SVM, ANN. Để có thể lựa chọn ML model chính xác chúng ta cần suy xét về phân phối (distribution) của các cá thể (instance) trong tập dữ liệu (dataset). Ở hình trên mô tả một tập dữ liệu (dataset) có 2 nhóm (class) được biểu thị bằng các ký hiệu vuông và cộng. ML model sau quá trình huấn luyện sẽ cho ra một đường phân định (decision boundary) giúp phân loại các cá thể (instance) trong tập dữ liệu (dataset). Trong trường hợp đơn giản như ở hình đầu tiên, đường phân định (decision boundary) của chúng ta chỉ cần là một đường thẳng tuyến tính (linear) đã có thể phân loại được hai nhóm (class) một cách chính xác. Nhưng ở hình ở giữa, mọi thứ đã phức tạp hơn một chút, chúng ta phải sử dụng tới 2 đường thẳng tuyến tính (linear) kết hợp mới phân định được các nhóm. Ở hình cuối cùng mọi thứ trở nên rất phức tạp, đường phân định (decision boundary) là một đường phi tuyến (nonlinear) để sinh ra được đường phân định (decision boundary) này cần phải sử dụng các nonlinear ML model. Để thuận tiện cho quá trình training, tập dữ liệu (dataset) sẽ được sẽ được chia ta thành 3 tập nhỏ hơn: tập dữ liệu huấn luyện (training set), tập dữ liệu xác nhận (validation set) và tập dữ liệu kiểm thử (testing set). Trong quá trình huấn luyện, ML model sẽ ‘học’ trên tập dữ liệu huấn luyện (training set) và sau đó kiểm tra trên tập dữ liệu xác nhận (validation set). Quá trình huấn luyện ML model cần đảm bảo sao cho ML model không bị thiếu vừa vặn (underfit) cũng như quá vừa vặn (overfit). Việc nhận biệt sẽ dựa vào chỉ số mất mát của việc huấn luyện (training loss) và chỉ số mất mát của việc xác nhận (validation loss). Chỉ số mất mát (loss) này sẽ cho biết lỗi (error) của ML model trong việc dự đoán. Nếu chỉ số mất mát ở cả quá trình huấn luyện (training loss) và xác nhận (validation loss) đều cao, đó là dấu hiệu của việc thiếu vừa vặn (underfit), lúc này chúng ta cần tiến hành huấn luyện (tranining) thêm cho ML model. Nếu chỉ số mất mát của việc huấn luyện (training loss) là thấp trong khi đó chỉ số mất mát của việc xác nhận (validation loss) lại rất cao, điều đó chứng tỏ ML model đã có dấu hiệu của việc quá vừa vặn (overfit) và cần dừng việc huấn luyện (training) cho ML model. 4. KIỂM THỬ Sau khi đã trải qua quá trình huấn luyện (training), model giờ có thể đưa ra dự đoán kết quả trên tập dữ liệu kiểm thử (testing set) và so sánh với giá trị thực của chúng. Để đánh giá hiệu năng (performance) của ML model một trong cách phổ biến đó là dựa vào ma trận nhầm lẫn (confusion matrix). Ma trận nhầm lẫn sẽ giúp chúng ta biết được có bao nhiêu cá thể (instance) được ML model dự đoán là khớp (match) với nhãn (label) của chúng và bao nhiêu bị dự đoán sai. Như hình trên chúng ta có 2 nhóm (class) 1 và 0, chúng ta sẽ ngầm hiểu nhóm 1 là dương tính (Positive) và nhóm 0 là âm tính (Negative). Từ đó sẽ có 4 giá trị trong ma trận nhầm lẫn (confusion matrix). True Positives (TPs): Số cá thể (instance) được dự đoán là dương tính (Positive) và nhãn (label) của chúng cũng là dương tính (Positive) True Negatives (TNs): Số cá thể (instance) được dự đoán là âm tính (Negative) và nhãn (label) của chúng cũng là âm tính (Negative) False Positives (FPs): Số cá thể (instance) được dự đoán là dương tính (Positive) nhưng nhãn (label) của chúng lại là âm tính (Negative) False Negatives (FNs): Số cá thể (instance) được dự đoán là âm tính (Negative) nhưng nhãn (label) của chúng lại là dương tính (Positive) Từ các con số TPs, TNs, FPs, FNs chúng ta sẽ tính được các chỉ số sau: Độ chính xác (accuracy) sẽ cho chúng ta biết tỉ lệ cá thể (instance) được dự đoán chính xác, nếu để ý chúng ta sẽ thấy tử số của accuracy chính là tổng giá trị ở các ô nằm trên đường chéo (diagonal) của ma trận nhầm lẫn (confusion matrix). Tuy nhiên độ chính xác (accuracy) đôi khi không nói lên hết được vấn đề, đặc biệt là nếu tập dữ liệu kiểm thử (testing set) có hiện tượng mất cân bằng (imbalanced dataset). Ví dụ trong bài toán phân loại gian lận (fraud) thẻ tín dụng, tập dữ liệu kiểm thử (testing dataset) của chúng ta có 100 cá thể (instance), trong đó 99 cá thể (instance) thuộc nhóm không gian lận và chỉ có 1 cá thể (instance) thuộc nhóm gian lận. ML model của chúng ta dự đoán 100 cá thể này đều thuộc nhóm không gian lận và theo cách tính độ chính xác (accuracy) sẽ là 0.99 hay 99%, wow một con số rất hoàn hảo đúng không, nhưng bạn có thấy có gì đó sai sai ? Vì lẽ đó mà chúng ta cần tính thêm các chỉ số như độ bao phủ (recall), độ chuẩn xác (precision). Độ bao phủ (recall) sẽ cho chúng ta biết trong tổng số các cá thể (instance) dương tính (positive) tỉ lệ được dự đoán chính xác là dương tính (positive) là bao nhiêu. Độ chuẩn xác (precision) sẽ cho chúng ta biết trong tổng số các cá thể (instance) được dự đoán là dương tính (positive) tỉ lệ các cá thể (instance) thực sự là dương tính (positive) là bao nhiêu. F1-score là chỉ số tổng hợp cân bằng giữa độ bao phủ (recall) và độ chuẩn xác (precision) . Dựa vào ma trận nhầm lẫn trên chúng ta có thể thấy, độ bao phủ (recall), độ chuẩn xác (precision) và F1-score của ML model sẽ đều là 0%. Như vậy độ bao phủ (recall) và độ chuẩn xác (precision) cho chúng ta thêm những cái nhìn toàn diện hơn về hiệu năng (peformance) của ML model. Ngoài việc sử dụng ma trận nhầm lẫn (confusion matrix) và tính các chỉ số trên, một phương pháp khác để kiểm tra hiệu năng hiệu năng (peformance) của ML model cũng khá phổ biến đó là dùng chỉ số AUC. AUC là viết tắt của Area Under Curve, hay diện tích dưới vòng cung. Để tính được AUC, chúng ta cần vẽ ra được vòng cung ROC (ROC curve), ROC là viết tắt của receiver operating characteristic curve. Vòng cung ROC sẽ cho chúng ta biết sự thay đổi của tỉ lệ dương tính đúng (True Positive Rate) và tỉ lệ dương tính sai (False Positive Rate) khi ngưỡng (threshold) của ML model thay đổi. Ngưỡng (threshold) của ML model thông thường sẽ là 0.5, khi output của ML model lớn hơn ngưỡng (threshold) thì sẽ được phân loại vào nhóm dương tính (Positive class) nếu nhỏ hơn ngưỡng (threshold) thì sẽ phân loại vào nhóm âm tính (Negative class). Chúng ta sẽ hiểu rõ hơn về ngưỡng khi đi sâu vào từng ML model. Vòng cung ROC ở hình trên chính là đường xanh kẻ gạch, và AUC sẽ là diện tích bao bởi hình cung đó. AUC sẽ giao động từ 0 cho đến 1, càng gần 1 thì ML model có hiệu năng (performance) càng tốt. 5. MỘT SỐ KHÁI NIỆM CƠ BẢN KHI TÌM HIỂU MACHINE LEARNING Có những khái niệm cơ bản cần nắm khi tìm hiểu về Machine learning. Data: dữ liệu đầu vào. Label: đầu ra (hay còn gọi là nhãn). Model: được tạo ra từ data và label, sử dụng model để dự đoán những data khác. Thư viện numpy: một thư viện toán học phổ biến và mạnh mẽ của Python. Thư viện tensorflow: thư viện mã nguồn mở hỗ trợ cho việc tính toán số học dựa trên biểu đồ mô tả sự thay đổi của dữ liệu. Loss: hàm đánh giá độ chính xác của giá trị dự đoán. Optimizer: hàm đưa ra giá trị dự đoán sao cho giá trị của hàm loss là nhỏ nhất. Epochs: Số lần lặp khi train model. Neural network: là một hệ thống tính toán lấy cảm hứng từ sự hoạt động của các neuron trong hệ thần kinh.</summary></entry><entry><title type="html">[ML] BÀI 1: TIỀN XỬ LÍ DỮ LIỆU</title><link href="https://nt-thuhang.github.io/ntth/ML-BAI1-PREPROCESSING-1" rel="alternate" type="text/html" title="[ML] BÀI 1: TIỀN XỬ LÍ DỮ LIỆU" /><published>2021-06-24T00:00:00+00:00</published><updated>2021-06-24T00:00:00+00:00</updated><id>https://nt-thuhang.github.io/ntth/ML-BAI1-PREPROCESSING-1</id><content type="html" xml:base="https://nt-thuhang.github.io/ntth/ML-BAI1-PREPROCESSING-1">&lt;p&gt;&lt;img src=&quot;https://serokell.io/files/df/dfsdv4ab.2_(23)_(1).jpg&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tiền xử lý dữ liệu&lt;/strong&gt; là một bước rất quan trọng trong việc giải quyết bất kỳ vấn đề nào trong lĩnh vực Học Máy. Hầu hết các bộ dữ liệu được sử dụng trong các vấn đề liên quan đến Học Máy cần được xử lý, làm sạch và biến đổi trước khi một thuật toán Học Máy có thể được huấn luyện trên những bộ dữ liệu này. Các kỹ thuật tiền xử lý dữ liệu phổ biến hiện nay bao gồm: xử lý dữ liệu bị khuyết (missing data), mã hóa các biến nhóm (encoding categorical variables), chuẩn hóa dữ liệu (standardizing data), co giãn dữ liệu (scaling data),… Những kỹ thuật này tương đối dễ hiểu nhưng sẽ có nhiều vấn đề phát sinh khi chúng ta áp dụng vào các dữ liệu thực tế. Bởi lẽ các bộ dữ liệu ứng với các bài toán trong thực tế rất khác nhau và mỗi bài toàn thì đối mặt với những thách thức khác nhau về mặt dữ liệu. Trong bài viết này, mình sẽ cùng nhau tìm hiểu về các kỹ thuật tiền xử lý dữ liệu và cách áp dụng chúng trong các bài toán thực tế.&lt;/p&gt;

&lt;h1 id=&quot;1-missing-data&quot;&gt;&lt;strong&gt;1. MISSING DATA&lt;/strong&gt;&lt;/h1&gt;
&lt;h2 id=&quot;11-phân-loại&quot;&gt;&lt;strong&gt;1.1 Phân loại&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;Dữ liệu bị thiếu được chia ra làm ba dạng:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;&lt;em&gt;Khuyết ngẫn nhiên (Missing at Random – MAR)&lt;/em&gt;&lt;/strong&gt;: sự khuyết dữ liệu của đặc trưng này có điều kiện hoặc phụ thuộc vào một hoặc một vài các đặc trưng khác.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;&lt;em&gt;Khuyết hoàn toàn ngẫu nhiên (Missing Completely at Random – MCAR)&lt;/em&gt;&lt;/strong&gt;:  Không có mối quan hệ nào giữa đặc trưng bị khuyết với các giá trị giả định hoặc các ràng buộc trên các đặc trưng khác. Ở đây, tập dữ liệu bị khuyết chỉ là một tập con ngẫu nhiên của bộ dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;&lt;em&gt;Khuyết không ngẫu nhiên (Missing not at Random – MNAR)&lt;/em&gt;&lt;/strong&gt;: Khuyết không ngẫu nhiên xảy ra khi một điểm dữ liệu bị khuyết phụ thuộc cả vào các giá trị giả định (ví dụ như những người giàu có thường không tiết lộ mức thu nhập của họ khi bạn khảo sát) và các giá trị của các đặc trưng khác (ví dụ như khi bạn muốn khảo sát tuổi của một người, mà người đó là con gái thì thường là bạn sẽ không nhận được câu trả lời từ họ).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Trong hai trường hợp đầu tiên, xóa đi các điểm dữ liệu bị thiếu dựa vào số lần xuất hiện của chúng là chấp nhận được. Nhưng trong trường hợp thứ ba, việc xóa đi các quan sát bị khuyết giá trị có thể khiến cho mô hình bị ảnh hưởng. Do đó, chúng ta cần rất lưu tâm trước khi xóa đi những điểm dữ liệu này.&lt;/p&gt;

&lt;p&gt;Ngoài ra, chúng ta cũng cần hiểu rằng cách bỏ qua (không xử lý gì) những điểm dữ liệu bị khuyết này là cách không nên áp dụng, nó có thể rất tai hại nếu như bạn không xử lý đúng đắn khi phân tích dữ liệu của bạn. &lt;em&gt;Bởi lẽ dữ liệu bị khuyết sẽ khiến bạn đưa ra những kết luận sai lầm về bộ dữ liệu của bạn khi bạn nhìn vào các giá trị sai về tổng, trung bình hoặc phân phối của bộ dữ liệu.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;12-xóa-dữ-liệu-khuyết&quot;&gt;&lt;strong&gt;1.2 Xóa dữ liệu khuyết&lt;/strong&gt;&lt;/h2&gt;

&lt;p&gt;Nói thẳng ra thì các gì mập mờ cũng không tốt. Ví dụ như TRÊN TÌNH BẠN DƯỚI TÌNH YÊU. Ủa là cái gì? Rõ ràng đi chứ. Cái gì mập mờ quá mình bỏ đi để không lại sai. Nhưng trong ML data càng nhiều là càng tốt nhưng nếu xóa đi quá nhiều thì tiếc lắm, mà không xóa thì lại dễ dẫn đến sai. Vậy chúng ta phải làm sao?&lt;/p&gt;
&lt;h3 id=&quot;listwise&quot;&gt;Listwise&lt;/h3&gt;

&lt;p&gt;Phương pháp xóa dữ liệu listwise xóa đi tất cả các điểm dữ liệu có một hoặc một vài giá trị đặc trưng bị khuyết. Phương pháp này thường chỉ được sử dụng khi bạn đang tiến hành một nghiên cứu để so sánh với một phương pháp xử lý khác. Vì trong thực tế thì phương pháp này đem lại nhiều bất lợi. Bởi lẽ dữ liệu khuyết hoàn toàn ngẫu nhiên MCAR thường hiếm gặp, do đó, phương pháp này nhiều khả năng tạo ra các tham số và ước lượng bị lệch cho mô hình.&lt;/p&gt;

&lt;h3 id=&quot;pairwise&quot;&gt;Pairwise&lt;/h3&gt;

&lt;p&gt;Phương pháp xóa pairwise cố gắng tối thiểu hóa sự mất mát khi sử dụng phương pháp xóa listwise. Để hiểu đơn giản về phương pháp xóa pairwise, ta hãy liên tưởng đến &lt;strong&gt;ma trận tương quan&lt;/strong&gt;. Mỗi giá trị tương quan thể hiện mức độ liên kết giữa hai biến (đặc trưng). Với mỗi cặp biến mà dữ liệu không bị khuyết, hệ số tương quan sẽ được đưa vào tính toán. Do đó, phương pháp xóa pairwise tối đa hóa các dữ liệu có sẵn bởi một phân tích cơ sở. Một thế mạnh của phương pháp này là nó làm tăng sức mạnh và tính hiệu quả của các phân tích mà bạn muốn thực hiện. Mặc dù phương pháp này được khuyến nghị dùng nhiều hơn là phương pháp xóa listwise, nhưng nó cũng sử dụng giả thiết rằng dữ liệu bị khuyết thuộc dạng khuyết hoàn toàn ngẫu nhiên MCAR.&lt;/p&gt;

&lt;h3 id=&quot;xóa-nguyên-cột-luôn-nếu-cột-không-quan-trọng&quot;&gt;Xóa nguyên cột luôn nếu cột không quan trọng&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://datasciencevn.com/thao-tac-voi-du-lieu/xu-ly-o-du-lieu-trong.html&quot;&gt;&lt;strong&gt;CÁC CÚ PHÁP CỦA CÁC LỆNH XÓA CỤ THỂ Ở LINK NÀY!&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;13-điền-khuyến-dữ-liệu&quot;&gt;&lt;strong&gt;1.3 Điền khuyến dữ liệu&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;Với một đặc trưng dữ liệu dạng số, có rất nhiều lựa chọn mà chúng ta có thể xem xét khi điền vào một giá trị bị khuyết, ví dụ:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Một giá trị hằng có ý nghĩa trong miền xác định của dữ liệu, ví dụ như 0.&lt;/li&gt;
  &lt;li&gt;Một giá trị của một đặc trưng từ một mẫu dữ liệu ngẫu nhiên trong tập dữ liệu.&lt;/li&gt;
  &lt;li&gt;Các giá trị thống kê cơ bản như giá trị trung bình, giá trị trung vị hay giá trị mốt (mode) của cột.&lt;/li&gt;
  &lt;li&gt;Một giá trị được ước lượng từ một mô hình dự đoán khác.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;cụ-thể&quot;&gt;Cụ thể&lt;/h4&gt;
&lt;h4 id=&quot;thay-thế-những-dữ-liệu-missing-với-các-giá-trị--1--99--999&quot;&gt;Thay thế những dữ liệu missing với các giá trị: -1, -99, -999&lt;/h4&gt;
&lt;p&gt;Với những features có tính liên tục thì việc chúng ta thay thế những giá trị missing bằng các giá trị &lt;strong&gt;-1, -99, -999, …&lt;/strong&gt; sẽ giúp cho những mô hình cây như (RF - Random Forest) hoạt động tốt hơn bởi khi thay thế bằng những giá trị ở trên thì các mô hình này có thể giải thích cho việc thiếu dữ liệu thông qua việc encoding này. &lt;strong&gt;Nhược điểm của nó làm giải hiệu suất của mô hình tuyến tính sẽ bị ảnh hưởng.&lt;/strong&gt;&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Fare&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fillna&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;99&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h4 id=&quot;thay-thế-bằng-giá-trị-mean-midian-mode&quot;&gt;Thay thế bằng giá trị mean, midian, mode&lt;/h4&gt;

&lt;p&gt;Với phương pháp này chúng ta điền những giá trị bị thiếu bằng giá trị &lt;strong&gt;mean&lt;/strong&gt; hay &lt;strong&gt;median&lt;/strong&gt; của một vài biến nếu biến liên tục và điền mode nếu biến là biến categorical. &lt;strong&gt;Tuy phương pháp này nhanh nhưng lại làm giảm phương sai của dữ liệu.&lt;/strong&gt; Bên cạnh đó khi thực hiện cách này thì nó &lt;em&gt;phù hợp với mô hình tuyến tính đơn giản và NN. Nhưng đối với những bài toán dựa trên tree thì có vẻ không phù hợp lắm.&lt;/em&gt;
Ví dụ code:&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fillna&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;Hoặc&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fillna&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;median&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;Hoặc với biến categorical chúng ta sử dụng mode:&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Cabin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fillna&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Cabin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h4 id=&quot;sử-dụng-mô-hình-dự-đoán-cho-data-impution&quot;&gt;Sử dụng mô hình dự đoán cho data impution&lt;/h4&gt;

&lt;p&gt;Ở đây chúng ta có thể sử dụng K-NN, Linear-Regression để dự đoán các giá trị còn thiếu:&lt;/p&gt;</content><author><name>[&quot;Nguyễn Thị Thu Hằng&quot;]</name></author><category term="machine_learning" /><summary type="html">Tiền xử lý dữ liệu là một bước rất quan trọng trong việc giải quyết bất kỳ vấn đề nào trong lĩnh vực Học Máy. Hầu hết các bộ dữ liệu được sử dụng trong các vấn đề liên quan đến Học Máy cần được xử lý, làm sạch và biến đổi trước khi một thuật toán Học Máy có thể được huấn luyện trên những bộ dữ liệu này. Các kỹ thuật tiền xử lý dữ liệu phổ biến hiện nay bao gồm: xử lý dữ liệu bị khuyết (missing data), mã hóa các biến nhóm (encoding categorical variables), chuẩn hóa dữ liệu (standardizing data), co giãn dữ liệu (scaling data),… Những kỹ thuật này tương đối dễ hiểu nhưng sẽ có nhiều vấn đề phát sinh khi chúng ta áp dụng vào các dữ liệu thực tế. Bởi lẽ các bộ dữ liệu ứng với các bài toán trong thực tế rất khác nhau và mỗi bài toàn thì đối mặt với những thách thức khác nhau về mặt dữ liệu. Trong bài viết này, mình sẽ cùng nhau tìm hiểu về các kỹ thuật tiền xử lý dữ liệu và cách áp dụng chúng trong các bài toán thực tế. 1. MISSING DATA 1.1 Phân loại Dữ liệu bị thiếu được chia ra làm ba dạng: Khuyết ngẫn nhiên (Missing at Random – MAR): sự khuyết dữ liệu của đặc trưng này có điều kiện hoặc phụ thuộc vào một hoặc một vài các đặc trưng khác. Khuyết hoàn toàn ngẫu nhiên (Missing Completely at Random – MCAR): Không có mối quan hệ nào giữa đặc trưng bị khuyết với các giá trị giả định hoặc các ràng buộc trên các đặc trưng khác. Ở đây, tập dữ liệu bị khuyết chỉ là một tập con ngẫu nhiên của bộ dữ liệu. Khuyết không ngẫu nhiên (Missing not at Random – MNAR): Khuyết không ngẫu nhiên xảy ra khi một điểm dữ liệu bị khuyết phụ thuộc cả vào các giá trị giả định (ví dụ như những người giàu có thường không tiết lộ mức thu nhập của họ khi bạn khảo sát) và các giá trị của các đặc trưng khác (ví dụ như khi bạn muốn khảo sát tuổi của một người, mà người đó là con gái thì thường là bạn sẽ không nhận được câu trả lời từ họ). Trong hai trường hợp đầu tiên, xóa đi các điểm dữ liệu bị thiếu dựa vào số lần xuất hiện của chúng là chấp nhận được. Nhưng trong trường hợp thứ ba, việc xóa đi các quan sát bị khuyết giá trị có thể khiến cho mô hình bị ảnh hưởng. Do đó, chúng ta cần rất lưu tâm trước khi xóa đi những điểm dữ liệu này. Ngoài ra, chúng ta cũng cần hiểu rằng cách bỏ qua (không xử lý gì) những điểm dữ liệu bị khuyết này là cách không nên áp dụng, nó có thể rất tai hại nếu như bạn không xử lý đúng đắn khi phân tích dữ liệu của bạn. Bởi lẽ dữ liệu bị khuyết sẽ khiến bạn đưa ra những kết luận sai lầm về bộ dữ liệu của bạn khi bạn nhìn vào các giá trị sai về tổng, trung bình hoặc phân phối của bộ dữ liệu. 1.2 Xóa dữ liệu khuyết Nói thẳng ra thì các gì mập mờ cũng không tốt. Ví dụ như TRÊN TÌNH BẠN DƯỚI TÌNH YÊU. Ủa là cái gì? Rõ ràng đi chứ. Cái gì mập mờ quá mình bỏ đi để không lại sai. Nhưng trong ML data càng nhiều là càng tốt nhưng nếu xóa đi quá nhiều thì tiếc lắm, mà không xóa thì lại dễ dẫn đến sai. Vậy chúng ta phải làm sao? Listwise Phương pháp xóa dữ liệu listwise xóa đi tất cả các điểm dữ liệu có một hoặc một vài giá trị đặc trưng bị khuyết. Phương pháp này thường chỉ được sử dụng khi bạn đang tiến hành một nghiên cứu để so sánh với một phương pháp xử lý khác. Vì trong thực tế thì phương pháp này đem lại nhiều bất lợi. Bởi lẽ dữ liệu khuyết hoàn toàn ngẫu nhiên MCAR thường hiếm gặp, do đó, phương pháp này nhiều khả năng tạo ra các tham số và ước lượng bị lệch cho mô hình. Pairwise Phương pháp xóa pairwise cố gắng tối thiểu hóa sự mất mát khi sử dụng phương pháp xóa listwise. Để hiểu đơn giản về phương pháp xóa pairwise, ta hãy liên tưởng đến ma trận tương quan. Mỗi giá trị tương quan thể hiện mức độ liên kết giữa hai biến (đặc trưng). Với mỗi cặp biến mà dữ liệu không bị khuyết, hệ số tương quan sẽ được đưa vào tính toán. Do đó, phương pháp xóa pairwise tối đa hóa các dữ liệu có sẵn bởi một phân tích cơ sở. Một thế mạnh của phương pháp này là nó làm tăng sức mạnh và tính hiệu quả của các phân tích mà bạn muốn thực hiện. Mặc dù phương pháp này được khuyến nghị dùng nhiều hơn là phương pháp xóa listwise, nhưng nó cũng sử dụng giả thiết rằng dữ liệu bị khuyết thuộc dạng khuyết hoàn toàn ngẫu nhiên MCAR. Xóa nguyên cột luôn nếu cột không quan trọng CÁC CÚ PHÁP CỦA CÁC LỆNH XÓA CỤ THỂ Ở LINK NÀY! 1.3 Điền khuyến dữ liệu Với một đặc trưng dữ liệu dạng số, có rất nhiều lựa chọn mà chúng ta có thể xem xét khi điền vào một giá trị bị khuyết, ví dụ: Một giá trị hằng có ý nghĩa trong miền xác định của dữ liệu, ví dụ như 0. Một giá trị của một đặc trưng từ một mẫu dữ liệu ngẫu nhiên trong tập dữ liệu. Các giá trị thống kê cơ bản như giá trị trung bình, giá trị trung vị hay giá trị mốt (mode) của cột. Một giá trị được ước lượng từ một mô hình dự đoán khác. Cụ thể Thay thế những dữ liệu missing với các giá trị: -1, -99, -999 Với những features có tính liên tục thì việc chúng ta thay thế những giá trị missing bằng các giá trị -1, -99, -999, … sẽ giúp cho những mô hình cây như (RF - Random Forest) hoạt động tốt hơn bởi khi thay thế bằng những giá trị ở trên thì các mô hình này có thể giải thích cho việc thiếu dữ liệu thông qua việc encoding này. Nhược điểm của nó làm giải hiệu suất của mô hình tuyến tính sẽ bị ảnh hưởng. dataset.Fare.fillna(-99,inplace=True) Thay thế bằng giá trị mean, midian, mode Với phương pháp này chúng ta điền những giá trị bị thiếu bằng giá trị mean hay median của một vài biến nếu biến liên tục và điền mode nếu biến là biến categorical. Tuy phương pháp này nhanh nhưng lại làm giảm phương sai của dữ liệu. Bên cạnh đó khi thực hiện cách này thì nó phù hợp với mô hình tuyến tính đơn giản và NN. Nhưng đối với những bài toán dựa trên tree thì có vẻ không phù hợp lắm. Ví dụ code: dataset.Age.fillna(dataset.Age.mean(),inplace=True) Hoặc dataset.Age.fillna(dataset.Age.median(),inplace=True) Hoặc với biến categorical chúng ta sử dụng mode: dataset.Cabin.fillna(dataset.Cabin.mode()[0],inplace=True) Sử dụng mô hình dự đoán cho data impution Ở đây chúng ta có thể sử dụng K-NN, Linear-Regression để dự đoán các giá trị còn thiếu:</summary></entry><entry><title type="html">[ML] BÀI 4: LOGISTIC PREGRESSION</title><link href="https://nt-thuhang.github.io/ntth/ML-BAI4-LOGISTIC-REGRESSION" rel="alternate" type="text/html" title="[ML] BÀI 4: LOGISTIC PREGRESSION" /><published>2021-06-24T00:00:00+00:00</published><updated>2021-06-24T00:00:00+00:00</updated><id>https://nt-thuhang.github.io/ntth/ML-BAI4-LOGISTIC-REGRESSION</id><content type="html" xml:base="https://nt-thuhang.github.io/ntth/ML-BAI4-LOGISTIC-REGRESSION">&lt;p&gt;Hôm nay chúng ta sẽ tìm hiểu về Logistic Regression model, đây là một linear model giúp giải quyết các bài toán classification ví dụ như phân loại ốm hay khỏe mạnh, gian lận hay không gian lận,..&lt;/p&gt;

&lt;h1 id=&quot;1-đường-phân-định---decision-boundary&quot;&gt;&lt;strong&gt;1. Đường phân định - Decision boundary&lt;/strong&gt;&lt;/h1&gt;

&lt;p&gt;Trong bài toán phân loại, chúng ta cần Logistic Regression tạo ra một đường phân định (decision boundary) giúp phân loại các nhóm (class) của dữ liệu như hình mô tả dưới đây:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://aiwithmisa.com/img/in-post/aml/logistic-regression.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Hàm số tuyến tính (linear function) chúng ta mong muốn sẽ là:&lt;/p&gt;
&lt;center&gt; Score = w0 + w1x&lt;/center&gt;

&lt;p&gt;Sự khác biệt của hàm số tuyến tính (linear function) trên với hàm số của Linear Regression nằm ở bên vế trái, giá trị của biến không phụ thuộc (dependent variable) y giờ được thay bằng score, vậy score này là gì ? Score này được kỳ vọng sẽ giúp chúng phân loại cá thể (instance) vào các nhóm (class). Ở đây chúng ta sẽ để ý đến 2 thứ:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Dấu của score&lt;/strong&gt; =&amp;gt; giúp phân biệt nhóm (class). Giả sử chúng ta có 2 nhóm (class) là -1 và 1. Nếu dấu của score là âm thì nó sẽ thuộc về nhóm (class) -1 và dấu là dương thì nó sẽ thuộc về nhóm (class) 1.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ lớn của score&lt;/strong&gt; =&amp;gt; xác định vị trí của cá thể so với đường  phân định (decision boundary) các thể càng ở xa càng chắc chắn điểm đó thuộc về nhóm (class) đó. Các cá thế (instance) ở càng gần đường phân định, tương ứng với score bằng 0 sẽ có thể thuộc về 1 trong 2 nhóm (class), và những điểm này là những điểm khá mơ hồ (confuse), ở hình trên chúng ta thấy có một vài cá thể (instance) thuộc nhóm (class) xanh nhưng thuộc khu vực của nhóm (class) đỏ và ngược lại.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;https://aiwithmisa.com/img/in-post/aml/score-logistic.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;h1 id=&quot;2-hàm-logistic---logistic-function&quot;&gt;&lt;strong&gt;2. Hàm Logistic - Logistic function&lt;/strong&gt;&lt;/h1&gt;

&lt;p&gt;Tuy nhiên score không thể làm chúng ta hài lòng, điều chúng ta muốn là xác xuất (probability) của cá thể (instance) này thuộc về nhóm (class) là bao nhiêu phần trăm. Do đó, score sẽ được đưa vào logistic function, hay tên gọi khác đó là softmax của score. Softmax trong trường hợp chỉ có 2 nhóm (class) - binary classification còn được gọi là Sigmoid. Vậy hàm số Sigmoid (Sigmoid function) có tác dụng gì ?&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://aiwithmisa.com/img/in-post/aml/sigmoid.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Sigmoid sẽ chuyển đổi score chúng ta có được ở trên, thành xác suất (probability) của cá thể đó thuộc nhóm (class) 1
.&lt;strong&gt;P(y = 1| x_{i}, w)&lt;/strong&gt;. Trong đó , &lt;strong&gt;x_{i}, w&lt;/strong&gt; chính là biểu thị của hàm số tuyến tính w0 + w1x , ký hiệu trên được hiểu là xác xuất của cá thể (instance) thuộc nhóm (class) 1 với hàm số tuyến tính (linear function) đã cho (given). Thông thường chúng ta sẽ đặt 0.5 là ngưỡng (Threshold) như đã đề cập ở bài số 3, nếu xác xuất (probability) lớn hơn 0.5 chúng ta sẽ quy định cá thể (instance) thuộc nhóm class (1), nếu nhỏ hơn sẽ thuộc nhóm (class) 0. Để hình dùng cụ thể hơn về cách Sigmoid chuyển đổi Score thành xác suất (probability) chúng ta hãy xem công thức của hàm số Sigmoid, cũng như đồ thị của nó.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://aiwithmisa.com/img/in-post/aml/sigmoid-plot.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Có thể thấy đặc chưng của Sigmoid function đó là bão hòa (saturate) ở 0 và 1 khi các giá trị của score càng lớn hoặc càng nhỏ, giúp chuyển đổi score ra xác xuất (probability) mà chúng ta mong muốn.&lt;/p&gt;

&lt;h1 id=&quot;3-àm-mất-mát---loss-function&quot;&gt;&lt;strong&gt;3. àm mất mát - Loss function&lt;/strong&gt;&lt;/h1&gt;

&lt;p&gt;Đối với các bài toán phân loại (classification), hàm mất mát (loss function) thường được sử dụng đó là cross entropy loss.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://i.postimg.cc/L51gS1qc/lossfunc-logictic-R.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Trong đó n là số cá thể (instance) của tập dữ liệu&lt;/p&gt;

&lt;p&gt;Để hiểu cách hoạt động của cross entropy loss, chúng ta hãy cùng xét trường hợp sau. Chúng ta có cá thể (instance) thuộc nhóm (class) 1, tương ứng với  bằng 1, tuy nhiên Logistic regression model của chúng ta lại dự đoán  bằng 0, khi đó  tương ứng với  và có giá trị âm vô cùng, loss của chúng ta sẽ rất lớn, chứng tỏ model đang dự đoán sai. Điều tương tự sẽ xảy ra trong trường hợp cá thể thuộc nhóm (class) 0, nhưng lại được dự đoán với xác suất là 1.&lt;/p&gt;

&lt;h1 id=&quot;4-kết-luận&quot;&gt;&lt;strong&gt;4. Kết luận&lt;/strong&gt;&lt;/h1&gt;

&lt;p&gt;Có thể thấy hồi quy Logistic - Logistic Regression là một biến thể của hồi quy tuyến tính Linear Regression giải quyết phân loại (classification) dữ liệu. Hai ML model này các tính chất tương đương nhau.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://colab.research.google.com/drive/1waGRJkeFmGQnK1sKzcAY5-CxltPff110?usp=sharing&quot;&gt;&lt;strong&gt;HÃY THỰC HÀNH THEO BÀI TẬP NÀY ĐỂ MÌNH CÓ THỂ HIỂU VỀ LOGISTIC REGRESSION HƠN NHÉ!&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;</content><author><name>[&quot;Nguyễn Thị Thu Hằng&quot;]</name></author><category term="machine_learning" /><summary type="html">Hôm nay chúng ta sẽ tìm hiểu về Logistic Regression model, đây là một linear model giúp giải quyết các bài toán classification ví dụ như phân loại ốm hay khỏe mạnh, gian lận hay không gian lận,.. 1. Đường phân định - Decision boundary Trong bài toán phân loại, chúng ta cần Logistic Regression tạo ra một đường phân định (decision boundary) giúp phân loại các nhóm (class) của dữ liệu như hình mô tả dưới đây: Hàm số tuyến tính (linear function) chúng ta mong muốn sẽ là: Score = w0 + w1x Sự khác biệt của hàm số tuyến tính (linear function) trên với hàm số của Linear Regression nằm ở bên vế trái, giá trị của biến không phụ thuộc (dependent variable) y giờ được thay bằng score, vậy score này là gì ? Score này được kỳ vọng sẽ giúp chúng phân loại cá thể (instance) vào các nhóm (class). Ở đây chúng ta sẽ để ý đến 2 thứ: Dấu của score =&amp;gt; giúp phân biệt nhóm (class). Giả sử chúng ta có 2 nhóm (class) là -1 và 1. Nếu dấu của score là âm thì nó sẽ thuộc về nhóm (class) -1 và dấu là dương thì nó sẽ thuộc về nhóm (class) 1. Độ lớn của score =&amp;gt; xác định vị trí của cá thể so với đường phân định (decision boundary) các thể càng ở xa càng chắc chắn điểm đó thuộc về nhóm (class) đó. Các cá thế (instance) ở càng gần đường phân định, tương ứng với score bằng 0 sẽ có thể thuộc về 1 trong 2 nhóm (class), và những điểm này là những điểm khá mơ hồ (confuse), ở hình trên chúng ta thấy có một vài cá thể (instance) thuộc nhóm (class) xanh nhưng thuộc khu vực của nhóm (class) đỏ và ngược lại. 2. Hàm Logistic - Logistic function Tuy nhiên score không thể làm chúng ta hài lòng, điều chúng ta muốn là xác xuất (probability) của cá thể (instance) này thuộc về nhóm (class) là bao nhiêu phần trăm. Do đó, score sẽ được đưa vào logistic function, hay tên gọi khác đó là softmax của score. Softmax trong trường hợp chỉ có 2 nhóm (class) - binary classification còn được gọi là Sigmoid. Vậy hàm số Sigmoid (Sigmoid function) có tác dụng gì ? Sigmoid sẽ chuyển đổi score chúng ta có được ở trên, thành xác suất (probability) của cá thể đó thuộc nhóm (class) 1 .P(y = 1| x_{i}, w). Trong đó , x_{i}, w chính là biểu thị của hàm số tuyến tính w0 + w1x , ký hiệu trên được hiểu là xác xuất của cá thể (instance) thuộc nhóm (class) 1 với hàm số tuyến tính (linear function) đã cho (given). Thông thường chúng ta sẽ đặt 0.5 là ngưỡng (Threshold) như đã đề cập ở bài số 3, nếu xác xuất (probability) lớn hơn 0.5 chúng ta sẽ quy định cá thể (instance) thuộc nhóm class (1), nếu nhỏ hơn sẽ thuộc nhóm (class) 0. Để hình dùng cụ thể hơn về cách Sigmoid chuyển đổi Score thành xác suất (probability) chúng ta hãy xem công thức của hàm số Sigmoid, cũng như đồ thị của nó. Có thể thấy đặc chưng của Sigmoid function đó là bão hòa (saturate) ở 0 và 1 khi các giá trị của score càng lớn hoặc càng nhỏ, giúp chuyển đổi score ra xác xuất (probability) mà chúng ta mong muốn. 3. àm mất mát - Loss function Đối với các bài toán phân loại (classification), hàm mất mát (loss function) thường được sử dụng đó là cross entropy loss. Trong đó n là số cá thể (instance) của tập dữ liệu Để hiểu cách hoạt động của cross entropy loss, chúng ta hãy cùng xét trường hợp sau. Chúng ta có cá thể (instance) thuộc nhóm (class) 1, tương ứng với bằng 1, tuy nhiên Logistic regression model của chúng ta lại dự đoán bằng 0, khi đó tương ứng với và có giá trị âm vô cùng, loss của chúng ta sẽ rất lớn, chứng tỏ model đang dự đoán sai. Điều tương tự sẽ xảy ra trong trường hợp cá thể thuộc nhóm (class) 0, nhưng lại được dự đoán với xác suất là 1. 4. Kết luận Có thể thấy hồi quy Logistic - Logistic Regression là một biến thể của hồi quy tuyến tính Linear Regression giải quyết phân loại (classification) dữ liệu. Hai ML model này các tính chất tương đương nhau. HÃY THỰC HÀNH THEO BÀI TẬP NÀY ĐỂ MÌNH CÓ THỂ HIỂU VỀ LOGISTIC REGRESSION HƠN NHÉ!</summary></entry><entry><title type="html">[PYTORCH] BÀI 0: GIỚI THIỆU PYTORCH</title><link href="https://nt-thuhang.github.io/ntth/DL-PYTORCH0" rel="alternate" type="text/html" title="[PYTORCH] BÀI 0: GIỚI THIỆU PYTORCH" /><published>2021-06-23T00:00:00+00:00</published><updated>2021-06-23T00:00:00+00:00</updated><id>https://nt-thuhang.github.io/ntth/DL-PYTORCH0</id><content type="html" xml:base="https://nt-thuhang.github.io/ntth/DL-PYTORCH0">&lt;h1 id=&quot;tại-sao-lại-là-pytorch&quot;&gt;&lt;strong&gt;Tại sao lại là Pytorch?&lt;/strong&gt;&lt;/h1&gt;
&lt;p&gt;Ngày nay, Deep Learning đã quá nổi bật với những công trình nghiên cứu thành công vang dội về các tính ứng dụng lẫn độ chính xác. Các công trình nổi bật làm cho trí tuệ nhân tạo như được thần thánh hóa trong mắt nhân loại như: xe tự hành(self-driving car), xác định vật thể trong ảnh (object detection),…&lt;/p&gt;

&lt;p&gt;Trong quá trình hỗ trợ phát triển ứng dụng cũng như triển khai các sản phẩm ra thực tế, chúng ta cần các Deep Learning framework. Có rất nhiều framework cho Deep Learning như: Pytorch, Tensorflow, Keras, Mxnet,… Tuy nhiên, Pytorch được xem như là framework được sử dụng nhiều nhất trong những paper.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://thegradient.pub/content/images/2019/10/ratio_medium-1.png&quot; alt=&quot;So sánh tỉ lệ số lượng paper sử dụng Pytorch và Tensorflow&quot; title=&quot;So sánh tỉ lệ số lượng paper sử dụng Pytorch và Tensorflow&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Các bạn có thể tham khảo qua bài viết này để biết thêm nhiều thông tin
&lt;a href=&quot;https://thegradient.pub/state-of-ml-frameworks-2019-pytorch-dominates-research-tensorflow-dominates-industry/&quot;&gt;Pytorch áp đảo Tensorflow trong giới research&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Vậy nên không quá khi nói Pytorch là một trong những Deep Learning framework tốt nhất hiện tại, cho cả làm nghiên cứu lẫn phát triển sản phẩm.&lt;/p&gt;</content><author><name>[&quot;Nguyễn Thị Thu Hằng&quot;]</name></author><category term="deep_learning" /><summary type="html">Tại sao lại là Pytorch? Ngày nay, Deep Learning đã quá nổi bật với những công trình nghiên cứu thành công vang dội về các tính ứng dụng lẫn độ chính xác. Các công trình nổi bật làm cho trí tuệ nhân tạo như được thần thánh hóa trong mắt nhân loại như: xe tự hành(self-driving car), xác định vật thể trong ảnh (object detection),… Trong quá trình hỗ trợ phát triển ứng dụng cũng như triển khai các sản phẩm ra thực tế, chúng ta cần các Deep Learning framework. Có rất nhiều framework cho Deep Learning như: Pytorch, Tensorflow, Keras, Mxnet,… Tuy nhiên, Pytorch được xem như là framework được sử dụng nhiều nhất trong những paper. Các bạn có thể tham khảo qua bài viết này để biết thêm nhiều thông tin Pytorch áp đảo Tensorflow trong giới research Vậy nên không quá khi nói Pytorch là một trong những Deep Learning framework tốt nhất hiện tại, cho cả làm nghiên cứu lẫn phát triển sản phẩm.</summary></entry></feed>