<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kashiwa on Medium]]></title>
        <description><![CDATA[Stories by Kashiwa on Medium]]></description>
        <link>https://medium.com/@ksw2000?source=rss-b570e94ee042------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gmW6aueZowb0y9aUpNN4zg.png</url>
            <title>Stories by Kashiwa on Medium</title>
            <link>https://medium.com/@ksw2000?source=rss-b570e94ee042------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:51:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ksw2000/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Implement an AVL Tree with Go (Part II)]]></title>
            <link>https://ksw2000.medium.com/implement-an-avl-tree-with-go-part-ii-68f5c1f71e50?source=rss-b570e94ee042------2</link>
            <guid isPermaLink="false">https://medium.com/p/68f5c1f71e50</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[trees]]></category>
            <dc:creator><![CDATA[Kashiwa]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 13:50:47 GMT</pubDate>
            <atom:updated>2024-09-17T03:18:14.756Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduce the deletion of nodes in an AVL tree, and then design a test and benchmark function to check its performance and effectiveness.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrcWLqM7P_pLx-AcHHl0jw.png" /><figcaption>Cover photo</figcaption></figure><p>I have discussed the basic concept of AVL tree in <a href="https://ksw2000.medium.com/implement-an-avl-tree-with-go-49e5952389d4">Implement an AVL Tree with Go. The article introduces how to search… | by Kashiwa | Medium</a></p><p>Before introducing the deletion of the AVL Tree, we should review how to remove a node in a binary tree.</p><ol><li>If the node we want to delete has no subtree, we can directly remove it. In other words, we set the pointer that points to it as nil (see Fig.1). If no pointer is pointing to it, then the node is the root of the tree, and we simply set the tree’s root as nil.</li><li>If the node we wish to delete has only a left subtree, we can connect its parent with this left subtree. (see Fig. 2)</li><li>If the node we want to delete has a right subtree or only a right subtree, we can replace it with its successor. The successor is the node that represents the smallest node among those greater than the node that should be removed. (See Fig. 3)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lo7U3gb44LZDFrww20U6Gw.png" /><figcaption>Fig. 1 The node we want to delete, the red node, has no children.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Abg7423KQItmlAPbNc6VzQ.png" /><figcaption>Fig. 2 The node we want to delete, the red node, has only left child.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Qy1aPaN1sVBPwm7ZeiMow.png" /><figcaption>Fig. 3 The node we want to delete, the red node, has right child.</figcaption></figure><p>After deleting the node, to adhere to the rules of the AVL tree, we need to update the height and rebalance the path between the root node and the deleted node.</p><pre>type AVLTree struct {<br>    root *AVLNode<br>}<br><br>type AVLNode struct {<br>    Key    int<br>    Val    interface{}<br>    left   *AVLNode<br>    right  *AVLNode<br>    height int // the height of the node<br>}<br><br>func (t *AVLTree) Delete(key int) {<br>    t.root = t.root.delete(key)<br>}<br><br>// n: the root node of the subtree<br>// key: the key of the node we want to delete it<br>func (n *AVLNode) delete(key int) *AVLNode {<br>    if n == nil {<br>        return nil<br>    }<br>    if key &lt; n.Key {<br>        n.left = n.left.delete(key)<br>    } else if key &gt; n.Key {<br>        n.right = n.right.delete(key)<br>    } else {<br>        if n.right != nil {<br>            // scenario 3, node has right child<br>            successor := n.right<br>            for successor.left != nil {<br>                successor = successor.left<br>            }<br>            // copy the key and value of the successor <br>            // to the node should be deleted originally<br>            n.Key = successor.Key<br>            n.Val = successor.Val<br>            n.right = n.right.delete(successor.Key)<br>        } else if n.left != nil {<br>            // scenario 2, node with only the left child<br>            n = n.left<br>        } else {<br>            // node has no children<br>            n = nil<br>            return n  // return the new root<br>        }<br>    }<br>    // update the height of node<br>    // and then rebalance the node<br>    if n != nil {<br>        n.updateHeight()<br>        n = n.rebalance()<br>    }<br>    return n<br>}</pre><h3>Test</h3><p>After implementing the delete function, we can design a series of test functions to test that the delete function is working properly.</p><pre>func TestAVLTreeCorrectness(t *testing.T) {<br>    // Declare an int array of length 1024.<br>    list := make([]int, 1024)<br>    // set i-th element to be i<br>    for i := range list {<br>        list[i] = i<br>    }<br>    // shuffle the list<br>    // the 2nd argument is used to swap the list<br>    rand.Shuffle(len(list), func(i, j int) {<br>        list[i], list[j] = list[j], list[i]<br>    })<br><br>    // create a new avl tree<br>    tree := new(AVLTree)<br>    // insert node with key`e` and value`e`<br>    for _, e := range list {<br>        tree.Insert(NewAVLNode(e, e))<br>     }<br><br>    min := 0<br><br>    // tree.Do() is a method that traverses the tree <br>    // in increasing order.<br>    // We implemented the method in the previous article<br>    tree.Do(func(n *AVLNode) {<br>        // check the tree is in increasing order<br>        if n.Key &lt; min {<br>            t.Fail()<br>        }<br>        min = n.Key<br>        <br>        // check that each node&#39;s balance factor is in [-1, 1]<br>        if n.balanceFactor() &gt; 1 || n.balanceFactor() &lt; -1 {<br>            t.Fail()<br>        }<br><br>        // check that the Search() method is working properly<br>        if found := tree.Search(n.Key); found == nil || found.Key != n.Val.(int) {<br>            t.Fail()<br>        }<br>    })<br><br>    // shuffle the list again<br>    rand.Shuffle(len(list), func(i, j int) {<br>        list[i], list[j] = list[j], list[i]<br>    })<br> <br>    for i := range list {<br>        // delete one of element in the tree<br>        tree.Delete(list[i])<br>        min := 0<br>        <br>        tree.Do(func(n *AVLNode) {<br>            // check the tree is in increasing order<br>            if n.Key &lt; min {<br>                t.Fail()<br>            }<br>            min = n.Key<br>            // check that each node&#39;s balance factor is in [-1, 1]<br>            if n.balanceFactor() &gt; 1 || n.balanceFactor() &lt; -1 {<br>                t.Fail()<br>            }<br>        })<br>    }<br>}</pre><p>We should write the above code to a file whose filename ends with _test , for example avl_test.go . To run the test function, please run the following command in the terminal.</p><pre>go test --run TestAVLTreeCorrectness</pre><p>If you want to print some information, use -v flag to enable verbose mode during the test.</p><pre>go test -v --run TestAVLTreeCorrectness</pre><h3>Performance</h3><p>Not only do we concern about correctness, but also about performance. We can compare the AVL tree we implemented with an existing package. In this section I will use github.com/karask/go-avltree as an example to compare its performance with ours.</p><p>Step 1. Create a simple dataset</p><pre>func generateData() ([]int, []int) {<br>    // fix the random seed<br>    r := rand.New(rand.NewSource(0))<br>    // create an int array of length 1024<br>    list := make([]int, 1024)<br>    for i := range list {<br>        list[i] = i<br>    }<br>    // shuffle the list<br>    r.Shuffle(len(list), func(i, j int) {<br>        list[i], list[j] = list[j], list[i]<br>    })<br>    // create a second array that duplicatesthe first one<br>    list2 := make([]int, len(list))<br>    copy(list2, list)<br>    r.Shuffle(len(list2), func(i, j int) {<br>        list2[i], list2[j] = list2[j], list2[i]<br>    })<br>    return list, list2<br>}</pre><p>Step2. Create a benchmark for the third-party package</p><pre>import &quot;github.com/karask/go-avltree&quot;<br>// import other dependencies<br><br>func BenchmarkAVLKarask(b *testing.B) {<br>    for i := 0; i &lt; b.N; i++ {<br>        list, list2 := generateData()<br>        tree := new(avltree.AVLTree)<br>        for _, key := range list {<br>            tree.Add(key, key)<br>        }<br>        for _, key := range list2 {<br>            tree.Remove(key)<br>        }<br>    }<br>}</pre><p>Step3. Create a benchmark for the third-party package</p><pre>func BenchmarkAVLOurs(b *testing.B) {<br>    for i := 0; i &lt; b.N; i++ {<br>        list, list2 := generateData()<br>        tree := new(AVLTree)<br>        for _, key := range list {<br>            tree.Insert(NewAVLNode(key, key))<br>        }<br>        for _, key := range list2 {<br>            tree.Delete(key)<br>        }<br>    }<br>}</pre><p>Step4. Run benchmarks</p><p>As in the previous section, we should write the above code to a file whose filename ends with _test. Of course, you can also write the benchmark function in the same file as the test function.</p><p>To run the test function, please execute the following command in the terminal. This command will run all test functions before executing benchmarks, and it will run the benchmark functions that start with BenchmarkAVL .</p><pre>go test -bench BenchmarkAVL</pre><p>If you do not want to run test funcion set -run to be none</p><pre>go test -bench BenchmarkAVL -run none</pre><p>We can view the result as shown below</p><pre>goos: windows<br>goarch: amd64<br>pkg: avl<br>cpu: Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz<br>BenchmarkAVLKarask-8        3314            313372 ns/op<br>BenchmarkAVLOurs-8          4759            252458 ns/op<br>PASS</pre><p>The first column contains the function name concatenated with the number of threads. The second column represents how many times the function can be executed in one second. The last column shows the time consumed for a single execution.</p><p><strong>See full code here:</strong> <a href="https://github.com/ksw2000/Medium/tree/main/implement-an-avl-tree-with-go">https://github.com/ksw2000/Medium/tree/main/implement-an-avl-tree-with-go</a></p><p><strong>See the relative articles:</strong></p><ol><li>Implement a an AVL Tree with Go:<br><a href="https://ksw2000.medium.com/implement-an-avl-tree-with-go-49e5952389d4">https://ksw2000.medium.com/implement-an-avl-tree-with-go-49e5952389d4</a></li><li>Implement a Binary Search Tree with Go: <a href="https://medium.com/@ksw2000/implement-a-binary-search-tree-with-go-969e716cc471">https://medium.com/@ksw2000/implement-a-binary-search-tree-with-go-969e716cc47</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68f5c1f71e50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement an AVL Tree with Go]]></title>
            <link>https://ksw2000.medium.com/implement-an-avl-tree-with-go-49e5952389d4?source=rss-b570e94ee042------2</link>
            <guid isPermaLink="false">https://medium.com/p/49e5952389d4</guid>
            <category><![CDATA[trees]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Kashiwa]]></dc:creator>
            <pubDate>Thu, 25 Aug 2022 16:29:36 GMT</pubDate>
            <atom:updated>2023-09-11T13:58:01.884Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLHwRdyDmAyUcTEzWlCgnQ.png" /><figcaption>cover photo</figcaption></figure><h3>What is AVL tree?</h3><blockquote>In computer science, an <strong>AVL tree</strong> (named after inventors <strong>A</strong>delson-<strong>V</strong>elsky and <strong>L</strong>andis) is a <strong>self-balancing binary search tree</strong>. It was the first such data structure to be invented. In an AVL tree, the heights of the two child subtrees of any node differ by at most one.<br> — <a href="https://en.wikipedia.org/wiki/AVL_tree">wikipedia</a></blockquote><p>There is a big disadvantage in naïve binary search trees. For example, if we insert nodes in increasing order, the binary tree will become just a linked list. That is to say, the time complexity of the search will become O(n), where n is the number of all nodes.</p><p>AVL is a self-balancing binary search tree. It is guaranteed that the time complexity of searching for nodes is always O(log n), regardless of the order in which you insert the nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*IvhUAxeNmgdL_Bfj6zBrqg.png" /><figcaption>Figure1. If we insert nodes in increasing order.</figcaption></figure><p><strong>Definition</strong></p><p>AVL tree checks <strong>the height of the left and the right sub-trees</strong> and assures that <strong>the difference is not more than 1</strong>. That is, AVL trees make sure that |height(node.left)-height(node.right)| ≤ 1</p><p>How to calculate the height of nodes?</p><ol><li>height(null) = -1</li><li>height(node) = max(Height(Node.left), height(node.right)) + 1</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*xWi_vJOYxWDG4cHhs8GyvA.png" /><figcaption>Figure 2. An example of calculating the height of nodes. The binary tree is not an AVL tree.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*cJZK7psAEt17vwskZDgF4w.png" /><figcaption>Figure 3. Another example of calculating the height of nodes. The binary tree is an AVL tree.</figcaption></figure><p>In Figure 2, The height of the left subtree of <strong>hanamaru</strong> is -1, and the height of the right subtree hanamaru is 1. Because 1-(-1) &gt; 1, this binary tree is not an AVL tree. As for Figure 3, there are no nodes that betray the rules of AVL trees, thus this tree is an AVL tree.</p><h4>Rotation</h4><p>To modify a binary tree to an AVL tree, we can use <strong>rotation</strong>. To realize what is rotation, first, please see the 4 states below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*YLRWTYi2nv9DuKb132MaMA.png" /><figcaption>Figure 4. Four states that we should consider. (a) RR type (b) LL type © RL type (d) LR type</figcaption></figure><p>All of the above 4 states can be converted to an AVL tree. We can use left rotation to convert Figure 4(a) into an AVL tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*Pu_4NN7CC-zz5DcurcxSKg.png" /><figcaption>Figure 5(a). An example of left rotation for an RR-type tree.</figcaption></figure><p>We can use the <strong>right rotation</strong> to convert Figure 4(b) into an AVL tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*bDq187AP4GcUvdwEwV8yIg.png" /><figcaption>Figure 5(b). An example of right rotation for an LL-type tree.</figcaption></figure><p>However, how do rotate RL type and LR type in Figure 4(c) and Figure 4(d) respectively? We can <strong>rotate them twice</strong>!</p><p>For RL types, right rotate Ayumu to convert it to RR type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*8S3op0IC5PZSHfTnWzg3Iw.png" /><figcaption>Figure 5(c). An example of rotation an RL-type tree in order to convert it to RR type.</figcaption></figure><pre>Hanamaru.rihgt.rightRotate()<br>Hanamaru.leftRotate()</pre><p>As for LR types, left rotate Hanamaru to convert it to LL type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*PCE-h-Fv-yTL90kz2-i6bw.png" /><figcaption>Figure 5(d). An example of rotation an LR-type tree in order to convert it to LL type.</figcaption></figure><pre>Ayumu.left.leftRotate()<br>Ayumu.rightRotate()</pre><h3>Implement</h3><h4>AVLNode</h4><p>Begin implementing the AVL tree, we create a structure for its nodes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/322297ffdebb20f2acbdaeb5aab3e7ab/href">https://medium.com/media/322297ffdebb20f2acbdaeb5aab3e7ab/href</a></iframe><p>The tree node not only needs the left node and the right node but also needs the height value.</p><p>Then, we should define how to update the height value.</p><pre>// pseudo code<br>if node has no child {<br>    height = 0<br>}else{<br>    height = max(node.left.height, node.right.height)+1<br>}</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dbf52c034267d1263ee7d1d311f1ce5/href">https://medium.com/media/8dbf52c034267d1263ee7d1d311f1ce5/href</a></iframe><blockquote>updateHeight() updates the height value in the node n . When calling updateHeight(), we should make sure that all the children of node n have the correct height.</blockquote><p>Next, we need to specify how to rebalance the tree. We can build a function that rotates the subtree by given the root of the subtree and returning the new node of the subtree. For example, see Figure 5(a), after calling hanamaru.LeftRotation(), the left rotation method should return new root, i.e., ruby.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da39a3819f20414c279cc4ef6217f4be/href">https://medium.com/media/da39a3819f20414c279cc4ef6217f4be/href</a></iframe><blockquote>rightRotation() and leftRotation() rotates the subtree whose root is n and returns the root node of the new subtree.</blockquote><p>It is not easy to understand how they work. So, I draw a graph to interpret it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*1H11Oqn6f_WoyGr_0q7bFA.png" /><figcaption>Figure 6(a). The steps of right rotation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*dcDwB4zFSp3mA1c8wrL9lg.png" /><figcaption>Figure 6(b). The steps of left rotation</figcaption></figure><p>In Figures 6(a) and 6(b), we can observe that the rectangle node’s children, n2, n3, and n4, do not be changed, so we do not need to update the height of the rectangle nodes. As for the circle nodes, n and n1, whose children were changed after rotating. Thus, we need to update the height of n and n1, because n1’s height is dependent on n’s height, we update n’s height first.</p><p>After defining the rotation method, we should build a <strong>rebalance</strong> method that detects the subtree type, and then rotates the subtree to make it satisfy the conditions of the AVL tree.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9064a9612c8a7847b3aefc790975173/href">https://medium.com/media/f9064a9612c8a7847b3aefc790975173/href</a></iframe><blockquote>blanceFactor() calculates the balance factor of the tree node n .<br>rebalance() reblances the subtree whose root node is n by right rotation or left rotation. It returns the root node of the new balanced subtree.</blockquote><p>When the balance factor is 0, 1, or -1, it means the difference between the height of the left subtree and the height of the right subtree are not exceed 1, so we can return the original node directly. However, when the balance factor is bigger than 1, it means that the left subtree is higher than the right subtree. That is, One of two scenarios (LL or LR) could occur. If a given node has a left node and its left node’s balance factor is smaller than zero, then we are faced with the LR-type problem. LR-type or RL-type should be rotated twice.</p><p>In this article, I only introduce how to insert a new node and search for a node. I will introduce how to remove nodes in the next article.</p><p>So, how to insert a new node into the AVL tree? There are usually 2 methods to insert a new node into the binary search tree. One of them is <strong>recursive</strong>, and the other one is <strong>iterative</strong>. When inserting a new node, we should record the nodes that pass through the path in order to recalculate the height of nodes and rebalance the nodes that we passed through.</p><p>If we use the iterative method to implement insert(), we should implicitly use a stack to record the path. Or, we can change the structure of AVLNode — adding a new field to record the parent of this node.</p><pre>type AVLNode struct{<br>    Key    int<br>    Val    interface{}<br>    left   *AVLNode<br>    right  *AVLnode<br>    parent *AVLnODE<br>    height int<br>}</pre><p>These methods are more difficult to implement and the performance is not necessarily better. Therefore, we can use the recursive method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3bdf541253d42001ac29dca9a957c57/href">https://medium.com/media/a3bdf541253d42001ac29dca9a957c57/href</a></iframe><blockquote>insert() inserts the node m into the subtree whose root node is n and returns the root node of the new subtree.</blockquote><p>The search function of the AVL tree is as same as the classic binary search tree.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/952af7fb776719baa25ce4bce0c4fe07/href">https://medium.com/media/952af7fb776719baa25ce4bce0c4fe07/href</a></iframe><blockquote>search() searches the tree whose root node is n and returns a non-nil node if found. If not found the key, returns nil.</blockquote><h4>AVLTree</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95ffcfc62b3d8f3275d30667dbea7fd4/href">https://medium.com/media/95ffcfc62b3d8f3275d30667dbea7fd4/href</a></iframe><h3>Test</h3><p>To traverse the tree, we still need to implement a traverse function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31db281580ac2cb85ab8c41a5c034d69/href">https://medium.com/media/31db281580ac2cb85ab8c41a5c034d69/href</a></iframe><p>Create a test file e.g., avl_test.go .</p><pre>import (<br>    &quot;fmt&quot;<br>    &quot;hash/fnv&quot;<br>    &quot;testing&quot;<br>)<br><br>func hash(s string) int {<br>    h := fnv.New32a()<br>    h.Write([]byte(s))<br>    return int(h.Sum32() % 255)<br>}<br><br>// go test -run TestAVLTree -v<br>func TestAVLTree(t *testing.T) {<br>    tree := new(AVLTree)<br>    list := []string{<br>        &quot;Chika&quot;, &quot;You&quot;, &quot;Ruby&quot;,<br>        &quot;Riko&quot;, &quot;Yoshiko&quot;, &quot;Mari&quot;,<br>        &quot;Kanan&quot;, &quot;Dia&quot;, &quot;Hanamaru&quot;,<br>    }<br><br>    for _, v := range list {<br>        fmt.Printf(&quot;Insert (%d %s)\n&quot;, hash(v), v)<br>        tree.Insert(NewAVLNode(int(hash(v)), v))<br>        tree.Do(func(a *AVLNode) {<br>            l := &quot;nil&quot;<br>            if left := a.left; left != nil {<br>                l = fmt.Sprintf(&quot;%3d&quot;, left.Key)<br>            }<br>            r := &quot;nil&quot;<br>            if right := a.right; right != nil {<br>                r = fmt.Sprintf(&quot;%3d&quot;, right.Key)<br>            }<br>            fmt.Printf(&quot;%3d left: %s right: %s balance: %2d height: %2d\n&quot;, a.Key, l, r, a.balanceFactor(), a.height)<br>        })<br>        fmt.Println(&quot;------------------&quot;)<br>    }<br>    <br>    tree.Do(func(a *AVLNode) {<br>        fmt.Printf(&quot;(%d, %s) -&gt; &quot;, a.Key, a.Val)<br>    })<br>    fmt.Println()<br>}</pre><p>Result:</p><pre>Insert (60 Chika)  <br> 60 left: nil right: nil balance:  0 height:  0 <br>------------------ <br>Insert (129 You)<br> 60 left: nil right: 129 balance: -1 height:  1 <br>129 left: nil right: nil balance:  0 height:  0 <br>------------------ <br>Insert (7 Ruby) <br>  7 left: nil right: nil balance:  0 height:  0<br> 60 left:   7 right: 129 balance:  0 height:  1 <br>129 left: nil right: nil balance:  0 height:  0 <br>------------------ <br>Insert (240 Riko) <br>  7 left: nil right: nil balance:  0 height:  0 <br> 60 left:   7 right: 129 balance: -1 height:  2<br>129 left: nil right: 240 balance: -1 height:  1 <br>240 left: nil right: nil balance:  0 height:  0 <br>------------------ <br>Insert (62 Yoshiko) <br>  7 left: nil right: nil balance:  0 height:  0 <br> 60 left:   7 right: 129 balance: -1 height:  2 <br> 62 left: nil right: nil balance:  0 height:  0<br>129 left:  62 right: 240 balance:  0 height:  1<br>240 left: nil right: nil balance:  0 height:  0 <br>------------------ <br>Insert (239 Mari) <br>  7 left: nil right: nil balance:  0 height:  0 <br> 60 left:   7 right:  62 balance:  0 height:  1 <br> 62 left: nil right: nil balance:  0 height:  0 <br>129 left:  60 right: 240 balance:  0 height:  2 <br>239 left: nil right: nil balance:  0 height:  0 <br>240 left: 239 right: nil balance:  1 height:  1 <br>------------------ <br>Insert (213 Kanan) <br>  7 left: nil right: nil balance:  0 height:  0 <br> 60 left:   7 right:  62 balance:  0 height:  1<br> 62 left: nil right: nil balance:  0 height:  0 <br>129 left:  60 right: 239 balance:  0 height:  2 <br>213 left: nil right: nil balance:  0 height:  0 <br>239 left: 213 right: 240 balance:  0 height:  1 <br>240 left: nil right: nil balance:  0 height:  0 <br>------------------ <br>Insert (152 Dia)   <br>  7 left: nil right: nil balance:  0 height:  0 <br> 60 left:   7 right:  62 balance:  0 height:  1<br> 62 left: nil right: nil balance:  0 height:  0<br>129 left:  60 right: 239 balance: -1 height:  3<br>152 left: nil right: nil balance:  0 height:  0 <br>213 left: 152 right: nil balance:  1 height:  1 <br>239 left: 213 right: 240 balance:  1 height:  2 <br>240 left: nil right: nil balance:  0 height:  0<br>------------------ <br>Insert (179 Hanamaru) <br>  7 left: nil right: nil balance:  0 height:  0 <br> 60 left:   7 right:  62 balance:  0 height:  1 <br> 62 left: nil right: nil balance:  0 height:  0 <br>129 left:  60 right: 239 balance: -1 height:  3 <br>152 left: nil right: nil balance:  0 height:  0 <br>179 left: 152 right: 213 balance:  0 height:  1 <br>213 left: nil right: nil balance:  0 height:  0 <br>239 left: 179 right: 240 balance:  1 height:  2<br>240 left: nil right: nil balance:  0 height:  0<br>------------------ <br>(7, Ruby) -&gt; (60, Chika) -&gt; (62, Yoshiko) -&gt; (129, You) -&gt; (152, Dia) -&gt; (179, Hanamaru) -&gt; (213, Kanan) -&gt; (239, Mari) -&gt; (240, Riko) -&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OUxdnBUIMKTHouWMU0hJIQ.png" /><figcaption>Figure 7(a)~(e). <strong>(a)</strong> Add (60, Chika) <strong>(b)</strong> Add (You, 129) (c) Add (Ruby, 7) <strong>(d)</strong> Add (Riko, 240) <strong>(e)</strong> Add (Yoshiko, 62)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgsB7D-zNLT1uZ6PKXqP_Q.png" /><figcaption>Figure 7(f)~(g). <strong>(f)</strong> Add (Mari, 239) <strong>(g)</strong> After rebalancing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*3HuCrZxEOv2RyWIrMJJUgw.png" /><figcaption>Figure 7(h)<strong>.</strong> Add (Kanan, 213)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*jPCJ9bb3s1KKMwd-6hoSTw.png" /><figcaption>Figure 7(i). After rebalancing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*-EDt2OIIfVm--NW5j0fPAQ.png" /><figcaption>Figure 7(j). Add (Dia, 152)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*JF4iInKhUbN1vMZwXEitVA.png" /><figcaption>Figure 7(k). Add (Hanamaru, 179)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*tZADWH7cafXw4vdj70lgMw.png" /><figcaption>Figure 7(l). After rebalancing</figcaption></figure><h3>Delete</h3><p>It is too complex to introduce both deletion and insertion in the same article. Therefore, I will explain how to delete a node in an AVL tree in another article.</p><p><a href="https://ksw2000.medium.com/implement-an-avl-tree-with-go-part-ii-68f5c1f71e50">Implement an AVL Tree with Go (Part II) | by Kashiwa | Sep, 2023 | Medium</a></p><p><strong>See full code here:</strong> <a href="https://github.com/ksw2000/Medium/tree/main/implement-an-avl-tree-with-go">https://github.com/ksw2000/Medium/tree/main/implement-an-avl-tree-with-go</a></p><p><strong>See the relative articles:</strong></p><ol><li>Implement a Binary Search Tree with Go: <a href="https://medium.com/@ksw2000/implement-a-binary-search-tree-with-go-969e716cc471">https://medium.com/@ksw2000/implement-a-binary-search-tree-with-go-969e716cc47</a></li></ol><p><strong>Reference:</strong></p><ol><li><a href="https://github.com/karask/go-avltree/blob/master/avltree.go">https://github.com/karask/go-avltree/blob/master/avltree.go</a></li><li><a href="https://www.geeksforgeeks.org/avl-tree-set-1-insertion/">https://www.geeksforgeeks.org/avl-tree-set-1-insertion/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49e5952389d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use malloc and free in C?]]></title>
            <link>https://ksw2000.medium.com/how-to-use-malloc-and-free-in-c-9ffea31f56bd?source=rss-b570e94ee042------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ffea31f56bd</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[Kashiwa]]></dc:creator>
            <pubDate>Mon, 11 Apr 2022 13:22:55 GMT</pubDate>
            <atom:updated>2023-08-22T17:15:49.058Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p>The article shows the concepts of <strong>memory layout</strong>, <strong>malloc</strong>, <strong>pointer</strong>, <strong>array, 2D array, </strong>and <strong>void*</strong> in C language.</p><h3>Memory layout</h3><p>A program consists of the <strong>text segment</strong> and the <strong>data segment</strong>.</p><ul><li>The <em>text segment</em> includes executable instructions.</li><li>The <em>data segment</em> is more complex than the <em>text segment</em>.</li></ul><p>Fig.1 below is the classic memory layout of a program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*Q4oit06-Gx8ABlLzJcr7Rw.png" /><figcaption>Fig. 1 | Memory layout of a program.</figcaption></figure><ol><li><em>system</em>: stores command-line arguments.</li><li><em>text</em>: contains executable instructions.</li><li><em>data</em>, <em>bss</em>: <strong>global variable</strong> and <strong>static variable.</strong> The former stores initialized data, and the latter stores the uninitialized data.</li><li><em>stack</em>: <strong>local variable</strong> in function. All local variables in a function appear in memory only when the function is called.</li><li><em>heap</em>: provide a space for you to dynamic memory allocation. This space is managed by the OS. You can allocate space and release through OS. We usually use malloc() to allocate space without initialization, however, you can use calloc() to allocate zero-filled space.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8f6f7a599f3bda62bda409728ac12c8/href">https://medium.com/media/a8f6f7a599f3bda62bda409728ac12c8/href</a></iframe><h3>1D Array</h3><p>Before introducing how to use malloc(), we need to review a basic array in C. In fact, an array is a fixed block of memories. For example, we can declare an int array {10, 20, 30} before runtime.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fb8bfdd904f022585bbd6f2d7514296/href">https://medium.com/media/9fb8bfdd904f022585bbd6f2d7514296/href</a></iframe><pre>sizeof(int): 4<br>list[0]: 000000000061FE14<br>list[1]: 000000000061FE18<br>list[2]: 000000000061FE1C</pre><p>Observe that list+1 does not mean list+1byte! Instead, list+1 means list+sizeof(int) i.e., list+4bytes.</p><blockquote>The decision of how many bytes C language offsets is the <strong>type of variable</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FX1ZhsLP8K4HPBLFGY1Xzg.png" /><figcaption>Fig. 2 | Offset of a pointer.</figcaption></figure><h3>2D Array</h3><p>How about a 2D array?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc1e615aa0da496e57c9fd82d5eb7b9b/href">https://medium.com/media/bc1e615aa0da496e57c9fd82d5eb7b9b/href</a></iframe><pre>sizeof(int): 4<br>list[0][0]: 000000000061FE00 list[0][1]:000000000061FE04<br>list[1][0]: 000000000061FE08 list[1][1]:000000000061FE0C<br>list[2][0]: 000000000061FE10 list[2][1]:000000000061FE14</pre><p>A 2D array is more complex than a 1D array.</p><pre>&amp;list[2][1] = *(list+2)+1</pre><pre>list        = 0x61FE00<br>list+2      = 0x61FE00+0x10 = 0x61FE10 (base+<strong>2*sizeof(int)*2</strong>)<br>*(list+2)+1 = 0x61FE10+0x04 = 0x61FE14 (base+<strong>1*sizeof(int)</strong>)</pre><p>2 does not mean 2 bytes, instead, 2 means 2* sizeof(int)*2 i.e., 16 (0x10).</p><blockquote>It is very important that the type of variable affects the offset of a pointer.</blockquote><h3>Malloc() &amp; Free()</h3><p>It is common that we cannot declare an array in <em>bss</em>, <em>data,</em> or <em>stack</em> segment without knowing the length of the list before runtime. Nevertheless, we can use a system call to request our operating system (OS) to give us a contiguous space in the <em>heap segment</em> at runtime.</p><p><strong>malloc()</strong> returns the first pointer of the contiguous spaces. We can release the same space by calling <strong>free()</strong>. Notice that free() releases <strong>the same</strong> spaces you allocate. That is, if you allocate 64 bytes at 0x10, you can call free(0x10) to release 64 bytes — you cannot call free(0x14). There is no function in the standard C library that is able to return the number of bytes you allocate by given the first pointer of the spaces you allocated. However, you shouldn’t worry about that free() does know or does not know how many bytes you allocate.</p><ol><li><strong>malloc(<em>b</em>)</strong> allocates <em>b</em>-byte contiguous memory by requesting OS (if need) and returns the first address of the space you allocated. The return type is <em>void*</em> because it is hardly necessary for the type of pointer.</li><li>If there is not sufficient space, malloc() returns NULL. Thus, you must check that the pointer that malloc() returned is non-null.</li><li><strong>free(<em>p</em>)</strong> deallocates memories by given the first pointer of contiguous memory.</li></ol><h3>void*</h3><p>void* is a type that can store any pointer. Well, why do we need int*, char* , and other pointer types? Wanting to fetch the value to which the pointer points, we do not know how many bytes we should fetch, for example, int needs to read 4 bytes while char needs to read only 1 byte.</p><p>In pure C language, <em>void*</em> can automatically convert to any type of pointers without explicitly converting. However, in C++, you <strong>must</strong> convert the type explicitly — but, why don’t you use <strong>new</strong>?</p><pre>int* p = (int*)malloc(sizeof(int));   // ok<br>int* p = malloc(sizeof(int));         // ok and concise</pre><p>You can not directly fetch the value that <em>void*</em> points to because the compiler does not know how many bytes it should fetch.</p><pre>int num = 10;<br>void* p = malloc(sizeof(int));<br>*p = 10; // ERROR!!</pre><h3>Dynamically allocate the 1D array</h3><p>1D array is a contiguous memory. For example, if we want to make an integer list that has 5 elements, we can allocate <em>5*sizeof(int)</em> spaces.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f15d3746ea94632a1b74a97b6754f4e/href">https://medium.com/media/2f15d3746ea94632a1b74a97b6754f4e/href</a></iframe><h3>Dynamically allocate the 2D array</h3><p>How to allocate a 2D array with 3 rows and 5 columns?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*JPsv1O7Vpg5vbXteCvZvdw.png" /><figcaption>Fig. 3 | Assume that sizeof(int*) = 8 and sizeof(int) = 4 in x86_64 system.</figcaption></figure><p>We can allocate a list that has 3 rows, i.e., a list can store 3 pointers of integer. Each one of the integer pointers (Fig.3 left) points to a 1d array(Fig. 3 right).</p><p>As for release, how do free those spaces? We should free 4 pointers separately.</p><blockquote>1. the int** that points to the list<br>2. the int* that points to list[0]<br>3. the int* that points to list[1]<br>4. the int* that points to list[2]</blockquote><p>Notice that malloc() and free() may interact with OS by system call which spends more time and reduce performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab94362d36b0116ba0cbb89be9a436ed/href">https://medium.com/media/ab94362d36b0116ba0cbb89be9a436ed/href</a></iframe><p>When you fetch array2D[1][3], the program will fetch array2D[1] first, i.e., *(array2D+1) , and then fetch array2D[1][3] *(*(array2D+1)+3)</p><p>Observe that if we want to make a <em>3*5</em> 2D array, we not only need <em>15</em> spaces to store integers but need additional <em>3</em> spaces in order to store the pointer of integers. It is caused by our program that unknown what the size of one column is (except for <strong>static declaration</strong>)</p><p><em>static declaration:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aaf2ce58f6c68488deea633349f77fc6/href">https://medium.com/media/aaf2ce58f6c68488deea633349f77fc6/href</a></iframe><p><em>dynamic declaration:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a950dad0eb10fe03a69f40d9f36acc6f/href">https://medium.com/media/a950dad0eb10fe03a69f40d9f36acc6f/href</a></iframe><blockquote>The C compiler sees <strong>list1</strong> as <strong>int[4]</strong>.<br>The C compiler sees <strong>list2</strong> as an <strong>int pointer</strong>.</blockquote><h3>Dynamically allocate the contiguous 2D array</h3><p>The previous section needs to call malloc() 4 times when allocating and needs to call free() 4 times when deallocating. Can we just allocate by calling single malloc() and deallocate by calling single free() in order to improve performance?</p><p>We can allocate all spaces we need at once. If we need a <em>3*5</em> 2D array, we at least need <em>sizeof(int)*3*5</em> bytes to store all elements. Besides, we need additional spaces to store integer pointers that point to the first element of rows, called <em>overhead</em> in the below example code. After allocating, we make the first 8 bytes point to list[0][0], and then make the second 8 bytes point to list[1][0], …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*Fwmj2R-QGdaAjSKda_mxpQ.png" /><figcaption>Fig.4(a) | Cotiguous allocate a 2D array where list[0] list[1] list[2] stores int* value. list[m][n] stores int value. Assume that sizeof(int*) = 8 and sizeof(int) = 4 in x86_64 system.</figcaption></figure><p>Assume that int** list = 0x00. When we fetch list[1][3], the program:</p><ol><li>fetch list+1 where 1 is 1*sizeof(int*) =&gt; 8bytes<br>i.e., fetch 0x00+0x08 = 0x08<br>0x08 stores the pointer to the list[1] i.e., 0x2C</li><li>list[1] = *list+1 = 0x2C (type: int*)</li><li>jump to *(list+1)+3 = 0x2C+3 where 3 is 3*sizeof(int) =&gt; 12bytes<br>i.e., fetch 0x2C+0x0C = 0x38<br>0x38 stores the value of integer.</li></ol><pre>&amp;list[1][3] = *(list+1)+3</pre><pre>list        = 0x00<br>list+1      = 0x00+0x08 = 0x08 (base+1*sizeof(int))<br>*(list+1)   = 0x2C<br>*(list+1)+3 = 0x2C+0x0C = 0x38</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*fA59JhbxWQMbE8HNaFKdNA.png" /><figcaption>Fig. 4(b) | Show the address of spaces in 3(a)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21ae816afd56c1abc1df73ee5176b3a8/href">https://medium.com/media/21ae816afd56c1abc1df73ee5176b3a8/href</a></iframe><h3>Conclusion</h3><ol><li>The type of variable affects the offset of a pointer.</li><li>malloc() and free() are symmetric. You can only call free() as many times as you call malloc(). In addition, you can only free() the space which is allocated at runtime. i.e., you can NOT free the space in the <em>bss segment, data segment,</em> or<em> stack segment.</em></li><li>malloc() is a kind of system call so you should call them as little as possible.</li><li>void* is just a type that can store a pointer. If you want to fetch the value pointed to by a void*, please convert the type first.</li><li>See full code at: <a href="https://github.com/ksw2000/Medium/tree/main/how-to-use-malloc-and-free-in-C">https://github.com/ksw2000/Medium/tree/main/how-to-use-malloc-and-free-in-C</a></li></ol><h3>Reference</h3><ol><li><a href="https://www.geeksforgeeks.org/memory-layout-of-c-program/">https://www.geeksforgeeks.org/memory-layout-of-c-program/</a></li><li><a href="https://blog.gtwang.org/programming/memory-layout-of-c-program/">https://blog.gtwang.org/programming/memory-layout-of-c-program/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ffea31f56bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manage Node.js Version by NVM]]></title>
            <link>https://ksw2000.medium.com/manage-node-js-version-by-nvm-3887edf66c2e?source=rss-b570e94ee042------2</link>
            <guid isPermaLink="false">https://medium.com/p/3887edf66c2e</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[node]]></category>
            <dc:creator><![CDATA[Kashiwa]]></dc:creator>
            <pubDate>Tue, 22 Mar 2022 09:37:59 GMT</pubDate>
            <atom:updated>2022-03-22T09:37:59.258Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*mhaX4gf4uEXTCsb1gFcC0w.png" /></figure><p>Consider that you have multiple NVM projects. One of them dependents on node v14, and one of them dependents on node v16. How to switch different versions of nodes?</p><h4>What is NVM?</h4><p>NVM, Node Version Manager, allows you to quickly install and use different versions of Node via the command line. You can see the NVM project on <a href="https://github.com/nvm-sh/nvm">https://github.com/nvm-sh/nvm</a></p><p><a href="https://github.com/nvm-sh/nvm">GitHub - nvm-sh/nvm: Node Version Manager - POSIX-compliant bash script to manage multiple active node.js versions</a></p><h4>Install NVM on Linux</h4><p>It is not difficult to install nvm on Linux. You can see instructions on <a href="https://github.com/nvm-sh/nvm#install--update-script">https://github.com/nvm-sh/nvm#install--update-script</a>.</p><p>At the beginning, download NVM and run the shell script by curl or wget.</p><pre>curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash</pre><p>or</p><pre>wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash</pre><p>The above script will set environment variables automatically in ~/.bashrc. However, we should restart the terminal to apply new environment variables or instead use source ~/.bashrc.</p><pre>source ~/.bashrc</pre><p>If you do not know what is barshrc, I found some pages that introduces bashrc.</p><ol><li>English: <a href="https://www.journaldev.com/41479/bashrc-file-in-linux">https://www.journaldev.com/41479/bashrc-file-in-linux</a></li><li>Chinese: <a href="https://www.itread01.com/content/1542833526.html">https://www.itread01.com/content/1542833526.html</a></li></ol><h4>Install NVM on Windows</h4><p>NVM does not supports Windows but there is a similar tool called nvm-windows .</p><p><a href="https://github.com/coreybutler/nvm-windows">GitHub - coreybutler/nvm-windows: A node.js version management utility for Windows. Ironically written in Go.</a></p><ol><li>Download installation executable file. <a href="https://github.com/coreybutler/nvm-windows/releases">https://github.com/coreybutler/nvm-windows/releases</a></li><li>Install.</li><li>Restart command line.</li><li>After installation. Type nvm version to check. If command line still can not find the path of nvm, please set environment variable manually .</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*cL5XlqjOPLqZOAHuG_lFYA.png" /><figcaption>See NVM’s version.</figcaption></figure><p>In my opinion, do not install NVM by chocolatey directly, because the version of nvm-windows on chocolatey is out of date. The new version of node.js is not supported by the older nvm-windows.</p><h4>Install Node by NVM.</h4><p>Instead of installing different NVM by yum or apt-install , in my experience, I recommend that install Node.js by NVM.</p><p>For example, if you want to install Node.js v16.14.2</p><pre>nvm install 16.14.2</pre><p>Besides, you can list all versions of Node.js on your environment by nvm list</p><pre>nvm list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*FQmZofrOiC6hAko6X1h8dg.png" /><figcaption>nvm list on windows 11</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*AAYcUx4MviAFQjeAJkG5Cw.png" /><figcaption>nvm list on Ubuntu 18</figcaption></figure><h4>Switch difference versions of Node by NVM</h4><p>After listing all the versions of Nodes. You can use one of them by nvm use</p><p>For example, if we have 3 versions of nodes</p><ol><li>Node v17.5.0</li><li>Node v16.6.1</li><li>Node v14.17.13</li></ol><p>We can switch to v16.6.1 by nvm use 16.6.1 or just nvm use 16</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*3HofeD-CgsJTBfLIyzbjXw.png" /><figcaption>Notice that I installed gsudo on my Windows. If you do not install gsudo in advance, please run the command on the administrative mode.</figcaption></figure><h4>Reference</h4><ol><li><a href="https://editor.leonh.space/2021/nvm/">https://editor.leonh.space/2021/nvm/</a></li><li><a href="https://www.onejar99.com/nvm-install-for-windows/">https://www.onejar99.com/nvm-install-for-windows/</a></li><li><a href="https://community.chocolatey.org/packages/nvm">https://community.chocolatey.org/packages/nvm</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3887edf66c2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement a Binary Search Tree with Go]]></title>
            <link>https://ksw2000.medium.com/implement-a-binary-search-tree-with-go-969e716cc471?source=rss-b570e94ee042------2</link>
            <guid isPermaLink="false">https://medium.com/p/969e716cc471</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[trees]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Kashiwa]]></dc:creator>
            <pubDate>Thu, 03 Feb 2022 07:01:17 GMT</pubDate>
            <atom:updated>2023-09-11T19:31:16.861Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p>Learning how to insert a new node and delete an existing node in a binary search tree with Go language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ir8xLZgqMayEBOKpOyRFgQ.png" /><figcaption>Cover photo</figcaption></figure><p>Update: 2022/10/27. Use a more intuitive method to implement a node of binary search tree and introduce the search method. Besides, provide 2 methods to implement inorder traversal.</p><p>Update: 2023/08/03. Bug fixes in Delete(). When replacing the deleted node with the successor, we should update not only the value but also the key.</p><p>Update: 2023/09/12. Give some alternative methods to implement node insertion and then compare the performance of iterative insertion and recursive insertion.</p><h3>What is a binary search tree?</h3><blockquote>In computer science, a <strong>binary search tree</strong> (<strong>BST</strong>), also called an <strong>ordered</strong> or <strong>sorted binary tree</strong>, is a rooted binary tree data structure whose internal nodes each store a key greater than all the keys in the node’s left subtree and less than those in its right subtree. The time complexity of operations on the binary search tree is directly proportional to the height of the tree.</blockquote><blockquote>— <a href="https://en.wikipedia.org/wiki/Binary_search_tree">wikipedia</a></blockquote><p>BST has some properties:</p><ul><li>The left subtree of a node contains only nodes with keys lesser than the node’s key.</li><li>The right subtree of a node contains only nodes with keys greater than the node’s key.</li><li>The left and right subtree each must also be a binary search tree.</li></ul><h3>Insert</h3><p>Insert() inserts a given new node to the given tree. Let’s see its abstract data type.</p><pre>// The abstract data type for binary search tree.<br>type BSTNode struct {<br>    Key   int<br>    Val   interface{}<br>    left  *BSTNode<br>    right *BSTNode<br>}<br><br>type BST struct {<br>    root *BSTNode<br>}</pre><p>If we have no root node, we must create a new node and set the new node as the root of the tree.</p><p>When inserting the new node, put the smaller node to the left part and the greater node to the right part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*GhwUo2sgrsUui1XqVpfdYw.png" /><figcaption>Figure1. An example of inserting new nodes into a binary search tree.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfIjwwSqfrKDqOjgeMvxtQ.png" /><figcaption>Figure2. An example of inserting new nodes into a binary search tree.</figcaption></figure><p>In order to implement insert() method, we can modify the pointer that points to the new node. For example, see figure 2(d), if we want to add (Ruby, 154) to the tree, we can modify the member rightin (Hanamaru, 152). We can modify the value (hanamaru.right) by using its pointer (&amp;hanamaru.right).</p><pre>func (b *BST) Insert(n *BSTNode) {<br>    // super is the pointer of the pointer<br>    // that points to the new node<br>    super := &amp;b.root<br>    for *super != nil {<br>        if n.Key &lt; (*super).Key {<br>            super = &amp;(*super).left<br>        } else {<br>            super = &amp;(*super).right<br>        }<br>    }<br>    *super = n<br>}</pre><p>The type of super at line 4 is **Node . It is a pointer of the pointer that points to the new node. We can modify the pointer that points to the new node by super.</p><p>There is an alternative way to implement insertion without using pointers. Pointers are more complex and less efficient to operate in Go and other common programming languages.</p><pre>func (b *BST) Insert2(n *BSTNode) {<br>    var parent *BSTNode<br>    current := b.root<br>    for current != nil {<br>        parent = current<br>        if n.Key &lt; current.Key {<br>            current = current.left<br>        } else {<br>            current = current.right<br>        }<br>    }<br>    if parent != nil {<br>        if parent.Key &gt; n.Key {<br>            parent.left = n<br>        } else {<br>            parent.right = n<br>        }<br>    } else {<br>        b.root = n<br>    }<br>}</pre><p>Node insertion can also be implemented recursively. Nevertheless, the recursive function consumes more memory to maintain a stack, making it usually less efficient than the iterative one.</p><pre>func (b *BST) InsertRec(n *BSTNode) {<br>    b.root = b.root.insertRec(n)<br>}<br><br>func (b *BSTNode) insertRec(n *BSTNode) *BSTNode {<br>    if b == nil {<br>        return n<br>    }<br>    if n.Key &lt; b.Key {<br>        b.left = b.left.insertRec(n)<br>    } else if n.Key &gt; b.Key {<br>        b.right = b.right.insertRec(n)<br>    }<br>    return b<br>}</pre><p>We can simply compare the performance of these functions by continuously inserting nodes.</p><pre>func generateData(size int) []int {<br>    r := rand.New(rand.NewSource(0))<br>    list := make([]int, size)<br>    for i := range list {<br>        list[i] = i<br>    }<br>    r.Shuffle(len(list), func(i, j int) {<br>        list[i], list[j] = list[j], list[i]<br>    })<br>    return list<br>}<br><br>func BenchmarkInsertIterative(b *testing.B) {<br>    for n := 0; n &lt; b.N; n++ {<br>        list := generateData(4096)<br>        tree := new(BST)<br>        for i := range list {<br>            tree.Insert(&amp;BSTNode{Key: list[i]})<br>        }<br>    }<br>}<br><br>func BenchmarkInsertIterative2(b *testing.B) {<br>    for n := 0; n &lt; b.N; n++ {<br>        list := generateData(4096)<br>        tree := new(BST)<br>        for i := range list {<br>            tree.Insert2(&amp;BSTNode{Key: list[i]})<br>        }<br>    }<br>}<br><br>func BenchmarkInsertRecursive(b *testing.B) {<br>    for n := 0; n &lt; b.N; n++ {<br>        list := generateData(4096)<br>        tree := new(BST)<br>        for i := range list {<br>            tree.InsertRec(&amp;BSTNode{Key: list[i]})<br>        }<br>    }<br>}</pre><pre>&gt; go test -bench=BenchmarkInsert -run=none<br>goos: windows<br>goarch: amd64<br>pkg: example.com<br>cpu: Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz<br>BenchmarkInsertIterative-8          2076            541820 ns/op<br>BenchmarkInsertIterative2-8         2152            531405 ns/op<br>BenchmarkInsertRecursive-8          1842            659766 ns/op<br>PASS<br><br>&gt; go version<br>go version go1.20.1 windows/amd64</pre><h3>Search</h3><p>search() gets the value in the tree by given a key.</p><p>It is not difficult to implement the search() method. At the first, initialize a current node which is the root of the node. Only if the node is non-nil, compare the key of current and the key you want to find. If the key you want to search is smaller than the current key, go to the left child node, otherwise, go to the right child node.</p><pre>func (b *BST) Search(key int) (n *BSTNode, found bool) {<br>    for current := b.root; current != nil; {<br>        if current.Key == key {<br>            return current, true<br>        } else if key &lt; current.Key {<br>            current = current.left<br>        } else {<br>            current = current.right<br>        }<br>    }<br>    return nil, false<br>}</pre><h3>Inorder Traverse</h3><p>In this section, I give two methods to implement traversal, recursive and iterative one. The front one is easier than the later one.</p><p>We can use inorder traversal to list the nodes in the tree in increasing order. It is the simplest way to implement inorder traverse by recursive.</p><pre>// Recursively inorder traverse.<br>func (n *BSTNode) do(do func(*BSTNode)) {<br>    if n != nil {<br>        n.left.do(do)<br>        do(n)<br>        n.right.do(do)<br>    }<br>}<br><br>func (b *BST) Do(do func(*BSTNode)) {<br>    b.root.do(do)<br>}</pre><p>Moreover, I provide the other version — an iterative way.</p><pre>// Iteratively inorder traverse.<br>func (b *Bst) List() []*Node {<br>    // ret is a list records ordered nodes<br>    // that will be returned<br>    ret := []*Node{}<br>    stack := []*Node{}<br>    current := b.root<br>    for len(stack) != 0 || current != nil {<br>        if current != nil {<br>            // push current into stack<br>            stack = append(stack, current)<br>            current = current.left<br>        } else {<br>            // pop stack<br>            current = stack[len(stack)-1]<br>            stack = stack[:len(stack)-1]<br>            ret = append(ret, current)<br>            current = current.right<br>        }<br>    }<br>    return ret<br>}</pre><p>It is not easy to understand this version. We can think that when the left child is non-null, we can directly visit it and record the path by pushing them to the stack. Until meeting the nil node, we pop the stack, record the value we popped and go to the right child node.</p><h3>Delete</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*UM7TN28q5b3OEGwj9HTP8Q.png" /><figcaption>Figure 3. An example of a binary search tree.</figcaption></figure><p>It is more difficult to delete a node than insert a node. There are 3 cases that would happen.</p><ol><li>If the deleted node has no child.</li><li>If the deleted node has only one left child or only one right child.</li><li>If the deleted node has both left child and right child.</li></ol><p>It is easy to implement delete() on case 1 or case 2. Let the pointer that points to the deleted node be super. If the deleted node has left child set super = deleted_node.left , else super = delted_node.right . Note that because case 1 has neither left child nor right child. Because case 1 does not have left child we execute the code super_pointer = deleted_node.right where deleted_node.right is nil. That is to say, case1 and case2 is the same case.</p><p><strong>Delete (Mari, 163) who has no children</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*IPD7z7y-S7L0ZfByCkDgLQ.png" /><figcaption>Figure 4. delete Mari who has no children.</figcaption></figure><p><strong>Delete (Ruby, 154) who has only right child</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*WxDETYaeOkQTmF8XIC05Rg.png" /><figcaption>Figure 5. Delete Ruby who has only one child.</figcaption></figure><p><strong>Delete (Hanayo, 156) who has both left child and right child</strong></p><ol><li>Find the successor. The node that is printed after the node we want to delete if we inorder traverse this binary search tree. In other words, find the smallest node in the right subtree. We can jump to the right child and go as left as possible. (Hanayo)→(Maki)→(Riko)→(You)</li><li>Replace deleted node (Hanayo) with the successor (You)</li><li>The pointer that points to the successor should be changed to point to the successor’s children. In fact, the successor only has right child because if it has left child, then it is not a successor. That is to say, we only need to set “the pointer that points to the successor” to “the successor’s right subtree”.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*N5EweVkzXhxBzGXKpO0VQg.png" /><figcaption>Figure 6. Find successor.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQi7O-kfZYslvMK1rUcqRA.png" /><figcaption>Figure 7. Replace deleted node with successor and connect the parent of successor to the child of successor.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/245e998349c3392ab81cfd5fa576e00e/href">https://medium.com/media/245e998349c3392ab81cfd5fa576e00e/href</a></iframe><h3><strong>Test</strong></h3><pre>// go test -v -run TestBST<br>func TestBST(t *testing.T) {<br>    nodes := []*person{<br>        {&quot;Hanayo&quot;, 156}, {&quot;Hanamaru&quot;, 152}, {&quot;Maki&quot;, 161},<br>        {&quot;Ruby&quot;, 154}, {&quot;Riko&quot;, 160}, {&quot;Eli&quot;, 162}, {&quot;Mari&quot;, 163},<br>        {&quot;Chisato&quot;, 155}, {&quot;You&quot;, 157}, {&quot;Ayumu&quot;, 159},<br>    }<br>    <br>    // Create a new binary search tree<br>    tree := new(BST)<br>    <br>    // Insert node to the tree<br>    for _, n := range nodes {<br>        tree.Insert(NewBSTNode(n.tall, n.name))<br>    }<br>    <br>    // print the tree inorder (way I, recursive)<br>    tree.Do(func(node *BSTNode) {<br>        fmt.Printf(&quot;(%d, %v)-&gt;&quot;, node.Key, node.Val)<br>    })<br>    fmt.Println(&quot;nil&quot;)<br>    <br>    // Print the tree inorder (way II, iterative)<br>    for _, node := range tree.List() {<br>        fmt.Printf(&quot;(%d, %v)-&gt;&quot;, node.Key, node.Val)<br>    }<br>    fmt.Println(&quot;nil&quot;)<br>    <br>    // Delete some nodes in tree<br>    tree.Delete(nodes[6].tall)<br>    tree.Delete(nodes[3].tall)<br>    tree.Delete(nodes[0].tall)<br>    <br>    for _, node := range tree.List() {<br>        fmt.Printf(&quot;(%d, %v)-&gt;&quot;, node.Key, node.Val)<br>    }<br>    fmt.Println(&quot;nil&quot;)<br>    <br>    // Search by key: 152<br>    if n, exist := tree.Search(152); exist {<br>        fmt.Println(152, n.Val)<br>    }<br>}</pre><p>Note that you can run the test function by running go test. You can also enable verbose mode by setting the -v flag.</p><p>Result:</p><pre>(152, Hanamaru)-&gt;(154, Ruby)-&gt;(155, Chisato)-&gt;(156, Hanayo)-&gt;(157, You)-&gt;(159, Ayumu)-&gt;(160, Riko)-&gt;(161, Maki)-&gt;(162, Eli)-&gt;(163, Mari)-&gt;nil<br>(152, Hanamaru)-&gt;(154, Ruby)-&gt;(155, Chisato)-&gt;(156, Hanayo)-&gt;(157, You)-&gt;(159, Ayumu)-&gt;(160, Riko)-&gt;(161, Maki)-&gt;(162, Eli)-&gt;(163, Mari)-&gt;nil<br>(152, Hanamaru)-&gt;(155, Chisato)-&gt;(157, You)-&gt;(159, Ayumu)-&gt;(160, Riko)-&gt;(161, Maki)-&gt;(162, Eli)-&gt;nil<br>152 Hanamaru</pre><p>Furthermore, we can design a more complex test function to check the correctness of the insertion and deletion operations.</p><pre>// go test -run TestBSTCorrectness<br>func TestBSTCorrectness(t *testing.T) {<br>    // generate an int list<br>    data := generateData(1024)<br>    // create an empty binary search tree<br>    tree := new(BST)<br>    // insert data<br>    for i := range data {<br>        tree.Insert(&amp;BSTNode{Key: data[i]})<br>    }<br><br>    // check the binary search tree is in increasing order<br>    // and the total number of nodes is equal to the length of `data`<br>    i := 0<br>    start := 0<br>    tree.Do(func(b *BSTNode) {<br>        if b.Key &gt;= start {<br>            start = b.Key<br>        } else {<br>            t.Fail()<br>        }<br>        i++<br>    })<br>    if i != len(data) {<br>        t.Fail()<br>    }<br>    <br>    // check that we can access all element by tree.Search()<br>    for i := range data {<br>        _, found := tree.Search(data[i])<br>        if !found {<br>            t.Fail()<br>        }<br>    }<br>    <br>    // check that we can remove each nodes<br>    k := len(data)<br>    for i := range data {<br>        tree.Delete(data[i])<br>        k--<br>        // check that the tree is in increasing order<br>        // and the total number of nodes is equal properly<br>        if i%32 == 0 {<br>            n := 0<br>            start := 0<br>            tree.Do(func(b *BSTNode) {<br>                if b.Key &gt;= start {<br>                    start = b.Key<br>                } else {<br>                    t.Fail()<br>                }<br>                n++<br>            })<br>            if n != k {<br>                t.Fail()<br>            }<br>        }<br>    }<br>}</pre><p>See the full code: <a href="https://github.com/ksw2000/Medium/tree/main/implement-a-binary-search-tree-with-go">https://github.com/ksw2000/Medium/tree/main/implement-a-binary-search-tree-with-go</a></p><p>See the relative articles:</p><ol><li>Implement an AVL Tree with Go: <a href="https://ksw2000.medium.com/implement-an-avl-tree-with-go-49e5952389d4">https://ksw2000.medium.com/implement-an-avl-tree-with-go-49e5952389d4</a></li></ol><p>Reference:</p><ol><li><a href="https://www.geeksforgeeks.org/binary-search-tree-data-structure/">https://www.geeksforgeeks.org/binary-search-tree-data-structure/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=969e716cc471" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement ResNet with PyTorch]]></title>
            <link>https://towardsdev.com/implement-resnet-with-pytorch-a9fb40a77448?source=rss-b570e94ee042------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9fb40a77448</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kashiwa]]></dc:creator>
            <pubDate>Thu, 27 Jan 2022 07:50:05 GMT</pubDate>
            <atom:updated>2023-09-12T08:51:59.429Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>This tutorial shows you how to build ResNet by yourself</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDM827OAo010YTRh5SNYgQ.jpeg" /></figure><p>Increasing network depth does not work by simply stacking layers together. Deep networks are hard to train because of the notorious “vanishing gradient problem” — as the gradient is back-propagated to earlier layers, repeated multiplication may make the gradient definitively small.</p><p>ResNet uses a technic called “Residual” to deal with the “vanishing gradient problem”. When stacking layers, we can use a “shortcut” to link<br>discontinuous layers. i.e., We can skip some layers, as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*rj6SSHtBfBZXKSgC.png" /><figcaption>A residual block</figcaption></figure><p>Before you read this article, I assume you already know what a convolutional, fully connected network is. In addition, you should be familiar with python and PyTorch.</p><h3>nn.Conv2d in PyTorch</h3><p>Let’s see how to use nn.Conv2d in PyTorch.</p><pre>import torch<br>from torch import nn<br>nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0)</pre><ol><li>in_channels: the number of input channels.</li><li>out_channels: the number of output channels.</li><li>kernel_size: the size of the convolving kernel. We will use 1, 3, 7 in the following tutorial.</li><li>stride: controls the stride for the cross-correlation, a single number or a tuple.</li><li>padding: padding added to all four sides of the input. (in TensorFlow, we can conveniently use valid or same , however in PyTorch how to implement padding=same ?)</li></ol><h4>Calculate the output size</h4><p>In PyTorch, we always use channel_first format. The shape of the tensor is (<em>b</em>, <em>c</em>, <em>h</em>, <em>w</em>), where</p><ul><li><em>b</em> is a batch size</li><li><em>c</em> denotes the number of channels</li><li><em>h</em> is the height of input planes in pixels</li><li><em>w</em> is the width in pixels</li></ul><p>output = floor[(input + 2*padding — kernel) / stride + 1]</p><p>For example, if input = (64, 64) padding = 1 kernel=3 stride=2, what is the size of output? output = (32, 32)</p><h3>ResNet18, 34</h3><p>There are many kinds of ResNet thus we see the simplest, ResNet18, firstly. Assume that our input is a 224*224 RGB image, and the output is 1000 classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*79p7WhWeMd54YRYr.png" /><figcaption>Table1. Architectures for ImageNet. Building blocks are shown in brackets, with the numbers of blocks stacked. Downsampling is performed by conv3_1, conv4_1, and conv5_1 with a stride of 2.</figcaption></figure><p>There are 3 main components that make up the ResNet.</p><ol><li>input layer (conv1 + max pooling) (Usually referred to as layer 0)</li><li>ResBlocks (conv2 without max pooing ~ conv5) (Usually referred to as layer1 ~ layer4)</li><li>final layer</li></ol><h4>STEP0: ResBlocks (layer1~layer4)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/0*IF_xejpvftYqp7N_.png" /><figcaption>ResBlocks in Table1. 3x3 means the convolution kernels, 64 means the filters. x2 is repeating number.</figcaption></figure><p>The most important component is ResBlocks, Let’s see how to build it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0i47cDbwXQ2f3vQy899EA.png" /><figcaption>Firgure1. The structure of ResNet18</figcaption></figure><p>In the figure above, obviously, we have two kinds of shortcuts. One is with downsampling (stride = 2), and the other is without downsampling (stride = 1). Thus, we can implement them respectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d8c8893438388a15698f17efaac5e27/href">https://medium.com/media/1d8c8893438388a15698f17efaac5e27/href</a></iframe><h4>STEP1: Layer0</h4><p>Layer0 consists of a 7*7 convolution and a 3*3 max pooling.</p><pre>self.layer0 = nn.Sequential(<br>    nn.Conv2d(in_channels, 64, kernel_size=7, stride=2, padding=3),<br>    nn.MaxPool2d(kernel_size=3, stride=2, padding=1),<br>    nn.BatchNorm2d(64),<br>    nn.ReLU()<br>)</pre><h4>STEP2: Final layer</h4><p>The final layer consists of a global average pooling (gap) and a fully connected layer (fc). GAP calculates the mean of each feature map and then concatenates all the values into a one-dimension list.</p><pre>self.gap = torch.nn.AdaptiveAvgPool2d(1)<br>self.fc = torch.nn.Linear(filters[4], outputs)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*xjs_olH5AU3HYY9L.png" /><figcaption>Global average pooling. Picture from: <a href="https://peltarion.com/knowledge-center/documentation/modeling-view/build-an-ai-model/blocks/global-average-pooling-2d">https://peltarion.com/knowledge-center/documentation/modeling-view/build-an-ai-model/blocks/global-average-pooling-2d</a></figcaption></figure><h4>STEP3: Done!</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f0c3dc784dee0388f87d3582a5cff0a/href">https://medium.com/media/2f0c3dc784dee0388f87d3582a5cff0a/href</a></iframe><p>Print the full structure by calling summary().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b597bc592dcd2963636087d9e88203fc/href">https://medium.com/media/b597bc592dcd2963636087d9e88203fc/href</a></iframe><p>As for ResNet34, we just need to modify the number of repeating ResBlocks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05ee6d7e28c484cf4feec2e0684a62fd/href">https://medium.com/media/05ee6d7e28c484cf4feec2e0684a62fd/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25cc18ee874c1879cdec56c838f64e70/href">https://medium.com/media/25cc18ee874c1879cdec56c838f64e70/href</a></iframe><h3>ResNet50, 101, 152</h3><figure><img alt="Bottlebeck" src="https://cdn-images-1.medium.com/max/757/0*0lzo5xGQzkg2w57j.png" /><figcaption>Figure2. Left: a building block for ResNet-18/34. Right: a “bottleneck” building block for ResNet-50/101/152.</figcaption></figure><h4>STEP0: ResBottleneckBlock</h4><p>The most obvious difference between ResNet34 and ResNet50 is ResBlocks shown in figure2. We need to rewrite this component into a new one called “ResBottleneckBlock”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QrrLrxYeUqFD-JwtyJJgAQ.png" /><figcaption>Figure3. Left: conv2_1 in table1(shortcut needs to adjust channels). Middle: conv2_2, conv2_3 in table1 (shortcut does nothing). Right: conv3_1 in table1 (shortcut needs not only to adjust channels but also to downsample the feature map).</figcaption></figure><p>Try to implement a class that can build a ResBottleneckBlock when given input_channel , output_channel , and downsample . It is easy to build 3 major convolution blocks (self.conv1, self.conv2, self.conv3). Nevertheless, since there are 3 different types of shortcuts, creating shortcuts is not simple. In fact, we can think of these 3 different types as just 2 different shortcuts, the shortcut doing something and the shortcut doing nothing. When in_channels is not equal to out_channels or the downsample is set to be True, the shortcut needs to do something. On the other hand, the shortcut needs to do nothing.</p><p>Let’s see how to implement it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2d9e7bd6802fad223f286410088abfc/href">https://medium.com/media/c2d9e7bd6802fad223f286410088abfc/href</a></iframe><p>We can generate 3 types of ResBottleneckBlock separately, as shown in Figure 3.</p><ul><li>Left: ResBottleneckBlock(64, 256, downsample=False)</li><li>Middle: ResBottleneckBlock(256, 256, downsample=False)</li><li>Right: ResBottleneckBlock(256, 512, downsample=True)</li></ul><h4>STEP1: Done!</h4><p>In order to be compatible with ResNet18/34, we use a boolean variable useBottleneckto specify whether use bottleneck or not. That is to say, if we want to generate ResNet-18/34, set useBottleneck False. If we want to generate ResNet-50/101/152, set useBottleneck True.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f39a0e1d81735b44ba1a233da5444f7/href">https://medium.com/media/3f39a0e1d81735b44ba1a233da5444f7/href</a></iframe><p>See how do build ResNet by using class ResNet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2626b8a02a615796bcd9c5d081011ce7/href">https://medium.com/media/2626b8a02a615796bcd9c5d081011ce7/href</a></iframe><p>See full code here: <a href="https://github.com/ksw2000/ML-Notebook/blob/main/ResNet/ResNet_PyTorch.ipynb">https://github.com/ksw2000/ML-Notebook/blob/main/ResNet/ResNet_PyTorch.ipynb</a></p><h3>Reference</h3><ol><li><a href="https://arxiv.org/pdf/1512.03385.pdf">https://arxiv.org/pdf/1512.03385.pdf</a></li><li><a href="https://zhuanlan.zhihu.com/p/141998754">https://zhuanlan.zhihu.com/p/141998754</a></li><li><a href="https://blog.csdn.net/abc13526222160/article/details/90057121">https://blog.csdn.net/abc13526222160/article/details/90057121</a></li><li><a href="https://zhuanlan.zhihu.com/p/157134695">https://zhuanlan.zhihu.com/p/157134695</a></li><li><a href="https://ksw2000.medium.com/implement-resnet-with-tensorflow2-4ee81e33a1ac">https://ksw2000.medium.com/implement-resnet-with-tensorflow2-4ee81e33a1ac</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9fb40a77448" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/implement-resnet-with-pytorch-a9fb40a77448">Implement ResNet with PyTorch</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[熬夜又不傷身的方法]]></title>
            <link>https://ksw2000.medium.com/%E7%86%AC%E5%A4%9C%E5%8F%88%E4%B8%8D%E5%82%B7%E8%BA%AB%E7%9A%84%E6%96%B9%E6%B3%95-47fa5d444819?source=rss-b570e94ee042------2</link>
            <guid isPermaLink="false">https://medium.com/p/47fa5d444819</guid>
            <dc:creator><![CDATA[Kashiwa]]></dc:creator>
            <pubDate>Sun, 23 Jan 2022 18:15:13 GMT</pubDate>
            <atom:updated>2022-04-21T19:50:38.077Z</atom:updated>
            <content:encoded><![CDATA[<p>現代人常常事情做不完，或者需要熬夜追劇玩遊戲，但長期熬夜對身體不好，有沒有方法熬夜又不傷身呢？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UpkwdDrtOdlwql8nX8Y7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M5c4rJw8_kUM-Iif.jpg" /></figure><p>沒有，乖乖睡覺吧你！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*z44oGvTIfT3BejZJ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47fa5d444819" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement ResNet with TensorFlow2]]></title>
            <link>https://towardsdev.com/implement-resnet-with-tensorflow2-4ee81e33a1ac?source=rss-b570e94ee042------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ee81e33a1ac</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[resnet]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kashiwa]]></dc:creator>
            <pubDate>Sun, 23 Jan 2022 17:23:37 GMT</pubDate>
            <atom:updated>2022-12-19T14:25:55.209Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>This tutorial shows you how to build ResNet by yourself</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHXuzbaLJlkym4lq9m_GNA.png" /></figure><p>Increasing network depth does not work by simply stacking layers together. Deep networks are hard to train because of the notorious “vanishing gradient problem” — as the gradient is back-propagated to earlier layers, repeated multiplication may make the gradient definitively small.</p><p>ResNet uses a technic called “Residual” to deal with the “vanishing gradient problem”. When stacking layers, we can use a “shortcut” to link <br>discontinuous layers. i.e., We can skip some layers, as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*ZZu7tjjNvKhwCxog.png" /><figcaption>A residual block</figcaption></figure><p>Before you read this article, I assume you already know what a convolutional, fully connected network is. In addition, you should be familiar with python and tensorflow2.</p><h3>Conv2D in Tensorflow</h3><p>Let’s see how to use Conv2D in Tensorflow Keras.</p><pre>import tensorflow.keras as keras<br>from keras import layers<br>layers.Conv2D(filters, kernel_size, strides, padding)</pre><ol><li>filters: Integer, the dimensionality of the output space (aka output channels). e.g., if your input is (h, w, c) and you set filters=64, you will get output (h’, w’, 64). In TensorFlow, we do not need to consider the size of the input channels, however, in Pytorch we need to consider the size of the input channels</li><li>kernel_size: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. We will only use 1, 3, 7 in the following tutorial.</li><li>strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along with the height and width. Can be a single integer to specify the same value for all spatial dimensions.</li><li>padding: one of valid or same (case-insensitive). valid means no padding. same results in padding with zeros evenly to the left/right or up/down of the input. When padding=&quot;same&quot; and strides=1, the output has the same size as the input.</li></ol><h4>Calculate the output size</h4><p>In TensorFlow, we often use channel_last format. The size of the tensor is (<em>b</em>, <em>h</em>, <em>w</em>, <em>c</em>), where</p><ul><li><em>b</em> is the batch size</li><li><em>h</em> is the height (or rows) of the picture (feature map)</li><li><em>w</em> is the width (or columns) of the picture (feature map)</li><li><em>c</em> is the channels (or <em>features, depth</em>) of the picture (feature map).</li></ul><p>When we use padding = same , we can just calculate the output height and output width as below:</p><p>output = ceil(input / strides)</p><p>If we use padding = valid , we can also calculate the output size as below:</p><p>output = ceil((input - filters + 1) /strides)</p><h3>ResNet18, 34</h3><p>There are many kinds of ResNet so we see the simplest, ResNet18, firstly. Assume that our input is a 224*224 RGB image, and the output is 1000 classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e8ffM0Wjh3ZGg2Ko.png" /><figcaption>Table1. Architectures for ImageNet. Building blocks are shown in brackets, with the numbers of blocks stacked. Downsampling is performed by conv3_1, conv4_1, and conv5_1 with a stride of 2.</figcaption></figure><p>There are 3 main components that make up the network.</p><ol><li>input layer (conv1 + max pooling) (Usually referred to as layer 0)</li><li>ResBlocks (conv2 without max pooing ~ conv5) (Usually referred to as layer1 ~ layer4)</li><li>final layer</li></ol><h4>STEP0: ResBlocks (layer1~layer4)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*Txg1DKjaENGSZvcvOjBJyw.png" /><figcaption>ResBlocks in Table1. 3x3 means the convolution kernels, 64 means the filters. x2 is repeating number.</figcaption></figure><p>The most important component is ResBlocks, Let’s see how to build it!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ee3653f7a5a891443304526ef55419c/href">https://medium.com/media/0ee3653f7a5a891443304526ef55419c/href</a></iframe><p>In the above implementation, there are 3 problems.</p><ol><li>We need to downsample (i.e., zoom out the size of feature map) on conv3_1, conv4_1, and conv5_1</li><li>We can use a variable to control the number of output filters.</li><li>We should apply batch normalization and ReLu function in midst of layers.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*veHZ-H_umXJfKrdqJIHJOw.png" /><figcaption>2 types of ResBlock. Left: conv2_1, conv2_2 in table1 (without downsampling). Right: conv3_1 in table1 (with downsampling)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acc05d1ed2852236da51c267e942bf67/href">https://medium.com/media/acc05d1ed2852236da51c267e942bf67/href</a></iframe><h4>STEP1: Input layer (layer0)</h4><p>Layer0 consists of a 7*7 convolution and a 3*3 max pooling.</p><pre>self.layer0 = keras.Sequential([<br>    layers.Conv2D(64, 7, 2, padding=&#39;same&#39;),<br>    layers.MaxPool2D(pool_size=3, strides=2, padding=&#39;same&#39;),<br>    layers.BatchNormalization(),<br>    layers.ReLU()<br>], name=&#39;layer0&#39;)</pre><h4>STEP2: Final layer</h4><p>The final layer consists of a global average pooling (gap) and a fully connected layer (fc). GAP calculates the mean of each feature map (h, w, 1) and then concatenates all the values into a list.</p><pre>self.gap = layers.GlobalAveragePooling2D()<br>self.fc = laers.Dense(1000, activation=&#39;softmax&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rm-7JLGRecmP1Kk2.png" /><figcaption>Global average pooling. Picture from: <a href="https://peltarion.com/knowledge-center/documentation/modeling-view/build-an-ai-model/blocks/global-average-pooling-2d">https://peltarion.com/knowledge-center/documentation/modeling-view/build-an-ai-model/blocks/global-average-pooling-2d</a></figcaption></figure><h4>STEP3: Done!</h4><pre>class ResNet18(keras.Model):<br>    def __init__(self, outputs=1000):<br>        super().__init__()<br>        self.layer0 = keras.Sequential([<br>            layers.Conv2D(64, 7, 2, padding=&#39;same&#39;),<br>            layers.MaxPool2D(pool_size=3, strides=2, padding=&#39;same&#39;),<br>            layers.BatchNormalization(),<br>            layers.ReLU()<br>        ], name=&#39;layer0&#39;)<br><br>        self.layer1 = keras.Sequential([<br>            ResBlock(64, downsample=False),<br>            ResBlock(64, downsample=False)<br>        ], name=&#39;layer1&#39;)<br><br>        self.layer2 = keras.Sequential([<br>            ResBlock(128, downsample=True),<br>            ResBlock(128, downsample=False)<br>        ], name=&#39;layer2&#39;)<br><br>        self.layer3 = keras.Sequential([<br>            ResBlock(256, downsample=True),<br>            ResBlock(256, downsample=False)<br>        ], name=&#39;layer3&#39;)<br><br>        self.layer4 = keras.Sequential([<br>            ResBlock(512, downsample=True),<br>            ResBlock(512, downsample=False)<br>        ], name=&#39;layer4&#39;)<br><br>        self.gap = layers.GlobalAveragePooling2D()<br>        self.fc = layers.Dense(outputs, activation=&#39;softmax&#39;)<br>    def call(self, input):<br>        input = self.layer0(input)<br>        input = self.layer1(input)<br>        input = self.layer2(input)<br>        input = self.layer3(input)<br>        input = self.layer4(input)<br>        input = self.gap(input)<br>        input = self.fc(input)<br><br>        return input</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*G35FVs7xlBeiqNrH9SGbcg.png" /><figcaption>Summary of ResNet18</figcaption></figure><p>In order to build ResNet34, we only need to modify the number of ResBlocks in ResNet18.</p><pre>class ResNet34(keras.Model):<br>    def __init__(self, outputs=1000):<br>        super().__init__()<br>        self.layer0 = keras.Sequential([<br>            layers.Conv2D(64, 7, 2, padding=&#39;same&#39;),<br>            layers.MaxPool2D(pool_size=3, strides=2, padding=&#39;same&#39;),<br>            layers.BatchNormalization(),<br>            layers.ReLU()<br>        ], name=&#39;layer0&#39;)<br><br>        self.layer1 = keras.Sequential([<br>            ResBlock(64, downsample=False),<br>            ResBlock(64, downsample=False),<br>            ResBlock(64, downsample=False)<br>        ], name=&#39;layer1&#39;)<br><br>        self.layer2 = keras.Sequential([<br>            ResBlock(128, downsample=True),<br>            ResBlock(128, downsample=False),<br>            ResBlock(128, downsample=False),<br>            ResBlock(128, downsample=False)<br>        ], name=&#39;layer2&#39;)<br><br>        self.layer3 = keras.Sequential([<br>            ResBlock(256, downsample=True),<br>            ResBlock(256, downsample=False),<br>            ResBlock(256, downsample=False),<br>            ResBlock(256, downsample=False),<br>            ResBlock(256, downsample=False),<br>            ResBlock(256, downsample=False)<br>        ], name=&#39;layer3&#39;)<br><br>        self.layer4 = keras.Sequential([<br>            ResBlock(512, downsample=True),<br>            ResBlock(512, downsample=False),<br>            ResBlock(512, downsample=False)<br>        ], name=&#39;layer4&#39;)<br><br>        self.gap = layers.GlobalAveragePooling2D()<br>        self.fc = layers.Dense(outputs, activation=&#39;softmax&#39;)<br>    def call(self, input):<br>        input = self.layer0(input)<br>        input = self.layer1(input)<br>        input = self.layer2(input)<br>        input = self.layer3(input)<br>        input = self.layer4(input)<br>        input = self.gap(input)<br>        input = self.fc(input)<br><br>        return input</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*W3C9wgzZ1a5LScMBQiJsOg.png" /><figcaption>Summary of ResNet34</figcaption></figure><h3>ResNet50, 101, 152</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*wtRyj6EXBuYqm53wSb-5pg.png" /><figcaption>Left: a building block for ResNet34. Right: a “bottleneck” building block for ResNet-50/101/152.</figcaption></figure><h4>STEP0: ResBottleneckBlock</h4><p>The biggest difference between ResNet34 and ResNet50 is ResBlocks. we need to rewrite the other version and we call the new version “ResBottleneckBlock”.</p><p>There are 3 types of ResBottleneckBlock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*KCL4Am8svXdwgmlQUsv3Tg.png" /><figcaption>Figure2. Left: conv2_1 in table1(shortcut needs to adjust channels). Middle: conv2_2, conv2_3 in table1 (shortcut does nothing). Right: conv3_1 in table1 (shortcut needs not only to adjust channels but also to downsample the feature map).</figcaption></figure><p>We can think of these 3 types as 2 conditions. One is a shortcut that does nothing, and the other is a shortcut that needs to do something. When features do not need downsampling and the input channel is equal to output channel, shortcut does nothing. When features need either downsampling nor changing its channels, shortcut does something.</p><pre>def __init__(self, filters, downsample):<br>    super().__init__()<br>    self.filters = filters<br>    self.downsample = downsample<br>    self.conv1 = layers.Conv2D(filters, 1, 1, padding=&#39;same&#39;)<br>    <br>    if downsample:<br>        self.conv2 = layers.Conv2D(filters, 3, 2, padding=&#39;same&#39;)<br>    else:<br>        self.conv2 = layers.Conv2D(filters, 3, 1, padding=&#39;same&#39;)<br>    <br>    self.conv3 = layers.Conv2D(filters*4, 1, 1, padding=&#39;same&#39;)</pre><p>It is easy to implement conv1, conv2, and conv3. Let’s see how to implement shortcut!</p><p>When we implement shortcut, we have to know how to get the input channels. It is not difficult in fact! We just need to extend the build() method from layer.Layer or keras.Model to get the input_shape. input_shape is a list with dimensions. As mentioned before, in TensorFlow we usually use the channel_last format, thus we can get the number of input channels by getting the last value of the input channel.</p><pre>def build(self, input_shape):<br>    if self.downsample or self.filters * 4 != input_shape[-1]:<br>        self.shortcut = layers.Conv2D(self.filters*4, 1,<br>            2 if self.downsample else 1, padding=&#39;same&#39;)<br>    else:<br>        self.shortcut = keras.Sequential()</pre><pre>class ResBottleneckBlock(keras.Model):<br>    def __init__(self, filters, downsample):<br>        super().__init__()<br>        self.downsample = downsample<br>        self.filters = filters<br>        self.conv1 = layers.Conv2D(filters, 1, 1)<br>        if downsample:<br>            self.conv2 = layers.Conv2D(filters, 3, 2, padding=&#39;same&#39;)<br>        else:<br>            self.conv2 = layers.Conv2D(filters, 3, 1, padding=&#39;same&#39;)<br>        self.conv3 = layers.Conv2D(filters*4, 1, 1)<br><br>    def build(self, input_shape):<br>        if self.downsample or self.filters * 4 != input_shape[-1]:<br>            self.shortcut = keras.Sequential([<br>                layers.Conv2D(<br>                    self.filters*4, 1, 2 if self.downsample else 1, padding=&#39;same&#39;),<br>                layers.BatchNormalization()<br>            ])<br>        else:<br>            self.shortcut = keras.Sequential()<br><br>    def call(self, input):<br>        shortcut = self.shortcut(input)<br><br>        input = self.conv1(input)<br>        input = layers.BatchNormalization()(input)<br>        input = layers.ReLU()(input)<br><br>        input = self.conv2(input)<br>        input = layers.BatchNormalization()(input)<br>        input = layers.ReLU()(input)<br><br>        input = self.conv3(input)<br>        input = layers.BatchNormalization()(input)<br>        input = layers.ReLU()(input)<br><br>        input = input + shortcut<br>        return layers.ReLU()(input)</pre><p>We can create 3 types of ResBottleneckBlock separately, as shown in Figure 2.</p><ul><li>Left: ResBottleneckBlock(64, downsample=False)</li><li>Middle: ResBottleneckBlock(64, downsample=False)</li><li>Right: ResBottleneckBlock(128, downsample=True)</li></ul><p>The difference between the left and the middle is that they have different input channels.</p><h4>STEP1: Done!</h4><pre>class ResNet(keras.Model):<br>    def __init__(self, repeat, outputs=1000):<br>        super().__init__()<br>        self.layer0 = keras.Sequential([<br>            layers.Conv2D(64, 7, 2, padding=&#39;same&#39;),<br>            layers.MaxPool2D(pool_size=3, strides=2, padding=&#39;same&#39;),<br>            layers.BatchNormalization(),<br>            layers.ReLU()<br>        ], name=&#39;layer0&#39;)<br><br>        self.layer1 = keras.Sequential([<br>            ResBottleneckBlock(64, downsample=False) for _ in range(repeat[0])<br>        ], name=&#39;layer1&#39;)<br><br>        self.layer2 = keras.Sequential([<br>            ResBottleneckBlock(128, downsample=True)<br>        ] + [<br>            ResBottleneckBlock(128, downsample=False) for _ in range(1, repeat[1])<br>        ], name=&#39;layer2&#39;)<br><br>        self.layer3 = keras.Sequential([<br>            ResBottleneckBlock(256, downsample=True)<br>        ] + [<br>            ResBottleneckBlock(256, downsample=False) for _ in range(1, repeat[2])<br>        ], name=&#39;layer3&#39;)<br><br>        self.layer4 = keras.Sequential([<br>            ResBottleneckBlock(512, downsample=True)<br>        ] + [<br>            ResBottleneckBlock(512, downsample=False) for _ in range(1, repeat[3])<br>        ], name=&#39;layer4&#39;)<br><br>        self.gap = layers.GlobalAveragePooling2D()<br>        self.fc = layers.Dense(outputs, activation=&#39;softmax&#39;)<br><br>    def call(self, input):<br>        input = self.layer0(input)<br>        input = self.layer1(input)<br>        input = self.layer2(input)<br>        input = self.layer3(input)<br>        input = self.layer4(input)<br>        input = self.gap(input)<br>        input = self.fc(input)<br><br>        return input</pre><pre>class ResNet50(ResNet):<br>    def __init__(self):<br>        super().__init__([3, 4, 6, 3])<br>    def call(self, input):<br>        return super().call(input)<br><br>class ResNet101(ResNet):<br>    def __init__(self):<br>        super().__init__([3, 4, 23, 3])<br>    def call(self, input):<br>        return super().call(input)<br><br>class ResNet152(ResNet):<br>    def __init__(self):<br>        super().__init__([3, 8, 36, 3])<br>    def call(self, input):<br>        return super().call(input)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*A6li_gh0_2QrzQryPsnldQ.png" /><figcaption>Summary of ResNet50</figcaption></figure><p>See full code here: <a href="https://github.com/ksw2000/ML-Notebook/blob/main/ResNet/ResNet_TensorFlow.ipynb">https://github.com/ksw2000/ML-Notebook/blob/main/ResNet/ResNet_TensorFlow.ipynb</a></p><h3>Reference</h3><ol><li><a href="https://arxiv.org/pdf/1512.03385.pdf">https://arxiv.org/pdf/1512.03385.pdf</a></li><li><a href="https://zhuanlan.zhihu.com/p/141998754">https://zhuanlan.zhihu.com/p/141998754</a></li><li><a href="https://blog.csdn.net/abc13526222160/article/details/90057121">https://blog.csdn.net/abc13526222160/article/details/90057121</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ee81e33a1ac" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/implement-resnet-with-tensorflow2-4ee81e33a1ac">Implement ResNet with TensorFlow2</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Sync.WaitGroup to Wait Goroutines in Go?]]></title>
            <link>https://ksw2000.medium.com/how-to-use-sync-waitgroup-to-wait-goroutine-in-go-f4c5adb9e49e?source=rss-b570e94ee042------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4c5adb9e49e</guid>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Kashiwa]]></dc:creator>
            <pubDate>Fri, 21 Jan 2022 06:50:53 GMT</pubDate>
            <atom:updated>2022-12-19T03:08:56.835Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>If you have many goroutines and your main goroutine finishes before the others, how do you wait for the other goroutines to finish?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*xBBKkySKinDZqB3dXsju-g.png" /><figcaption>How to wait goroutines?</figcaption></figure><p>WaitGroup is a counter. If there is a running goroutine, the counter increases one. If there is a goroutine done, the counter decreases one. Until the counter reset to zero, the goroutine is blocked by using the Wait() method of WaitGroup. That is, as long as the counter is non-zero, the goroutine is blocked.</p><ol><li>var wg sync.WaitGroup : declare new WaitGroup</li><li>wg.Add() : increase counter when there are new goroutine</li><li>wg.Done() : decrease counter after the goroutine is done</li><li>wg.Wait() : block this goroutine until the counter reset to zero.</li></ol><p>Let’s see the example code below:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;math/rand&quot;<br>    &quot;sync&quot;<br>    &quot;time&quot;<br>)<br><br>func main() {<br>    var wg sync.WaitGroup<br>    for i := 0; i &lt; 10; i++ {<br>        wg.Add(1)<br>        go func(j int) {<br>            defer wg.Done()<br>            time.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)<br>            fmt.Println(&quot;Routine&quot;, j, &quot;is done.&quot;)<br>        }(i)<br>    }<br>    fmt.Println(&quot;Main routine is blocked&quot;)<br>    wg.Wait()<br>    fmt.Println(&quot;Main routine is done&quot;)<br>}</pre><blockquote>Main routine is blocked<br>Routine 3 is done.<br>Routine 7 is done.<br>Routine 8 is done.<br>Routine 5 is done.<br>Routine 0 is done.<br>Routine 9 is done.<br>Routine 2 is done.<br>Routine 6 is done.<br>Routine 1 is done.<br>Routine 4 is done.<br>Main routine is done</blockquote><ol><li>You can pass value to routines by using the arguments of the function.</li><li>You can use defer defers the execution of a function until the surrounding function returns. i.e., execute code after the function is done.</li><li>You can try to omit wg.Wait() and see what will happen?</li></ol><pre>func main() {<br>    var wg sync.WaitGroup<br>    for i := 0; i &lt; 10; i++ {<br>        go func(j int) {<br>            wg.Add(1)<br>            defer wg.Done()<br>            time.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)<br>            fmt.Println(&quot;Routine&quot;, j, &quot;is done.&quot;)<br>        }(i)<br>    }<br>    fmt.Println(&quot;Main routine is blocked&quot;)<br>    // wg.Wait()<br>    fmt.Println(&quot;Main routine is done&quot;)<br>}</pre><blockquote>Main routine is blocked<br>Main routine is done</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4c5adb9e49e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement a Very Simple Hashmap with C]]></title>
            <link>https://towardsdev.com/implement-a-very-simple-hashmap-with-c-9030f1b1ecef?source=rss-b570e94ee042------2</link>
            <guid isPermaLink="false">https://medium.com/p/9030f1b1ecef</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Kashiwa]]></dc:creator>
            <pubDate>Thu, 20 Jan 2022 20:54:45 GMT</pubDate>
            <atom:updated>2022-12-19T14:10:35.955Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Why do we need hashmap and how do implement it with C?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*IcWGXdEY8iyAL8iR-_Gvxg.png" /><figcaption>cover photo</figcaption></figure><p>Imagine that you want to map a number to a string, e.g., 1 to Ayumu, 2 to Honoka, 3 to Chika. It is easy to implement by using array.</p><pre>#include &lt;stdio.h&gt;<br>int main() {<br>    char* map[] = {&quot;&quot;, &quot;Ayumu&quot;, &quot;Honoka&quot;, &quot;Chika&quot;};<br>    printf(&quot;1-&gt;%s\n&quot;, map[1]);<br>    printf(&quot;2-&gt;%s\n&quot;, map[2]);<br>    printf(&quot;3-&gt;%s\n&quot;, map[3]);<br>    return 0;<br>}</pre><blockquote>1-&gt;Ayumu<br>2-&gt;Honoka<br>3-&gt;Chika</blockquote><p>However, if you want to map a string to a number, how do you do?</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;<br>int main() {<br>    char* map[] = {&quot;&quot;, &quot;Ayumu&quot;, &quot;Honoka&quot;, &quot;Chika&quot;};<br>    int listLen = 4;<br>    // try to get &#39;A&#39;<br>    int i, find = -1;<br>    for (i = 0; i &lt; listLen; i++) {<br>        if (!strcmp(map[i], &quot;Ayumu&quot;)) {<br>            find = i;<br>            break;<br>        }<br>    }<br>    if (find != -1) {<br>        printf(&quot;Ayumu-&gt;%d&quot;, find);<br>    } else {<br>        printf(&quot;Not found&quot;);<br>    }<br>    return 0;<br>}</pre><blockquote>Ayumu-&gt;1</blockquote><p>But now, if you need to map 1000 keys to 1000 values and unfortunately you want to fetch the last pair, this linear-search method takes a lot of time obviously.</p><h4>Convert string into an integer</h4><p>What if use a function to convert a string into an integer? For example, convert “Ayumu” to 5, convert “Honoka” to 6, and convert “Chika” to 2. Then, we can create a list like this below:</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;<br>int main() {<br>    char* map[] = {&quot;&quot;, &quot;Ayumu&quot;, &quot;Honoka&quot;, &quot;Chika&quot;};<br>    int listLen = 4;<br>    // try to get &#39;A&#39;<br>    int i, find = -1;<br>    for (i = 0; i &lt; listLen; i++) {<br>        if (!strcmp(map[i], &quot;Ayumu&quot;)) {<br>            find = i;<br>            break;<br>        }<br>    }<br>    if (find != -1) {<br>        printf(&quot;Ayumu-&gt;%d&quot;, find);<br>    } else {<br>        printf(&quot;Not found&quot;);<br>    }<br>    return 0;<br>}</pre><p>This skill is called “<strong>hash</strong>”</p><blockquote>A <strong>hash function</strong> is any function that can be used to map data of arbitrary size to fixed-size values. The values returned by a hash function are called <em>hash values</em>, <em>hash codes</em>, <em>digests</em>, or simply <em>hashes</em>. ─ <a href="https://en.wikipedia.org/wiki/Hash_function">wikipedia</a></blockquote><p>However, if we have another key-value pair (Chisato, 4) and accidentally the hash value of “Chisato” is 5 which has been occupied by “Honoka”. What can we do?</p><p>This problem is called “<strong>collision</strong>”. There are a lot of methods to solve such a problem. For example, we can link all keys which have the same hash value to a list. i.e., when two keys have the same hash value, we can use liked list to record them.</p><pre>int map[] = {0, 0, 3, 0, 0, 1, 2, 0};<br>printf(&quot;Ayumu-&gt;%d&quot;, map[convertStringToInt(&quot;Ayumu&quot;)]);</pre><blockquote>[ 0 ] → null<br>[ 1 ] → null<br>[ 2 ] → pair(“Chika”, 3)<br>…<br>[ 5 ] → pair(“Chisato”, 4) → pair(“Ayumu”, 1)<br>[ 6 ] → pair(“Honoka”, 2)</blockquote><h4>Implement</h4><p>First, we need to define the structure of hashmap. We record the capacity and length of hashmap. The capacity of hashmap means the length of the list. The larger the capacity, the lower the chance of collision.</p><pre>struct pair {<br>    char* key;<br>    int value;<br>    struct pair* next;<br>};</pre><pre>typedef struct pair {<br>    char* key;<br>    int   val;<br>    struct pair* next;<br>}Pair;<br><br>typedef struct hashmap {<br>    Pair** list;       // the list of Pair*<br>    unsigned int cap;  // capacity, the length of list<br>    unsigned int len;  // length, the number of pairs<br>}HashMap;</pre><p>Now, we can create an empty hashmap.</p><pre>HashMap* newHashMap(){<br>    HashMap* this = malloc(sizeof(this));<br>    this-&gt;cap = 8;    // default 8<br>    this-&gt;len = 0;<br>    this-&gt;list = calloc((this-&gt;cap), sizeof(Pair*));<br>    return this;<br>}</pre><p>Besides, we need a hash function</p><pre>unsigned hashcode(HashMap* this, char* key) {<br>    unsigned code;<br>    for (code = 0; *key != &#39;\0&#39;; key++) {<br>        code = *key + 31 * code;<br>    }<br>    return code % (this-&gt;cap);<br>}</pre><p>Implement get() function, which returns value by given map and key.</p><pre>int get(HashMap* this, char* key) {<br>    Pair* current;<br>    for (current = this-&gt;list[hashcode(this, key)]; current;<br>         current = current-&gt;next) {<br>        if (!strcmp(current-&gt;key, key)) {<br>            return current-&gt;val;<br>        }<br>    }<br>    fprintf(stderr, &quot;%s is not found\n&quot;, key);<br>    exit(EXIT_FAILURE);<br>}</pre><p>Implement set() function, which adds key-value pair into map. If the key is already in the map, update its value.</p><pre>void set(HashMap* this, char* key, int val) {<br>    unsigned index = hashcode(this, key);<br>    Pair* current;<br>    for (current = this-&gt;list[index]; current;<br>         current = current-&gt;next) {<br>        // if key has been already in hashmap<br>        if (!strcmp(current-&gt;key, key)) {<br>            current-&gt;val = val;<br>            return;<br>        }<br>    }<br>    // key is not in the hashmap<br>    Pair* p = malloc(sizeof(*p));<br>    p-&gt;key = key;<br>    p-&gt;val = val;<br>    p-&gt;next = this-&gt;list[index];<br>    this-&gt;list[index] = p;<br>    this-&gt;len++;<br>}</pre><p>Test</p><pre>int main() {<br>    HashMap* m = newHashMap();<br><br>    // set value<br>    set(m, &quot;Ayumu&quot;, 1);<br>    set(m, &quot;Honoka&quot;, 2);<br>    set(m, &quot;Chika&quot;, 3);<br>    set(m, &quot;Chisato&quot;, 4);<br><br>    // get value<br>    printf(&quot;Ayumu-&gt;%d\n&quot;, get(m, &quot;Ayumu&quot;));<br>    printf(&quot;Honoka-&gt;%d\n&quot;, get(m, &quot;Honoka&quot;));<br>    printf(&quot;Chika-&gt;%d\n&quot;, get(m, &quot;Chika&quot;));<br>    printf(&quot;Chisato-&gt;%d\n&quot;, get(m, &quot;Chisato&quot;));<br><br>    // replace value<br>    set(m, &quot;Ayumu&quot;, 10);<br>    printf(&quot;Ayumu-&gt;%d\n&quot;, get(m, &quot;Ayumu&quot;));<br>    printf(&quot;Map cap:%u len:%u\n&quot;, m-&gt;cap, m-&gt;len);<br><br>    return 0;<br>}</pre><blockquote>Ayumu-&gt;1<br>Honoka-&gt;2<br>Chika-&gt;3<br>Chisato-&gt;4<br>Ayumu-&gt;10<br>Map cap:8 len:4</blockquote><p>See complete code on my Github: <a href="https://github.com/ksw2000/Medium/blob/main/implement-a-very-simple-hashmap-with-c/hashmap.c">implement-a-very-simple-hashmap-with-c/hashmap.c</a></p><h3>Problems</h3><ol><li>If we do not know how many pairs we need to put into the map, how to set the capacity of the hashmap when we create a hashmap? If capacity is too large, it wastes space. If capacity is too small, it takes a lot of time to linear search the linked list.</li><li>Liked list needs O(n) time in order to search the correct key. Can we use a binary tree or even a red-black tree to boost performance?</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9030f1b1ecef" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/implement-a-very-simple-hashmap-with-c-9030f1b1ecef">Implement a Very Simple Hashmap with C</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>