<?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 Jsrimr on Medium]]></title>
        <description><![CDATA[Stories by Jsrimr on Medium]]></description>
        <link>https://medium.com/@jsrimr2?source=rss-89f68ff4afb8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EX2nquK-c-EhB1nUdpuB0A.jpeg</url>
            <title>Stories by Jsrimr on Medium</title>
            <link>https://medium.com/@jsrimr2?source=rss-89f68ff4afb8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:53:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jsrimr2/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[Towards Easier RL : Take joRLdy !]]></title>
            <link>https://medium.com/@jsrimr2/towards-easier-rl-take-jorldy-cfbcbce70128?source=rss-89f68ff4afb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfbcbce70128</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[jorldy]]></category>
            <dc:creator><![CDATA[Jsrimr]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 16:21:48 GMT</pubDate>
            <atom:updated>2022-01-03T16:21:48.928Z</atom:updated>
            <content:encoded><![CDATA[<h3>Towards Easier RL : Take joRLdy !</h3><blockquote>Have you ever suffered from tuning RL models changing config, model, and environments? : You should use <a href="https://github.com/kakaoenterprise/JORLDY">JORLDY</a> (<a href="https://github.com/kakaoenterprise/JORLDY">https://github.com/kakaoenterprise/JORLDY</a>)</blockquote><p>I started studying deep learning watching AlphaGo which naturally led me to get interested in reinforcement learning (RL).</p><p>However, I soon got frustrated</p><p>installing “gym[atari]” envs which use image data,</p><p>finding RL implementations other than OpenAI-baseline which is tensorflow-based and too high abstractions,</p><p>suffering from non-stable code structures which makes it hard to variate the code to experiment different architectures, hyperparmeters,</p><p>dreaming famous <a href="https://www.ray.io/">ray</a>-based parallel processing.</p><p>And here comes the JORLDY, and I instinctively realized that this was the one I imagined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*0u_n3mZAEb1i7wjsChrDrA.png" /><figcaption>JORLDY is structured intuitively</figcaption></figure><p>I installed JORLDY via docker and started to lick it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tts_b_rV17DrKfMUbDZ4nw.png" /><figcaption>JORLDY Dockerfile</figcaption></figure><p>Everything went as expected.</p><p>For example, I set a problem statement. Is multi-step learning crucial in RAINBOW?</p><p>In JORLDY, all I have to do was modifying agent parameters as below picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ge-vo_lL9lG2kZt_BxDeA.png" /></figure><p>This is the first time to meet JORLDY, but everything was prepared in handy. I even didn’t read README yet.</p><p>If I were to build this experiment by myself, I would not be confident if changing some setting wouldn’t affect other factors. RL has highly-sensitive nature and this worsen my worries more. However, with JORLDY, I’m much free from those engineering issues.</p><p>After few hours, I could check that multi-step learning is crucial outperforming single-step learning always.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pk8C6iUpzOK3ig1flKDkGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rU7bl-xZ-jsUzezVOpqwWQ.png" /><figcaption>Experimenting using JORLDY is so handy</figcaption></figure><p>I’m yet to fully tour JORLDY, but I really feel this fit to me.</p><ol><li>Config file is ready for almost every RL algorithm and various environments.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*f0r64prA7NPcafYA-vu7-A.png" /><figcaption>Config file structure</figcaption></figure><p>2. Logs are kept in structured manner. Under timestamp named directory, {steps}_{score}.gif, checkpoint, config, tensorboard log files are prepared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*YSgI0XuBPcOfIHQ1gsrs-w.png" /><figcaption>Logs are stacked by env/algorithms. Under that, timestamp named log dirs are ready</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*yMmnfJU-QWslgbLHWcrFFw.gif" /><figcaption>JORLDY generates evaluation result by GIF. No more X11 or weight download needed for evaluation</figcaption></figure><p>I always dreamed this kind of RL framework which seems so easy but structured. However, watching git graph, it took more than a year to prepare this framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhhdWA5jYPD9k6IdNgjoBw.png" /><figcaption>It took more than a year to polish out everything</figcaption></figure><p>Also, JORLDY seems to have high standards. They implemented r2d2, but didn’t deploy it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNIT3N3BZY66M6mTETTIlA.png" /><figcaption>R2D2 is missing… Developers may have thought that quality is under their standards</figcaption></figure><p>I’m getting more and more interested in JORLDY… I’ll gonna dig more in the JORLDY framework and come back again.</p><p>Since I am really interested in multiprocessing-parallel env code currently, I think I would come up with those parallel things.</p><p>I always failed to understand distributed or parallel codes, but this time I feel different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmpRQbKpUOLlRlqB2FNT8Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfbcbce70128" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Risk-aware Crypto Trading agent using Rainbow-IQN]]></title>
            <link>https://medium.com/@jsrimr2/risk-aware-crypto-trading-agent-using-rainbow-iqn-b208a735384d?source=rss-89f68ff4afb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b208a735384d</guid>
            <category><![CDATA[iqn]]></category>
            <category><![CDATA[cryptocurrency-investment]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Jsrimr]]></dc:creator>
            <pubDate>Sat, 01 Jan 2022 03:03:13 GMT</pubDate>
            <atom:updated>2022-01-01T03:03:13.864Z</atom:updated>
            <content:encoded><![CDATA[<p>Codes : <a href="https://github.com/jsrimr/udacity-final-project">https://github.com/jsrimr/udacity-final-project</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0TBo5PFW6xTnN0vGFINu2A.png" /><figcaption>Sample decisions from the Agent</figcaption></figure><h3>Introduction</h3><p>There were several approaches to adapt Deep Reinforcement Learning(DRL) algorithms into trading. However, using RL algorithms in real-world trading invokes many concerns because of the lack of robustness. DRL agents trained in simulation environment could simply show poor performance and this could lead to huge loss.</p><p>In this project, we use several extensions of DQN and Internal Quantile Networks to manage the risks. This project aims to investigate the effect of risk-aware strategies in margin trading environment.</p><p>To do so, three OpenAI Gym mimicking environment is developed. Long-only, short-available, leverage-available environments. In the simulation environment, same algorithm agents with or without risk-aware mechanisms are compared. We show that variant CVaR risk measures control risk sensitivity and this risk-sensitivity could significantly diminish the loss and finally outperform the benchmark return with great margins. We exploit this risk management skills to maximize the profit using leverage and show the suggested algorithm works in real-world revealing trade results on Binance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVI63PpcNtNnKbsRXSnA2g.png" /><figcaption>Return rate comparison between algorithms. IQN is good at diminishing the Loss</figcaption></figure><figure><img alt="Trading results on Binance" src="https://cdn-images-1.medium.com/max/1024/0*DJo06TlhiW4aHwID" /></figure><h3>Background</h3><h4>Implicit quantile networks(IQN)</h4><p>Any distributional RL algorithm is characterized by two aspects:the parameterization of the return distribution, and the distance metric or loss function being optimized.</p><p>Together, these choices control assumptions about the random returns and how approximations will be traded off. Categorical DQN (Bellemare et al., 2017, C51) combines acategorical distribution and the cross-entropy loss. However, these algorithms are restricted to assigning probabilities to an a priori fixed, discrete set of possible returns. Dabneyet al. (2018) propose an alternate pair of choices, parameter-izing the distribution by a uniform mixture of Diracs whose locations are adjusted using quantile regression.</p><p>Their algorithm, QR-DQN, while restricted to a discrete set of quantiles, automatically adapts return quantiles to minimize the Wasserstein distance between the Bellman updated and current return distributions.</p><p>In this paper, we use the extended approach of Dabney et al.(2018), which is internal qunatile networks(IQN) from learning a discrete set of quantiles to learning the full quantile function, a continuous map from probabilities to returns. When combined with a base distribution, such as U([0,1]), this forms an implicit distribution capable of approximating any distribution over returns given sufficient network capacity.</p><p>IQN is a deterministic parametric function trained to reparameterize samples from a base distribution, e.g. $ \tau \sim U([0,1]) $, to the respective quantile values of a target distribution. IQN provides an effective way to learn an implicit representation of the return distribution, yielding a powerful function approximator for a new DQN-like agent.</p><p>The algorithm provides, a fully integrated distributional RL agent without prior assumptionson the parameterization of the return distribution. IQN can be trained with as little as a single sample from each state-action value distribution, or as many as computational limits allow to improve the algorithm’s data efficiency. Furthermore, IQN allows us to expand the class of control policies to a large class of risk-sensitive policies connectedto distortion risk measures.</p><h4>Transformer</h4><p>Transformer is a self-attention model. Recently, attention mechanisms havebecome an integral part of models that must capture global dependencies (Bahdanau et al., 2014; Xu et al., 2015; Yang et al., 2016; Gregor et al., 2015; Chen et al., 2018). In particular, self-attention (Cheng et al., 2016; Parikh et al., 2016), also called intra-attention, calculates the response at a position in a sequence by attending to all positions within the same sequence.</p><h3>Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*B_dweRTFYIimXrsQP3zC2g.png" /><figcaption>The architecture of proposed model</figcaption></figure><h4>Architectures</h4><p>The model basically outputs Q-value for each action when inputted observation(OHLCV data) and info.</p><p>Info includes agent’s current position and average holding price, remaining trading time until the end, remaining cash.</p><p>The observation is put through the transformer encoder layer and then outputted features are concatenated with the info features.</p><p>These concatenated features again pass through the two hidden layers which are composed with 512, 32 layers each.</p><p>Then, $ \tau $ is sampled from U[0,1] and processed with</p><p>$$</p><p>\pi_j(\tau):=ReLU(\sum_{i=0}^{n-1}cos(\pi i \tau)\omega_{ij} + b_j).</p><p>$$</p><p>Finally, the product of the feature from neural net and processed $\tau$ becomes the expected Q-value of the action.</p><h4>Model training</h4><p>Training the model follows the methodology of IQN. The model is a deterministic parametric function trained to reparameterize samples from a base distribution,</p><p>e.g. $ \tau \sim U([0,1]) $, to the respective quantile values of a target distribution.</p><p>Let $ F_Z^{-1}(\tau) $ be the quantile function at $ \tau \in [0,1] $ for the random variable Z.</p><p>For notational simplicity we write $ Z_{\tau} := F_Z^{-1}(\tau) $, thus for $ \tau \in U([0,1]) $ the resulting state-action return distribution sample is $ Z_{\tau}(x,a) \sim Z(x,a). $</p><p>Let $ \beta : [0,1] \rightarrow [0,1] $ be a distortion risk measure, with identity corresponding to risk-neutrality. Then, the distorted expectation of Z(x,a) under $ \beta $ is given by</p><p>$$</p><p>\pi_{\beta}(x)=arg\max\limits_{a\in A}Q_{\beta}(x,a)</p><p>$$</p><p>For two samples $ \tau, \tau’ \sim U([0,1]) $, and policy $ \pi_{\beta} $, the sampled temporal difference (TD) error at step t is</p><p>$$</p><p>\delta_t^{\tau,\acute{\tau}}=\gamma_t+\gamma Z_{\tau’}(x_{t+1},\pi_{\beta}(x_{t+1}))-Z_{\tau}(x_t,a_t)</p><p>$$</p><p>Then, the IQN loss function is given by</p><p>$$</p><p>L(x_t,a_t,r_t,x_{t+1})=\frac{1}{N’}\sum_{i=0}^{N}\sum_{j=1}^{N’}\rho_{\tau_i^\kappa}(\delta_t^{\tau,\tau’})</p><p>$$</p><h3>Experiments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e3VxaA2YkKqGRK6lla6iaA.png" /></figure><p>We show the agent could manage its risks and make profit from both price direction. Now we further exploit this risk management ability using leverage to maximize the profit.</p><p>However, using leverage is often not recommended for investors because of the risk of liquidation. Once liquidated, even if the price turns to favor direction later, you cannot get back your money. No matter how successful agent did at the past, one single liquidation could lead to losing everything.</p><p>In this experiment, we assumes 10x leverage, so if the price deviates more than 10 percent from the targeted position, the agent will be swapped out. This extreme risk of liquidation turns down people using leverage. However, at the same time, leverage allows uncomparable opportunity to make huge profit.</p><p>However, using leverage is often not recommended for investors because of the risk of liquidation. Once liquidated, even if the price turns to favor direction later, you cannot get back your money. No matter how successful agent did at the past, one single liquidation could lead to losing everything.</p><p>In this experiment, we assumes 10x leverage, so if the price deviates more than 10 percent from the targeted position, the agent will be swapped out. This extreme risk of liquidation turns down people using leverage. However, at the same time, leverage allows uncomparable opportunity to make huge profit.</p><p>Under spot trading environment, even if the agent is so sure that the price would drastically rise, all of things it can do is to invest all the budget it has. However, under leverage-available environment, agent could mobilize external money and make 10x more profit.</p><p>This could be inspected in the above figure, leverage agent could make profit up to 1000\% while long-only agent and baseline return maximum was under 400\%</p><p>Therefore, we conclude that if the agent could manage the risk, leverage is the best option to maximize the return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzVm-0jvjjPa8B5BZRevXg.png" /><figcaption>Risk-sensitive agent is more safe from the Loss</figcaption></figure><h3>Conclusion</h3><p>Observing only OHLCV data, it is not always possible to predict the future price accurately. We bypass this problem in this paper, but additional data more than OHLCV could help predict the future price and improve the model more accurately.</p><p>We only used value-based approach in the work, but policy-gradient based approach could be also tried with constrained policy optimization. Since policy-gradient allows continuous actions, the agent could use more flexible policy and this could lead to improvement. For example, DDPG + CPO worths try.</p><p>There are certain patterns where sudden strong price drop brings another or two strong drops. This is caused by chained stop loss and margin calls. If the agent could exploit this pattern and if only, this agent would get much stable and high yield. In sum, it’d be a good idea to lead the agent to focus on these specific patterns using supervised learning or hierarchical RL.</p><p>We have proposed adaption of recent work using IQN to learn the optimal policy under risk of liquidation. Our adaption leads to a siginificant improvement in the return in the leverage-available environment, restricting the risk of liquidation and maximize the return with the leverage.</p><p>Finally, we show substantial gains in the real trading experiments, successfully making profit while controlling the loss.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b208a735384d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Including these ‘hidden’ coins into your portfolio will earn you high profits]]></title>
            <link>https://medium.com/@jsrimr2/including-these-hidden-coins-into-your-portfolio-will-earn-you-high-profits-cb705a5d9a62?source=rss-89f68ff4afb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb705a5d9a62</guid>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[cryptocurrency-investment]]></category>
            <dc:creator><![CDATA[Jsrimr]]></dc:creator>
            <pubDate>Fri, 01 Oct 2021 09:08:11 GMT</pubDate>
            <atom:updated>2021-10-02T00:17:09.632Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXkdHHvlTLiblM30GyTlhQ.png" /><figcaption>Top Gainers at Binance Future market</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oF44kd4gZOfFhziPEqfHMA.png" /><figcaption>These coins outperformed Bitcoin</figcaption></figure><blockquote>Buy COTI, CELO, CELR and BTCDOM!</blockquote><p><em>Codes are available at : </em><a href="https://github.com/jsrimr/crypto_analysis"><em>https://github.com/jsrimr/crypto_analysis</em></a></p><p>Have you ever thought all Alt-coins are just a leveraged version of Bitcoin? Myself, thought so. I thought holding Alt-coins means you earn double or more when the market is bullish and you lose double or more when the market is bearish.</p><p>According to the portfolio <a href="https://www.investopedia.com/terms/m/modernportfoliotheory.asp">theory</a>, it is important to find assets with low correlation, because the portfolio with low-correlation assets is expected to earn more w.r.t the risk.</p><p>This is why investment institutions doesn’t allot every asset into a single stock. However, in crypto market, it seems every coin follows the direction of bitcoin. If it’s true, we may invest only in bitcoin ( In case you decided to attend to crypto market). If it turns out false, we may could find stronger coin which soars more and drops less than bitcoin</p><p>To find out if my naive hypothesis true, I conducted some research.</p><h4><strong>My main Questions are</strong></h4><ol><li>Are altcoins are just a leveraged version of Bitcoin?</li><li>Is the relationship found in question1 applies same regardless of the market situation?</li><li>Is the relationship found in question1 applies consistently regardless of the time?</li></ol><p>and let’s find answer one by one.</p><p>I prepared price of all coin pairs from Binance-future market. Frequency is ‘1m’ and I used the data from Sep.10 to Sep.30.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUgHn5KIF448gotLaPJswg.png" /><figcaption>Example of the used data in the research</figcaption></figure><h4>Question1</h4><p>To answer the question 1, we need to find correlationship between the coins.<br>If correlationship coefficient is high, this means the ROE curve of that pair could be synthesized by Bitcoin.</p><p>For example, if one of coin has 1.0 correlationship, then ROE curve of this coin is equivalent to 2X or 3X Bitcoin leverage. (Maybe 2.5X, it remains to find) This is because high correlationship means linear relationship exists between them.</p><p>As you can see in the below table, most of the coins showed strong linear relationship with Bitcoin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GU0Wi8X40s5yvKUwdsoiMQ.png" /></figure><p>However, [‘COTI’, ‘CELO’, ‘BTCDOM’, ‘CELR’, ‘OMG’, ‘DYDX’, ‘AVAX’, ‘ATOM’, ‘REN’, ‘1000SHIB’] showed negative correlation. This is about 7% of all coins, and this means not every coins are leverage version of Bitcoin.</p><p>Moreover, these negative correlated coins could highly help the portfolios to secure stable returns compared to the risk. These coins not only had negative correlation, but they way outperformed bitcoin. If you could find those coins in advance, you can enjoy huge alpha.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0SSLoeQAy0M1A6DkhpmEmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cpm5ZSe2p33ORkyzU-fSg.png" /><figcaption>Left : Normal coins following Bitcoin, Right : Decoupling coins outperforming Bitcoin.</figcaption></figure><p>The left figure shows price trends of randomly selected 5 coins and bitcoin. You can see that every coin in the left figure moves similarly. This means they have high correlation.</p><p>On the other hand, in the right figure, coins with negative correlation to bitcoin are listed. You can see the coins move relatively independent from each other. Not only they decoupled from bitcoin, they way outperform the performance of bitcoin consistently through the given data time.</p><p><strong>Question 1 Conclusion : not every coins are leverage version of Bitcoin.</strong></p><h4>Question 2</h4><p>Is the relationship found in question1 applies same regardless of the market situation? To find the answer, I computed correlation when the bitcoin price is lower than the previous time frame.</p><pre>coins showed negative correlation [all-time data] : [&#39;BTCDOM&#39;, &#39;CELO&#39;, &#39;COTI&#39;, &#39;CELR&#39;, &#39;OMG&#39;, &#39;DYDX&#39;, &#39;AVAX&#39;, &#39;ATOM&#39;, &#39;REN&#39;, &#39;1000SHIB&#39;] :</pre><pre>coins showed negative correlation [bearish-time data] : [‘BTCDOM’, ‘CELO’, ‘COTI’, ‘CELR’, ‘OMG’, ‘DYDX’, ‘AVAX’, ‘ATOM’, ‘REN’]</pre><p>The lists from two different times didn’t vary much. Only ‘1000SHIB’ was eliminated from the list.</p><p><strong>Question 2 Conclusion : Coins decoupled in normal situation still decoupled when the market is bear.</strong></p><h4>Question 3</h4><p>Do decoupling coins consistently decouple with bitcoin? To answer this question, I splitted the data into 4 subsets and listed decoupling coins from each subset.</p><p>‘BTCDOM’ appeared at every subset, while “OMG”, “HBAR”, “CELO”, “LUNA” occured three times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zx6lrn9oBjw4r4DNCZaFew.png" /><figcaption>Occurence of each pairs</figcaption></figure><p><strong>Question 3 Conclusion : </strong>BTCDOM decoupled for all time periods in the data, but other coins did not.</p><h4>Summary</h4><ol><li>Are altcoins are just a leveraged version of Bitcoin?<br>: No, 7% of Alt-coins don’t have linear relationship with Bitcoin</li><li>Is the relationship found in question1 applies same regardless of the market situation?<br>: Weakly yes. The coins showed decoupling behavior in general also showed decoupling behavior when Bitcoin price is going down.</li><li>Is the relationship found in question1 applies consistently regardless of the time?<br>: Weakly yes. BTCDOM decoupled for all time periods in the data, but other coins did not.</li></ol><p>Advice :</p><p>According to the figure1., the coins showed decoupling behavior didn’t coupled into Bitcoin very quickly. As a result, it’s a good practice to invest small money in to diverse your portfolio. I recoomend 3C — (CELO, CELR, COTI)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb705a5d9a62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classifying movie reviews in your language using Hugging-Face Model]]></title>
            <link>https://medium.com/@jsrimr2/classifying-movie-reviews-in-your-language-using-hugging-face-model-9197eaea669d?source=rss-89f68ff4afb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9197eaea669d</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[nsmc]]></category>
            <dc:creator><![CDATA[Jsrimr]]></dc:creator>
            <pubDate>Tue, 21 Sep 2021 03:44:44 GMT</pubDate>
            <atom:updated>2021-09-22T06:35:22.919Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rH2VPcF3VQM2qEzra3Ae-Q.png" /><figcaption>Classified Movie Reviews in Korean</figcaption></figure><p>Full code : <a href="https://github.com/jsrimr/KoBERT-nsmc">https://github.com/jsrimr/KoBERT-nsmc</a></p><h3>Base Knowledge</h3><ol><li>NLP tasks</li></ol><p>NLP tasks include question answering, sequence classification, named entity recognition, etc. However, in order to conduct such tasks, one needs huge amount of data and computing power to train the model. This naturally leads to the idea of borrowing the trained model from somewhere else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KgTzu3T35NPqw31ZCsGyyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KOssCGi1l0GzfoCqROHVQ.png" /><figcaption>Sequence Classification Examples from <a href="https://huggingface.co/transformers/task_summary.html">https://huggingface.co/transformers/task_summary.html</a></figcaption></figure><p>2. What is Hugging Face</p><p>Hugging face is the where you can borrow strong models! It’s almost industry standard in NLP as I heard. You can quickly browse hugging face here. <a href="https://huggingface.co/transformers/quicktour.html">https://huggingface.co/transformers/quicktour.html</a></p><p>When using Hugging Face model, you should remember what you are borrowing from them. You are borrowing “Tokenizer” and the “Model”.</p><p>Tokenizer splits natural languages to small segments and turn these into digit representations so that the computer could handle it . The Example is given in the below picture. What you will going to input to your model is batch[‘input_ids’].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6DqHQIqLt1-ehKI2da9avw.png" /><figcaption>Tokenizer splits natural language into token segments and digitize them</figcaption></figure><p>Then, the model do the downstream tasks. Downstream task means the task what you really want to do with the pre-trained model. We could borrow many kinds of pre-trained model from hugging face and play with them. You can naively just import the model and use it in the inference, but also can fine-tune the model to get better performance. I will cover this in the next section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dnyy1vjrl3EI21Cw0hOAxg.png" /><figcaption>You will feed the tokenized inputs to the model and get the logits</figcaption></figure><p>3. What is Pre-training and Fine-tuning? (Altogether, transfer learning)</p><p>To conduct NLP tasks, the model needs to learn how to generate useful features from tokens and learn to extract relevant information from the features to conduct downstream tasks. However, this feature generation and extracting ability often requires huge amount of computing power which individuals could not afford.</p><p>But, Ta-da! Hugging face affords you such a powerful model for free! With few lines of code, you could acquire the ability to generate useful features and the model that could use those features! You could check all of Hugging-face pre-trained model in here <a href="https://huggingface.co/models">https://huggingface.co/models</a>.</p><p>Furthermore, if you want to improve the pre-trained model to fit to your own dataset, you could fine-tune the pre-trained model. Fine-tuning means you add one additional linear layers to match the output size of your dataset, and then slowly re-training the whole model to fit the data. This adding-layer job seems somewhat frustrating, but don’t panic! Hugging face does this job with one-line of code. For more details, <a href="https://huggingface.co/transformers/training.html">https://huggingface.co/transformers/training.html</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sk-OtQLa4Diw95faZhMvdw.png" /><figcaption>You could add additional layer by specifying ‘num_labels’</figcaption></figure><p>Okay! So far we have established essential knowledge of NLP and hugging faces. Now we are going to implement sentence classification using my own language KOREAN! Korean is notorious for its complex syntax which makes processing token and training models extremely hard. However, I don’t have to worry about those huddles, because I’m gonna use Tokenizer and Model from Hugging-Face!</p><h3>Fine-tuning Implementation using PyTorch</h3><ul><li>Build Dataset</li></ul><p>Korean-google, NAVER provides this movie-review corpus data(<a href="https://github.com/e9t/nsmc">https://github.com/e9t/nsmc</a>). In the below picture, you could see that the data is composed of three columns, [id, document,label]. We will build tokenized dataset from this raw data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSmf9qxCuMCWICpnE2xUbw.png" /><figcaption>Raw Data of movie reviews</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b68a1596d713b0f11e91ca8c9d1d9d9/href">https://medium.com/media/4b68a1596d713b0f11e91ca8c9d1d9d9/href</a></iframe><p>These are the essential code snippets to build dataset. First, you import tokenizer, then read raw_data from the file. Then, you convert natural language into digitized-tokens, and pass them to PyTorch TensorDataset API.</p><ul><li>Feed the model</li></ul><p>After the data is ready, it’s time to train the model!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/079156bf8e6fc4e1ff3562a9ba5a2876/href">https://medium.com/media/079156bf8e6fc4e1ff3562a9ba5a2876/href</a></iframe><p>To fine-tune the pre-trained model to fit to custom data, we need to build a training-loop just like we are training a normal model in other tasks.</p><p>In the given code, Trainer receives datasets and build model. Then, it iterates the training loop, getting data from the data_loader and train on it.</p><ul><li>Results</li></ul><p>The metrics are ‘accuracy’ and the model achieves 89.63% accuracy after the fine-tuning. Before fine-tuning, vanilla pre-trained model achieves 69.31% accuracy. This is the power of fine-tuning.</p><h3>Others</h3><ul><li>Tips when using hugging-face model</li></ul><ol><li>Check what task model you’re using. For example, the model I am using is “kobert”, and this model should be paired with AutoModelForSequenceClassification, not AutoModelForMaskedLM. There are many AutoModel classes, so be careful!</li></ol><h3>Trials to improve the performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*7pbQaHJlRiE4EHp_MZqSGg.png" /><figcaption>Performance comparison. Purple : alternative model, Green : Original Model, Blue : alternative preprocessing</figcaption></figure><ol><li>Use other pre-trained Model<br>The repo (<a href="https://github.com/monologg/KoBERT-nsmc">https://github.com/monologg/KoBERT-nsmc</a> ) I forked from used ‘monologg/KoBERT-nsmc’, and I expected somehow other pre-trained model could perform better. So, I searched for other Korean Bert pretrained model(‘kykim/bert-kor-base’) and tried it.<br>To change the model, I changed several lines of code to alter tokenizer and the model. (commits : <a href="https://github.com/jsrimr/KoBERT-nsmc/commit/92f13594828cf712b6ae90801aa518c9949b62e8">https://github.com/jsrimr/KoBERT-nsmc/commit/92f13594828cf712b6ae90801aa518c9949b62e8</a>) model.<br>The performance significantly improved from 89.3% to 90.7% after changing the model</li><li>Change Preprocessing Method</li></ol><p>Unlike English, in Korean, it is important to segment by morpheme because the postposition plays a big role in forming meaning. For example, ‘특수효과는 볼 만했다&#39; is a negative review while ‘특수효과가 볼 만했다’ is a positive review. The only difference is ‘는&#39; and ‘가&#39;, but normal preprocessing method would omit this. So, It is important to split the tokens by morpheme in Korean.</p><p>Package ‘konlpy’ does this job, so I tried using it. Only three lines of code is required.</p><pre>from konlpy.tag import Okt</pre><pre>self.okt=Okt()</pre><pre>outputs = &quot; &quot;.join(self.okt.morphs(outputs))</pre><p>However, the result was not that charming. Max accuracy decreased from 89.3 % to 89.25%. I think it’s because of the preprocessing method and hyperparmeter is optimizely set to the original repo.</p><p>The full codes are available at <a href="https://github.com/jsrimr/KoBERT-nsmc">https://github.com/jsrimr/KoBERT-nsmc</a></p><p>Reference</p><ul><li>HuggingFace crash course : <a href="https://www.youtube.com/watch?v=GSt00_-0ncQ">https://www.youtube.com/watch?v=GSt00_-0ncQ</a></li><li>Bert Model and Datasets are from : <a href="https://github.com/monologg/KoBERT-nsmc">https://github.com/monologg/KoBERT-nsmc</a></li><li>Hugging Face documentation : <a href="https://huggingface.co/transformers/usage.html">https://huggingface.co/transformers/usage.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9197eaea669d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>