<?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 Sebastian Guggisberg on Medium]]></title>
        <description><![CDATA[Stories by Sebastian Guggisberg on Medium]]></description>
        <link>https://medium.com/@sebastian-guggisberg?source=rss-673026f7b16a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kaMR_Vy8dbQMmlYX</url>
            <title>Stories by Sebastian Guggisberg on Medium</title>
            <link>https://medium.com/@sebastian-guggisberg?source=rss-673026f7b16a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:08:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sebastian-guggisberg/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[Step-By-Step Guide to Decentralized Finance Without Gas Fees on Ethereum with Polygon]]></title>
            <link>https://medium.com/geekculture/step-by-step-guide-to-decentralized-finance-without-gas-fees-on-ethereum-with-polygon-43dcc7fc2021?source=rss-673026f7b16a------2</link>
            <guid isPermaLink="false">https://medium.com/p/43dcc7fc2021</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[polygon]]></category>
            <category><![CDATA[decentralized-finance]]></category>
            <category><![CDATA[matic]]></category>
            <dc:creator><![CDATA[Sebastian Guggisberg]]></dc:creator>
            <pubDate>Fri, 30 Apr 2021 17:36:59 GMT</pubDate>
            <atom:updated>2021-05-02T23:14:36.558Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZ6Ej0QvuzG6nLQ2tnLKoQ.png" /><figcaption>Image from <a href="https://undraw.co/">undraw.co</a></figcaption></figure><p>Ethereum is currently on a run, crushing one all-time high after another and winning substantial market share from Bitcoin. One of the reasons for this might be its rich ecosystem consisting of decentralized applications in various fields, such as Decentralized Finance (DeFi) or Non-fungible Tokens (NFT).</p><p>Especially DeFi offers huge potentials for returns that even outperform stock market investments. However, there is one big catch: Due to the popularity of the previously mentioned fields, the Ethereum network is highly congested and transaction fees are exceeding profit margins for smaller investors.</p><p>But no worries, in this article I present you a way to circumvent the high gas fees on the Ethereum main layer by using Polygon’s layer 2 scaling solutions. In the following paragraphs, you will find a step-by-step guide to create and fund your account to get started with DeFi.</p><blockquote>Disclaimer: I am not a financial advisor. I am not advising you to invest in Decentralized Finance applications or cryptocurrencies. Always do your research and due diligence before investing. Never invest more than you can afford to lose.</blockquote><h3>Intro to DeFi and Polygon</h3><p>I don’t want to go into too much detail about DeFi, since there are a lot of great resources available online such as the official Ethereum <a href="https://ethereum.org/en/defi/">website</a> or the <a href="https://www.youtube.com/watch?v=H-O3r2YMWJ4">Finematics Youtube channel</a>. But here a few points, that distinguish DeFi from traditional finance [1]:</p><ul><li>DeFi offers new and potentially lucrative investment opportunities (lending, liquidity providing, yield farming…)</li><li>In DeFi your money is held by yourself and not by companies (banks)</li><li>DeFi is open to anyone</li><li>DeFi markets are open 24/7</li><li>DeFi is built upon transparency where every transaction is permanently and immutably written to a public ledger</li></ul><p>Although DeFi is generally open to anyone, the already mentioned congestion of the Ethereum network leads to very high transaction costs (in peak times +100$) which ultimately excludes participants with less financial resources. Luckily, innovative scaling solutions are currently being deployed to Ethereum that make transactions much faster and cheaper.</p><p><a href="https://medium.com/u/ea91a1cf958">Polygon (previously Matic Network)</a> currently offers scaling solutions with their Plasma and PoS (Proof-of-stake) chains and plans to offer rollups in the future. Two major DeFi apps on Ethereum, namely <a href="https://aave.com/">Aave</a> (lending/borrowing protocol) and <a href="https://polygon.curve.fi/">Curve</a> (automated market maker), launched their successful applications already on Polygon were able to attract a lot of capital (1.85 billion and 180 million $ respectively as of April 29th, 2021). Especially Curve offers attractive rewards that no bank account can compete with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gniH1KqUkvK6XSKHSRULvw.png" /><figcaption>Base APY and rewards APY on <a href="https://polygon.curve.fi/">Curve</a> as of April 29th, 2021</figcaption></figure><h3>Creating your Account for DeFi</h3><p>To use DeFi, you need an Ethereum wallet to store your cryptocurrencies. Although there are several options out there, I recommend <a href="https://metamask.io/">Metamask</a> which is a browser extension and makes the interaction with Decentralized Apps easy. When you first download Metamask, make sure that it is the real Metamask from <a href="https://metamask.io/">https://metamask.io/</a>.</p><p>Once you have set up your account, you could fund it with ETH or another Ethereum compatible currency (ERC-20 token). But since we want to use DeFi on Polygon, we need to prepare our wallet for the Polygon Mainnet. To do so, click on the Network selection dropdown in Metamask and then select Custom RPC. There you have to enter the following configurations with the new RPC URL <a href="https://rpc-mainnet.maticvigil.com/">https://rpc-mainnet.maticvigil.com/</a> and the Block Explorer URL <a href="https://explorer.matic.network/">https://explorer.matic.network/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*CNp3hPQDtyeqmYhk5aAPxg.png" /><figcaption>Network configuration for Polygon</figcaption></figure><p>After the configuration of your Metamask wallet, I recommend visiting <a href="https://wallet.matic.network/">https://wallet.matic.network/</a> and login in with your wallet. This is the official Polygon wallet that provides a bridge to transfer funds between the Ethereum Mainnet and Polygon. You should also get airdropped 0.001 MATIC that helps you to pay for your first transactions.</p><h3>Fund your Account for DeFi</h3><p>We are almost ready to use DeFi on Polygon, however, we need to fund our account first. If you already hold cryptocurrencies in your wallet on the Ethereum Mainnet, then you could use the Matic wallet to transfer those funds. Remember, you will pay Ethereum based fees to send your coins to the Polygon Mainnet.</p><p>Fiat on-ramp services, such as <a href="https://ramp.network/">Ramp</a>, provide another, very convenient solution. To start with DeFi, I would recommend buying some stable coins that are 1:1 pegged to the US Dollar (such as DAI or USDC) to invest in DeFi protocols. You could also buy some MATIC (to pay for transactions), but this can also be done with your stable coins on a decentralized exchange (more below). In the following, I will show you, how to buy DAI for your Polygon account with Ramp.</p><p>If you open Ramp and start the buying process, you can select the desired cryptocurrency you would like to purchase. If you search for DAI, you will find three options (DAI on Ethereum, DAI on Polygon Chain, and xDAI). Make sure to select DAI on Polygon Chain. If you choose DAI on Ethereum, you will notice a big difference in network fees (12.44€ vs. 0.01€). After picking your desired amount you would like to buy, click proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WoMMDzM6lP1HgPvXjfS98w.png" /></figure><p>After providing your email address and validating it, you will be asked to enter your Polygon address. You can easily copy your address to your clipboard from your Metamask wallet by clicking the account button. Make sure the two addresses match and then you are good to make your purchase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FeXgBtyehbvwC090fjDUsg.png" /></figure><p>In the next steps, you have to choose your payment method and then proceed with the payment. Ramp makes it easy to pay with Revolut, but the fees are higher than with a normal bank transfer. Although credit card purchases are the most convenient way to pay for your DAI, they come with the highest fees. You will receive your DAI after the proposed time depending on your payment method.</p><h3>Use DeFi</h3><p>Congratulations, you can now start exploring new investment opportunities without paying tremendous amounts in transaction fees! Before you jump into DeFi however, I recommend getting familiar with the topic first and learning more about the risks that come with these applications and investments.</p><p>As a first step, I would strongly recommend you to get some MATIC to always be able to move your funds and pay the transaction costs, even though they are incredibly cheap. One way of doing this is by using Ramp as described above and buy MATIC directly. But since you already have DAI, we could use those to buy some MATIC on a decentralized exchange such as <a href="https://quickswap.exchange/">QuickSwap</a>.</p><p>If you decide to provide liquidity to Curve, go to their application and connect your Metamask wallet. Then click on the aave pool (only pool as of April 29th, 2021) and deposit. Now you can deposit your DAI. To earn MATIC rewards on your provided liquidity, you have to stake your curve liquidity provider tokens in gauge. Again, this is no financial advice, and please make sure, you are familiar with the risks if you want to invest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5Ww2GjiwZSA1fIs3yiknA.png" /><figcaption>Curve x Polygon deposit user interface</figcaption></figure><h3>Conclusion</h3><p>Congratulations, you made it this far and you have set up your account and maybe even started exploring DeFi at a fraction of the cost compared to the Ethereum Mainnet.</p><p>I hope my guide was helpful and valuable for you! Feel free to ask me if something was unclear. If you would like me to write more about DeFi, please let me know in which fields you would be interested.</p><p>Thank you very much for reading and I wish you a successful day :)</p><h3>References</h3><p>[1] Ethereum Foundation. <em>Decentralized finance (DeFi)</em>. Retrieved from <a href="https://ethereum.org/en/defi/">https://ethereum.org/en/defi/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43dcc7fc2021" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/step-by-step-guide-to-decentralized-finance-without-gas-fees-on-ethereum-with-polygon-43dcc7fc2021">Step-By-Step Guide to Decentralized Finance Without Gas Fees on Ethereum with Polygon</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can We Beat the Bookmaker with Machine Learning?]]></title>
            <link>https://medium.com/data-science/can-we-beat-the-bookmaker-with-machine-learning-45e3b30fc921?source=rss-673026f7b16a------2</link>
            <guid isPermaLink="false">https://medium.com/p/45e3b30fc921</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[betting-strategies]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[passive-income-online]]></category>
            <category><![CDATA[side-project]]></category>
            <dc:creator><![CDATA[Sebastian Guggisberg]]></dc:creator>
            <pubDate>Sun, 21 Jun 2020 21:15:31 GMT</pubDate>
            <atom:updated>2020-06-21T21:15:31.402Z</atom:updated>
            <content:encoded><![CDATA[<h4>Predicting profitable soccer bets with a LSTM model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vIHp478XyxqL8oxk" /><figcaption>Photo by <a href="https://unsplash.com/@introspectivedsgn?utm_source=medium&amp;utm_medium=referral">Erik Mclean</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong><em>Note from the editors:</em></strong><em> This article is for educational and entertainment purposes only. If you want to use the presented model for real bets, do so at your own risk. Please make sure that this is in alignment with the terms and conditions of your bookmaker.</em></p><p>With the outbreak of the illness and the corresponding shutdown of the economy, millions of people, unfortunately, lost their jobs. Desperate times call for desperate measures and we might be interested in creating new unconventional sources of income. What about using machine learning to predict soccer game results and thus assisting us in placing profitable bets?</p><p>In this article, we use a simple Long Short-term Memory (LSTM) model to predict soccer results. We build a program that iteratively trains the model on the previous rounds before predicting the outcomes of the next round.</p><p>You can follow along with<strong> </strong><a href="https://colab.research.google.com/drive/1t81lv6pB4n0iPdm84taWOwaqVDEmsKUD?usp=sharing"><strong>this Google Colab notebook</strong></a>.</p><h3>LSTMs</h3><p>If you don’t know what LSTM models are, I highly recommend <a href="https://medium.com/u/1bdc81ea939d">Michael Phi</a> explaining them in his <a href="https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21">outstanding article</a>.</p><p>In a nutshell, LSTMs are a special kind of Recurrent Neural Network and are often used for sequence models (e.g. natural language processing) or time series prediction (e.g. stock market, demand, temperature). Since soccer games over a season represent a sequence of data and a model could use previous events to predict the future, we give it a shot with a LSTM betting model.</p><h3>Getting the data</h3><p>The foundation for every Machine Learning model lies in the data. Fortunately, we can easily google for datasets containing game scores and betting odds. For our model, we will use the data of the 2018/2019 Bundesliga which can be downloaded from <a href="https://www.football-data.co.uk/germanym.php">here</a>.</p><p>Since the downloaded csv contains a lot of data we don’t need for our model, let’s simply drop the unnecessary columns. In <a href="https://github.com/guggio/soccer_bets">my GitHub repository</a> you will find a reduced dataset including only the date of the game, the teams, goals and full time result as well as bet odds from B365 (home win, draw and away win). Let’s take a look at the first five rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYOx387FzTSCKwWLxopplw.png" /></figure><h3>Data preparation</h3><p>Instead of building our model to predict the full time result neglecting the goal difference, we want it to predict the difference between the goals scored by the home and away team. Further, we want to coordinate training and prediction of the outcomes by rounds, e.g. train the model on the first 9 rounds and predict the results of the 10th round to place bets and so on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6b8357a5bbaa3b27e3c04567bff52b9/href">https://medium.com/media/a6b8357a5bbaa3b27e3c04567bff52b9/href</a></iframe><p>Since neural networks require tensors of floating-point data or integers, we cannot simply use the teams’ names as input for our model (Chollet, 2018, p. 101). In order for our model to be able to use the teams as input, we assign each team a unique integer value. For this, we create a team name vocabulary and represent every team by their individual id based on their index in the vocabulary. For the actual training, we will input these indices into an embedding layer which is explained below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/410a78b531ecf107f0a146fa7c76ff91/href">https://medium.com/media/410a78b531ecf107f0a146fa7c76ff91/href</a></iframe><p>Chollet (2018, p. 101) also suggests that the data should be normalised (all values should be small and in the same range) to facilitate the training process for the network. Since we predict the difference between the goals scored by the home and away team, and these values can be realistically in the range of -5 (0:5) to 5 (5:0) or even further distributed, we should definitely scale the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65b94cedb625e6f4ba6cdcf6705e1228/href">https://medium.com/media/65b94cedb625e6f4ba6cdcf6705e1228/href</a></iframe><p>After preparing the data, the first five rows should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEBlsF58-QBWqfdBthElOg.png" /></figure><h3>Modeling</h3><p>As mentioned above, the model should be trained on the previous rounds and then make predictions for the next round’s games. To create distinctive feature (X) and label (y) sets, I modified <a href="https://medium.com/u/102e34a0beb1">Venelin Valkov</a>’s create_dataset function of his <a href="https://towardsdatascience.com/demand-prediction-with-lstms-using-tensorflow-2-and-keras-in-python-1d1076fc89a0">demand prediction model</a> to meet our requirements. If you are interested in further applications of LSTMs, I definitely recommend his article.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f41d32d2bd17a8901765e708942d26e/href">https://medium.com/media/0f41d32d2bd17a8901765e708942d26e/href</a></iframe><p>Let’s suppose we want to observe the first five rounds of the season before making any bets. The data of these observation rounds are thus used to make some adjustments to the model’s architecture. Specifically, we want to figure out, how much training the model requires before it overfits.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d50fef68b10542d3181444a9a274c61e/href">https://medium.com/media/d50fef68b10542d3181444a9a274c61e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qXEi81JR4YU7I0YO9oM-ng.png" /></figure><p>As we can see in the chart above, the train loss decreases for around 20 epochs before the model seems to start overfitting. Thus, we will later train the model for 20 epochs before making our predictions.</p><blockquote>Note: You might see different results when you are running the model. Unfortunately, Keras’ <a href="https://keras.io/getting_started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development">suggestions</a> to make the model reproducible do not seem to work with Google Colab.</blockquote><h3>Creating the program</h3><p>In order to set up a program to iteratively train on the previous rounds, predict the outcomes of the next round’s games and then place the bets, we should split the whole process into pieces and define functions for each step.</p><ul><li><strong>Data selection</strong>: Selecting the previous rounds for training and the current round for prediction</li><li><strong>Modeling, training and prediction</strong>: functions to create and train the model as well as make predictions and format the output</li><li><strong>Betting</strong>: Choosing games to place bets based on the model’s predictions</li><li><strong>Putting it all together</strong>: Iterative training and prediction of rounds and compilation of the results</li></ul><h4>Data formatting</h4><p>Since we loop over the dataset and train the model on the rounds before the round we want to predict, we have to recreate the dataset after every round. We use the create_dataset function from above to create a train and test set for every iteration. Since we need to return multiple values, let’s put them into a dictionary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31c9035ee9ac45953430804626c78fc9/href">https://medium.com/media/31c9035ee9ac45953430804626c78fc9/href</a></iframe><h4>Modeling, training and prediction</h4><p>Above I already outlined how we are going to model our LSTM and you might be wondering, what an Embedding layer is and why we need it. According to Chollet (2018, p. 186), this layer can be understood as a dictionary that maps integer indices (i.e. team indices) to dense vectors which can then be used as the input for the model. We need it since otherwise our rather meaningless team indices (from 0 to 17) could potentially be misinterpreted by our model.</p><p>I used rather random values for the hyperparameters and definitely encourage you to test different combinations in order to optimise the model’s performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d2247ac381853938aad219e69d43f09/href">https://medium.com/media/1d2247ac381853938aad219e69d43f09/href</a></iframe><p>Since we let the model predict scaled game scores, we have to inversely transform these predictions in order to retrieve the predictions in the wanted format. To create a new data frame containing the model’s predictions, we need to reshape the inversely transformed game scores. Finally, we stack the actual and prediction scores into a dictionary that is then returned by the function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bc1d613c98a6e4d8e68d935a221bff9/href">https://medium.com/media/4bc1d613c98a6e4d8e68d935a221bff9/href</a></iframe><h4>Betting</h4><p>Based on the model’s predictions, we want to place our bets. I am definitely no betting expert, but I would suggest betting only in cases when the model is quite confident that either the home or away team is going to win (score ≥ |1.1|).</p><p>The calculate_bets function creates two lists, one containing the bet units we invested (1 if we bet on this game, otherwise 0) and another one the winnings. The winnings are 0 for games that we did not consider for betting or in case we placed a losing bet (e.g predicted home win, but it was a draw). If the model correctly predicts either a home or away win, the winnings for this game are equal to the corresponding odds of this outcome.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/170ca79f5235938edd1deae0bf54fe47/href">https://medium.com/media/170ca79f5235938edd1deae0bf54fe47/href</a></iframe><p>Before we can create a loop that puts everything together and predicts every round of the season, we create a new data frame based on the test set (one round of 9 games) and add the retransformed actual and predicted scores as well as columns for the invested and won bet units.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/660b18b95cc438e3b58846f7366eaf95/href">https://medium.com/media/660b18b95cc438e3b58846f7366eaf95/href</a></iframe><p><strong>Putting it all together</strong></p><p>Now, we can add all the pieces from above together and define a function that loops over the rounds, create the train, test sets and the model. Then the model is trained and the results predicted and later put together in a data frame.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/912f526049c85564b86054ff556c5528/href">https://medium.com/media/912f526049c85564b86054ff556c5528/href</a></iframe><h3>Let’s beat the bookie</h3><p>Having all the pieces put together, it is time for us to beat the bookmakers!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b851f65a3e5a306817cc574a4d7673b2/href">https://medium.com/media/b851f65a3e5a306817cc574a4d7673b2/href</a></iframe><p>As I already mentioned above, the model cannot create reproducible results, which means, that your results might differ from mine.</p><p>My model made a total of 92 bets meaning that it invested 92 bet units. The model is probably a way better game predictor than I am and made winnings of 94.71 bet units, meaning that the net winnings account to 2.71 bet units 🔥</p><p>In order to analyse how our model performed in each round and see the winnings over time, let’s plot the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23c2c347cb71abad9109588b5326d645/href">https://medium.com/media/23c2c347cb71abad9109588b5326d645/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FiufYwpRUss_dcndXMIP1g.png" /></figure><p>We can see, that the 9th, 20th, and 21st round were among the worst, since we did not win any bet. In order to improve the model it would definitely make sense to look further at these rounds and figure out what might have led to these results. Potentially, the clear favourites were defeated by the underdogs or our model just made bad predictions.</p><h3>Conclusion</h3><p>Congratulations, you just beat the bookmaker. Well, at least hypothetically, in 2018/2019.</p><p>We both know that the model is far from perfect, but it is a simple approach that seemed to work for the 2018/2019 Bundesliga season. Additionally, we worked with some data, built a LSTM model with Keras and plotted the results. I am sure that the model could also be applied onto other leagues and even different sports such as ice hockey, basketball or American football.</p><p>If you have any suggestions for additional features or model architectures that might improve the model, please let me know. I consider extending the current model in a future article with more advanced features.</p><p>Thank you very much for reading!</p><p>Stay save and Happy Coding!</p><h3>References</h3><p>Chollet, F. (2018). Deep Learning with Python. New York: Manning Publications Co.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45e3b30fc921" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/can-we-beat-the-bookmaker-with-machine-learning-45e3b30fc921">Can We Beat the Bookmaker with Machine Learning?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine Tuning BERT for Text Classification with FARM]]></title>
            <link>https://medium.com/data-science/fine-tuning-bert-for-text-classification-with-farm-2880665065e2?source=rss-673026f7b16a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2880665065e2</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sebastian Guggisberg]]></dc:creator>
            <pubDate>Fri, 29 May 2020 14:14:14 GMT</pubDate>
            <atom:updated>2020-05-29T14:44:33.297Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simple and fast transfer learning with state-of-the-art NLP models</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LuMR5Y_dNuAev6FZ" /><figcaption>Photo by <a href="https://unsplash.com/@timothyeberly?utm_source=medium&amp;utm_medium=referral">Timothy Eberly</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Last fall while struggling to fine tune the pre-trained multilingual BERT model for argumentation mining (detecting argumentative structures in text) in the context of my Master’s Thesis, I stumbled across the open source framework <a href="https://github.com/deepset-ai/FARM">FARM</a> (<strong>F</strong>ramework for <strong>A</strong>dapting <strong>R</strong>epresentation <strong>M</strong>odels) by <a href="https://medium.com/u/1cb8bc239339">Deepset.ai</a>. Not only did they provide a German BERT model, but also an easily implementable framework with extensive features for transfer learning. I wouldn’t say that it saved my thesis, but at least a lot of nerves and hair on my head 😅.</p><p>In this article I provide a guide for classifying news article genres using the framework on the raw BBC News Article dataset by D. Greene and P. Cunningham [1]. The process of preparing the data can be found in my last <a href="https://towardsdatascience.com/how-to-split-a-dataframe-into-train-and-test-set-with-python-eaa1630ca7b3">article</a>.</p><p>First, I will briefly describe transfer learning and BERT. Then, I will provide you with the guide that will make you a real FARMer 👩‍🌾👨‍🌾.</p><h3>BERT and Transfer Learning</h3><p>BERT (Bidirectional Encoder Representations from Transformers) was published one year ago by Devlin, Chang, Lee, &amp; Toutanova [2] . This innovative new model achieved new state-of-the-art results in eleven NLP tasks, such as Question Answering (SQuAD) or Named Entity Recognition (NER).</p><p>It combines the technical innovations such as bidirectional training of Transformers for language modelling with the ability for transfer learning for a variety of different tasks. If you’re interested in learning more about the model, I strongly suggest reading the original <a href="https://arxiv.org/pdf/1810.04805.pdf">paper</a>, since I won’t describe it in more detail.</p><p>Adapting the learnings from one problem to a new and different problem represents the idea of Transfer Learning. If we think about it, human learning is heavily based on this learning approach. Thanks to transfer learning, learning Java felt quite easy for me, since I already had an understanding of programming concepts and Python syntax when I started the learning process.</p><p>In order to actually succeed at solving the new problems though, specialised fine tuning on the unknown task is necessary. Thus, we are discovering in the following sections how to use a pre-trained BERT model and fine tune it for the task of classifying news articles’ genre based on their text.</p><h3>Become a FARMer 👩‍🌾👨‍🌾</h3><p>After this short introduction to the topic, let’s get prepared for the field.</p><p>First, we might take a look at the possibilities we have with FARM. The framework does not only support text classification with BERT in English, but also several other downstream tasks with more than a handful of state-of-the-art models in various languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0RYwLSOMegTKfhnyTwkjIQ.png" /><figcaption>Available models and supported tasks with FARM — <a href="https://github.com/deepset-ai/FARM#core-features">Source</a></figcaption></figure><p>So, now we are definitely ready to get out to the field. Launch your preferred IDE (I will describe how to use it in Google Colab), take a deep breath and let’s go.</p><h4>Setup</h4><p>Before typing and running the first line in Colab, you should choose GPU as hardware accelerator in the notebook settings (Edit &gt; Notebook settings). This will accelerate the training significantly.</p><p>In order to use FARM in Google Colab, you have to install it. There are two different ways of doing this:</p><p>If you want to work with a stable release, then look for the latest release under the release tab of the <a href="https://github.com/deepset-ai/FARM/releases">Github repository</a>. Currently, the latest release is version 0.4.3 which we are installing with the following command to Google Colab:</p><pre>!pip install farm==0.4.3</pre><p>In case, you want to work with their cutting-edge (yet to be released) features, then install it with the following command. But be aware that this approach does not necessarily install a stable release and things might not go as smoothly as expected.</p><pre>!git clone https://github.com/deepset-ai/FARM.git<br>!pip install -r FARM/requirements.txt<br>!pip install FARM/</pre><p>After installing FARM to our environment, we also need to load the data for training our model. By cloning <a href="https://github.com/guggio/bbc_news">my GitHub repository</a>, we can access the data from Colab.</p><pre>!git clone https://github.com/guggio/bbc_news</pre><p>If we open our left panel in the Colab UI, we can now see the bbc_news folder added to our files. For fine tuning we will use the train and test data located in the generated_data folder within the bbc_news directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*LOF3F99YgDRCrBp9jiyuhg.png" /></figure><p>In a next step, we want to import all the classes and functions that are required for the training steps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca4dc0ce4cfaa58ea4f37bf0f33f18bc/href">https://medium.com/media/ca4dc0ce4cfaa58ea4f37bf0f33f18bc/href</a></iframe><p>If we are interested in more detailed analytics for our experiment, we can track the training on FARM’s <a href="https://public-mlflow.deepset.ai/#/">public MLflow server</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18f7fb037cab6233bb30492102959796/href">https://medium.com/media/18f7fb037cab6233bb30492102959796/href</a></iframe><p>So, we are almost ready to get into the real coding part. But before jumping into it, let’s initialise some variables to the environment which we will need in the process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5db5003c73849a2ecb7b5e0e285edc4d/href">https://medium.com/media/5db5003c73849a2ecb7b5e0e285edc4d/href</a></iframe><p>We set a seed value to make the runs reproducible (same shuffling for every run) and fetch the correct device to accelerate the training process. Additionally, we determine the number of training epochs, the batch size and the frequency of evaluating our model on the development set.</p><h4>Data Handling</h4><p>I remember desperately trying to preprocess my data for argumentation mining (per token classification, similar to NER) and ultimately failing due to BERT’s wordpiece tokenisation following the conventional approach with HuggingFace.</p><p>Luckily, the preprocessing task with FARM was much more convenient thanks to FARM’s data handling structure. Additionally, this structure based on blocks makes the process highly customisable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OCTjbQUme-G4Rs_1zta4XQ.jpeg" /><figcaption>FARM’s Data Handling based on blocks — <a href="https://farm.deepset.ai/data_handling.html#building-blocks">Source</a></figcaption></figure><p>In order to transform inputs (files or requests) into PyTorch datasets, we utilise processors.</p><p>For doing its job, the processor requires a tokenizer which we can simply load based on our wanted language model. Since we are working with English texts that contain capitalised and lowercased words, we will use the base cased BERT model and set do_lower_case false.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb0d6dd1fbfdab7e85f7376eb10c2b02/href">https://medium.com/media/bb0d6dd1fbfdab7e85f7376eb10c2b02/href</a></iframe><p>After initialising the tokenizer, we create our processor to handle the data. As already mentioned, we can customise the blocks for the data handling process according to our needs.</p><p>Thus, we can simply input the desired customisations as parameters into the Processor constructor. For our text classification task, we use the TextClassificationProcessor class. For a different task we would obviously switch to the corresponding Processor class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c564274720bcda9cd8228b15500819d8/href">https://medium.com/media/c564274720bcda9cd8228b15500819d8/href</a></iframe><p>Once the processor is created, we can load the data silo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afd16e70418fc5831e6b4bbc54d0bda5/href">https://medium.com/media/afd16e70418fc5831e6b4bbc54d0bda5/href</a></iframe><h4>Modeling and Training</h4><p>The overview above shows how versatile the framework is in terms of applicable language models and supported tasks. This flexibility requires an adaptive model with easily exchangeable components to meet the requirements of the corresponding task and model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhmoHAnvDJM4Ng5xj5F9qg.jpeg" /><figcaption>FARM’s Adaptive Model — <a href="https://farm.deepset.ai/modeling.html">Source</a></figcaption></figure><p>The adaptive model consists of the pre-trained language model that we want to fine tune and one or multiple prediction heads. The prediction head is the final layer that is put onto the model in order to convert the model’s vector representation into actual predictions.</p><p>Enough talking about the adaptive model’s structure, let’s define our model and initialise the optimiser.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d243ac09e32fe46194914f5cf3627b34/href">https://medium.com/media/d243ac09e32fe46194914f5cf3627b34/href</a></iframe><p>One more step is required before we can start training our model. We have to feed everything to the trainer, which manages the training process and evaluates the model in the defined frequency on the dev set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b537464dd7d15a6d1bda7d6451d047c/href">https://medium.com/media/2b537464dd7d15a6d1bda7d6451d047c/href</a></iframe><p>Now, it is time to push the button. Let the training start:</p><pre>trainer.train()</pre><p>This will start the training process which will take between 3–4 minutes for our data set. Then it is time to reap what we sow 🌽</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*7BbtCfk2ZetuP_5Eu1vjOg.png" /><figcaption>Training results</figcaption></figure><p>Just after two epochs, the model is performing incredibly well on the test set with an overall macro average F1 Score of 0.97. Note that these results were achieved without any hyper-parameter tuning.</p><p>In order to maximise our model’s performance, we could re-run the training with different settings, such as a different number of epochs, different batch sized, different dropout rates etc. Another option for hyper-parameter optimisation is running experiments based on a json-configuration file which I might describe in a future article.</p><p>In case we initialised the ML-logging at the beginning, we can now access further information of our experiment on the <a href="https://public-mlflow.deepset.ai/">MLflow server</a>, such as the development of the training loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t16NuX2gyNRJX4gE5yNrWQ.png" /><figcaption>Training loss</figcaption></figure><h4>Saving and Running Inference</h4><p>After training our model, we definitely want to try it on different texts as well. Unfortunately, we cannot run inference on the trained model directly, since the adaptive model class does not offer such functionalities. Thus, we have to save it in order to load it with the Inferencer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc1ca492fec026d97ae57ebbf9631af6/href">https://medium.com/media/fc1ca492fec026d97ae57ebbf9631af6/href</a></iframe><p>We could also extract the model from Colab and download it with the following command. Go to the left panel in the Colab UI and select the zip-file and download it.</p><pre>!zip -r saved_models/model.zip saved_models/bert-english-news-article</pre><p>To run inference on sample texts, we need to format them in a list of dictionaries where ‘text’ is the key and the actual article text represents the corresponding value.</p><p>To facilitate the inferencing step, I prepared helper functions and added two article texts in my <a href="https://github.com/guggio/bbc_news/tree/master/generated_data/inferencing">repository</a>. An additional helper selects the predictions from the results and returns a dataframe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09875e6d15b0a5487ef8358ed60e53c3/href">https://medium.com/media/09875e6d15b0a5487ef8358ed60e53c3/href</a></iframe><p>Let’s classify the prepared articles!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce71b943eed2318289846a8d04a51ea4/href">https://medium.com/media/ce71b943eed2318289846a8d04a51ea4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TfYsdwifmEHzYfZLyclmHw.png" /><figcaption>Results of the inference</figcaption></figure><h3>Conclusion</h3><p>If you made it this far, you will have a wonderful harvest! 🌽</p><p>As presented in this article, transfer learning with FARM is an easy and straightforward process that offers a lot of customisation possibilities. Thus, you might consider <a href="https://github.com/deepset-ai/FARM">FARM</a> for your next NLP problems.</p><p>I hope my tutorial was helpful and valuable for you! Feel free to ask me if something was unclear in my guide. You can checkout my <a href="https://github.com/guggio/bbc_news">source code here</a>.</p><p>Thank you very much for reading and Happy Coding!</p><h3>References</h3><p>[1] D. Greene and P. Cunningham. “Practical Solutions to the Problem of Diagonal Dominance in Kernel Document Clustering”, Proc. ICML 2006.</p><p>[2] Devlin, J., Chang, M.-W., Lee, K., &amp; Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. Google AI Language. <a href="https://arxiv.org/pdf/1810.04805.pdf">https://arxiv.org/pdf/1810.04805.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2880665065e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/fine-tuning-bert-for-text-classification-with-farm-2880665065e2">Fine Tuning BERT for Text Classification with FARM</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</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 Split a Dataframe into Train and Test Set with Python]]></title>
            <link>https://medium.com/data-science/how-to-split-a-dataframe-into-train-and-test-set-with-python-eaa1630ca7b3?source=rss-673026f7b16a------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaa1630ca7b3</guid>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[data-preparation]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sebastian Guggisberg]]></dc:creator>
            <pubDate>Tue, 26 May 2020 17:27:30 GMT</pubDate>
            <atom:updated>2020-05-29T14:31:34.289Z</atom:updated>
            <content:encoded><![CDATA[<h4>A short guide for using sklearn train_test_split on a pandas dataframe</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7Ob33nRMq07BZPbNtfItw.png" /><figcaption>Illustration by Author</figcaption></figure><p>In this short article, I describe how to split your dataset into train and test data for machine learning, by applying sklearn’s train_test_split function. I use the data frame that was created with the program from my last article. The data is based on the raw BBC News Article dataset published by D. Greene and P. Cunningham [1].</p><p>Feel free to check out the <a href="https://github.com/guggio/bbc_news">source code here</a> if you’re interested.</p><p>If you missed my first guide to extract information from text files, you might want to check it out to get a better understanding of the data we are dealing with.</p><p><a href="https://towardsdatascience.com/transforming-text-files-to-data-tables-with-python-553def411855">Transforming  Text Files to Data Tables with Python</a></p><h3>Data Understanding</h3><p>Since I want to keep this guide rather short, I will not describe this step as detailed as in my last article. The most important information to mention in this section is how the data is structured and how to access it.</p><p>As can be seen in the screenshot below, the data is located in the generated_data folder. We also want to save the train and test data to this folder, once these files have been created. Additionally, the script runs in the prepare_ml_data.py file which is located in the prepare_ml_data folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*CQ3q85OCyHoyIXYcFaAFKA.png" /><figcaption>Screenshot of the filesystem</figcaption></figure><p>As presented in my last article about transforming text files to data tables, the bbc_articles.tsv file contains five columns. However, for this tutorial, we are only interested in the text and genre columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htBifq2yy9631XBYqAxC5g.png" /><figcaption>Columns of the dataset</figcaption></figure><h3>Load the data</h3><p>In a first step, we want to load the data into our coding environment. For this, we need the path to the directory, where the data is stored. We save the path to a local variable to access it in order to load the data and use it as a path to save the final train and test set. Since the data is stored in a different folder than the file where we are running the script, we need to go back one level in the filesystem and access the targeted folder in a second step. We achieve this by joining ‘..’ and the data folder which results in ‘../generated_data/’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e25c749ace7ca9508381dba23214981b/href">https://medium.com/media/e25c749ace7ca9508381dba23214981b/href</a></iframe><p>With the path to the generated_data folder, we create another variable directing to the data file itself, which is called bbc_articles.tsv. Since it is a tab-separated-values file (tsv), we need to add the ‘\t’ separator in order to load the data as a Pandas Dataframe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d8c96f7e6b8e9783e13928f25973ea3/href">https://medium.com/media/0d8c96f7e6b8e9783e13928f25973ea3/href</a></iframe><h3>Selecting the data for splitting (optional)</h3><p>The following command is not required for splitting the data into train and test set. Nevertheless, since I don&#39;t need all the available columns of the dataset, I select the wanted columns and create a new dataframe with only the ‘text’ and ‘genre’ columns.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dd7e93c44f76babbd494f885e222361/href">https://medium.com/media/1dd7e93c44f76babbd494f885e222361/href</a></iframe><h3>Splitting and saving</h3><p>Now, we have the data ready to split it. Luckily, the train_test_split function of the sklearn library is able to handle Pandas Dataframes as well as arrays. Therefore, we can simply call the corresponding function by providing the dataset and other parameters, such as following:</p><ul><li><strong>test_size</strong>: <br>This parameter represents the proportion of the dataset that should be included in the test split. The default value for this parameter is set to 0.25, meaning that if we don’t specify the test_size, the resulting split consists of 75% train and 25% test data.</li><li><strong>random_state</strong>:<br>This parameter controls the shuffling applied to the data before the split. By defining the random state we can reproduce the same split of the data across multiple function calls.</li><li><strong>shuffle</strong>:<br>This parameter indicates whether the data should be shuffled before splitting. Since our dataset is ordered by genre, we definitely want to shuffle it. Otherwise the train and test set would not contain the same genres.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4caf13a2e6ff4ef01d356c024e2f4033/href">https://medium.com/media/4caf13a2e6ff4ef01d356c024e2f4033/href</a></iframe><p>After splitting the data, we use the directory path variable to define a file path for saving the train and the test data. By transforming the dataframes to a csv while using ‘\t’ as a separator, we create our tab-separated train and test files.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fa06d9cdc66ff660dbc44402c2699fd/href">https://medium.com/media/5fa06d9cdc66ff660dbc44402c2699fd/href</a></iframe><h3>Conclusion</h3><p>In this short article, I described how to load data in order to split it into train and test set. The corresponding data files can now be used to for training and evaluating text classifiers (depending on the model though, maybe additional data cleaning is required).</p><p>In future articles, I will describe how to set up different deep learning models (such as LSTM and BERT) to train text classifiers, that predict an article’s genre based on its text. Below find a link to my article where I used the FARM framework to fine tune BERT for text classification.</p><p><a href="https://towardsdatascience.com/fine-tuning-bert-for-text-classification-with-farm-2880665065e2">Fine Tuning BERT for Text Classification with FARM</a></p><p>Thank you very much for reading and Happy Coding!</p><h3>References</h3><p>[1] D. Greene and P. Cunningham. “Practical Solutions to the Problem of Diagonal Dominance in Kernel Document Clustering”, Proc. ICML 2006.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaa1630ca7b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-split-a-dataframe-into-train-and-test-set-with-python-eaa1630ca7b3">How to Split a Dataframe into Train and Test Set with Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transforming  Text Files to Data Tables with Python]]></title>
            <link>https://medium.com/data-science/transforming-text-files-to-data-tables-with-python-553def411855?source=rss-673026f7b16a------2</link>
            <guid isPermaLink="false">https://medium.com/p/553def411855</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sebastian Guggisberg]]></dc:creator>
            <pubDate>Sat, 23 May 2020 11:00:42 GMT</pubDate>
            <atom:updated>2020-05-24T14:53:48.859Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transforming Text Files to Data Tables with Python</h3><h4>A reusable approach to extract information from any text file</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bTbTW4xLZa-cAR2n" /><figcaption>Photo by <a href="https://unsplash.com/@qwitka?utm_source=medium&amp;utm_medium=referral">Maksym Kaharlytskyi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, I describe how to transform a set of text files into a data table which can be used for natural language processing and machine learning. To showcase my approach I use the raw BBC News Article <a href="http://mlg.ucd.ie/datasets/bbc.html">dataset</a> published by D. Greene and P. Cunningham in 2006.</p><p>Before jumping into the IDE and start coding, I usually follow a process consisting of understanding the data, defining an output, and translating everything into code. I consider the tasks before coding usually as the most important since they help to structure and follow the coding process more efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6l0MqrwP09-gRfgfQndZA.png" /><figcaption>My three-step process for this project</figcaption></figure><h3>1. Data Understanding</h3><p>Before being able to extract any information from a text file, we want to know how its information is structured as well as how and where the text files are stored (e.g. name, directory).</p><h4>Structure</h4><p>To understand the structure, we take a look at some of the text file to get a sense of how the data is structured.</p><pre>Claxton hunting first major medal<br><br>British hurdler Sarah Claxton is confident she can win her first major medal at next month&#39;s European Indoor Championships in Madrid.<br><br>The 25-year-old has already smashed the British record over 60m hurdles twice this season, setting a new mark of 7.96 seconds to win the AAAs title. &quot;I am quite confident,&quot; said Claxton. &quot;But I take each race as it comes. &quot;As long as I keep up my training but not do too much I think there is a chance of a medal.&quot; Claxton has won the national 60m hurdles title for the past three years but has struggled to translate her domestic success to the international stage.<br>...</pre><p>In the context of news articles, it can be easily assumed that the first and second section correspond to the title and the subtitle respectively. The following paragraphs represent the article’s text. Looking at the sample data, we also recognise that the segments are separated by new lines which can be used for splitting the text.</p><h4>Storage</h4><p>To write a script that automatically runs through every text file, we need to know how the text files are stored. Thus, we are interested in the naming and organisation of the directories. Potentially, we need to restructure things, so we can loop more easily through the files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*-_daJNr-04MWT0ABN29ZXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*dL07LsXpw1GvrKqounX4sQ.png" /><figcaption>Naming and organisation of the text files</figcaption></figure><p>Luckily for us, the <a href="http://mlg.ucd.ie/datasets/bbc.html">BBC news dataset</a> is already well structured for automating the information extraction. As it can be seen in the screenshots above, the text files are stored in directories according to their genre. The names are also similar for every genre and are made up by leading zeros (if the file number is below 100), the file number, and “.txt”.</p><h3>2. Output Definition</h3><p>Based on the insights of the data understanding step, we can define what information should be included in the output. In order to determine the output, we have to consider the learnings of the previous step as well as think about potential use cases for the output.</p><p>Based on the information we can potentially extract from the text files, I come up with two different use cases for machine learning training:</p><ul><li>Text classification (genre prediction based on the text)</li><li>Text generation (title or subtitle generation based on the text)</li></ul><p>In order to fulfil the requirements for both potential use cases, I would suggest extracting the following information.</p><figure><img alt="Extracting text files to gain informations about the genre, title, subtitle, text, and token count." src="https://cdn-images-1.medium.com/max/1024/1*f9urjDVrvcGG9VT-1e6HdA.png" /><figcaption>Targeted output for the text file information extraction</figcaption></figure><p>I would also include the length of the text (in number of tokens), to make it easier to filter for shorter or longer texts later on. To store the extracted data, I would suggest a tab-separated-values (.tsv) file, since commas or semicolons could be present in the text column.</p><h3>3. Coding</h3><p>Thanks to the previous steps, we know the data we are dealing with and what kind of information we want to output at the end of the transformation process. As you might know by now, I like to break tasks into smaller parts. The coding step doesn’t constitute an exception to this :) Generally, I would split the coding into at least three different parts and wrap them in individual functions:</p><ul><li>Reading and splitting a file</li><li>Extracting the information</li><li>Building the data frame</li></ul><p>In order to make this news article extractor reusable, I create a new class that implements the functions.</p><h4>Reading and splitting a file</h4><p>In order to read a file with python, we need the corresponding path consisting of the directory and the filename. As we observed in the Data Understanding step, the files are stored in their corresponding genre’s directory. This means that to access a file, we need the base path (‘data’ for me), its genre and its name.</p><p>If the file exists, we want to read it, split it by the new line characters (‘\n’), filter empty strings and return the remaining text sections as a list. In the case, that the file doesn’t exist (e.g. the file number is larger than the number of available files), we want to return an empty list. I prefer this rather than working with exceptions or returning none, if the file doesn’t exist.</p><pre>def read_and_split_file(self, genre: str, file_name: str) -&gt; list:<br>    text_data = list()<br>    current_file = os.path.abspath(os.path.join(&#39;data&#39;, genre, file_name))<br>    if os.path.exists(current_file):<br>        open_file = open(current_file, &#39;r&#39;, encoding=&quot;latin-1&quot;)<br>        text_data = open_file.read().split(&#39;\n&#39;)<br>        text_data = list(filter(None, text_data))<br>    return text_data</pre><p>As you can see in the code above, uses the os package. Thus, we need to import this package.</p><h4>Extracting the information</h4><p>In order to extract the information of the text files and prepare these for the next step, I would suggest pursuing this for every genre. This means, that we loop over every file in the corresponding genre’s directory. By keeping a current_number variable, we can format the filename with the leading zeros and then read and split the file by calling the above-implemented method.</p><p>If the returned list is empty, we want to stop the loop, since this means, that we reached the end of the loop and that there aren’t any new files left in the directory.</p><p>Otherwise, we add the returned information of the reading and splitting function to specific data containers, such as titles, subtitles, and texts. Since I suggested to also provide the token count of the text in the final output, we can use the nltk package to tokenize the text and add the length of the list of tokens to our token_counts list. Finally, we increment the current_number by 1 to continue the extraction process with the next file.</p><pre>def extract_genre_files(self, genre: str) -&gt; pd.DataFrame:<br>    found = True<br>    current_number = 1<br>    titles = list()<br>    subtitles = list()<br>    texts = list()<br>    token_counts = list()<br>    while found:<br>        file_name = &quot;{:03d}.txt&quot;.format(current_number)<br>        text_data = self.read_and_split_file(genre, file_name)<br>        if len(text_data) != 0:<br>            titles.append(text_data[0])<br>            subtitles.append(text_data[1])<br>            article_text = &#39; &#39;.join(text_data[2:])<br>            texts.append(article_text)<br>            token_counts.append(len(nltk.word_tokenize(article_text)))<br>            current_number += 1<br>        else:<br>            found = False<br><br>    genres = [genre] * len(titles)<br>    data = {&#39;genre&#39;: genres, &#39;title&#39;: titles, &#39;subtitle&#39;: subtitles, &#39;text&#39;: texts, &#39;token_counts&#39;: token_counts}<br>    data_frame = pd.DataFrame(data)<br>    return data_frame</pre><p>After finishing the loop through the genre files, we create a data frame based on the extracted information that was stored inside the specific lists. Similar to the previous step, we need to import two packages (nltk and pandas). Please also make sure, that you have downloaded the ‘punkt’ data of the nltk package, since it is required to tokenize texts.</p><pre>import nltk<br># nltk.download(&#39;punkt&#39;)<br>import pandas as pd</pre><h4>Building the data frame</h4><p>In a final step, we have to create a loop over the existing genres, extract the information per genre by calling the above-implemented method, concatenating the output for every genre and finally saving the concatenated data frame as a csv with the desired separator.</p><pre>def transform_texts_to_df(self, name, genre_list, delimiter = &#39;\t&#39;):<br>    article_df_list = list()<br>    for genre in genre_list:<br>        article_df_list.append(self.extract_genre_files(genre))<br>    df = pd.concat(article_df_list)<br>    df.to_csv(name, sep=delimiter)<br>    return df</pre><p>After implementing the class and its method, we need to create an instance of the ArticleCSVParser class and call the transform_texts_to_df method by providing the desired name for the resulting csv and a list containing every genre. Et voilà.</p><pre>if __name__ == &quot;__main__&quot;:<br>    genre_list = [&#39;business&#39;, &#39;entertainment&#39;, &#39;politics&#39;, &#39;sport&#39;, &#39;tech&#39;]<br>    parser = ArticleCSVParser()<br>    df = parser.transform_texts_to_df(&#39;bbc_articles.csv&#39;, genre_list)<br>    print(df.head())</pre><h3>Conclusion</h3><p>In this article, I showed how to transform text files into a data frame and save it as a csv/tsv. In order to reuse the class for a different data set, just create a new class that inherits from the ArticleCSVParser and override the methods that have to be changed.</p><p>You can find the complete code and dataset also in this <a href="https://github.com/guggio/bbc_news/tree/master/article_to_csv">repository</a>.</p><p>I hope you enjoyed and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=553def411855" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/transforming-text-files-to-data-tables-with-python-553def411855">Transforming  Text Files to Data Tables with Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>