<?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 Gabriel Naya on Medium]]></title>
        <description><![CDATA[Stories by Gabriel Naya on Medium]]></description>
        <link>https://medium.com/@gabriel-naya73?source=rss-4213edda07c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*mfIycxBDLi8n68Kw1-z6-g.jpeg</url>
            <title>Stories by Gabriel Naya on Medium</title>
            <link>https://medium.com/@gabriel-naya73?source=rss-4213edda07c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:23:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gabriel-naya73/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[What is beyond our model?]]></title>
            <link>https://medium.com/data-science/what-is-beyond-our-model-23b1354e905b?source=rss-4213edda07c------2</link>
            <guid isPermaLink="false">https://medium.com/p/23b1354e905b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gabriel Naya]]></dc:creator>
            <pubDate>Mon, 11 Jan 2021 21:52:12 GMT</pubDate>
            <atom:updated>2021-01-12T00:31:12.401Z</atom:updated>
            <content:encoded><![CDATA[<h4>We explore an architecture for a complete software solution: deploy a Python model, from the user interface to the connection with the model and obtaining the results.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*os6KuE5LJWlhjjjR" /><figcaption>Photo by <a href="https://unsplash.com/@xavier_von_erlach?utm_source=medium&amp;utm_medium=referral">Xavier von Erlach</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Background</h3><p>For a long time and especially in our exploration stage in the field of machine learning challenges, we focused on the search for a model that, starting from the data in a particular state, can act to obtain a result in the ranges of accurate we consider acceptable.<br>Well, the field of work to obtain the model is so extensive, complex, and fascinating in itself that it can make us lose sight of the rest of the components involved in a software solution.<br>Therefore our model will be surrounded by another set of problems as complex, extensive, and fascinating as the model itself we have developed, for example:</p><ul><li>The extraction and transformation of data to have a dataset similar to the one we started</li><li>The deployment of the model in production</li><li>Data collection and subsequent validation to monitor and correct our initial model.</li></ul><p>We will then meet the fields of <a href="https://es.wikipedia.org/wiki/Extract,_transform_and_load">ETL</a>, <a href="https://towardsdatascience.com/data-quality-impact-on-the-dataset-7dab41d36f8a">Data Wrangling</a> and <a href="https://en.wikipedia.org/wiki/MLOps">MLOps</a>.<br>As data scientists, it is no longer enough to find a model that will solve the challenge; we have to at least think about all these related areas’ feasibility. <br>Let us suppose for a moment that we manage to secure the data collection pipeline. <br>Let us suppose we defend ourselves during our feature engineering pipeline from new cases or anomalous data.<br>Let us suppose we get an efficient way to put it into production and store the datasets, and we can supervise the model behavior. <br>Ugh! It seems that we have everything planned. Right?</p><p><strong>Probably not!</strong></p><p>Possibly we lack software that interacts with the user to present the predictions results. Sometimes our model will connect with complex environments. It is necessary to create an API between them so that the model can display its results; sometimes it will be necessary to develop software to use our model.<br>This article will present a complete solution in a test case; the components and tools used can change by any other type of language, library, and architecture.</p><h3>The use case</h3><p>We start from a model developed in Python, which receives a CSV and returns an Excel file, adding a column with the prediction result.</p><p>We need to deploy in a server this model, and develop an user interface that:</p><ul><li>Login user</li><li>Allow the user to select a CSV file from any source in the appropriate format and upload it to the model.</li><li>Display a panel to the user with all the uploaded files and their status (processed, failure, progress).</li><li>Advertise the user when a model is finished processing.</li></ul><p>Additionally, we will envelope the model in an API to calling as a service by other software.</p><h3>Solution structure</h3><p>The proposed solution consists of six components and three access points.</p><p><strong>The components are in order of appearance:</strong><br>1) User Interface (WordPress + PHP)<br>2) Database (MySQL)<br>3) Repository in the server to store the input and output datasets<br>4) Scheduler (cronJob) to schedule the search of pending jobs and invoke the model<br>5) API for model execution (Pyhton — Uvicorn — Starlette)<br>6) Machine learning model in Python</p><p><strong>The access points to the system are:</strong><br>a) User, when uploading a new dataset to the application<br>b) Scheduler, when detecting a job to be processed<br>c) Someone with the right credentials wants to specifically invoke the model’s API to process a dataset registered in the database directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_LsPperwU0feFIk8BocDIA.png" /><figcaption>Image by author</figcaption></figure><p>The idea is that a user uploads through the interface a CSV to be processed. <br>Component 1 allows that and controls that the CSV is correct. It saves the database a job in “pending” status and deposits in the input repository the dataset.<br>Then, the scheduler checks every “x” time there is a pending job, takes it, and changes to an “in-process” state, invoking the function that invokes the model. The process’s result is deposited in the output repository, updating the task’s status to “Processed.”<br>From the user panel (point #1), you can detect jobs with errors, remove them from the job list, archive them, or retry them.</p><h3>The components</h3><h4>1 — User panel</h4><p>The user panel developed in Wordpress®, through a plugin the access and management of users:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nVM9vY6ls7_HtGuR4SVHZw.png" /><figcaption>Image by author</figcaption></figure><p>After access, the panel has a header where the user can select a dataset validated in its structure before loading it into the database as pending and leaving it in the input repository.</p><h4>2 — The database</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*KSXMOyk_w31dKSBOvStsyQ.png" /><figcaption>Image by author</figcaption></figure><p>The selected database was MySQL</p><p>The table “wp_records” on which the tasks recorded has the structure</p><h4>3 — Data repository</h4><p>The input and output repository are two directories defined on the server where the files are kept as entries generated in the task table.<br>Once the Python model processes a dataset and returns a CSV with the result, it saved in an output directory.</p><h4>4 — Scheduler ejecution</h4><p>The following code (process_files) is indicative of how to process the files, opens the database (open_db), looks for if there are tasks in the state “PENDING” and if there are, takes the first of them and invokes the prediction process (process_file).</p><pre>import mysql.connector as mysql<br>from mysql.connector import Error<br>from datetime import datetime<br>from jproperties import Properties</pre><pre>if __name__ == &#39;__main__&#39;:<br>   result = &#39;&#39;<br>   try:<br>      db = open_bd()<br>      cursor = db.cursor()<br>      sql_Query = &quot;SELECT id FROM wp_records WHERE status_file=&#39;IN PROCESS&#39;&quot;<br>      cursor.execute(sql_Query)<br>      records = cursor.fetchall()<br>      if (len(records) != 0):<br>          result = &#39;There are files in progress&#39; + str(records[0][0])<br>      else:<br>          sql_Query = &quot;SELECT id FROM wp_records WHERE status_file=&#39;PENDING&#39;&quot;<br>          cursor.execute(sql_Query)<br>          records = cursor.fetchall()<br>          if (len(records) &gt; 0):<br>             id = records[0][0]<br>             <strong>result = process_file(id)</strong><br>      except Error as e:<br>          result = &#39;Error &#39; + e<br>      finally:<br>          if (db.is_connected()):<br>             db.close()<br>             cursor.close()<br>             result = result + &#39; (BD correctly closed)&#39;</pre><p>The code to open the database has a configuration file ConfigFile.properties where the database and access credentials are defined.</p><pre>def open_bd():<br>   configs = Properties()<br>   with open(&#39;ConfigFile.properties&#39;, &#39;rb&#39;) as config_file:<br>      configs.load(config_file)<br>      host = configs.get(&quot;HOST&quot;)[0]<br>      user = configs.get(&quot;USER&quot;)[0]<br>      pass = configs.get(&quot;PASSWORD&quot;)[0]<br>      database = configs.get(&quot;DBNAME&quot;)[0]<br>      <br>      db = mysql.connect(<br>           host = host,<br>           user = user,<br>           passwd = pass,<br>           database=database)<br>      return db</pre><p>The code to process a specific file (a database id could be something like this):</p><pre><strong>def process_file(prm_id):</strong><br>   os.environ[&#39;TZ&#39;] = &#39;America/Montevideo&#39;<br>   time.tzset()<br>   resultado = &#39;&#39;<br>   try:<br>      db = open_bd()<br>      cursor = db.cursor()<br>      sql_Query = &quot;SELECT path_up FROM wp_records WHERE id=%s&quot;<br>      id = (prm_id,)<br>      cursor.execute(sql_Query, id)<br>      record = cursor.fetchone()<br>      input_file = str(record[0])<br>      upd_Query = &quot;UPDATE wp_records SET status_file = &#39;IN PROGRESS&#39;,date_init=%s WHERE id=%s&quot;<br>      today = datetime.today()<br>      params = (str(today),prm_id,)<br>      cursor.execute(upd_Query, params)<br>      db.commit()<br>      outfile = &#39;&#39;<br>      <strong>output_file = predictions.prediction(input_file)</strong><br>      today = datetime.today()<br>      upd_Query = &quot;UPDATE wp_registros SET status_file=&#39;PROCESS OK&#39;,path_result = %s,date_result=%s WHERE id=%s&quot;<br>      params = (output_file,str(today),prm_id,)<br>      cursor.execute(upd_Query, params)<br>      db.commit()<br>      resultado = &#39;OK - File was created [&#39; + output_file + &#39;]&#39;<br>   except Error as e:<br>      result = &#39;Error &#39; + e + &#39; processing id &#39; +  prm_id<br>   finally:<br>      if (db.is_connected()):<br>         db.close()<br>         cursor.close()<br>         result = result + &#39; (BD closed)&#39;<br>         return result</pre><h4>5 — Uvicorn and Startlette API</h4><p>The following is a Python code for developing an API using Uvicorn and Starlette, which must be installed (using pip install).</p><p>In our API we deploy three methods:</p><ul><li><strong>/</strong> to verify that the server is running and our API is working</li><li><strong>/process_file?id=id_base_data</strong> is a method to process a certain file, we must pass by parameter the id of the task table corresponding to the file to be processed (remember that in component 1 were created the entries in this table and downloaded the datasets into the repository)</li><li><strong>/process_all</strong> without parameters serves to search all entries for a slope and process it.</li></ul><pre>from starlette.applications import Starlette<br>from starlette.responses import JSONResponse<br>import uvicorn<br>import connect<br>import pendings<br>from datetime import datetime</pre><pre>app = Starlette(debug=True)<br>@app.route(&#39;<strong>/</strong>&#39;)<br>async def homepage(request):<br>   return JSONResponse({&#39;MySAMPLE&#39;: &#39;It works!&#39;})</pre><pre>@app.route(&quot;<strong>/process_file</strong>&quot;, methods=[&quot;GET&quot;])<br>   async def process_file(request):<br>   elid = request.query_params[&quot;id&quot;]<br>   before = datetime.today()<br>   <strong>result = connect.process_file(elid)</strong><br>   after = datetime.today()<br>   return JSONResponse({<br>      &quot;resulta&quot;: result,<br>      &quot;Start&quot; : str(before),<br>      &quot;End&quot; : str(after)})</pre><pre>@app.route(&quot;<strong>/process_all</strong>&quot;, methods=[&quot;GET&quot;])<br>async def process_all(request):<br>   before = datetime.today()<br>   <strong>result = pendings.process_files()</strong><br>   after = datetime.today()<br>   return JSONResponse({<br>      &quot;result&quot;: result,<br>      &quot;Start&quot; : str(before),<br>      &quot;End&quot; : str(after)})</pre><pre>if __name__ == &#39;__main__&#39;:<br>   <strong>uvicorn.run(app, host=&#39;0.0.0.0&#39;, port=8000)</strong></pre><p>The code that runs through the slopes and the one that processes a file specified in item #4</p><h4>6 — The Python model</h4><p>The model is in another module of the application and is not displayed in this article since it is not our goal to detail it here.</p><h3>Summary</h3><p>Unlike previous articles where we focused on the tools and approaches to a specific Machine Learning challenge, this time, we have presented another part of the effort, perhaps not as attractive but essential to transforming a solution to a use case into a complete solution.</p><p>Of course, each solution’s architecture defining according to the problem, with the client’s existing structure, the knowledge we have of the tools for each instance, or the people who complement our team.</p><p>There are many libraries and tools for each stage.</p><blockquote><strong>In a nutshell: talk about other aspects close to the model that could be necessary for a complete solution.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23b1354e905b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-is-beyond-our-model-23b1354e905b">What is beyond our model?</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[Data quality impact on the dataset]]></title>
            <link>https://medium.com/data-science/data-quality-impact-on-the-dataset-7dab41d36f8a?source=rss-4213edda07c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dab41d36f8a</guid>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[six-sigma]]></category>
            <category><![CDATA[data-governance]]></category>
            <dc:creator><![CDATA[Gabriel Naya]]></dc:creator>
            <pubDate>Sat, 14 Mar 2020 20:08:18 GMT</pubDate>
            <atom:updated>2020-03-15T16:11:22.305Z</atom:updated>
            <content:encoded><![CDATA[<h4>We look at the different aspects of data quality that impact on the dimensions of our dataset, and the importance of data quality in the organization that produces it.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FZlraFqhG8n_jZDg" /><figcaption>Photo by <a href="https://unsplash.com/@kmuza?utm_source=medium&amp;utm_medium=referral">Carlos Muza</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Background</h3><p>For the last year, my introduction in the machine learning field has been the focus on learning how to solve regression or classification problems on a given dataset. <br>When we started working on real use cases, we found that the dataset we received is the result of an organization that has developed a work to be able to elaborate it. <br>The quality of that dataset is directly related to the organization that manufactures it and how that organization works on data quality. <br>The sustainability of our model could also be related to the quality of data in the organization.<br>Beyond data engineering, the accuracy of the model itself, and the performance in its production, if the organization it serves does not have data quality as a priority, probably the model will not be sustained over time.</p><h4>Then, what is data quality?</h4><p>First, the data represents real-world objects, to talk about data quality in this article, we will work on a dataset format. Each column is a “dataset” of the dataset, and each cell is the particular value that that dataset acquires for a row.<br>Usually, when we think about data quality, we think about the value of the data and its accuracy. However, data quality encompasses multiple aspects, which are called dimensions and which we will discuss in more detail later, but are common dimensions of data: accuracy, uniqueness, completeness, validity, consistency.<br>The most common definition of data quality is that which determines that the data can fulfill the function for which it was collecting.</p><h4>Importance and benefits</h4><blockquote>Maintaining data quality is a difficult but necessary task. In order to achieve consistent and reliable data, businesses must constantly manage data quality so that they build trust and enable quicker, more knowledgeable decisions<em>.¹</em></blockquote><p>Poor data quality has a direct impact on the effectiveness and efficiency of the organization, especially over the entire life cycle of a task, and errors in different dimensions of the data can lead to financial losses or serious errors.<br>In contrast, an organization that works on the quality of the data it collects and produces, benefits on different levels:</p><ul><li>Incomplete or duplicated information is avoided.</li><li>Saves on communications and quality of service</li><li>Saves the cost of non-quality data, which leads to the cost of data quality paying for itself</li><li>Significantly improves the quality of results and inputs for future models or organizational decision making</li></ul><p>Undoubtedly the importance of data quality; the severity of the impact of errors and benefits vary from one use case to another, so it is difficult to cover these concepts conceptually without applying them directly on an example</p><h3>Types of errors in a dataset</h3><p>To develop the content of this case study article to help us affirm the concepts, we will use the well-known Kaggle dataset for learning: <a href="https://www.kaggle.com/c/home-data-for-ml-course/overview">Housing Prices Competition for Kaggle Learn Users</a>²</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*JACi9AS5DmyQn8V4NtxiUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2ZJvyjj5Dk-kEnV_V0UtQ.png" /></figure><h4>Errors due to incomplete information</h4><p>They can refer to missing cells within a datum (for example, the Alley field contains only 91 of the 1460 records, or worse, the “PoolQC” field). These are the famous “null” or “NaN” fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*guOSzwZ67hYVuTEw0vUJNQ.png" /></figure><p>But they can also be errors due to the omission of some data that may be relevant to a study.</p><p>Specifically, for the exercise of predicting sales prices, if in the dataset designed the “Neighborhood” or “LotArea” column was omitting, the quality of the predictions would be strongly affected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*3bWF47Qls3a-rq8P4faogQ.png" /><figcaption>Null values visualization using missingno</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*4ANpLlkHgNFX2IMKOx8gwg.png" /><figcaption>Correlation matrix about the location of missing values</figcaption></figure><h4>Syntax errors</h4><p>Syntax errors are related to the format of the data and how its value is representing. For example, in the YearBuilt field, we could not find values lowers than in 1700, or higher than the current year (2020).</p><p>In other hands, the Street data can support the following values:<br> Grvl — Gravel <br> Pave — Paved<br>If we found a value different from these and different from null, we would be facing a syntactic error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*aUFFskz851d3BpO58ypxZg.png" /></figure><p>If a date field is expecting to be in the format MM-DD-YYYY and some cells are YYYY-MM-DD or DD/MM/YYYY, we are also facing a syntax error.<br>As it is a dataset for educational use, it is challenging to find syntactic errors in the data. Still, we could look for outliers values, taking, for example, column GrLivArea, a data that appears in the last quintile that could be wrong entered data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*Ymp_T8vIumUZo1aPMqiYCg.png" /></figure><h4>Semantic errors</h4><p>Semantics conveys the meaning of data. <br>If in building year we input the sale year, we will have correct data from the syntactic (a valid year), but not from the semantic point of view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*1qL2kDaaNoOCC3DweIgXow.png" /><figcaption>No houses with YearBuilt greater than YearSold</figcaption></figure><p>However, if we look at the renovation year, data should indicate whether there was remodeling after construction and before sold. But we found a row in which the year of reconstruction is after the sale:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*4RsIVUyh0xRPlrBcDCZFmw.png" /><figcaption><em>YearRemodAdd: Remodel date (same as construction date if no remodeling or additions)</em></figcaption></figure><p>In this case, we faced with an error that can be syntactic and semantic:</p><ul><li>If there is no remodeling, it is syntactic since according to the definition the year if there is no remodeling, it must be equal to the year of construction</li><li>If remodeling was 2008, it is a semantic error since it does not represent a remodeling in the period between building and sale.</li></ul><p>A clear semantic error would be that the data “sale price” contains the area of the land (data entry error) or that the sale price corresponds to a partial commercial transaction, for example, a partial ground sale.</p><h3>Data quality dimensions</h3><p>At the beginning of this article, we mentioned some dimensions of quality: accuracy, uniqueness, completeness, validity, consistency.<br>One <strong>dimension</strong> is a set of quality factors with the same purpose; accuracy as a dimension is composed of semantic accuracy (closeness of the value to reality), syntactic, and precision (adequate scale of the data), among others.<br>A<strong> metric</strong> is a mechanism we use to measure one of the factors of the dimension, for example, the semantic correctness in the dimension accuracy of the LotArea data, we are going to measure it in the difference of square feet between the real value, and the one entered to the dataset. <br>The<strong> measurement</strong> is the process that implements the metric to obtain the value on the dimension factor. In the same example of the LotArea data, the dimension accuracy, the precision factor, the “difference in square feet” metric can be measured by a professional, estimated by an evaluator, using computer tools such as GoogleMaps®, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dgPAkeJEEUqRcamR" /><figcaption>Photo by <a href="https://unsplash.com/@linper?utm_source=medium&amp;utm_medium=referral">Linda Perez Johannessen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Over time, measurement processes evolve, or by characteristics of the type of problem, the same metric applied to a dimension can be measure in different ways, even as a way to validate or improve the measurement.<br>Dimensional factors can be related to their value (e.g. accuracy) as well as their intention and scheme (e.g. syntactic and semantic correctness).</p><h4>Main dimensions of data quality</h4><p>The names and approaches to defining dimensions corresponding and applying to each data of our dataset can vary given the context, as well as the theoretical and conceptual framework with which they are analyzed and defined.</p><h4>Accuracy</h4><blockquote>The proximity between a data value v and a data value v’, considered as the correct representation of the real-world phenomenon that v tries to represent.³</blockquote><p><strong>Semantic correctness</strong>: Proximity between the value <em>v</em> of an attribute and its real value <em>v’</em>.<br>If we have the LotArea data that represents the square footage of the land and in a cell, but if the price of the transaction is registered here by mistake, we will have a very weak correction (unless by chance the price and area data are similar!). <br>If, on the other hand, the square footage of the land is inputting in the data, the semantic correction is strong.</p><p><strong>Syntactic correctness</strong>: It represents the proximity between the value <em>v</em> of an attribute and the elements of the domain of definition of this attribute. If the YrSold data is representing, years of sales after today, or before the beginning of the dataset records, cannot be included.</p><p><strong>Accuracy</strong>: Captures the degree of detail that a data has that makes it useful for a specific use or that allows it to be discriminating from other data that are not the same. <br>If the LotArea data is in hectares without decimals, it would not be handy for estimation in urban datasets. <br>If you want to measure the time of production processes and you do not store the “Hour, minute, second”; if you only save the starting and finish day, you will not be able to access the calculation of hours, minutes, and seconds.</p><h4>Consistency</h4><blockquote>It captures the violation of semantic rules defined over a set of business entities or their attributes. In a relational model, integrity constraints are an example of such semantic rules.³</blockquote><p><strong>Inter-entity integrity: </strong>It captures rule satisfaction between attributes of different business entities. Also known as referential integrity refers to an attribute of an entity consistency with other entities.<br>For example, in a list of items of a recipe, the product code is related to a “products” entity, it is a violation of that rule if the recipe has an item with a non-existent product code, or that was removed from the products entity.</p><p><strong>Intra-entity integrity: </strong>Captures the satisfaction of rules between attributes of the same entity. Also known as relational integrity, it refers to the integrity within an entity. <br>For example, one address with the zone belongs to the state. <br>Or in the recipe example, where the item is from another recipe or one procedure does not apply to one thing (e.g., beating the flour).</p><p><strong>Domain integrity: </strong>Captures the satisfaction of rules about the possible values that an attribute can take<br>Examples of domain integrity violations are if the identity document types admitted on an input-form can be passport or DNI, and a civic credential is registering.</p><h4>Completeness</h4><blockquote>Captures the satisfaction of rules about the possible values that an attribute can take³</blockquote><p><strong>Coverage: </strong>Captures the ratio of the number of entities in a given data collection to the total number of entities that should exist in that collection.<br>Coverage measurement can be on a closed domain or an open domain. <br>The coverage ratio is the proportion of covered items over the total items in the domain.</p><p><strong>Density: </strong>Captures the ratio of the number of attribute instances with non-zero values to the total number of instances of that attribute<br>The density ratio will depend on the criterion assumed about the null values of a certain data.</p><h4>Uniqueness</h4><blockquote>It captures the degree to which a piece of real-world data is uniquely representing.³</blockquote><p><strong>Non-duplication</strong>: Captures the degree of duplication (or repetition) of the same data. It refers to the possibility of a tuple being duplicated in the dataset representing the same entity. <br>In the case of the housing dataset, each tuple represents a transaction, so the definition of uniqueness is not given by having two tuples referring to the same property, but yes to the same transaction on the same property.<br>In a club roll, for example, a case of duplication would be two rows representing the same person.</p><p><strong>Non-contradiction:</strong> Captures the degree of duplication (or repetition) of the same instance of the real-world entity that is represented with contradictory data.<br>For example, it refers to a club’s membership that has two tuples with similar identifiers (for example, DNI 1971449–3 and 1971449–8) referring to people with similar names but different addresses or contradictory data (different genders).</p><h4>Timeliness</h4><blockquote>Captures how quickly real-world changes are reflecting in updated data³</blockquote><p><strong>Freshness</strong> is a type of non-structural accuracy dependent on the time variable, which means that data that is correct at one time may not be correct at another time.</p><p><strong>Actuality: </strong>Captures the time delay between a change in the real world and the corresponding data update.<br>If age is represented in its numerical value without referring to the date of birth, it systematically presents a problem of actuality.<br>The same applies to any measurement of a living organism.</p><p>Could exist some exogenous changes to the nature of the data; for example, the telephone company decides to add a prefix to all phones in such an area as of March 1. If no update is applying to the data, it automatically becomes out of date on that day.</p><p><strong>Timeliness:</strong> Captures the delay between the update of data and the moment it is available for use.<br>For example, if we carry out a study on the evolution of sales in the last year, and the meeting delayed by six months, we will inevitably face a problem of the opportunity of the validity of the data.</p><h3>What to do in the organization?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nbgLtHyog-Ewx8sB" /><figcaption>Photo by <a href="https://unsplash.com/@maximilianweisbecker?utm_source=medium&amp;utm_medium=referral">Maximilian Weisbecker</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Data Governance</h4><blockquote>A large amount of data that company’s business processes are delivering is a source of information that can help generate value by supporting decision making with quantitative, reliable, and timely elements. This need to use data to generate relevant information requires the establishment of a set of definitions, rules, and processes that regulate how the data will be treated, this set is called Data Governance.⁴</blockquote><p>Data governance affects different aspects of the organization, such structure, rules, decision making, responsibilities, and the entire operation of data management.</p><p>The organization data governance programs, then, are aimed at improving some or all of the above aspects.</p><p>Usually, we work with one of the following frameworks:</p><ul><li>DMBOK — Data Management Book of Knowledge. It provides specific details to define, implement, and operate the Management and Use of Data.⁵</li><li>TOGAF — The Open Group Architecture Framework. Defines the process for creating a data architecture as part of the overall architecture of an enterprise. It can be a precursor to implementing Data Management.⁶</li><li>COBIT — Control Objectives for Information and related Technology. It delivers Data Governance as a part of the overall Governance of the Information Technology area. It has a model to determine the degree of maturity of the Data Management processes in use in an organization.⁷</li><li>DGI Data Governance Framework. It is a simple reference framework to generate Data Governance. It provides a logical structure to classify, organize, and communicate complex decision-making activities and the execution of actions related to the data of an enterprise.⁸</li></ul><h4>Six-sigma methodology</h4><blockquote>The method applied, which is called DMAIC (Define, Measure, Analyze, Improve, Control), uses statistical tools, as well as devices that observe process variables and their relationships, which help manage their characteristics.<br>In short, it is a data-based method for taking Quality to near-perfect levels, different from other approaches because it also corrects problems before they occur. More specifically, it is a disciplined effort to examine companies’ repetitive processes.⁹</blockquote><p>e c</p><h3>Summary</h3><p>We have tried to develop some definitions linked to data quality, to introduce the concept within artificial intelligence, machine learning, or data scientists enthusiast.</p><p>In the different courses and tutorials focused on these disciplines, we rarely think about the origin of the dataset and the work that the organization that delivers it does to generate it.</p><p>When we work on real-life use cases and models that must be fed back and retrained with the new information, we will find that the level of data quality of the organization can make our work fail in the long term.</p><p>We must be attentive to all these elements before putting the work in production and help organizations to improve it.</p><h4>References</h4><p>[1] <a href="https://www.edq.com/glossary/data-quality-importance/">https://www.edq.com/glossary/data-quality-importance/</a></p><p>[2] <a href="https://www.kaggle.com/c/home-data-for-ml-course/overview">https://www.kaggle.com/c/home-data-for-ml-course/overview</a></p><p>[3] <a href="https://www.gub.uy/agencia-gobierno-electronico-sociedad-informacion-conocimiento/sites/agencia-gobierno-electronico-sociedad-informacion-conocimiento/files/documentos/publicaciones/Framework%20para%20la%20Gesti%C3%B3n%20de%20la%20Calidad%20de%20Datos%20v1.0.pdf">https://www.gub.uy/agencia-gobierno-electronico-sociedad-informacion-conocimiento/sites/agencia-gobierno-electronico-sociedad-informacion-conocimiento/files/documentos/publicaciones/Framework%20para%20la%20Gesti%C3%B3n%20de%20la%20Calidad%20de%20Datos%20v1.0.pdf</a></p><p>[4] <a href="https://msaffirio.wordpress.com/2017/01/11/gobernabilidad-de-datos/">https://msaffirio.wordpress.com/2017/01/11/gobernabilidad-de-datos/</a></p><p>[5] <a href="https://www.dama.org/content/body-knowledge">https://www.dama.org/content/body-knowledge</a></p><p>[6]<a href="http://www.opengroup.org/subjectareas/enterprise/togaf">http://www.opengroup.org/subjectareas/enterprise/togaf</a></p><p>[7] <a href="http://www.isaca.org/cobit/pages/default.aspx">http://www.isaca.org/cobit/pages/default.aspx</a></p><p>[8] <a href="http://www.datagovernance.com/the-dgi-framework/">http://www.datagovernance.com/the-dgi-framework/</a></p><p>[9] <a href="http://triflenew.blogspot.com/2015/03/six-sigma.html">http://triflenew.blogspot.com/2015/03/six-sigma.html</a></p><h4>Sources</h4><p><a href="https://www.fing.edu.uy/inco/grupos/gris/wiki/uploads/ProyectosGrado/ValverdeBianchi-ProyGrado.pdf">FING: https://www.fing.edu.uy/inco/grupos/gris/wiki/uploads/ProyectosGrado/ValverdeBianchi-ProyGrado.pdf</a></p><p>AGESIC: <a href="https://www.gub.uy/agencia-gobierno-electronico-sociedad-informacion-conocimiento/sites/agencia-gobierno-electronico-sociedad-informacion-conocimiento/files/documentos/publicaciones/Framework%20para%20la%20Gesti%C3%B3n%20de%20la%20Calidad%20de%20Datos%20v1.0.pdf">https://www.gub.uy/agencia-gobierno-electronico-sociedad-informacion-conocimiento/sites/agencia-gobierno-electronico-sociedad-informacion-conocimiento/files/documentos/publicaciones/Framework%20para%20la%20Gesti%C3%B3n%20de%20la%20Calidad%20de%20Datos%20v1.0.pdf</a></p><p>Experian: <a href="https://www.edq.com/glossary/data-quality-importance/">https://www.edq.com/glossary/data-quality-importance/</a></p><p>Sigma: <a href="http://sigma-data.com/que-es-la-calidad-de-datos/">http://sigma-data.com/que-es-la-calidad-de-datos/</a></p><p>CPE — Data quality and machine learning courses</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dab41d36f8a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/data-quality-impact-on-the-dataset-7dab41d36f8a">Data quality impact on the dataset</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[Available hyperparameter optimization techniques]]></title>
            <link>https://medium.com/data-science/available-hyperparameter-optimization-techniques-dc60fb836264?source=rss-4213edda07c------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc60fb836264</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Gabriel Naya]]></dc:creator>
            <pubDate>Tue, 07 Jan 2020 19:34:53 GMT</pubDate>
            <atom:updated>2020-01-08T14:29:20.434Z</atom:updated>
            <content:encoded><![CDATA[<h3>Available hyperparameter-optimization techniques</h3><h4>We apply three different techniques of hyperparameter optimization on a classification model set to compare their accuracy.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pxDkDWG3ipmIBrYW" /><figcaption>Photo by <a href="https://unsplash.com/@vaniashows?utm_source=medium&amp;utm_medium=referral">Vania Shows</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Background</h3><p>I have often received articles referring to automation searching for hyperparameter optimization. Once I have understood the intent and scope of these techniques, I have wondered how much a model can be improved through this optimization.<br>The aim of this article is then to investigate the different available optimization techniques, and test them on a simple example, compare them and see an overview of the improvements obtained.</p><p>Hyperparameters are model adjustable parameters that must be tuned to obtain a model with optimal performance. Then, optimizing the hyperparameters of a model is a crucial task to increase the performance of the selected algorithm.</p><p>We need to know, to some extent, the implication that each hyperparameter has in each algorithm and its possible values. Understanding in-depth the meaning of each of these hyperparameters in the different algorithms is something necessary and a huge task that sometimes implies knowing the way the algorithm works internally and the mathematics behind it. The content of this article does not reach that depth, although we will use different algorithms to analyze by selecting some hyperparameters in each of them.</p><p>Anyone who has used any algorithm has probably already made some manual optimization attempts on the default set of values. This manual adjustment usually takes a long time, is not always done rigorously and makes it difficult to systematize the results</p><p>Secondly, we can apply available automated and quite simple techniques such as Grid Search and Random Search, which usually give better results, but with a high cost of time and machine computation. We will apply both techniques to compare their results</p><p>Finally, we will apply Bayesian optimization, which is a method to find the minimum of a function, using the hyperopt library of Python on the best of the tested algorithms. The implementation of this technique may not be so easy, but it can give us better results in performance or time than the previous ones.</p><h3>The dataset</h3><p>The dataset we will use for the exercise is <a href="https://www.kaggle.com/c/titanic/data">Kaggle’s Titanic passenger dataset</a>, which is a binary classification exercise to predict which passengers have survived and which have not.</p><pre>import os<br>import numpy as np  # linear algebra<br>import pandas as pd  #<br>from datetime import datetime<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import SGDClassifier<br>from sklearn.linear_model import RidgeClassifier<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.svm import SVC<br>from sklearn.ensemble import BaggingClassifier<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.linear_model import LogisticRegression<br>import lightgbm as lgb<br>from sklearn.metrics import confusion_matrix<br>import scikitplot as skplt</pre><pre>%matplotlib inline</pre><pre>np.random.seed(7)<br>train = pd.read_csv(&#39;./data/train.csv&#39;, index_col=0)<br>y = train.Survived  #.reset_index(drop=True)<br>features = train.drop([&#39;Survived&#39;], axis=1)<br>features.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*x-xWJxIkRQLIaeikS8rLCw.png" /></figure><p>Metric selected is accuracy¹: the percentage of passengers correctly predicted. <br>Accuracy = (TP+TN) / (Total)</p><h3>Feature engineering and results data frame</h3><p>We are going to apply fundamental techniques of data engineering that will allow us to use the algorithms without errors (remember that it is not the objective of this article to obtain a good result, only to compare the performance when applying optimization techniques).</p><p>We select eight algorithms to perform the work; this decision is based on reusing part of the work of <a href="https://machinelearningmastery.com/author/jasonb/">Jason Brownlee</a>² and <a href="https://towardsdatascience.com/@williamkoehrsen?source=post_page-----dfda59b72f8a----------------------">Will Koehrsen³</a> that have developed much of the code used here.</p><p>Each of these models will be a different column in our results table:</p><ol><li>Stochastic Gradient Boosting</li></ol><p>2. Ridge Classifier</p><p>3. K-Nearest Neighbors (KNN)</p><p>4. Support Vector Machine (SVM)</p><p>5. Bagged Decision Trees</p><p>6. Random Forest</p><p>7. Logistic Regression</p><p>8. LGBM</p><p>For each of these columns, we will try to apply the following optimization techniques:</p><ul><li>Default hyperparameters</li><li>Sklearn GridSearchCV</li><li>Sklearn RandomizedSearchCV</li><li>Hyperopt for Python</li></ul><pre>features = features.drop([&#39;Cabin&#39;], axis=1)<br>features = features.drop([&#39;Name&#39;], axis=1)<br>objects = [col for col in features.columns if features[col].dtype == &quot;object&quot;]</pre><pre>features.update(features[objects].fillna(&#39;None&#39;))<br>numeric_dtypes = [&#39;int16&#39;, &#39;int32&#39;, &#39;int64&#39;, &#39;float16&#39;, &#39;float32&#39;, &#39;float64&#39;]<br>numerics = [col for col in features.columns if features[col].dtype in numeric_dtypes]<br>features.update(features[numerics].fillna(0))<br>features.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*gaoFsml1sgO7VjrYJyQkug.png" /></figure><pre># dummies and split<br>X = pd.get_dummies(features)<br>X_train, X_valid, y_train, y_valid = train_test_split(X,y,train_size=0.70,test_size=0.30,random_state=0)</pre><pre>#Results dataframe<br>cols = [&#39;Case&#39;,&#39;SGD&#39;,&#39;Ridge&#39;,&#39;KNN&#39;,&#39;SVM&#39;,&#39;Bagging&#39;,&#39;RndForest&#39;,&#39;LogReg&#39;,&#39;LGB&#39;]</pre><pre>resul = pd.DataFrame(columns=cols)<br>resul.set_index(&quot;Case&quot;,inplace=True)<br>resul.loc[&#39;Standard&#39;] = [0,0,0,0,0,0,0,0]<br>resul.loc[&#39;GridSearch&#39;] = [0,0,0,0,0,0,0,0]<br>resul.loc[&#39;RandomSearch&#39;] = [0,0,0,0,0,0,0,0]<br>resul.loc[&#39;Hyperopt&#39;] = [0,0,0,0,0,0,0,0]</pre><pre>resul.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*eJoolmH_x-P5BnX4sMr8Xg.png" /><figcaption>Empty dataframe for results</figcaption></figure><h3>Row 1 — Default hyperparameters of each algorithm</h3><p>As mentioned above, the first row of our results table is the starting point of the analysis, taking the default values for the hyperparameters of each of the algorithms:</p><pre>#Models creation<br>sgd   = SGDClassifier()<br>ridge = RidgeClassifier()<br>knn   = KNeighborsClassifier()<br>svc   = SVC(gamma=&#39;auto&#39;)<br>bag   = BaggingClassifier()<br>rf    = RandomForestClassifier(n_estimators=10)<br>lr    =  LogisticRegression(solver=&#39;liblinear&#39;)<br>lgg   = lgb.LGBMClassifier()</pre><pre>models = [sgd,ridge,knn,svc,bag,rf,lr,lgg]</pre><pre>col = 0<br>for model in models:<br>    model.fit(X_train,y_train.values.ravel())<br>    resul.iloc[0,col] = model.score(X_valid,y_valid)<br>    col += 1</pre><pre>resul.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*742QnZvFaJxVOcspuH9urg.png" /></figure><h3>Row 2—Applying GridSearchCV</h3><blockquote>“Grid search works by trying every possible combination of parameters you want to try in your model. Those parameters are each tried in a series of cross-validation passes. This technique has been in vogue for the past several years as a way to tune your models” ⁴.</blockquote><p>Now we must define a dictionary with the different parameters and their values for each algorithm</p><pre>from sklearn.model_selection import GridSearchCV<br>from sklearn.model_selection import RepeatedStratifiedKFold</pre><pre>#SGD<br>loss = [&#39;hinge&#39;, &#39;modified_huber&#39;, &#39;log&#39;]<br>penalty = [&#39;l1&#39;,&#39;l2&#39;]<br>alpha= [0.0001,0.001,0.01,0.1]<br>l1_ratio= [0.15,0.05,.025]<br>max_iter = [1,5,10,100,1000,10000]<br>sgd_grid = dict(loss=loss,penalty=penalty,max_iter=max_iter,alpha=alpha,l1_ratio=l1_ratio)</pre><pre>#Ridge<br>alpha = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]<br>ridge_grid = dict(alpha=alpha)</pre><pre>#K-Nearest - Neighborg<br>n_neighbors = range(1, 21, 2)<br>weights = [&#39;uniform&#39;, &#39;distance&#39;]<br>metric = [&#39;euclidean&#39;, &#39;manhattan&#39;, &#39;minkowski&#39;]<br>knn_grid = dict(n_neighbors=n_neighbors,weights=weights,metric=metric)</pre><pre>#Support Vector Classifier<br>kernel = [&#39;poly&#39;, &#39;rbf&#39;, &#39;sigmoid&#39;]<br>C = [50, 10, 1.0, 0.1, 0.01]<br>gamma = [&#39;scale&#39;]<br>svc_grid = dict(kernel=kernel,C=C,gamma=gamma)</pre><pre>#Bagging Classifier<br>n_estimators = [10, 100, 1000]<br>bag_grid = dict(n_estimators=n_estimators)</pre><pre>#Random Forest<br>n_estimators = [10, 100, 1000,10000]<br>max_features = [&#39;sqrt&#39;, &#39;log2&#39;]<br>rf_grid = dict(n_estimators=n_estimators,max_features=max_features)</pre><pre>#Logistic Regrresion<br>solvers = [&#39;newton-cg&#39;, &#39;lbfgs&#39;, &#39;liblinear&#39;]<br>penalty = [&#39;l2&#39;]<br>c_values = [100, 10, 1.0, 0.1, 0.01]<br>lr_grid = dict(solver=solvers,penalty=penalty,C=c_values)</pre><pre>#LGB<br>class_weight = [None,&#39;balanced&#39;]<br>boosting_type = [&#39;gbdt&#39;, &#39;goss&#39;, &#39;dart&#39;]<br>num_leaves = [30,50,100,150] #list(range(30, 150)),<br>learning_rate = list(np.logspace(np.log(0.005), np.log(0.2), base = np.exp(1), num = 10)) #1000<br>lgg_grid = dict(class_weight=class_weight, boosting_type=boosting_type, num_leaves=num_leaves, learning_rate =learning_rate)</pre><p>Then, apply GridSearchCV for each one:</p><pre>models = [sgd,ridge,knn,svc,bag,rf,lr,lgg]<br>grids = [sgd_grid,ridge_grid,knn_grid,svc_grid,bag_grid,rf_grid,lr_grid,lgg_grid]</pre><pre>col = 0<br>for ind in range(0,len(models)):<br>    cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, <br>                                 random_state=1)</pre><pre>    grid_search = GridSearchCV(estimator=models[col], <br>                  param_grid=grids[col], n_jobs=-1, cv=cv,  <br>                  scoring=&#39;accuracy&#39;,error_score=0)</pre><pre>    grid_clf_acc = grid_search.fit(X_train, y_train)<br>    resul.iloc[1,col] = grid_clf_acc.score(X_valid,y_valid)<br>    col += 1</pre><pre>resul.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*jMqgGsK3UfqbhV_Yh5HthA.png" /></figure><p>The different algorithms have many more parameters that have not been deliberately including here, and you could force searches to many more values in each hyperparameter. <br>This reduction has been developing according to the time and computing capacity that we are willing to invest.</p><h3>Row 3— Applying RandomSearchCV</h3><blockquote>“Enter randomized search. Consider trying every possible combination takes a lot of brute force computation. Data Scientists are an impatient bunch, so they adopted a faster technique: randomly sample from a range of parameters. The idea is that you will cover on the near-optimal set of parameters faster than grid search. This technique, however, is naive. It doesn’t know or remember anything from its previous runs.” ⁴</blockquote><p>For practical purposes, the code is identical to GridSearchCV by modifying:</p><pre>random_search = RandomizedSearchCV(models[col], <br>                param_distributions=grids[col],n_iter=n_iter_search, <br>                cv=cv)</pre><p>instead of</p><pre>grid_search = GridSearchCV(estimator=lr, param_grid=lr_grid, <br>              n_jobs=-1, cv=cv, scoring=&#39;accuracy&#39;,error_score=0)</pre><p>Here the complete code:</p><pre>from scipy.stats import randint as sp_randint<br>from sklearn.model_selection import RandomizedSearchCV</pre><pre>col = 0<br>for ind in range(0,len(models)):<br>    cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, <br>                                 random_state=1)<br>    n_iter_search = 3<br>    random_search = RandomizedSearchCV(models[col],<br>    param_distributions=grids[col],n_iter=n_iter_search, cv=cv)</pre><pre>    random_search.fit(X_train,y_train)<br>    resul.iloc[2,col] = random_search.score(X_valid,y_valid)<br>    col += 1</pre><pre>resul.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*k2FDUwFHQjUC5_54dnLGSQ.png" /></figure><h3>Analyzing the results</h3><p>So far, if we check the results grid, we find that the application of automated search techniques has given good results.<br>In some cases, like SGD or SVM algorithm has been much improved, from a 67–69% floor to 78–76%.<br>The general trend has been to improve 1, 2, or 3 percentage points, obtaining better results with GridSearchCV than with RandomSearchCV, being the random application times better than those of the grid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*HgM_lnb6Xb9zidc4IbJj1Q.png" /></figure><p>Let’s analyze the winning algorithm (Light Gradient Boost) in his version of GridSearchCV:</p><pre>cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3,  <br>                             random_state=1)<br>n_iter_search = 3<br>grid_search = GridSearchCV(estimator=lgg, param_grid=lgg_grid, <br>              n_jobs=-1, cv=cv, scoring=&#39;accuracy&#39;,error_score=0)<br>grid_win = grid_search.fit(X_train, y_train)</pre><pre>#Predict values based on new parameters<br>yv_pred = grid_win.predict(X_valid)</pre><pre>print(confusion_matrix(y_valid, yv_pred))<br>skplt.metrics.plot_confusion_matrix(y_valid, yv_pred,figsize=(8,8))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*ymkWp5K5oZJM7HZxFhBSgg.png" /></figure><p>To know the hyperparameters found in this version of the algorithm we use:</p><pre>print(&quot;Best: %f using %s&quot; % (grid_win.best_score_, grid_win.best_params_))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*varZlJAmiuQftr6eOj4L8w.png" /></figure><h3>Row 4 — Applying bayesian hyperoptimization with hyperopt library</h3><p>I must confess that before I understood how to apply the Bayesian optimization technique, I felt quite lost and confused, to the point of being close to giving up. <br>The documentation and examples both from the library and from other articles that I could take as references are quite vague, or too dull, or very outdated. <br>All this until I found this <a href="https://towardsdatascience.com/automated-machine-learning-hyperparameter-tuning-in-python-dfda59b72f8a">excellent tutoria</a>l⁵ and its <a href="https://github.com/WillKoehrsen/hyperparameter-optimization/blob/master/Bayesian%20Hyperparameter%20Optimization%20of%20Gradient%20Boosting%20Machine.ipynb">code</a>⁶ by <a href="https://towardsdatascience.com/@williamkoehrsen?source=post_page-----dfda59b72f8a----------------------">Will Koehrsen</a>, which I advise you to review and try step by step since it is clear and exhaustive. Following him, the first thing we are going to do is to define our objective function that must return a dictionary at least with the tags ‘loss’ and ‘status’.</p><pre>import csv<br>from hyperopt import STATUS_OK<br>from timeit import default_timer as timer</pre><pre>MAX_EVALS = 500<br>N_FOLDS = 10</pre><pre>def objective(params, n_folds = N_FOLDS):</pre><pre>   &quot;&quot;&quot;Objective function for Gradient Boosting Machine Hyperparameter Optimization&quot;&quot;&quot;</pre><pre>   # Keep track of evals<br>   global ITERATION<br>   ITERATION += 1</pre><pre>   # Retrieve the subsample if present otherwise set to 1.0<br>   subsample = params[&#39;boosting_type&#39;].get(&#39;subsample&#39;, 1.0)</pre><pre>   # Extract the boosting type<br>   params[&#39;boosting_type&#39;] = params[&#39;boosting_type&#39;]<br>         [&#39;boosting_type&#39;]<br>   params[&#39;subsample&#39;] = subsample</pre><pre>   # Make sure parameters that need to be integers are integers<br>   for parameter_name in [&#39;num_leaves&#39;, &#39;subsample_for_bin&#39;, <br>                          &#39;min_child_samples&#39;]:<br>       params[parameter_name] = int(params[parameter_name])</pre><pre>   start = timer()<br>   # Perform n_folds cross validation<br>   cv_results = lgb.cv(params, train_set, num_boost_round = 10000, <br>                       nfold = n_folds, early_stopping_rounds = 100, <br>                       metrics = &#39;auc&#39;, seed = 50)<br>   run_time = timer() - start</pre><pre>   # Extract the best score<br>   best_score = np.max(cv_results[&#39;auc-mean&#39;])</pre><pre>   # Loss must be minimized<br>   loss = 1 - best_score</pre><pre>   # Boosting rounds that returned the highest cv score<br>   n_estimators = int(np.argmax(cv_results[&#39;auc-mean&#39;]) + 1)</pre><pre>   # Write to the csv file (&#39;a&#39; means append)<br>   of_connection = open(out_file, &#39;a&#39;)<br>   writer = csv.writer(of_connection)<br>   writer.writerow([loss, params, ITERATION, n_estimators, <br>                   run_time])</pre><pre>   # Dictionary with information for evaluation<br>   return {&#39;loss&#39;: loss, &#39;params&#39;: params, &#39;iteration&#39;: ITERATION,<br>           &#39;estimators&#39;: n_estimators, &#39;train_time&#39;: run_time, <br>           &#39;status&#39;: STATUS_OK}</pre><blockquote>Domain Space: The domain space represents the range of values we want to evaluate for each hyperparameter. Each iteration of the search, the Bayesian optimization algorithm will choose one value for each hyperparameter from the domain space. When we do random or grid search, the domain space is a grid. In Bayesian optimization the idea is the same except this space has <em>probability distributions </em>for each hyperparameter rather than discrete values.</blockquote><pre>space = {<br>&#39;class_weight&#39;: hp.choice(&#39;class_weight&#39;, [None, &#39;balanced&#39;]),<br>&#39;boosting_type&#39;: hp.choice(&#39;boosting_type&#39;, [<br>{&#39;boosting_type&#39;: &#39;gbdt&#39;, &#39;subsample&#39;: hp.uniform(&#39;gdbt_subsample&#39;, 0.5, 1)},<br>{&#39;boosting_type&#39;: &#39;dart&#39;, &#39;subsample&#39;: hp.uniform(&#39;dart_subsample&#39;, 0.5, 1)},<br>{&#39;boosting_type&#39;: &#39;goss&#39;, &#39;subsample&#39;: 1.0}]),</pre><pre>&#39;num_leaves&#39;: hp.quniform(&#39;num_leaves&#39;, 30, 150, 1),<br>&#39;learning_rate&#39;: hp.loguniform(&#39;learning_rate&#39;, np.log(0.01), <br>                                                np.log(0.2)),<br>&#39;subsample_for_bin&#39;: hp.quniform(&#39;subsample_for_bin&#39;, 20000, <br>                                                      300000),<br>&#39;min_child_samples&#39;: hp.quniform(&#39;min_child_samples&#39;, 20, 500, 5),<br>&#39;reg_alpha&#39;: hp.uniform(&#39;reg_alpha&#39;, 0.0, 1.0),<br>&#39;reg_lambda&#39;: hp.uniform(&#39;reg_lambda&#39;, 0.0, 1.0),<br>&#39;colsample_bytree&#39;: hp.uniform(&#39;colsample_by_tree&#39;, 0.6, 1.0)}</pre><p>Here use different domain distribution types (look for complete distributions list in <a href="https://github.com/hyperopt/hyperopt/wiki/FMin">the hyperopt documentation</a>):</p><ul><li>choice : categorical variables</li><li>quniform : discrete uniform (integers spaced evenly)</li><li>uniform: continuous uniform (floats spaced evenly)</li><li>loguniform: continuous log uniform (floats spaced evenly on a log scale)</li></ul><pre>from hyperopt import tpe<br>from hyperopt import Trials</pre><pre># optimization algorithm<br>tpe_algorithm = tpe.suggest</pre><pre># Keep track of results<br><strong>bayes_trials = Trials()</strong></pre><pre># File to save first results<br>out_file = &#39;./gbm_trials.csv&#39;<br>of_connection = open(out_file, &#39;w&#39;)<br>writer = csv.writer(of_connection)</pre><pre># Write the headers to the file<br>writer.writerow([&#39;loss&#39;, &#39;params&#39;, &#39;iteration&#39;, &#39;estimators&#39;, &#39;train_time&#39;])<br>of_connection.close()</pre><p>Finally, with all the code ready, we look for the best combination of parameters through the fmin function:</p><pre>from hyperopt import fmin</pre><pre># Global variable<br>global  ITERATION<br>ITERATION = 0<br>MAX_EVALS = 100</pre><pre># Create a lgb dataset<br>train_set = lgb.Dataset(X_train, label = y_train)</pre><pre># Run optimization<br>best = fmin(fn = objective, space = space, algo = tpe.suggest,<br>            max_evals = MAX_EVALS, trials = bayes_trials, <br>            rstate =np.random.RandomState(50))</pre><p>It triggers the process of finding the best combination. In the original example, the variable MAX_EVALS was set to 500; due to performance issues for this exercise, it was reduced to 100, which may have affected the final result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*g-FBaeZO__dffW1vg-6Cgg.png" /></figure><p>Once the process is finishing, we can take the Trials object (bayes_trials in our case) and analyze its results:</p><pre># Sort the trials with lowest loss (highest AUC) first<br>bayes_trials_results = sorted(bayes_trials.results, key = lambda x: x[&#39;loss&#39;])<br>bayes_trials_results[:2]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*hCgYD2e4ZKFQRrP30mjXOQ.png" /></figure><p>We can also load a dataframe from the CSV, and use the ‘ast’ library to transform a text into a dictionary and feed our final model with the best result.</p><pre>results = pd.read_csv(&#39;./gbm_trials.csv&#39;)</pre><pre># Sort with best scores on top and reset index for slicing<br>results.sort_values(&#39;loss&#39;, ascending = True, inplace = True)<br>results.reset_index(inplace = True, drop = True)<br>results.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*xgwaKPbD7i3ulmybobiKlA.png" /></figure><pre>import ast</pre><pre># Convert from a string to a dictionary<br>ast.literal_eval(results.loc[0, &#39;params&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*Bodl5ddN7G16qMxWGFnCaQ.png" /></figure><pre># Extract the ideal number of estimators and hyperparameters<br>best_bayes_estimators = int(results.loc[0, &#39;estimators&#39;])<br>best_bayes_params = ast.literal_eval(results.loc[0, &#39;params&#39;]).copy()</pre><pre># Re-create the best model and train on the training data<br>best_bayes_model = lgb.LGBMClassifier(n_estimators=best_bayes_estimators, n_jobs = -1,<br>                   objective = &#39;binary&#39;, random_state = 7,<br>                   **best_bayes_params)<br>best_bayes_model.fit(X_train, y_train)</pre><pre># Evaluate on the testing data<br>preds = best_bayes_model.predict(X_valid)<br>print(confusion_matrix(y_valid, preds))<br>print (best_bayes_model.score(X_valid,y_valid))<br>skplt.metrics.plot_confusion_matrix(y_valid, preds,figsize=(8,8))</pre><pre>resul.iloc[3,7] = best_bayes_model.score(X_valid,y_valid)<br>resul.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*bDjJenl6xxZXdjmqFdVO-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*fi7zpdGez-iJ67ljAoSgDA.png" /><figcaption>Hyperopt applyed on LGB model</figcaption></figure><h3>Summary</h3><p>We have developed the complete code to apply three available optimization techniques, on eight different classification algorithms.<br>The time and computational capacity required to apply these techniques is a topic to take into account; it seems necessary to perform this optimization when the state of the art of the selected model is high enough.<br>Parameter optimization does not necessarily imply a continuing improvement in the results of the trained model, over the test data, since the selection of parameters could be generating overfitting.<br>Finally, it should be noted that the improvements observed on the different models have generally been of a considerable magnitude, which leaves at least the door open to the possibility of increasing the performance of the algorithm through any of these techniques.</p><h3>Sources and references</h3><p>[1] <a href="https://en.wikipedia.org/w/index.php?title=Accuracy_and_precision&amp;action=edit&amp;section=4">https://en.wikipedia.org/w/index.php?title=Accuracy_and_precision&amp;action=edit&amp;section=4</a></p><p><em>In binary classification Accuracy is also used as a statistical measure of how well a </em><a href="https://en.wikipedia.org/wiki/Binary_classification"><em>binary classification</em></a><em> test correctly identifies or excludes a condition. That is, the accuracy is the proportion of true results (both </em><a href="https://en.wikipedia.org/wiki/True_positive"><em>true positives</em></a><em> and </em><a href="https://en.wikipedia.org/wiki/True_negative"><em>true negatives</em></a><em>) among the total number of cases examined… The formula for quantifying binary accuracy is:</em></p><p><em>Accuracy = (TP+TN)/(TP+TN+FP+FN)</em></p><p><em>where: TP = True positive; FP = False positive; TN = True negative; FN = False negative</em></p><p>[2] <a href="https://machinelearningmastery.com/hyperparameters-for-classification-machine-learning-algorithms/">https://machinelearningmastery.com/hyperparameters-for-classification-machine-learning-algorithms/</a></p><p>[3] <a href="https://towardsdatascience.com/automated-machine-learning-hyperparameter-tuning-in-python-dfda59b72f8a">https://towardsdatascience.com/automated-machine-learning-hyperparameter-tuning-in-python-dfda59b72f8a</a></p><p>[4] <a href="https://medium.com/apprentice-journal/hyper-parameter-optimization-c9b78372447b">https://medium.com/apprentice-journal/hyper-parameter-optimization-c9b78372447b</a></p><p>[5] <a href="https://towardsdatascience.com/automated-machine-learning-hyperparameter-tuning-in-python-dfda59b72f8a">https://towardsdatascience.com/automated-machine-learning-hyperparameter-tuning-in-python-dfda59b72f8a</a></p><p>[6] <a href="https://github.com/WillKoehrsen/hyperparameter-optimization/blob/master/Bayesian%20Hyperparameter%20Optimization%20of%20Gradient%20Boosting%20Machine.ipynb">https://github.com/WillKoehrsen/hyperparameter-optimization/blob/master/Bayesian%20Hyperparameter%20Optimization%20of%20Gradient%20Boosting%20Machine.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc60fb836264" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/available-hyperparameter-optimization-techniques-dc60fb836264">Available hyperparameter optimization techniques</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[Image labeling]]></title>
            <link>https://medium.com/swlh/image-labeling-a76ea756d874?source=rss-4213edda07c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a76ea756d874</guid>
            <category><![CDATA[image-clustering]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[image-labelers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Gabriel Naya]]></dc:creator>
            <pubDate>Wed, 01 Jan 2020 23:44:14 GMT</pubDate>
            <atom:updated>2020-01-02T22:02:57.984Z</atom:updated>
            <content:encoded><![CDATA[<h4>We explore platform.ai for image labeling, clustering, and eventually create a model into the tool for the full tag dataset.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mcVx98UQOmyjuu_F" /><figcaption>Photo by <a href="https://unsplash.com/@barglm?utm_source=medium&amp;utm_medium=referral">Martin Bargl</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Background</h3><p>In the context of an OCR application use case, we received a set of images of two different classes. To optimize the search region of interest (ROI), we explored some tools to quickly tag and sort the images.</p><h3>Using platform.ai¹ for images labeling</h3><p>Once we start working on the platform, we can create data sets (Collections) and create different labeling projects and prediction models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*UroByz_Q5VJZG7n4HAXvaw.png" /></figure><p>The user interface for creating collections, uploading images, or creating projects is quite intuitive and straightforward and does not support a further explanation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*z0ZDXDDwRfdXzeA6D621Rw.png" /></figure><h3>How to use platform.ai</h3><p>After starting a project, we find the following scenario: a set of 2D classifications of the distance between images. These layers can be browsed in the lower area to find the one that best suits our objectives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1FtwPbApnPe8TEGojcTNw.png" /></figure><p>In the upper left area, we have the main button that takes us back to the projects and collections view.<br>Selecting a set of images with the mouse activates the icon to view them as a gallery. In this view, we can choose a subset and assign it to one of the categories we’re going to create in the upper right text box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbFPg1Z5v24K_g2j_AEIGw.png" /></figure><p>When we have some images correctly labeled, we can try to train a model that tag the rest of the pictures. To do this, we use the create model and train it button on the top left taskbar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eps7XoDNTrYjESVpVhmLGw.png" /></figure><p>In our case, the model obtained an accuracy of 74% because the dataset with which we handle is very confusing. If we work with well-differentiated classes, the accuracy achieved is significantly higher.</p><p>After training we can download a CSV file with the URLs of each image and its predictions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GdU98SfqjNXR_SSrioKT6g.png" /></figure><p>In the cases marked in red in the CSV, the model has not worked correctly. In this cases, we start from an error in our labeling when using the image gallery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*nInks9k3Y18zswZj07OAjw.png" /><figcaption>Manual labeling error, labeled as Other must be Errors</figcaption></figure><p>And in many cases we found that the model has managed to correctly label the images (marked in green in the CSV):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*6-Uq9VkqIhOY_QHczV6EVw.png" /><figcaption>Correctly predicted as Errors</figcaption></figure><h3>Summary</h3><p>In a nutshell, we found a tool that allowed us to label and classify our data set quickly, and then apply some manual corrections to it and finish the correct labeling.<br>From this clustering of our dataset, we were able to create other classification models according to the tools we know best.<br>Let’s hope now that the OCR application will be much more efficient since we have identified the type of image. Therefore, we can quickly locate the region of interest to work on the image, and even the language since in our case study, there are messages in Spanish and others in English.</p><h3>References</h3><p>[1] <a href="http://www.platform.ai/">www.platform.ai</a> is not an open-source tool, and in fact, the work here was develope with the free version, but this seems quite limited. Besides, the state of the art of the product is far from being in a quality stage; however, to label a small data set as it is our case, it fully accomplishes its purpose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a76ea756d874" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/image-labeling-a76ea756d874">Image labeling</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image data augmentation to balance dataset in classification tasks]]></title>
            <link>https://medium.com/analytics-vidhya/image-data-augmentation-to-balance-dataset-in-classification-tasks-5e25bbd9a228?source=rss-4213edda07c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e25bbd9a228</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[data-augmentation]]></category>
            <dc:creator><![CDATA[Gabriel Naya]]></dc:creator>
            <pubDate>Fri, 27 Dec 2019 17:07:31 GMT</pubDate>
            <atom:updated>2019-12-28T14:00:25.015Z</atom:updated>
            <content:encoded><![CDATA[<h4>Try an image classification model with an unbalanced dataset, and improve its accuracy through data augmentation techniques.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Be41Veo_NPmvBQaV" /><figcaption>Photo by <a href="https://unsplash.com/@usgs?utm_source=medium&amp;utm_medium=referral">USGS</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We will create an image classification model from a minimal and unbalanced data set, then use data augmentation techniques to balance and compare the results.</p><h3>The dataset</h3><p>Our dataset has 200 flower images and 20 bird images in a 1:10 ratio. To form this dataset we used techniques to download image URLs through the Google® search engine, as described step by step in <a href="https://medium.com/analytics-vidhya/fantastic-and-straightforward-image-classification-with-fastai-library-for-pytorch-30c3380ac284">last article</a>.</p><h4>Downloading and checking the images</h4><p>Once we have the list of the URLs for each category in our CSV files, we will run the code to download the photos and build our data set.<br>Path ‘data/data_aug’ is the base directory for us. In that directory, we have placed the two CSV files of the categories; let’s execute the code to create the subdirectories where the images will be downloaded and verify them.</p><pre>%reload_ext autoreload<br>%autoreload 2<br>%matplotlib inline<br>from fastai.vision import *</pre><pre>classes = [&#39;birds&#39;,&#39;flowers&#39;]<br>path = Path(&#39;data/data_aug&#39;)</pre><pre>#creating folders<br>for folder in classes:<br>   dest = path/folder<br>   dest.mkdir(parents=True, exist_ok=True)</pre><pre>#downloading images from urls in csv<br>file = &#39;urls_&#39;+&#39;<strong>birds</strong>&#39;&#39;.csv&#39;<br>dest = path/&#39;birds&#39;<br>download_images(path/file, dest, max_pics=<strong>20</strong>)</pre><pre>file = &#39;urls_&#39;+&#39;<strong>flowers</strong>&#39;&#39;.csv&#39;<br>dest = path/&#39;flowers&#39;<br>download_images(path/file, dest, max_pics=<strong>200</strong>)</pre><pre>#verifying images<br>for c in classes:<br>   print(c)<br>   verify_images(path/c, delete=True, max_size=500)</pre><h4>Creating and visualizing the dataset</h4><p>After having the photos downloaded and checked in the directories corresponding to each category, we can create a fast.ai DataFrame to be able to put inside the tagged images and start visualizing and working with them. We reserve 20% for validate set.</p><pre>np.random.seed(7)</pre><pre>data = ImageDataBunch.from_folder(path, train=&quot;.&quot;, <strong>valid_pct=0.2</strong>, ds_tfms=get_transforms(), size=224, num_workers=4).normalize(imagenet_stats)</pre><p>And run the code to display a random 3-row batch:</p><pre>data_gt.show_batch(rows=3, figsize=(7,8))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*D2f-tZqmftQlYHcpZZUxAw.png" /></figure><h3>The classification model</h3><p>For this exercise, we are going to use a convolutional network, of resnet34 format¹. <br>Within the “models”, there is a set of pre-defined network architectures, involving different structures and complexities².</p><pre>learn_gt = cnn_learner(data_gt, models.resnet34, metrics=error_rate)</pre><pre>learn_gt.fit_one_cycle(4)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*vjcKihCXam5f59VSOpDcSQ.png" /></figure><pre>learn_gt.save(&#39;gt_stage-1&#39;)<br>learn_gt.load(&#39;gt_stage-1&#39;)<br>learn_gt.unfreeze()</pre><pre>learn_gt.lr_find()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*0Oy86t-xOByFF0cVFL9Fkg.png" /></figure><pre>learn_gt.fit_one_cycle(2, max_lr=slice(1e-5,1e-2))<br>learn_gt.save(&#39;gt_stage-2&#39;)<br>learn_gt.load(&#39;gt_stage-2&#39;)</pre><h4>Results in the confusion matrix</h4><pre>interp = ClassificationInterpretation.from_learner(learn_gt)<br>interp.plot_confusion_matrix()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*H_6--Ez4K_8Ep2jHJ0PTpw.png" /></figure><p>As we can see the model is very ineffective in predicting the class<br>Less represented class (birds) where there is a lot of confusion about the validation set.</p><h3>Data augmentation</h3><p>We must create 180 new images in the bird’s category. To do this, we’ll loop through each of the real images creating ten additional pictures for each one using fast.ai’s apply_tfms method from fast.ai.</p><pre>path = Path(&#39;data/data_aug&#39;)<br>path_hr = path/&#39;birds&#39;</pre><pre>il = ImageList.from_folder(path_hr)<br>tfms = get_transforms(max_rotate=25)</pre><pre>def data_aug_one(ex_img,prox,qnt):<br>   for lop in range(0,qnt):<br>      image_name = str(prox).zfill(8) +&#39;.jpg&#39;<br>      dest = path_hr/image_name<br>      prox = prox + 1<br>      new_img = open_image(ex_img)<br>      new_img_fin = new_img.apply_tfms(tfms[0], new_img, xtra={tfms[1][0].tfm: {&quot;size&quot;: 224}}, size=224)<br>      new_img_fin.save(dest)</pre><pre>prox = 20<br>qnt = 10<br>for imagen in il.items:<br>   data_aug_one(imagen,prox,qnt)<br>   prox = prox + qnt</pre><p>If we visualize any of the source images and their ten new images, we’ll find things like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFDYBcQCn8Ckxs5aOkGE_Q.png" /><figcaption>On left original picture, on rigth ten transformed images</figcaption></figure><p>Details about “apply_tfms” transform function work and all its possibilities can found <a href="https://docs.fast.ai/vision.transform.html#get_transforms">here</a>.</p><h3>The same model with balanced data</h3><p>We created a new model with the balanced data sets</p><pre>np.random.seed(7)</pre><pre>tfms = get_transforms()<br>data = ImageDataBunch.from_folder(path, train=&quot;.&quot;, valid_pct=0.2, ds_tfms=tfms, size=224, num_workers=4).normalize(imagenet_stats)</pre><pre>learn = cnn_learner(data, models.resnet34, metrics=error_rate)<br>learn.fit_one_cycle(4)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*2yFCnzpevSsxgLS20cuuWQ.png" /></figure><pre>interp = ClassificationInterpretation.from_learner(learn)<br>interp.plot_confusion_matrix()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*J1QUiCsvHMJN3nc63oXOew.png" /></figure><h3>Okay, now let’s present a new images set</h3><p>We took twenty new images, ten from each category, and we see that the accuracy, although much improved from the initial version, still presents some problems when categorizing. Out of 20 new images, the model predicted 18 correctly and two wrong:</p><pre>path = Path(&#39;data/data_aug_test&#39;)<br>defaults.device = torch.device(&#39;cpu&#39;)<br>img = open_image(path/&#39;bird01.jpg&#39;)<br>img</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*SyqqQoBE8qdIcskS6EQ4PQ.jpeg" /></figure><pre>pred_class,pred_idx,outputs = learn.predict(img)<br>pred_class</pre><p>Category birds</p><pre>for test in range(1,11):<br>   image_name = &#39;bird&#39;+str(test).zfill(2)+&#39;.jpg&#39;<br>   img = open_image(path/image_name)<br>   pred_class,pred_idx,outputs = learn.predict(img)<br>   print (&#39;For image &#39; + image_name + &#39; predicted class: &#39;);<br>   print (pred_class)</pre><pre>   image_name = &#39;flower&#39;+str(test).zfill(2)+&#39;.jpg&#39;<br>   img = open_image(path/image_name)<br>   pred_class,pred_idx,outputs = learn.predict(img)<br>   print (&#39;For image &#39; + image_name + &#39; predicted class: &#39;);<br>   print (pred_class)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*VABB-fKZCB3BxQjc63Z9EA.png" /></figure><p>The image flower07.jpg predicted as a bird, and the image bird08.jpg predicted as a flower.</p><p>Here the confusion images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*fPj3texiXUhkg_kyAUAV2g.jpeg" /><figcaption>bird08.jpg</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*6mKWBPj8G32tSIVP5tCrQg.jpeg" /><figcaption>flower07.jpg</figcaption></figure><h3>Summary</h3><p>As we could see, the difference of training the same model with a balanced dataset and an unbalanced one is fundamental; however, if the dataset is minimal, it may be that the accuracy we reach is not enough.</p><p>In a previous <a href="https://medium.com/analytics-vidhya/fantastic-and-straightforward-image-classification-with-fastai-library-for-pytorch-30c3380ac284">article</a>, we created a very similar model from 200 images of each category. When we presented him with the same 20 new test images, he had the same confusion in the same photos.</p><p>We used the apply_tfms method from fast.ai to perform the transformations of the few initial images of birds, creating a data set 10 times larger.</p><h3>Sources and references</h3><p>[1] — <a href="https://towardsdatascience.com/an-overview-of-resnet-and-its-variants-5281e2f56035">https://towardsdatascience.com/an-overview-of-resnet-and-its-variants-5281e2f56035</a></p><p>[2] — <a href="https://medium.com/@14prakash/understanding-and-implementing-architectures-of-resnet-and-resnext-for-state-of-the-art-image-cf51669e1624">https://medium.com/@14prakash/understanding-and-implementing-architectures-of-resnet-and-resnext-for-state-of-the-art-image-cf51669e1624</a></p><p><a href="https://medium.com/usf-msds/deep-learning-best-practices-1-weight-initialization-14e5c0295b94">Deep Learning Best Practices (1) — Weight Initialization</a></p><p>Into fast.ai course referred, this technique is inspired by: Francisco Ingham and Jeremy Howard / [<a href="https://www.pyimagesearch.com/2017/12/04/how-to-create-a-deep-learning-dataset-using-google-images/">Adrian Rosebrock</a>]</p><p><a href="https://course.fast.ai/">https://course.fast.ai,</a> lesson 2, Jupyter Notebook: lesson2-download</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e25bbd9a228" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/image-data-augmentation-to-balance-dataset-in-classification-tasks-5e25bbd9a228">Image data augmentation to balance dataset in classification tasks</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Metrics and Python II]]></title>
            <link>https://medium.com/data-science/metrics-and-python-ii-2e49597964ff?source=rss-4213edda07c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e49597964ff</guid>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Gabriel Naya]]></dc:creator>
            <pubDate>Thu, 05 Dec 2019 18:50:52 GMT</pubDate>
            <atom:updated>2020-06-14T22:14:53.426Z</atom:updated>
            <content:encoded><![CDATA[<h4>In the <a href="https://towardsdatascience.com/metrics-and-python-850b60710e0c">previous article</a>, we take a metrics guide for regression problems. Now we are going to look at the metrics most used for classification problems</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y0_a2H0Mswzp7bf5" /><figcaption>Photo by <a href="https://unsplash.com/@amutiomi?utm_source=medium&amp;utm_medium=referral">Miguel A. Amutio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The dataset</h3><p>We make a dataset with three arrays: real values, predicted values, and likelihood values.<br><em>real_values</em>: A data set with 1000 elements between 0 and 1.<br><em>pred_values</em>: A variation of the real dataset, emulates a prediction, changing only the first 150 values.<br><em>prob_values</em>: Is the pred_values array but contains the percent of probability of being zero or one, instead of the real value 0 or 1. It will be used for ROC charts and Recall versus Precision.</p><pre>real_values = []<br>prob_values = []<br>pred_values = []</pre><pre>for k in range(0,1000):<br>   value = random.uniform(0, 1)<br>   real_values.append(int(round(value,0)))</pre><pre>   if k &lt; 150:<br>      value2 = random.uniform(0, 1)<br>      prob_values.append(value2)<br>      pred_values.append(int(round(value2,0)))<br>   else:<br>      prob_values.append(value)<br>      pred_values.append(int(round(value,0)))</pre><h3>Confusion matrix</h3><p>The Confusion Matrix is not a metric in itself but is an essential tool for classifying real data and predictions, so its components are the trigger for the first set of metrics.</p><pre>from sklearn.metrics import confusion_matrix<br>import scikitplot as skplt<br>print(confusion_matrix(real_values, pred_values))<br>skplt.metrics.plot_confusion_matrix(real_values, pred_values,figsize=(8,8))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*6JhBAphsgarcHl4lCicwqg.jpeg" /></figure><h3>Binary classification — Table 2.1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LM42F4nqhoAd1sczdysKlQ.jpeg" /><figcaption><a href="https://kreilabs.com/wp-content/uploads/2019/12/Metrics_table.pdf">https://kreilabs.com/wp-content/uploads/2019/12/Metrics_table.pdf</a></figcaption></figure><p>You can download complete file in <a href="https://kreilabs.com/wp-content/uploads/2019/12/Metrics_table.pdf">https://kreilabs.com/wp-content/uploads/2019/12/Metrics_table.pdf</a></p><p>Here we can see pyhton implementation for table metrics in matrix_metrix routine:</p><pre>import sklearn.metrics<br>import math</pre><pre>def matrix_metrix(real_values,pred_values,beta):<br>   CM = confusion_matrix(real_values,pred_values)<br>   TN = CM[0][0]<br>   FN = CM[1][0] <br>   TP = CM[1][1]<br>   FP = CM[0][1]<br>   Population = TN+FN+TP+FP<br>   Prevalence = round( (TP+FP) / Population,2)<br>   Accuracy   = round( (TP+TN) / Population,4)<br>   Precision  = round( TP / (TP+FP),4 )<br>   NPV        = round( TN / (TN+FN),4 )<br>   FDR        = round( FP / (TP+FP),4 )<br>   FOR        = round( FN / (TN+FN),4 ) <br>   check_Pos  = Precision + FDR<br>   check_Neg  = NPV + FOR<br>   Recall     = round( TP / (TP+FN),4 )<br>   FPR        = round( FP / (TN+FP),4 )<br>   FNR        = round( FN / (TP+FN),4 )<br>   TNR        = round( TN / (TN+FP),4 ) <br>   check_Pos2 = Recall + FNR<br>   check_Neg2 = FPR + TNR<br>   LRPos      = round( Recall/FPR,4 ) <br>   LRNeg      = round( FNR / TNR ,4 )<br>   DOR        = round( LRPos/LRNeg)<br>   F1         = round ( 2 * ((Precision*Recall)/(Precision+Recall)),4)<br>   FBeta      = round ( (1+beta**2)*((Precision*Recall)/((beta**2 * Precision)+ Recall)) ,4)<br>   MCC        = round ( ((TP*TN)-(FP*FN))/math.sqrt((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN))  ,4)<br>   BM         = Recall+TNR-1<br>   MK         = Precision+NPV-1</pre><pre>   mat_met = pd.DataFrame({<br>&#39;Metric&#39;:[&#39;TP&#39;,&#39;TN&#39;,&#39;FP&#39;,&#39;FN&#39;,&#39;Prevalence&#39;,&#39;Accuracy&#39;,&#39;Precision&#39;,&#39;NPV&#39;,&#39;FDR&#39;,&#39;FOR&#39;,&#39;check_Pos&#39;,&#39;check_Neg&#39;,&#39;Recall&#39;,&#39;FPR&#39;,&#39;FNR&#39;,&#39;TNR&#39;,&#39;check_Pos2&#39;,&#39;check_Neg2&#39;,&#39;LR+&#39;,&#39;LR-&#39;,&#39;DOR&#39;,&#39;F1&#39;,&#39;FBeta&#39;,&#39;MCC&#39;,&#39;BM&#39;,&#39;MK&#39;],     &#39;Value&#39;:[TP,TN,FP,FN,Prevalence,Accuracy,Precision,NPV,FDR,FOR,check_Pos,check_Neg,Recall,FPR,FNR,TNR,check_Pos2,check_Neg2,LRPos,LRNeg,DOR,F1,FBeta,MCC,BM,MK]})</pre><pre>   return (mat_met)</pre><p>When we call matrix_metrix function:</p><pre>beta = 0.4<br>mat_met = matrix_metrix(real_values,pred_values,beta)<br>print (mat_met)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*3teiI238Fvj1ag34DnA89A.jpeg" /><figcaption>Note: Prevalence is 0.505, code has a mistake at first version</figcaption></figure><h4>Predicted and real values</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*7clgS2NTAFKdIakxUUUgPA.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Confusion_matrix">https://en.wikipedia.org/wiki/Confusion_matrix</a></figcaption></figure><p><strong>TP = True positive</strong></p><p><strong>TN = True negative</strong></p><p><strong>FP = False positive</strong> — Equivalent with false alarm or Type I error¹</p><p><strong>FN = False negative — </strong>Equivalent with miss or <a href="https://en.wikipedia.org/wiki/Type_II_error">Type II error</a> ²</p><h4>Total rates*</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*YEV6ofnMWfAZolvTzIskUQ.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Confusion_matrix">https://en.wikipedia.org/wiki/Confusion_matrix</a></figcaption></figure><p><strong>Prevalence:</strong> Serves to measure the balance of data within the total population. <br>It is possible to measure the prevalence of positives or negatives and the sum of both quotients is = 1, a balanced data set would give coefficients close to 0.5<br>If, on the contrary, one of the factors is close to 1 and the other to 0, we are going to have an unbalanced data set.</p><p><strong>Accuracy:</strong> It is the measure of success of the system, the total of positive and negative achievements over the total population, indicates the degree of success of the model. According to the <a href="https://slack-redir.net/link?url=https%3A%2F%2Fmedium.com%2Fmercadolibre-datablog%2Fcost-sensitive-classification-in-fraud-prevention-263170d8fcfe&amp;v=3">cost of the sensitivity</a>³ of the case study, and the balance of the data (prevalence).</p><h4>Predicted rates*</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*-aiHUx5j57BfgpZRELzxLA.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Confusion_matrix">https://en.wikipedia.org/wiki/Confusion_matrix</a></figcaption></figure><p><strong>PPV</strong> — Positive predictive value o precisión</p><p><strong>NPV</strong> — Negative predictive value</p><blockquote>The PPV and NPV describe the performance of a diagnostic test or other statistical measure. A high result can be interpreted as indicating the accuracy of such a statistic. The PPV and NPV are not intrinsic to the test; they depend also on the <a href="https://en.wikipedia.org/wiki/Prevalence">prevalence</a>. ⁴</blockquote><p><strong>FDR</strong> — False Discovery rate (Type I) [iv]</p><p><strong>FOR</strong> — False Omission Rate</p><p><strong>check_Pos:</strong> PPV + FDR = 1</p><p><strong>check_Neg:</strong> FOR + NPV = 1</p><h4>Condition rates*</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*MwyoEEwqI_hzQ03uwZyvTw.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Confusion_matrix">https://en.wikipedia.org/wiki/Confusion_matrix</a></figcaption></figure><p>Recall, sensitivity, probability of detection, and power are the same measure, which assumes different names and applications depending on the field of study.<br>In the literature referring to binary classification problems, the use of the term recall is more frequent.</p><blockquote><strong>“Sensitivity</strong> and <strong>specificity</strong> are statistical measures of the performance of a binary classification test, also known in statistics as a classification function, that are widely used in medicine:</blockquote><blockquote>· <strong>Sensitivity</strong> measures the proportion of actual positives that are correctly identified as such.</blockquote><blockquote>· <strong>Specificity</strong> (also called the <strong>true negative rate</strong>) measures the proportion of actual negatives that are correctly identified as such (e.g., the percentage of healthy people who are correctly identified as not having the condition).⁵</blockquote><p><strong>FPR —<em> </em></strong>false positive ratio (or false alarm ratio) is the probability of falsely rejecting the null hypothesis for a particular test.</p><p><strong>FNR </strong>— false negative rate is the proportion of positives which yield negative test outcomes with the test, i.e., the conditional probability of a negative test result given that the condition being looked for is present.</p><p>In statistical hypothesis testing, this fraction is given the letter β. The “<a href="https://en.wikipedia.org/wiki/Statistical_power">power</a>” (or the “sensitivity”) of the test is equal to 1−β.</p><h4>Combinated rates*</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*Ml6XMa_IJAu8fmKuik5wRw.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Confusion_matrix">https://en.wikipedia.org/wiki/Confusion_matrix</a></figcaption></figure><p><em>Not to be confused with Likelihood-ratio test.</em></p><p><strong>LR (+ -)</strong> Likelihood ratios: They are used for assessing the value of performing a diagnostic test. ⁶</p><p><strong>DOR</strong> — diagnostic odds ratio is a measure of the effectiveness of a diagnostic test ⁷</p><h3>Binary classification — Table 2.2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yskpl3M5e6cMI-2v7eX15g.jpeg" /><figcaption><a href="https://kreilabs.com/wp-content/uploads/2019/12/Metrics_table.pdf">https://kreilabs.com/wp-content/uploads/2019/12/Metrics_table.pdf</a></figcaption></figure><p>From the matrix_metrix function used for Table 1, we also got the values for this Table 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/1*dsvStGJDt5k_ycax28TK3w.jpeg" /></figure><h4>F1 Score</h4><blockquote>In statistical analysis of binary classification, the <strong>F1 score</strong> (also <strong>F-score</strong> or <strong>F-measure</strong>) is a measure of a test’s accuracy. It considers both the precision <em>p</em> and the recall <em>r</em> of the test to compute the score: <em>p</em> is the number of correct positive results divided by the number of all positive results returned by the classifier, and <em>r</em> is the number of correct positive results divided by the number of all relevant samples (all samples that should have been identified as positive). The F1 score is the harmonic mean of the precision and recall, where an F1 score reaches its best value at 1 (perfect precision and recall) and worst at 0.⁸</blockquote><h4>F-Beta Score⁹</h4><p>Beta is a parameter for score analysis, if we use Beta equal to 1, we have the harmonic mean; then we have the <strong><em>F1 score</em></strong>:</p><p>We could take some Rules of Thumb:</p><ul><li>To give more weight to the <strong>Precision</strong>, we must select a Beta value <em>between 0–1</em><strong><em> 0 &lt; Beta &lt; 1</em></strong></li><li>To give more weight to the <strong>Recall</strong>, we pick a Beta Value in the interval <strong><em>1 &lt; Beta &lt; +infinite</em></strong></li></ul><h4>ROC versus Precision-recall and AUC ¹⁰</h4><p>We can find <a href="https://machinelearningmastery.com/roc-curves-and-precision-recall-curves-for-classification-in-python/">an excellent and very complete article</a> regarding the concepts and implementation of these instruments.</p><p><strong>ROC</strong> — Receive operating characteristic</p><blockquote>It is a plot of the false positive rate (x-axis) versus the true positive rate (y-axis) for a number of different candidate threshold values between 0.0 and 1.0. Put another way, it plots the false alarm rate versus the hit rate.</blockquote><p><strong>Precision-recall curves</strong></p><blockquote>A precision-recall curve is a plot of the precision (y-axis) and the recall (x-axis) for different thresholds, much like the ROC curve. A no-skill classifier is one that cannot discriminate between the classes and would predict a random class or a constant class in all cases. The no-skill line changes based on the distribution of the positive to negative classes. It is a horizontal line with the value of the ratio of positive cases in the dataset. For a balanced dataset, this is 0.5.</blockquote><p><strong>AUC — Area under curve</strong></p><p>The area under the curve (AUC) can be used as a summary of the model skill.</p><p>We based on the mentioned article for the following code</p><pre>#ROC Implementation<br>from sklearn.metrics import roc_curve<br>from sklearn.metrics import roc_auc_score<br>from matplotlib import pyplot</pre><pre>fpr, tpr, thresholds = roc_curve(real_values, prob_values)<br>auc = roc_auc_score(real_values, prob_values)<br>print(&#39;AUC: %.3f&#39; % auc)</pre><pre>pyplot.plot(fpr, tpr, linestyle=&#39;--&#39;, label=&#39;Roc curve&#39;)<br>pyplot.xlabel(&#39;False Positive Rate&#39;)<br>pyplot.ylabel(&#39;True Positive Rate&#39;)<br>pyplot.legend()</pre><pre>pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*k0JX3cZwXB-zAyCbIuyOHg.jpeg" /></figure><pre>#Precision-recall implementation</pre><pre>precision, recall, thresholds = sklearn.metrics.precision_recall_curve(real_values,prob_values)</pre><pre>pyplot.plot(recall, precision, linestyle=&#39;--&#39;, label=&#39;Precision versus Recall&#39;)<br>pyplot.xlabel(&#39;Recall&#39;)<br>pyplot.ylabel(&#39;Precision&#39;)<br>pyplot.legend()</pre><pre>pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*60KlZ1reAZPj0PF05AV0Ag.jpeg" /></figure><h4>Other implementations and metrics from Sklearn</h4><p>Here a simple and fast report about binary classification values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*hixqgIqcIPz3bh_HaI41TA.jpeg" /></figure><p>And here a function for get many metrics directly from sklearn:</p><pre>def sk_metrix(real_values,pred_values,beta):<br>   Accuracy = round( sklearn.metrics.accuracy_score(real_values,pred_values) ,4)<br>   <br>   Precision  = round( sklearn.metrics.precision_score(real_values,pred_values),4 )<br>   <br>   Recall     = round( sklearn.metrics.recall_score(real_values,pred_values),4 )</pre><pre>   F1         = round ( sklearn.metrics.f1_score(real_values,pred_values),4)<br>   <br>   FBeta      = round ( sklearn.metrics.fbeta_score(real_values,pred_values,beta) ,4)</pre><pre>   MCC        = round ( sklearn.metrics.matthews_corrcoef(real_values,pred_values)  ,4)</pre><pre>   Hamming    = round ( sklearn.metrics.hamming_loss(real_values,pred_values) ,4)</pre><pre>   Jaccard    = round ( sklearn.metrics.jaccard_score(real_values,pred_values) ,4)</pre><pre>   Prec_Avg   = round ( sklearn.metrics.average_precision_score(real_values,pred_values) ,4)</pre><pre>   Accu_Avg   = round ( sklearn.metrics.balanced_accuracy_score(real_values,pred_values) ,4)</pre><pre>   mat_met = pd.DataFrame({<br>&#39;Metric&#39;: [&#39;Accuracy&#39;,&#39;Precision&#39;,&#39;Recall&#39;,&#39;F1&#39;,&#39;FBeta&#39;,&#39;MCC&#39;,&#39;Hamming&#39;,&#39;Jaccard&#39;,&#39;Precision_Avg&#39;,&#39;Accuracy_Avg&#39;],<br>&#39;Value&#39;: [Accuracy,Precision,Recall,F1,FBeta,MCC,Hamming,Jaccard,Prec_Avg,Accu_Avg]})</pre><pre>   return (mat_met)</pre><p>Calling sk_metrix function</p><pre>sk_met = sk_metrix(real_values,pred_values,beta)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/1*e74Cgj-JSRg6WkE1_-Fasg.jpeg" /></figure><h3>Summary</h3><p>The number of metrics arising from the confusion matrix is quite large and may be challenging to cover to refine the use of each indicator according to the use case. <br>The most common metrics may be F1-Score, ROC, precision-recall AUC, prevalence, and sensitivity.</p><p>This series of articles intended to create a table in which to quickly have a guide of the majority of metrics used for each case study; mastering their application exceeds our scope and also seems to be quite difficult.<br>Remember that the table can be <a href="https://kreilabs.com/wp-content/uploads/2019/12/Metrics_table.pdf">download in pdf format</a>.</p><p>In the next article, we will see more classification metrics and specific metrics for recommendation systems in table 2.3</p><h3>References</h3><p>[*] <a href="https://en.wikipedia.org/wiki/Sensitivity_and_specificity">https://en.wikipedia.org/wiki/Confusion_matrix</a></p><p>[1] type i error</p><p>[2] type ii error</p><p>[3] <a href="https://medium.com/mercadolibre-datablog/cost-sensitive-classification-in-fraud-prevention-263170d8fcfe">https://medium.com/mercadolibre-datablog/cost-sensitive-classification-in-fraud-prevention-263170d8fcfe</a></p><p>[4] The <strong>positive and negative predictive values</strong> (<strong>PPV</strong> and <strong>NPV</strong> respectively) are the proportions of positive and negative results in <a href="https://en.wikipedia.org/wiki/Statistics">statistics</a> and <a href="https://en.wikipedia.org/wiki/Diagnostic_test">diagnostic tests</a> that are <a href="https://en.wikipedia.org/wiki/True_positive">true positive</a> and <a href="https://en.wikipedia.org/wiki/True_negative">true negative</a> results, respectively.<a href="https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values#cite_note-1">[1]</a> “The PPV and NPV describe the performance of a diagnostic test or other statistical measure. A high result can be interpreted as indicating the accuracy of such a statistic. The PPV and NPV are not intrinsic to the test; they depend also on the <a href="https://en.wikipedia.org/wiki/Prevalence">prevalence</a>.<a href="https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values#cite_note-AltmanBland1994-2">[2]</a> The PPV can be derived using <a href="https://en.wikipedia.org/wiki/Bayes%27_theorem">Bayes’ theorem</a>. Although sometimes used synonymously, a <em>positive predictive value</em> generally refers to what is established by control groups, while a <a href="https://en.wikipedia.org/wiki/Pre-_and_post-test_probability">post-test probability</a> refers to a probability for an individual. Still, if the individual’s <a href="https://en.wikipedia.org/wiki/Pre-test_probability">pre-test probability</a> of the target condition is the same as the prevalence in the control group used to establish the positive predictive value, the two are numerically equal.</p><p>( <a href="https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values">https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values</a>)</p><p>[5] <a href="https://en.wikipedia.org/wiki/Sensitivity_and_specificity">https://en.wikipedia.org/wiki/Sensitivity_and_specificity</a></p><p>[6] <a href="https://en.wikipedia.org/wiki/Likelihood_ratios_in_diagnostic_testing#positive_likelihood_ratio">https://en.wikipedia.org/wiki/Likelihood_ratios_in_diagnostic_testing#positive_likelihood_ratio</a></p><p>[7] <a href="https://en.wikipedia.org/wiki/Diagnostic_odds_ratio">https://en.wikipedia.org/wiki/Diagnostic_odds_ratio</a></p><p>[8] <a href="https://en.wikipedia.org/wiki/F1_score">https://en.wikipedia.org/wiki/F1_score</a></p><p>[9] <a href="http://www.marcelonet.com/snippets/machine-learning/evaluation-metrix/f-beta-score">http://www.marcelonet.com/snippets/machine-learning/evaluation-metrix/f-beta-score</a></p><p>[10] <a href="https://machinelearningmastery.com/roc-curves-and-precision-recall-curves-for-classification-in-python/">https://machinelearningmastery.com/roc-curves-and-precision-recall-curves-for-classification-in-python/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e49597964ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/metrics-and-python-ii-2e49597964ff">Metrics and Python II</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[Metrics and Python]]></title>
            <link>https://medium.com/data-science/metrics-and-python-850b60710e0c?source=rss-4213edda07c------2</link>
            <guid isPermaLink="false">https://medium.com/p/850b60710e0c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gabriel Naya]]></dc:creator>
            <pubDate>Sun, 24 Nov 2019 22:07:04 GMT</pubDate>
            <atom:updated>2019-11-26T14:50:47.428Z</atom:updated>
            <content:encoded><![CDATA[<h4>In a series of three articles, we will describe a set of basic statistical concepts and the metrics used for regression and classification</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9xW9scKJDxkU-u8Y" /><figcaption>Photo by <a href="https://unsplash.com/@christina?utm_source=medium&amp;utm_medium=referral">Isabella Christina</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a programmer I lacked on studies about mathematical and statistical concepts. <br>Now with more experience I’ve decided to compile and share some of the metrics and concepts that I’ve faced for different problems I encountered.</p><p>In this series of articles, we will briefly review each of them, their use, their formulas, examples, and implementation in Python, so we can see them all together and have this chart on hands, if necessary.<br>Here is <strong>part one</strong>, referring to the most used metrics for regression cases.</p><h3>Dataset and model</h3><p>For this article, we have used the Kaggle dataset on housing prices, because it is a typical example of regression with which many of us are familiar.<br>Elementary engineering features have been done to be able to present a minimum reasonable model, which serves as an example for the development of metrics.</p><pre>from scipy.stats import boxcox_normmax<br>from scipy.special import boxcox1p<br>from sklearn.linear_model import LinearRegression</pre><pre>train = pd.read_csv(&#39;../input/home-data-for-ml-course/train.csv&#39;)<br>y = train.SalePrice.reset_index(drop=True)</pre><pre>features = train<br>end_features = [&#39;OverallQual&#39;,&#39;GrLivArea&#39;,&#39;GarageCars&#39;,&#39;GarageArea&#39;,&#39;TotalBsmtSF&#39;,&#39;1stFlrSF&#39;,&#39;FullBath&#39;,&#39;TotRmsAbvGrd&#39;,&#39;MSSubClass&#39;,&#39;MSZoning&#39;]<br>features = features[end_features]</pre><pre>features[&#39;MSSubClass&#39;] = features[&#39;MSSubClass&#39;].apply(str)<br>features[&#39;MSZoning&#39;] = features.groupby(&#39;MSSubClass&#39;)[&#39;MSZoning&#39;].transform(lambda x: x.fillna(x.mode()[0]))</pre><pre>objects = [col for col in features.columns if features[col].dtype == &quot;object&quot;]<br>features.update(features[objects].fillna(&#39;None&#39;))</pre><pre>numeric_dtypes = [&#39;int16&#39;, &#39;int32&#39;, &#39;int64&#39;, &#39;float16&#39;, &#39;float32&#39;, &#39;float64&#39;]<br>numerics = [col for col in features.columns if features[col].dtype in numeric_dtypes]<br>features.update(features[numerics].fillna(0))</pre><pre>for i in numerics:<br>    features[i] = boxcox1p(features[i], boxcox_normmax(features[i] + 1))</pre><pre>X = pd.get_dummies(features).reset_index(drop=True)</pre><pre>#----------------- The model<br>reg = LinearRegression().fit(X, y)<br>y_pred = reg.predict(X)</pre><h3>Regression metrics summary</h3><p>Here is a simple table with the review of the metrics we are going to describe, the last column of the table is the result of our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lke9jk2uY-ppHO0h0xytQw.png" /></figure><h3>MAE: Mean absolute error</h3><blockquote>MAE measures the average magnitude of the errors in a set of predictions, without considering their direction. It’s the average over the test sample of the absolute differences between prediction and actual observation where all individual differences have equal weight.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*A4AwqjvFDZMYR40Z.jpg" /><figcaption><a href="https://www.dataquest.io/blog/understanding-regression-error-metrics/">https://www.dataquest.io/blog/understanding-regression-error-metrics/</a></figcaption></figure><p>The mean absolute error uses the same scale as the data. This is known as a scale-dependent accuracy measure and, therefore, cannot be used to make comparisons between series using different scales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/0*sA9a9MlNiZ1dI7so.jpg" /><figcaption><a href="https://www.dataquest.io/blog/understanding-regression-error-metrics/">https://www.dataquest.io/blog/understanding-regression-error-metrics/</a></figcaption></figure><pre>from sklearn.metrics import mean_absolute_error<br>print (&#39;Sk MAE: &#39; + str(mean_absolute_error(y,y_pred)) )</pre><pre>def MAE(predict,target):<br>    return (abs(predict-target)).mean()</pre><pre>print (&#39;My MAE: &#39; + str(MAE(y_pred,y)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*qc8rvM6qq3Zp6DQ5-CJhug.png" /></figure><h3>MSE: Mean squared error</h3><blockquote>MSE is a <a href="https://en.wikipedia.org/wiki/Risk_function">risk function</a>, corresponding to the <a href="https://en.wikipedia.org/wiki/Expected_value">expected value</a> of the squared error loss. The fact that MSE is almost always strictly positive (and not zero) is because of <a href="https://en.wikipedia.org/wiki/Randomness">randomness</a> or because the estimator <a href="https://en.wikipedia.org/wiki/Omitted-variable_bias">does not account for information</a> that could produce a more accurate estimate. The MSE is a measure of the quality of an estimator — it is always non-negative, and values closer to zero are better.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*7RxO773DPeY8IYeD.png" /><figcaption><a href="https://www.geeksforgeeks.org/ml-mathematical-explanation-of-rmse-and-r-squared-error/">https://www.geeksforgeeks.org/ml-mathematical-explanation-of-rmse-and-r-squared-error/</a></figcaption></figure><p>“Minimizing MSE is a key criterion in selecting estimators: see <a href="https://en.wikipedia.org/wiki/Minimum_mean-square_error">minimum mean-square error</a>. Among unbiased estimators, minimizing the MSE is equivalent to minimizing the variance, and the estimator that does this is the <a href="https://en.wikipedia.org/wiki/Minimum_variance_unbiased_estimator">minimum variance unbiased estimator</a>. However, a biased estimator may have lower MSE; see <a href="https://en.wikipedia.org/wiki/Estimator_bias">estimator bias</a>.</p><p>In <a href="https://en.wikipedia.org/wiki/Statistical_modelling">statistical modelling</a> the MSE can represent the difference between the actual observations and the observation values predicted by the model. In this context, it is used to determine the extent to which the model fits the data as well as whether removing some explanatory variables is possible without significantly harming the model’s predictive ability.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/0*9uUU5Fya4YMbl_7C.jpg" /><figcaption><a href="https://www.geeksforgeeks.org/ml-mathematical-explanation-of-rmse-and-r-squared-error/">https://www.geeksforgeeks.org/ml-mathematical-explanation-of-rmse-and-r-squared-error/</a></figcaption></figure><pre>from sklearn.metrics import mean_squared_error<br>print (&#39;Sk MSE: &#39; + str(mean_squared_error(y,y_pred)) )</pre><pre>def MSE(predict,target):<br>    return ((predict-target)**2).mean()<br>print (&#39;My MSE: &#39; + str(MSE(y_pred,y)) )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*wpAi82rvvw_zfd0VWXrhOQ.png" /></figure><h3>RMSE: Root mean square error</h3><blockquote>RMSE is a quadratic scoring rule that also measures the average magnitude of the error. It’s the square root of the average of squared differences between prediction and actual observation.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*at-j68ROeSmiruDE.png" /><figcaption><a href="https://www.includehelp.com/ml-ai/root-mean-square%20error-rmse.aspx">https://www.includehelp.com/ml-ai/root-mean-square%20error-rmse.aspx</a></figcaption></figure><p>Comparision RMSE vs MAE</p><p><strong>Similarities</strong>:</p><ul><li>Express average model prediction error in same units of the variable of interest.</li><li>Can range from 0 to ∞ and are indifferent to the direction of errors.</li><li>Lower values are better.</li></ul><p><strong>Difference</strong>:</p><ul><li>Taking the square root before they are averaged, RMSE gives a relatively high weight to large errors, so RMSE should be useful when large errors are undesirable.</li></ul><pre>def RMSE(predict, target):<br>    return np.sqrt(((predict - target) ** 2).mean())<br>print (&#39;My RMSE: &#39; + str(RMSE(y_pred,y)) )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*_aC9Cc28lXCJihComPsucg.png" /></figure><h3>MAPE: Mean absolute percentage error</h3><blockquote>Measure of prediction accuracy of a forecasting method in <a href="https://en.wikipedia.org/wiki/Statistics">statistics</a>, for example in <a href="https://en.wikipedia.org/wiki/Trend_estimation">trend estimation</a>, also used as a <a href="https://en.wikipedia.org/wiki/Loss_function">loss function</a> for regression problems in <a href="https://en.wikipedia.org/wiki/Machine_learning">machine learning</a>. It usually expresses accuracy as a percentage.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*N8USfmlDmXq7YuNy.png" /></figure><p>Although the concept of MAPE sounds very simple and convincing, it has major drawbacks in practical application <a href="https://en.wikipedia.org/wiki/Mean_absolute_percentage_error#cite_note-tofallis2015-3">[*]</a>, and there are many studies on shortcomings and misleading results from MAPE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*sB6BWioIO5PTBbt9.jpg" /><figcaption><a href="https://www.dataquest.io/blog/understanding-regression-error-metrics/">https://www.dataquest.io/blog/understanding-regression-error-metrics/</a></figcaption></figure><pre>def MAPE(predict,target):<br>    return ( abs((target - predict) / target).mean()) * 100</pre><pre>print (&#39;My MAPE: &#39; + str(MAPE(y_pred,y)) )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*XSFuU72NqZlxBHOe70GM1Q.png" /></figure><h3>RMSLE: Root Mean Squared Logarithmic Error</h3><blockquote>In case of RMSLE, you take the log of the predictions and actual values. So basically, what changes is the variance that you are measuring. I believe RMSLE is usually used when you don’t want to penalize huge differences in the predicted and the actual values when both predicted and true values are huge numbers.</blockquote><p>RMSLE measures the ratio between actual and predicted.</p><p>log(pi+1)−log(ai+1)log(pi+1)−log(ai+1)</p><p>can be written as log((pi+1)/(ai+1))log((pi+1)/(ai+1))</p><p>It can be used when you don’t want to penalize huge differences when the values are huge numbers.</p><p>Also, this can be used when you want to penalize under estimates more than over estimates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*FqvDmgsC4OQ8PcSHRH3IVg.png" /></figure><p>Lets have a look at the below example</p><p>Case a) : Pi = 600, Ai = 1000 — RMSE = 400, RMSLE = 0.5108</p><p>Case b) : Pi = 1400, Ai = 1000 — RMSE = 400, RMSLE = 0.3365</p><pre>import math</pre><pre>def RMSLE(predict, target):<br>    total = 0 <br>    for k in range(len(predict)):<br>        LPred= np.log1p(predict[k]+1)<br>        LTarg = np.log1p(target[k] + 1)<br>        if not (math.isnan(LPred)) and  not (math.isnan(LTarg)): <br>            total = total + ((LPred-LTarg) **2)<br>        <br>    total = total / len(predict)        <br>    return np.sqrt(total)</pre><pre>print (&#39;My RMSLE: &#39; + str(RMSLE(y_pred,y)) )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*AYtFXD-trF5-8xplQa1piA.png" /></figure><h3>R² and R-Squared: Coefficient of determination</h3><blockquote>R² and R-Squared help us to know how good our regression model as compared to a very simple model that just predicts the mean value of target from the train set as predictions.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/0*-lBX506Imc6Hjqpu" /><figcaption><a href="https://www.datasciencecentral.com/profiles/blogs/r-squared-in-one-picture">https://www.datasciencecentral.com/profiles/blogs/r-squared-in-one-picture</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/0*ap7U_Ij6D7Z_XMnF.gif" /></figure><pre>def R2(predict, target):<br>    return 1 - (MAE(predict,target) / MAE(target.mean(),target))</pre><pre>def R_SQR(predict, target):<br>    r2 = R2(predict,target)<br>    return np.sqrt(r2)</pre><pre>print (&#39;My R2         : &#39; + str(R2(y_pred,y)) )<br>print (&#39;My R          : &#39; + str(R_SQR(y_pred,y)) )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*h067I7RJGyv-dNqCxMdTfQ.png" /></figure><h3>Adjusted R²</h3><blockquote>A model performing equal to baseline would give R-Squared as 0. Better the model, higher the r2 value. The best model with all correct predictions would give R-Squared as 1. However, on adding new features to the model, the R-Squared value either increases or remains the same. R-Squared does not penalize for adding features that add no value to the model. So an improved version over the R-Squared is the adjusted R-Squared</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*1jxDmwoJF8R4tOVq.png" /><figcaption><a href="http://www.haghish.com/statistics/stata-blog/stata-programming/adjusted_R_squared.php">http://www.haghish.com/statistics/stata-blog/stata-programming/adjusted_R_squared.php</a></figcaption></figure><pre>def R2_ADJ(predict, target, k):<br>    r2 = R2(predict,target)<br>    n = len(target)<br>    return (1 -  ( (1-r2) *  ( (n-1) / (n-(k+1)) ) ) )</pre><pre>k= len(features.columns)<br>print (&#39;My R2 adjusted: &#39; + str(R2_ADJ(y_pred,y,k)) )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*tTKizNxplALd60P82TPmng.png" /></figure><h3>Summary</h3><p>Putting the main regression metrics in a single table, and programming the functions for each of them has been an excellent personal experience.<br>Applying them on the same exercise, since it allowed me to compare their uses, understand their formulas, and while developing the article, to have a complete picture. <br>Hopefully, the article has been useful, and any comments or corrections will be welcome.</p><p><em>Next week we will deliver the second part of this series, an article on classification metrics …</em></p><h3>Sources</h3><ul><li><a href="https://en.wikipedia.org/wiki/Mean_absolute_error">Mean absolute error - Wikipedia</a></li><li><a href="https://medium.com/human-in-a-machine-world/mae-and-rmse-which-metric-is-better-e60ac3bde13d">MAE and RMSE — Which Metric is Better?</a></li><li><a href="https://www.dataquest.io/blog/understanding-regression-error-metrics/">Tutorial: Understanding Regression Error Metrics in Python</a></li><li><a href="https://www.geeksforgeeks.org/ml-mathematical-explanation-of-rmse-and-r-squared-error/">ML | Mathematical explanation of RMSE and R-squared error - GeeksforGeeks</a></li><li><a href="https://en.wikipedia.org/wiki/Mean_squared_error">Mean squared error - Wikipedia</a></li><li><a href="https://www.includehelp.com/ml-ai/root-mean-square%20error-rmse.aspx">Root-Mean-Square Error (RMSE) | Machine Learning</a></li><li><a href="https://en.wikipedia.org/wiki/Root-mean-square_deviation">Root-mean-square deviation - Wikipedia</a></li><li><a href="https://www.forecastpro.com/Trends/forecasting101August2011.html">Welcome to Forecast Pro - Software for sales forecasting, inventory planning, demand planning, S&amp;OP and collaborative planning.</a></li><li><a href="https://en.wikipedia.org/wiki/Mean_absolute_percentage_error">Mean absolute percentage error</a></li><li><a href="https://www.quora.com/What-is-the-difference-between-an-RMSE-and-RMSLE-logarithmic-error-and-does-a-high-RMSE-imply-low-RMSLE">What is the difference between an RMSE and RMSLE (logarithmic error), and does a high RMSE imply low RMSLE?</a></li></ul><p><a href="https://en.wikipedia.org/wiki/Coefficient_of_determination">https://en.wikipedia.org/wiki/Coefficient_of_determination</a></p><ul><li><a href="https://www.analyticsvidhya.com/blog/2019/08/11-important-model-evaluation-error-metrics/?utm_source=twitter.com&amp;utm_medium=social">11 Important Model Evaluation Metrics for Machine Learning Everyone should know</a></li><li><a href="http://www.haghish.com/statistics/stata-blog/stata-programming/adjusted_R_squared.php">Calculating Adjusted R Squared in Stata</a></li><li><a href="https://en.wikipedia.org/wiki/Coefficient_of_determination">Coefficient of determination - Wikipedia</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=850b60710e0c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/metrics-and-python-850b60710e0c">Metrics and 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[Impact of using transfer learning in NLP]]></title>
            <link>https://medium.com/data-science/impact-of-using-transfer-learning-in-nlp-59ffc4ffb806?source=rss-4213edda07c------2</link>
            <guid isPermaLink="false">https://medium.com/p/59ffc4ffb806</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <dc:creator><![CDATA[Gabriel Naya]]></dc:creator>
            <pubDate>Mon, 11 Nov 2019 16:22:15 GMT</pubDate>
            <atom:updated>2019-11-12T16:42:49.916Z</atom:updated>
            <content:encoded><![CDATA[<h4>We analyze the impact of classifying movie reviews sentiments based on a language model trained from scratch, or a pre-trained model using the corpus wikitext-103</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cL2hAG4lfxgD2Na5" /><figcaption>Photo by <a href="https://unsplash.com/@pavement_special?utm_source=medium&amp;utm_medium=referral">Riccardo Annandale</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Background</h4><p>In different classification works with NLP, we have used <a href="https://arxiv.org/pdf/1801.06146.pdf">ULMFiT</a>. We can find two excellent articles on this methodology in <a href="https://towardsdatascience.com/transfer-learning-in-nlp-for-tweet-stance-classification-8ab014da8dde">Transfer Learning in NLP for Tweet Stance Classification</a> and <a href="https://medium.com/bitbroker-labs/universal-language-model-fine-tuning-for-text-classification-ulmfit-73ea2b383926">Universal Language Model Fine-tuning for Text Classification-ULMFiT</a>.</p><p>ULMFiT has implemented in version1 of the fastai¹ library, and they have developed some techniques that make it very convenient to do transfer learning.</p><p>In the <a href="https://arxiv.org/pdf/1801.06146.pdf">original paper</a>, ULMFiT consists of three stages:</p><ul><li>Training the language model on a corpus that captures high-level natural language features, using a general-domain dataset.</li><li>Adjust and fine-tuning the language model created in stage one, and using transfer learning, créate a new model language on the target dataset.</li><li>Create and fine-tuning the classifier using model language learning tuned in stage two.</li></ul><p>The main objective of this article is to measure the difference and impact between starting at stage three(classifier), from a pre-trained language model (stage two) or directly from scratch.</p><p>In other words, the stage two model is created with and without transfer learning, comparing the initial results.</p><p>In the first part of this article, we are going to import the dataset and carry out the necessary data transformation operations.</p><p>Then we will measure the impact of using a language model that receives transfer-learning from another already trained model, or of creating the language model directly from the dataset, and compare both results.</p><p>Finally, we are going to use the best of the language models created in the previous section to develop a sentiment classifier on NLP.</p><h4>The dataset</h4><p>The <a href="http://ai.stanford.edu/~amaas/data/sentiment/">dataset</a> for binary sentiment classification has been curated by Andrew Maas² et al. and contains a total of 100,000 reviews on IMDB³ . 25,000 of them labeled as positive and negative for training; another 25,000 labeled for testing.</p><p>There are other 50,000 additional unlabeled data that we will use for creating our model language learning.</p><pre>df = pd.read_csv(path/&#39;texts.csv&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*m6CowVChrd7O3HAUKxbvmg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*C0RG8tYMVhu9o61W6H5jqg.jpeg" /></figure><h3>Part 1 — Import dataset and feature engineering</h3><blockquote>“Since a text is composed of words, and can’t apply mathematical functions to them directly, we first have to convert them to numbers. In fastai, this is done in two different steps: tokenization and numericalization. In fastai API, TextDataBunch does it for us *.”</blockquote><pre>%reload_ext autoreload<br>%autoreload 2<br>%matplotlib inline<br>from fastai.text import *<br>path = untar_data(URLs.IMDB_SAMPLE)<br>data_lm = TextDataBunch.from_csv(path, &#39;texts.csv&#39;)</pre><h4>Tokenization</h4><pre>data = TextClasDataBunch.from_csv(path, &#39;texts.csv&#39;)<br>data.show_batch()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*FcjzGw52cViOG6Yb0si3hg.jpeg" /></figure><h4>Numericalization</h4><p>Once we have tokens from our texts, TextDataBunch converts to integers by creating a list of all the words used. The maximum vocabulary size by default is 60,000 and replace the ones that don’t cut by the unknown token UNK.</p><p>The correspondence from ids to tokens is store in the vocab attribute, in a dictionary called itos.</p><pre>data.vocab.itos[:10]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*d90shyYXqGGN73N97iM4_Q.jpeg" /></figure><p>Now if we look at our datasets, we’ll see the tokenized text as:</p><pre>data.train_ds[0][0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*Rbkyq4nZOKZz3yxrB8riWA.png" /></figure><p>And if we look al train_ds, all are numbers:</p><pre>data.train_ds[0][0].data[:10]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*VCSYeFC5BMuW16-cABb8hg.png" /></figure><h3>Part 2 — Creating a language model learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ey-B4VzeQu4eSXgP" /><figcaption>Photo by <a href="https://unsplash.com/@opticonor?utm_source=medium&amp;utm_medium=referral">Conor Luddy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Language modelling</h4><p>“A language model attempts to learn the structure of natural language through hierarchical representations, and thus contains both low-level features (word representations) and high-level features (semantic meaning). A key feature of language modelling is that it is generative, meaning that it aims to predict the next word given a previous sequence of words. It is able to do this because language models are typically trained on very large datasets in an unsupervised manner, and hence the model can ‘learn’ the syntactic features of language in a much deeper way than word embeddings.</p><p><a href="http://ruder.io/nlp-imagenet/">In his post</a>, Sebastian Ruder does a very elegant job of highlighting why language modelling is so powerful for a broad range of NLP tasks. Unlabelled language data is relatively easy to obtain (it is freely available in the form of large text corpora), so by feeding a language model a sufficiently large dataset, it is now possible to perform unsupervised pre-training on billions of words while incorporating a deeper knowledge of language syntax.”⁴</p><p>We will use from the API of fastai, the language_model_learner that is a type of learner ⁵, that assume a language model from a dataset, taking a set of configurations.</p><p>Language_model_learner admits the property “pre-trained (Bool)”, whose default option is True and assumes a model as transfer learning for each language.</p><h4>Creating our language model learning from scratch</h4><p>This technique has been used to create a language model for differents idioms, here is <a href="https://towardsdatascience.com/pre-trained-language-model-in-any-language-7531ea7217d4">an article</a> with an excellent example in Vietnamese⁶.</p><pre>path = untar_data(URLs.IMDB)<br>data_lm = (TextList.from_folder(path)<br>.filter_by_folder(include=[&#39;train&#39;, &#39;test&#39;, &#39;unsup&#39;])<br>.split_by_rand_pct(0.1)<br>.label_for_lm()<br>.databunch(bs=bs))</pre><pre>data_lm.save(&#39;data_lm.pkl&#39;)</pre><blockquote>“We have to use a special kind of TextDataBunch for the language model, that ignores the labels (that&#39;s why we put 0 everywhere), will shuffle the texts at each epoch before concatenating them all together (only for training, we don&#39;t shuffle for the validation set) and will send batches that read that text in order with targets that are the next word in the sentence.*”</blockquote><pre>data_lm = load_data(path, &#39;data_lm.pkl&#39;, bs=bs)<br>data_lm.show_batch()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*Ucwug3xOLp0QPLxk0sxWLw.jpeg" /></figure><p>Here is where we indicate to the API that we intend the “learn” model not to take the default weights from the pre-trained transfer learning, but to start without assuming pre-training:</p><pre>learn = language_model_learner(data_lm, AWD_LSTM, <strong>pretrained=False</strong>, drop_mult=0.3)</pre><p>After adjusting the learning rate and training, we obtain an accuracy of 0.284114</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*ez-2zkWn6vDuGvIU3pNF7g.jpeg" /></figure><h4>Using a pre-trained model for transfer learning</h4><p>The model pre-trained on a bigger dataset used in fastai, is a cleaned subset of Wikipedia called <a href="https://einstein.ai/research/blog/the-wikitext-long-term-dependency-language-modeling-dataset">wikitext-103</a>.</p><blockquote>“We are going to use that ‘knowledge’ of the English language to build our classifier, but first, like for computer vision, we need to fine-tune the pretrained model to our particular dataset. Because the English of the reviews left by people on IMDB isn’t the same as the English of wikipedia, we’ll need to adjust the parameters of our model by a little bit. Plus there might be some words that would be extremely common in the reviews dataset but would be barely present in wikipedia, and therefore might not be part of the vocabulary the model was trained on. *”</blockquote><pre>learn = language_model_learner(data_lm, AWD_LSTM, drop_mult=0.3)<br>learn.lr_find()<br>learn.recorder.plot(skip_end=15)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*DBUWXx34rYbGfavXKsMFow.jpeg" /></figure><h4>Preparing the model to be used in a classifier</h4><p>Not only should the model be saved for the next part, but also its encoder. This part is essential because to reuse this model, the list of words and their Ids must be the same.</p><pre><strong>learn.save_encoder(&#39;fine_tuned_enc&#39;)</strong></pre><h3>Part 3 — The movie reviews sentiments classifier: taking the model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7RrCof2MZKlC5d_a" /><figcaption>Photo by <a href="https://unsplash.com/@georgiavagim?utm_source=medium&amp;utm_medium=referral">Georgia Vagim</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><pre>path = untar_data(URLs.IMDB)<br>data_clas = (TextList.from_folder(path, vocab=data_lm.vocab)<br>.split_by_folder(valid=&#39;test&#39;)<br>.label_from_folder(classes=[&#39;neg&#39;, &#39;pos&#39;])<br>.databunch(bs=bs))</pre><pre>data_clas.save(&#39;data_clas.pkl&#39;)<br>data_clas = load_data(path, &#39;data_clas.pkl&#39;, bs=bs)</pre><p>We create the classifier, and assign it the encoder of the previous stage.</p><pre>learn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=0.5)<br><strong>learn.load_encoder(&#39;fine_tuned_enc&#39;)</strong></pre><p><strong><em>The results …</em></strong></p><p><strong><em>On left, model language from scratch, on right, the model with transfer learning:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*XHQz49YJAH8QqzZyI1rBPQ.png" /></figure><p>Finally, after adjustments of learning rate and some additional pieces of training we obtain a classifier of sentiments on the dataset of movie reviews with an accuracy of 0.943960.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*P3nox45Csw2Km2Yjt3wH8g.jpeg" /></figure><h3>Summary</h3><p>We have experimented with the application of a pre-trained language model from a previous data body and a language model from scratch, obtaining better results when using transfer learning.</p><p>Using the tools of fastai and UMLFiT, we can apply this through the data corpus of Wikipedia, to pre-train in any language, which in NLP is a great advantage due to the bias of tools and datasets in English.</p><p>Finally, remember that it is essential to keep the encoder between the language model and the text classifier. The basis of this exercise was token from the <a href="https://fast.ai course/">fastai course</a>, lesson3 and 4, where you can find the complete code and access to the dataset.</p><p>I hope that the article has been useful to see the positive impact of using transfer learning in NLP, similar to that used in computer vision. Any correction, comment or idea will be welcome.</p><h4>References</h4><p>[1] <a href="https://course.fast.ai/">https://course.fast.ai/</a></p><p>[2] <a href="http://ai.stanford.edu/~amaas/">http://ai.stanford.edu/~amaas/</a></p><p>[3] <a href="https://www.imdb.com/">https://www.imdb.com/</a></p><p>[4] <a href="https://towardsdatascience.com/transfer-learning-in-nlp-for-tweet-stance-classification-8ab014da8dde">https://towardsdatascience.com/transfer-learning-in-nlp-for-tweet-stance-classification-8ab014da8dde</a></p><p>[5] <a href="https://docs.fast.ai/basic_train.html#Learner">https://docs.fast.ai/basic_train.html#Learner</a></p><p>[6] <a href="https://towardsdatascience.com/pre-trained-language-model-in-any-language-7531ea7217d4">https://towardsdatascience.com/pre-trained-language-model-in-any-language-7531ea7217d4</a></p><p>[*] Many concepts from this article were directly token from lesson 3 and lesson 4 in <a href="https://course.fast.ai/">fast.ai course</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59ffc4ffb806" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/impact-of-using-transfer-learning-in-nlp-59ffc4ffb806">Impact of using transfer learning in NLP</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[Feature engineering and ensembled models for the top 10 in Kaggle “Housing Prices Competition”]]></title>
            <link>https://medium.com/data-science/feature-engineering-and-ensembled-models-for-the-top-10-in-kaggle-housing-prices-competition-efb35828eef0?source=rss-4213edda07c------2</link>
            <guid isPermaLink="false">https://medium.com/p/efb35828eef0</guid>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[kaggle-competition]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[housing-prices]]></category>
            <dc:creator><![CDATA[Gabriel Naya]]></dc:creator>
            <pubDate>Sun, 03 Nov 2019 18:41:29 GMT</pubDate>
            <atom:updated>2019-11-04T14:51:25.447Z</atom:updated>
            <content:encoded><![CDATA[<h4>We detail step by step the procedure to develop a regression model to be in the “top 10” of this global competition.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZE7FLX_09SvRLHW5" /><figcaption>Photo by <a href="https://unsplash.com/@jesseroberts?utm_source=medium&amp;utm_medium=referral">Jesse Roberts</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Kaggle¹ is one of the most significant online communities of data scientists and machine learners. Within <a href="https://www.kaggle.com/">Kaggle</a>, it is common to find competitions, where different users generate prediction models and submit their results to be position according to the score, in the leaderboard.</p><p>The competition that supports the online courses that every beginner performs is “<a href="https://www.kaggle.com/c/home-data-for-ml-course">Housing Prices Competition for Kaggle Learn Users</a>” .</p><p>A global and learning-oriented competence, therefore, the material circulating on the web is profuse, even for those looking well can be found directly with complete codes of excellent models that come very close to 1% on the scoreboard.</p><p>This article is base on the code exposed by <a href="https://www.kaggle.com/sandeepkumar121995">Sandeep Kumar</a> in Kaggle. This <a href="https://www.kaggle.com/sandeepkumar121995/blending-of-6-models-top-10">code</a> was our most important starting point in the competition. While this code alone is not enough to reach the top 10, it uses many exciting techniques. To the methods used there, we have added others that have made the difference to position our model in the top 10.</p><p>Because every detail counts when you start trying to improve within 1%, you need to be very methodical and thorough in handling data engineering as well as model parameters.</p><h3>Dataset and workflow</h3><p>The dataset has 1460 rows of houses with their corresponding 79 features and the target variable: the price of each house. There is also a test set with 1459 other houses.</p><p>In this article, we are going to work them unified for the different techniques that we are going to apply and separating them before realizing the final prediction to raise the results.</p><p>The workflow with the dataset will then be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4CQuiP4uxZDWcerZYUJDBg.png" /></figure><p>a) Import the train_features and test_features data.</p><p>b) Save and remove the index (Id) and prepare train_features without the objective variable</p><p>c) Create a data frame “features” that joint them</p><p>d) Perform data engineering</p><p>e) After finished in data engineering work, split again in X_train and X_test the datasets.</p><p>f) Make the models, fit, and prediction</p><p>g) If we apply any transformation to the target variable (Y), we must invert this transformation over the prediction.</p><p>h) Submit results</p><h3>The target variable: SalePrice</h3><p>We are facing a regression exercise, and we must calculate the selling price of each house, of each row of the dataset.</p><p>Our objective then is the column SalePrice, first, let’s see its general behavior:</p><pre>train[&#39;SalePrice&#39;].describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*mJ0w-gtCMmD7Y6C0ePy5WA.png" /></figure><p>Let’s now see its practice in any model using it directly, or applying the logarithm to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*VyxX1Nt-Z3sHEIFMMKTZQw.png" /></figure><p>So we see the improvement is significant going down from 12934 to 8458 if we change the model training, taking as a result of the logarithm of the target variable instead of ‘SalePrice’ directly.</p><h3>Feature engineering</h3><h4>Correlation with the target variable</h4><blockquote>“The purpose of the correlation is to examine the direction and strength of the association between two quantitative variables. Thus we will know the intensity of the relationship between them and whether, as the value of one variable increases, the value of the other variable increases or decreases.”²</blockquote><p>If you want to know more about the incidence of the correlation of variables and the target variable, you can review this previous issue³ for a detailed analysis.</p><p>We are going to create a data frame with the numeric columns and apply the Pandas “corr()” method to them and evaluate the SalePrice target:</p><pre>data_corr = train.select_dtypes(include=[np.number])<br>data_corr.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*K-r8j6J6Y35BRn4o7ZB5Ng.png" /></figure><pre>corr = data_corr.corr()<br>corr.head(20)<br>corr.sort_values([&#39;SalePrice&#39;], ascending=False, inplace=True)<br>corr[&#39;SalePrice&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*aRVbsJtK-jlgmj9Si6mQcA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*u0TGHh2rRAWMUNK05p86IQ.png" /></figure><p>Here we have an ordered list of variables related to the target variable, the increase in model precision may be thought to decrease as we use variables less and less correlated to the target variable.</p><h4>Outliers values in dataset</h4><blockquote>“… Outliers significantly affect the process of estimating statistics (<em>e.g.</em>, the average and standard deviation of a sample), resulting in overestimated or underestimated values. Therefore, the results of data analysis are considerably dependent on the ways in which the missing values and outliers are processed…”⁴</blockquote><p>In the <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5548942/">article</a> from which this quotation is token, excellent concepts about the treatment of outliers’ values can be found in-depth.</p><p>Let’s take as an example one of the variables that have the highest incidence in its correlation with a price: GrLivArea.</p><p>To visualize outliers, we usually use boxplots.</p><p>Here an excellent article about the use of boxplot and outliers detection⁵ , and his main features:</p><ul><li>Box plots have box from LQ to UQ, with median marked</li><li>They portray a five-number graphical summary of the data Minimum, LQ, Median, UQ, Maximum</li><li>Helps us to get an idea on the data distribution</li><li>Helps us to identify the outliers easily</li><li>25% of the population is below first quartile,</li><li>75% of the population is below third quartile</li><li>If the box is pushed to one side and some values are far away from the box then it’s a clear indication of outliers</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HuRIfPdjmvHfJSV3P-ktZA.png" /></figure><p>We perform a check on any model, using the entire training set, cutting the Outliers &gt; 4500 and cutting the Outliers &gt; 4000, obtaining the following values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2J9HgLzjqceZAprBDPZ6g.png" /></figure><p>The difference in performance between cutting at 4000 or 4500 does not seem significant; however, the improvement in accuracy when slice GrLivArea registers greater than 4500 is considerable.</p><p>In principle and on the training data, it would seem a suitable strategy. Still, it is necessary to look for a balance between what is slice in the entry of the model since it can generate overfitting or take away possibilities of generalization to our model.</p><h4>Droping unnecessary columns and filling nulls values</h4><p>If we deploy null values in the data frame before and after these operations with this code, we are going to obtain graphs as in the following image.</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br>plt.figure(figsize=(12, 6))<br>sns.heatmap(features.isnull())<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDML6p16kdEZo2HjeRfAzg.png" /></figure><p>Remember that all null values must be clear before entering a model.</p><p>Many of these data we can already know that we are not going to precise them or that the attempt to fill the null values is not viable for them; we apply the drop of the column directly.</p><pre>features.drop([&#39;Street&#39;], axis=1, inplace=True)<br>features.drop([&#39;Fence&#39;], axis=1, inplace=True)</pre><p>Everyday use for filling in missing data is to fill it in with “None” or “zero,” depending on the type of data.</p><p>Let’s see here two examples to assign the most frequent value (Pandas mode function) or how to apply the amount of the average of the whole column or a cluster of it.</p><p>These examples are only for illustrative purposes; you can apply any Pandas function and make the grouping by any attribute that you want to make the cluster. It can also be used to create new features of the “cluster” type.</p><p><strong>Example a</strong>: Application of the most frequent MSZoning value, grouped for each MSSubClass</p><pre>features[&#39;MSZoning&#39;] = features.groupby(&#39;MSSubClass&#39;)[&#39;MSZoning&#39;].transform(lambda x: x.fillna(x.mode()[0]))</pre><p><strong>Example b</strong>: Application of the mean value of LotFrontage, grouped for each Neighborhood</p><pre>features[&#39;LotFrontage&#39;] = features.groupby(&#39;Neighborhood&#39;)[&#39;LotFrontage&#39;].transform(lambda x: x.fillna(x.median()))</pre><p><strong>Example c</strong>: Apply the most frequent amount to complete your features</p><pre>features[&#39;Exterior1st&#39;] = features[&#39;Exterior1st&#39;].fillna(features[&#39;Exterior1st&#39;].mode()[0])</pre><p>Finally, we must make sure that there is no value left with null so we can apply a fill to None or zero depending on the type of column:</p><pre>objects = [col for col in features.columns if features[col].dtype == &quot;object&quot;]<br>features.update(features[objects].fillna(&#39;None&#39;))</pre><pre>numerics = [col for col in features.columns if features[col].dtype in np.number]<br>features.update(features[numerics].fillna(0))</pre><h4>Creation of variables according to others</h4><p>You can create new variables to add specific information that helps the model define the data sets, or to simplify the model by creating averages, sums, or Boolean variables.</p><p>Each of these variables must be carefully selected, and the impact on the model must be measured to see whether or not it adds quality to the result, and in the case of being used to “simplify” if the loss of eliminated columns does not affect the accuracy of the model.</p><pre>features[&#39;CondTot&#39;] = (features[&#39;Condition1&#39;] + features[&#39;Condition2&#39;]) / 2</pre><pre>features[&#39;OverTot&#39;] = features[&#39;OverallQual&#39;] + features[&#39;OverallCond&#39;]</pre><pre>features[&#39;TotalSF&#39;] = features[&#39;TotalBsmtSF&#39;] + features[&#39;1stFlrSF&#39;] + features[&#39;2ndFlrSF&#39;]</pre><pre>features[&#39;haspool&#39;] = features[&#39;PoolArea&#39;].apply(lambda x: 1 if x &gt; 0 else 0)</pre><h4>Skew features</h4><blockquote>For normally distributed data, the skewness should be about 0. For unimodal continuous distributions, a skewness value &gt; 0 means that there is more weight in the right tail of the distribution. The function <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skewtest.html#scipy.stats.skewtest">skewtest</a> can be used to determine if the skewness value is close enough to 0, statistically speaking.⁵</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*ge4oEAmQtx-TpjsE-5mU4Q.png" /></figure><p>We use the Scipy.boxcoxp1 ⁶ that compute the Box-Cox transformation of 1 + <em>x</em>. The Box-Cox transformation computed by <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.boxcox1p.html#scipy.special.boxcox1p"><strong>boxcox1p</strong></a> is:</p><pre>y = ((1+x)**lmbda - 1) / lmbda  <strong>if</strong> lmbda != 0<br>log(1+x)                        <strong>if</strong> lmbda == 0</pre><pre>Returns <em>nan</em> if x &lt; -1. Returns <em>-inf</em> if x == -1 and lmbda &lt; 0.</pre><p>For getting the lambda value to input in boxcoxp1, we use boxcox_normmax(features[ind)) from Scipy, that Compute optimal Box-Cox transform parameter for input data⁷</p><p>This transformation can be done only on features that have all their positive values; if you need to do a conversion on elements with negative values, see the reference note⁸ .</p><pre>from scipy.stats import skew<br>from scipy.special import boxcox1p<br>from scipy.stats import boxcox_normmax</pre><pre>numerics = [col for col in features.columns if features[col].dtype in np.number]</pre><pre>skew_f = features[numerics].apply(lambda x: skew(x)).sort_values(ascending=False)</pre><pre>highest_skew =  skew_f[skew_f &gt; 0.5]<br>highest_skew</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*v5JWvfwPUhwI-WGhVuM4NA.png" /></figure><pre>skew_idx = highest_skew.index<br>for ind in skew_idx:<br>    features[ind] = boxcox1p(features[ind], boxcox_normmax(features[ind))</pre><pre>features[highest_skew.index].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*NbNZR9q-FB7pbTQzoMQpRQ.png" /></figure><h4>Creation of features related to the target variable</h4><p>When creating variables related to the target variable, it is necessary to do them only on the train data set and then try to take them to the test dataset, since there we do not know the value of the target variable “Y”.</p><p>This type of variables with which we have added a significant improvement in the leaderboard of the competition</p><p>For example, we can calculate the price per square meter, linked to each neighborhood or class of housing, then we first figure it in the train set:</p><pre>train[&#39;Sqr&#39;] = train[&#39;SalePrice&#39;] / train[&#39;LotArea&#39;]<br>train[&#39;Sqr&#39;] = train.groupby(&#39;Neighborhood&#39;)[&#39;Sqr&#39;].transform(lambda x: x.median())</pre><p>Then we make a dictionary with the prices for each neighborhood:</p><pre>d = {}<br>for indice_fila, x_train in train.iterrows():<br>    d.update({x_train[&#39;Neighborhood&#39;]:x_train[&#39;Sqr&#39;]})</pre><p>And finally, we created the feature in the test dataset</p><pre>test[&#39;Sqr&#39;] = 0.00<br>for indice, x_test in test.iterrows():<br>    test.loc[test.index == indice ,&#39;Sqr&#39;] = d[x_test[&#39;Neighborhood&#39;]]</pre><h3>Categorical object variables</h3><blockquote>“What one hot encoding does is, it takes a column which has categorical data, which has been label encoded and then splits the column into multiple columns. The numbers are replaced by “1” and “0”, depending on which column has what value… ” ⁹</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*8OxRQYauxaor9txkaKBtOA.png" /></figure><p>Categorizing object features can be very convenient, the discussion of which columns to use to apply OHE to them is broad and their limits diffuse, since each different value within the column will be transformed into a new dimension of the matrix input to the model. Sometimes it may be convenient to create a new feature that groups different values to reduce dimensionality, for example, a set of neighborhoods that have similar characteristics and prices.</p><p>Some numeric columns, we may want to categorize them, for which it is convenient to change the type to string since finally, we will apply get_dummies to all the columns of type object.</p><pre>features[&#39;MSSubClass&#39;] = features[&#39;MSSubClass&#39;].apply(str)<br>features[&#39;MoSold&#39;] = features[&#39;MoSold&#39;].astype(str) <br>final_features = pd.get_dummies(features).reset_index(drop=True)</pre><h4>The dummy variable trap:</h4><blockquote>“The dummy variable trap manifests itself directly from one-hot-encoding applied on categorical variables … size of one-hot vectors is equal to the number of unique values that a categorical column takes up and each such vector contains exactly one ‘1’ in it. This ingests multicollinearity into our dataset … “¹⁰</blockquote><p>In other words, when performing the transformation, the set of features of the added OHE is aligned to the target variable, and therefore any column is usually removed. In our model, we have not applied this technique.</p><h4>Overfit</h4><p>Sandeep Kumar’s original work includes at the end of feature engineering and applying get_dummies, a code that looks for those columns that have a lot of zero values (above 99.94%), which are drop.</p><p>This technique indirectly mitigates in categorized variables the effect of the dummy variable trap and also avoids including in the model columns that by the impact of the content of the categorization are irrelevant for a model that seeks to extract the main characteristics and generalize them.</p><pre>overfit = []<br>for i in X.columns:<br>    counts = X[i].value_counts()<br>    zeros = counts.iloc[0]<br>    if zeros / len(X) * 100 <strong>&gt; 99.94:<br>       </strong>overfit.append(i)</pre><pre>overfit = list(overfit)<br><strong>overfit.append(&#39;MSZoning_C (all)&#39;)<br></strong>overfit</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*zx8z6YmNeopvL3CNopIurg.png" /></figure><pre>X = X.drop(overfit, axis=1).copy()</pre><h3>Ensemble models</h3><p>The regression algorithms have had no problem supporting the columns after categorization, so except in strictly inconvenient cases, it does not seem necessary or even a good idea to remove them. However, this is only one approach; at the end of this article, we will see other approaches to the problem very different, and as much or even more useful.</p><p>In this case, then, it is not necessary to reduce the dimensionality of the model since training time with different algorithms is not a problem, and brute force does not seem a bad strategy.</p><h4>What does “ensemble models” mean?</h4><blockquote>“Ensemble models give us excellent performance and work in a wide variety of problems. They’re easier to train than other types of techniques, requiring less data with better results. In machine learning, ensemble models are the norm. Even if you aren’t using them, your competitors are … <a href="https://www.analyticsvidhya.com/blog/2018/06/comprehensive-guide-for-ensemble-models/">Ensemble models</a> are comprised of several weak models that aren’t so great themselves, known as weak learners. When you combine them, they fill in each other’s weaknesses and render better performance than they would when deployed alone.”¹¹</blockquote><h4>Model metrics</h4><p>The competition metric is the Mean Absolute Error (MAE).</p><p>For the initial measurement, RMSE and CV_RMSE used.</p><p>Because the CV_RMSE is negative, to apply the square root, it is necessary to flip it.¹²</p><pre>def rmsle(y, y_pred):<br>    return np.sqrt(mean_squared_error(y, y_pred))</pre><pre>def cv_rmse(model):<br>    rmse = np.sqrt(-cross_val_score(model, X, y, scoring=&quot;neg_mean_squared_error&quot;, cv=kfolds))<br>    return rmse</pre><h4>The models</h4><p>It is an example of one of the original models used by Sandeep Kumar, where we can see lots of hyperparameters uses:</p><pre>gbr = GradientBoostingRegressor(n_estimators=3000, learning_rate=0.05,max_depth=4, max_features=&#39;sqrt&#39;, min_samples_leaf=15, min_samples_split=10, loss=&#39;huber&#39;, random_state=42)</pre><h4>Making the ensemble models</h4><p>In the same operation that we carried out for the GBR model, we can carry it out with other different regression models. Then in a function, we assign them an incidence coefficient on the total value, in such a way that the ratios add up to 1.</p><p>Sandeep Kumar blend models:</p><pre>def blend_models_predict(X):<br>   return (<br>(0.1 * elastic_model_full_data.predict(X)) + \<br>(0.1 * lasso_model_full_data.predict(X)) + \<br>(0.1 * ridge_model_full_data.predict(X)) + \<br>(0.1 * svr_model_full_data.predict(X)) + \<br>(0.1 * gbr_model_full_data.predict(X)) + \<br>(0.15 * xgb_model_full_data.predict(X)) + \<br>(0.1 * lgb_model_full_data.predict(X)) + \<br>(0.25 * stack_gen_model.predict(np.array(X))))</pre><p>Mi blend model:</p><pre>def blend_models_predict(X=X):<br>    return (<br>(0.10 * elastic_model_full_data.predict(X)) +<br>(0.05 * lasso_model_full_data.predict(X)) +<br>(0.05 * ridge_model_full_data.predict(X)) +<br>(0.05 * svr_model_full_data.predict(X)) +<br>(0.20 * gbr_model_full_data.predict(X)) +<br>(0.20 * xgb_model_full_data.predict(X)) +<br>(0.10 * lgb_model_full_data.predict(X)) +<br>(0.25 * stack_gen_model.predict(np.array(X))))</pre><p>We were able to use other models, such as linear regressor, tree regressors, etc. The importance assigned to each model depends on the confidence we have in the algorithm on the test dataset, sometimes algorithms such as GBR, XGB, or LGB work very well in the fit but fall by overfitting to use them in the test set. On the other hand, models like SVR or RIDGE tend to have less precision but are more stable.</p><h3>Putting it all together and many hours of effort</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*GsqTCFdR-anvZMYvNDb3nQ.png" /></figure><h3>Other approaches</h3><p>When we managed to place our model in the top 10 of the world competition and to know that our knowledge was very scarce, with the desire to go for more but feeling on a plateau, I contacted <a href="https://www.kaggle.com/adamsuwik">Adam Suwik</a> who was in the #3 at the time, and still remains there in the top positions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*BgtjvMl7IGWMbU8nWM5nsQ.png" /></figure><p>Very kindly Adam agreed to share the approach of his model in a very illustrative <a href="https://www.kaggle.com/c/home-data-for-ml-course/discussion/100526#652503">post</a>.</p><p>We transcribe here some of the most significant passages for this article:</p><blockquote>“… This is no secret knowledge, only simple logical thinking (although specialist knowledge in the subject would be very helpful too).</blockquote><blockquote>Adjusting the data to the model — most likely Linear Regression will be the # 1 choice. Unfortunately, most of the data does not make much sense and may adversely affect the result. For example, quality — it is not the case that excellent quality of a small house and a large villa has the same value — it should rather be replaced by “size in square feet in exellent quality”. And it seems to me that most of the data should be prepared in such a way — combined with the size of a plot, house area, basement area, pool size, etc.</blockquote><blockquote>Combining data / simplifying the model — that’s what I use a lot. The world is not that complicated. In this case, it seems to me that 3 features would be enough — how big the house is?, how nice it is? how comfortable is it?, maybe a few additional ones like a swimming pool, an additional garage space, etc. …</blockquote><blockquote>Dropping data — I use it a lot too. If I do not see value or think that the information is contained elsewhere, or if I have somehow engineered data, I drop whatever I can. Some expertise would be pretty useful here, but using just common sense, much of the data that seems to have an impact is really secondary. Nobody builds a luxury home on cheap foundations and viceversa …</blockquote><blockquote>Clusters — not always the same rules apply to entire populations, if I am able to isolate a large group of similar cases, I will build a separate model for them. From life experience — if you look at the price per square foot you will notice that for smaller apartments it is definitely bigger.</blockquote><blockquote>And I probably could describe a few other things, but it all comes down to one thing — analyze all the data carefully and think about how to engineer them to fit the model you use. I believe in one principle: “garbage in, garbage out”. What quality of data you provide, the quality of result you will get…</blockquote><blockquote>NaN’s. Unfortunately, the answer is just as above — there are no secrets — do whatever seems to make sense. I like “0”, “none”, I really like my own predictions, I hate the average, it’s like admitting to the lack of any idea and just minimizing cost of assumed mistakes…”</blockquote><p>It is another approach, and there are many more approaches to the web. To be in 1% of any competition is in itself a good enough model and a sign that we are on the right way.</p><h3>Summary</h3><p>We have seen how important it is to start a job supported in the preliminary work that others have shared, in this case, the transfer learning of the Sandeep Kumar model. Thanks him!</p><p>This previous transfer learning gave us a floor and essential knowledge from which to start, much more elaborated and refined than the experience that a rookie takes from online courses.</p><p>Then, after many hours of effort and systematic tests, we saw the impact of each technique on the different variables to make decisions about the engineering features and the ensemble of models.</p><p>One day I got that idea that makes the difference, being distracted the head still thinking, the idea was to calculate the value of square feet based on a given concept, and the satisfaction of having reached that top ten was an incredible moment.</p><p>The objective of this Kaggle competition is to learn</p><p>This post aimed to transmit the techniques that you can use if you are stuck until the mud in the game as I was a few months ago hopefully, help you get on an exact path towards improving your model, or maybe help you light that little lamp that makes the difference.</p><p>I will be grateful for comments and reports if something could be doing better.</p><h3>References</h3><p>[1] <a href="https://en.wikipedia.org/wiki/Kaggle">Kaggle</a> is an online community of data scientists and machine learners, owned by <a href="https://en.wikipedia.org/wiki/Google_LLC">Google LLC</a> . Kaggle allows users to find and publish data sets, explore and build models in a web-based data-science environment, work with other data scientists and machine learning engineers, and enter competitions to solve data science challenges. Kaggle got its start by offering machine learning competitions and now also offers a public data platform, a cloud-based workbench for data science, and short form AI education. On 8 March 2017, Google announced that they were acquiring Kaggle.</p><p>[2] <a href="https://www.google.com/url?sa=t&amp;source=web&amp;rct=j&amp;url=https://personal.us.es/vararey/adatos2/correlacion.pdf&amp;ved=2ahUKEwiaytLbhqnlAhUGLLkGHeL2B24QFjAMegQIBxAB&amp;usg=AOvVaw1mijaxh5F0qXIXMpeadD5j">https://www.google.com/url?sa=t&amp;source=web&amp;rct=j&amp;url=https://personal.us.es/vararey/adatos2/correlacion.pdf&amp;ved=2ahUKEwiaytLbhqnlAhUGLLkGHeL2B24QFjAMegQIBxAB&amp;usg=AOvVaw1mijaxh5F0qXIXMpeadD5j</a></p><p>[3] <a href="https://medium.com/analytics-vidhya/incidence-of-correlation-and-time-features-in-a-regression-model-6fc1c4653e4f?source=your_stories_page---------------------------">Incidence of correlation and time features in a regression model</a></p><p>[4] <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5548942/">Statistical data preparation: management of missing values and outliers</a></p><p>“… There are basically three methods for treating outliers in a data set. One method is to remove outliers as a means of trimming the data set. Another method involves replacing the values of outliers or reducing the influence of outliers through outlier weight adjustments. The third method is used to estimate the values of outliers using robust techniques.</p><p><strong>Trimming</strong>: Under this approach, a data set that excludes outliers is analyzed. The trimmed estimators such as mean decrease the variance in the data and cause a bias based on under- or overestimation. Given that the outliers are also observed values, excluding them from the analysis makes this approach inadequate for the treatment of outliers.</p><p><strong>Winsorization</strong>: This approach involves modifying the weights of outliers or replacing the values being tested for outliers with expected values. The weight modification method allows weight modification without discarding or replacing the values of outliers, limiting the influence of the outliers. The value modification method allows the replacement of the values of outliers with the largest or second smallest value in observations excluding outliers.</p><p><strong>Robust estimation method</strong>: When the nature of the population distributions is known, this approach is considered appropriate because it produces estimators robust to outliers, and estimators are consistent. In the recent years, many studies have proposed a variety of statistical models for robust estimation; however, their applications are sluggish due to complicated methodological aspects. “</p><p>[5] <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skew.html">https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skew.html</a></p><p>[6] <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.boxcox1p.html">https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.boxcox1p.html</a></p><p>[7]<a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.boxcox_normmax.html?highlight=normmax#scipy.stats.boxcox_normmax">https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.boxcox_normmax.html?highlight=normmax#scipy.stats.boxcox_normmax</a></p><p>[8] <a href="https://www.kaggle.com/rtatman/data-cleaning-challenge-scale-and-normalize-data">https://www.kaggle.com/rtatman/data-cleaning-challenge-scale-and-normalize-data</a></p><p>“One thing you can do is add a fixed value that’s just bigger than your smallest negative to make all your value normal. Another normalization method is the <a href="https://cran.r-project.org/web/packages/jtrans/jtrans.pdf">Johnson Transformation</a>, which can handle negative values.</p><p>[9] <a href="https://towardsdatascience.com/choosing-the-right-encoding-method-label-vs-onehot-encoder-a4434493149b">https://towardsdatascience.com/choosing-the-right-encoding-method-label-vs-onehot-encoder-a4434493149b</a></p><p>[10] <a href="https://towardsdatascience.com/one-hot-encoding-multicollinearity-and-the-dummy-variable-trap-b5840be3c41a">https://towardsdatascience.com/one-hot-encoding-multicollinearity-and-the-dummy-variable-trap-b5840be3c41a</a></p><p>[11] <a href="https://medium.com/@ODSC/ensemble-models-demystified-c871d5ee7793">https://medium.com/@ODSC/ensemble-models-demystified-c871d5ee7793</a></p><p>[12] <a href="https://github.com/scikit-learn/scikit-learn/issues/2439">https://github.com/scikit-learn/scikit-learn/issues/2439</a></p><p>The Mean Square Error returned by sklearn.cross_validation.cross_val_score is always a negative. While being a designed decision so that the output of this function can be used for maximization given some hyperparameters, it’s extremely confusing when using cross_val_score directly. At least I asked myself how a the mean of a square can possibly be negative and thought that cross_val_score was not working correctly or did not use the supplied metric. Only after digging in the sklearn source code I realized that the sign was flipped.</p><p>This behavior is mentioned in make_scorer in scorer.py, however it’s not mentioned in cross_val_score and I think it should be, because otherwise it makes people think that cross_val_score is not working correctly</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efb35828eef0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/feature-engineering-and-ensembled-models-for-the-top-10-in-kaggle-housing-prices-competition-efb35828eef0">Feature engineering and ensembled models for the top 10 in Kaggle “Housing Prices Competition”</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[Image classification and deploy with Pytorch]]></title>
            <link>https://medium.com/data-science/fantastic-and-straightforward-image-classification-with-fastai-library-for-pytorch-30c3380ac284?source=rss-4213edda07c------2</link>
            <guid isPermaLink="false">https://medium.com/p/30c3380ac284</guid>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Gabriel Naya]]></dc:creator>
            <pubDate>Sun, 27 Oct 2019 12:44:47 GMT</pubDate>
            <atom:updated>2020-01-09T21:49:45.826Z</atom:updated>
            <content:encoded><![CDATA[<h3>Image classification from scratch to deployment</h3><h4>We review the technique to classify images and to clean the training dataset. We create an image dataset with Google, apply the model on a real case, and add a guide for deploying the model with Starlette and Uvicorn</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oxuKBZpzmmLAzawe" /><figcaption>Photo by <a href="https://unsplash.com/@harshaldesai?utm_source=medium&amp;utm_medium=referral">Harshal Desai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Background</h3><p>These days, due to certain circumstances, I found myself doing a <a href="https://course.fast.ai/">free Pytorch course designed with fast.ai</a> , the material on which this article is entirely based (lesson 2) and which has fascinated me, given the simplicity, usefulness, and solidity of these libraries.</p><p>In this article we will discover some tools of fast.ai for Pytorch, after completing its reading we will know:</p><ul><li>How to create a dataset with Google’s image search engine</li><li>How to develop and tuning a neural net to classify images</li><li>How to use ImageCleaner to clean the training dataset and improve it.</li><li>An example with a real case, and private dataset applied</li><li>An illustrative guide on how to deploy the model</li></ul><h3>Creating a dataset from the Google search engine</h3><p>The first thing I saw in the fast.ai online course is not explicit related to Pytorch or fast.ai, but to a way to create a dataset directly from the Google image search engine.</p><p>This technique is inspired by the work of Francisco Ingham and Jeremy Howard/Adrian Rosebrock¹.</p><h4>Creating the list of URLs for each category</h4><p>We are going to create a data set with three classes of images based on photos of birds, wildcats, and airplanes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0AcDvUtNJ39LF9MgfUMUwA.png" /></figure><p>We must assemble each one of the categories separately, to get the images of aircraft, we search in our browser, for example: “aircraft photography”.</p><p>To refine the search, we can use all the search engine tools, such as exclude unwanted elements in the name of the image (using -textToExclude, for example: -camera -airport) or filter only specific categories using the tag buttons.</p><p>For public use of the Dataset, you must filter in “Tools — Rights of use” and respect the copyright according to the case that applies.</p><p>Once we have in our browser the desired images, we will execute two Javascript sentences on the console.</p><blockquote>“Press Ctrl-Shift-J in Windows/Linux and Cmd-Opt-J in Mac, and a small window the javascript ‘Console’ will appear. You will need to get the URLs of each of the images. Before running the following commands, you may want to disable adblocking extensions (uBlock, AdBlockPlus, etc.) in Chrome. Otherwise, the window.open() command doesn’t work. Then you can run the following commands: ”²</blockquote><pre>urls <strong>=</strong> Array.from(document.querySelectorAll(&#39;.rg_di .rg_meta&#39;)).map(el<strong>=&gt;</strong>JSON.parse(el.textContent).ou);</pre><pre>window.open(&#39;data:text/csv;charset=utf-8,&#39; <strong>+</strong> escape(urls.join(&#39;\n&#39;)));</pre><p>This code will start the download of a file, which we must rename as urls_[ClassName].csv. We have used as a convention for the name of the files the prefix ‘urls_’ and then the name of the class; this is very important for the functioning of the code that we will see later,</p><p>We repeat the operation of filtering images in the browser and downloading their URLs in a file renamed to CSV for each of the other three categories until you get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*-ipg1wkaDFCP8g1BPhwSjw.png" /></figure><p>If we take a look inside each of these files, we will see that they are simple files with the list of URLs of the filtered images</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*RCkBtccIC_2SuhAqmxVNJA.png" /></figure><h4>Downloading and verifying the images in each path</h4><p>Once we have the list of URLs for each category in our CSV files, we’ll run the code to download the images and build our data set. In my case, I’ve created a ‘data/photos’ path, which is my base path. There I have placed the three CSV files of the categories and then we execute the code to create the subdirectories where the images will be download</p><pre>from fastai.vision import *<br>classes = [&#39;birds&#39;,&#39;flowers&#39;,&#39;aircrafts&#39;]<br>path = Path(&#39;data/photos&#39;)<br>for folder in classes:<br>    dest = path/folder<br>    dest.mkdir(parents=True, exist_ok=True)</pre><pre>path.ls()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*7qVBBRpnlaQCnzoiQInXyA.png" /></figure><p>To make the real download of the images we use</p><pre>for cla in classes:<br>   print (cla)<br>   file = &#39;urls_&#39;+cla+&#39;.csv&#39;<br>   dest = path/cla<br>   download_images(path/file, dest, max_pics=200)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*U9Uz1h3Gf_PNehpmXYZQMw.png" /></figure><p>Then we execute code to verify that all downloaded images are correct, and that removes images that may be corrupt (delete=True)</p><pre>for c in classes:<br>   print(c)<br>   verify_images(path/c, delete=True, max_size=500)</pre><p>To review the documentation for each of these statements you can run the doc() command, for example:</p><pre>doc(verify_images)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gC9IoGbicKPRRlTtMg0coQ.png" /></figure><h4>Creating and visualizing the Dataset</h4><p>After having the images downloaded and verified in the path corresponding to each category, we can create a fast.ai DataBunch (similar DataFrame), put inside the tagged images, and start visualizing or working with them</p><pre>np.random.seed(7)</pre><pre>data = ImageDataBunch.from_folder(path, train=&quot;.&quot;, valid_pct=0.2, ds_tfms=get_transforms(), size=224, num_workers=4).normalize(imagenet_stats)</pre><p>And run the code to display a batch of 3 rows at random inside Dataset</p><pre>data.show_batch(rows=3, figsize=(7,8))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*xA-XE__ApHBsucaMVailoQ.png" /></figure><h3>The model first version</h3><p>For this exercise, we are going to use a convolutional neural net, in resnet34 format³. Within the models, there is a set of pre-defined net architectures, involving different structures and complexities⁴.</p><p>The resnet34 configuration is, in principle, sufficiently efficient and straightforward for the proposed scope</p><pre>learn = cnn_learner(data, models.resnet34, metrics=error_rate)<br>learn.fit_one_cycle(4)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*lU4Z_tJX-LMXljEUvpu29Q.png" /></figure><p>After the first training, we see that the net has not gone wrong at all, achieving an accuracy of 95% (error_rate = 0.045455), and the training time is perfect.</p><p>To be able to adjust this precision a little more, we have a method that graphs the behavior of the learning-rate parameter:</p><pre>learn.lr_find()</pre><p>We see how the method searches through 20 pass the loss of the neural net for different learning rate values. Then we can graph them looking for the range that best suits and re-enter with that setting:</p><pre>learn.recorder.plot()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*uIh-ujeUOAO86zBcyF5Yeg.png" /></figure><p>The left graph shows us the result of learning_rate in the neural net, and we must then look for the range of most significant learning, given between the beginning of the sustained decline, until the end of the fall and the start of the ascent.</p><p>This environment, marked by the bottom red bars in the graph on the right, gives us a start in the middle between 1e-⁶ and 1e-⁵, so we can roughly say that the beginning is nearly (<strong>1e-⁶ / 2</strong>); the final range is clearly at <strong>1e-</strong>³</p><pre>learn.fit_one_cycle(2, max_lr=slice(<strong>1e-6/2</strong>,<strong>1e-3</strong>))</pre><p>And we see that the accuracy of the model improves, reaching 96.5%, with an error_rate = 0.034091</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*pO_hNiVnm5VRCzKQNIogzA.png" /></figure><p>Let’s save this version of the model so we can go back over it</p><pre>learn.save(&#39;stage-2&#39;)</pre><h3>Cleaning the training Dataset</h3><h4>Confusion Matrix</h4><p>Although, in this case, the accuracy obtained could be sufficient, we will see two exciting tools to try to understand that circumstances have confused the training in addition to the classic “confusion matrix”<strong>*</strong>.</p><pre>learn.load(&#39;stage-2&#39;);<br>interp = ClassificationInterpretation.from_learner(learn)<br>interp.plot_confusion_matrix()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*aDXaa4cmEu6GtLx1WV87eA.png" /></figure><p>Let’s use now the ImageCleaner, a widget of fastai.widgets that will help us to delete or re-label those images of our model that are incorrect.</p><h4>ImageCleaner for top losses</h4><p>For the first cleaning training dataset tool, we need to find the path of the images that have the highest loss with the .from_toplosses method to locate the corresponding indexes and pass them to the ImageCleaner.</p><p>The widget does not delete the images of the corresponding path, but generates a new CSV file (cleaned.csv) with the list of the pictures “not for remove” and with the correct category in case, it has been reassigning</p><pre>from fastai.widgets import *</pre><pre>db = (ImageList.from_folder(path)<br>.split_none()<br>.label_from_folder()<br>.transform(get_transforms(), size=224)<br>.databunch())</pre><pre>learn_cln = cnn_learner(db, models.resnet34, metrics=error_rate)<br>learn_cln.load(&#39;stage-2&#39;);</pre><p>We create a new learn_cln model reading from the folders (from_folder), and we take the weights of the stage-2 saved in the previous stage.</p><p>Then separate the Dataset and the indices taken from the main training losses. With these objects, we invoke the ImageCleaner that will display on-screen the elements of confusion (from_toplosses) to allow us to eliminate them or reassign them to the correct class</p><pre>ds, idxs = DatasetFormatter().from_toplosses(learn_cln)<br>ImageCleaner(ds, idxs, path)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*C691Ym3HoQqeSDvhFKSWkg.png" /></figure><p>The tool shows us in batch a set of confusing images and allows us to delete or re-classify them in the category box below each image. By clicking on next-batch, the file cleaned.csv re-label or removes them from its list. We must repeat this procedure until no more images in the widget.</p><h4>ImageCleaner for duplicates</h4><p>The second tool for debugging our training images is the one that presents us with images that “could” be the same, to leave only one of them</p><pre>ds, idxs = DatasetFormatter().from_similars(learn_cln)<br>ImageCleaner(ds, idxs, path, duplicates=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*eGW7He__fJqd_D-6Id_w1w.png" /></figure><p>In this case, the original Dataset used is clean enough not to present confusion by duplicate images. However, in the following example, we will see how it applies to the finding of similarities between images.</p><h3>The model after image cleaning</h3><p>Here we have each directory with the original images, and the cleaned.CSV file contains the list of images that will remain and those that will be moved by a re-labeling</p><p>Here we must be careful handling code since it is necessary to regenerate the DataBunch (Data Frame with the images and their labels). Still, in this case, we are going to indicate that the origin is “from_csv” (in the previous example, it was “from_folder”).</p><pre>db = (ImageList.<strong>from_csv</strong>(path, &#39;cleaned.csv&#39;, folder=&#39;.&#39;)<br>.no_split()<br>.label_from_df()<br>.transform(get_transforms(), size=224)<br>.databunch())</pre><pre>learn_cln = cnn_learner(db, models.resnet34, metrics=error_rate)<br>learn_cln.fit_one_cycle(2, max_lr=slice(1e-6/2,1e-3))</pre><p>By re-training the model, you reach 100% accuracy without finding confusing values and without error_rate on the training model. Great!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*2kXz7hRPnGMGPY6xGn9jZA.png" /></figure><h3>A real case of use</h3><p>So far, we have worked a classification model of images using “resnet34” on a dataset created by us from Google.</p><p>For article purposes, conditions are sufficient to illustrate the power of machine learning, visualization, and cleaning dataset tools.</p><p>A real case has been raised recently, consists of taking the images attached to the tickets of users who report needs on ERP software. The objective was to classify these images in the following categories: ‘reports,’ ‘errors,’ ‘screen,’ ‘tickets.’</p><p>Images were hosted on a server, below the ‘attach’ path, in subdirectories numbered with the ID of the user reporting the error, message, or need.</p><p>We used the following Python code to unify the images in a directory, and from there, the client “tagged” them separating in the folders corresponding to each category.</p><pre>import os<br>import sys<br>from shutil import copyfile</pre><pre>dir_ori = &#39;attach&#39;<br>dest = &#39;attach/images&#39;<br>os.chdir(dir_ori)</pre><pre>for x in os.listdir(&#39;.&#39;):<br>   if os.path.isdir(x):<br>       newdir = os.path.join(dir_ori,x)<br>       os.chdir(newdir)<br>       for w in os.listdir(newdir):<br>           if os.path.isfile(w):<br>               file, ext = os.path.splitext(w)<br>               if ext.lower() == &#39;.jpg&#39;:<br>                  if sys.platform == &quot;win32&quot;:<br>                     os.popen(&#39;copy &#39;+w+&#39; &#39;+dest)<br>                  else<br>                     os.popen(&#39;cp &#39;+w+&#39; &#39;+dest)<br>       os.chdir(dir_ori)</pre><p>Once the files were unifying, an application was install so that the client could label them in their corresponding folders, and the same training and toning procedure was applied, obtaining the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*xwdsZwI3_7-vbskgDSzgzw.png" /></figure><p>We close initial accuracy (before ImageCleaner) of just over 85%.</p><p>Here we see a clear example of the ImageCleaner with the search for similar, which we could not see in the previous model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*gLEOW9iN2-FV9PheRyY4Fw.png" /></figure><p>After the training dataset cleaning and relabeling of the confusing cases, we retake the dataBuch from the cleaned.csv, and when re-training the model, taking as data source the clean base, we obtain a 100% accuracy again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*GqokgE0IIIi3cYqSGw3X-g.png" /></figure><p>Great, great!</p><h3>Deploy the model</h3><p>Following the content of lesson 2 of the fast.ai course, and in order not to waste excellent content that appears there, we are going to spread it because, on many occasions, it is difficult for people away from programming, imagine how to deploy a model.</p><h4>Prediction in the work environment</h4><p>First, let’s see how the model behaves predicting from our working environment in the Jupyter Notebook</p><pre>learn.export()</pre><p>This command creates a file called “export.pkl” in the working directory, which contains everything necessary for the deploy of the model (weights, metadata of the classes, and transformations or normalizations used).</p><pre>defaults.device = torch.device(&#39;cpu&#39;)<br>img = open_image(path/&#39;birds&#39;/&#39;00000022.jpg&#39;)<br>img</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*MwNQG4aFdKrMWMlauBHqvg.png" /></figure><p>Now that we have to take a look of 00000022.jpg, we test the model:</p><pre>learn = load_learner(path)<br>pred_class,pred_idx,outputs = learn.predict(img)<br>pred_class</pre><p>And the result, of course, is the category birds!</p><h4>Prediction in a service with Starlette⁵ and Uvicorn⁶</h4><p>Now, let’s orient ourselves about putting the model into production. For that, we are his framework is restrictive on Python 3.6+ and to install it we run from the Python environment</p><pre>$ pip3 install starlette or $ pip install starlette</pre><p>We’ll also need to build a server; in this case, we’ll use Uvicorn [vii] which we install</p><pre>$ pip3 install uvicorn o $ pip install uvicorn</pre><p>Let’s try a simple Python code to see if we can create an API</p><pre>from starlette.applications import Starlette<br>from starlette.responses import JSONResponse<br>import uvicorn</pre><pre>app = Starlette(debug=True)<br>@app.route(&#39;/&#39;)</pre><pre>async def homepage(request):<br>    return JSONResponse({&#39;MySAMPLE&#39;: &#39;It works!&#39;})</pre><pre>if __name__ == &#39;__main__&#39;:<br>    uvicorn.run(app, host=&#39;0.0.0.0&#39;, port=8000)</pre><p>When you run it, Uvicorn server will be built that gives you access from your browser to <a href="http://localhost:8000/">http://localhost:8000/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*DVRhwq-yNVMDOw1s8O1YwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*dLiY9iZ7bhYgYhbhdZqo0g.png" /></figure><p>Finally, we could apply the prediction receiving as parameter the URL of some of the images, which we would invoke for example with</p><p><a href="http://localhost:8000/classify-url?url=imagen.jpg">http://localhost:8000/classify-url?url=imagen.jpg</a></p><p>Here, the code from Simon Willison⁷ as a reference of complete deployment (remember we need to take model.pkl file in deployment environment)</p><pre>from fastai.vision import</pre><pre>@app.route(&quot;/classify-url&quot;, methods<strong>=</strong>[&quot;GET&quot;])</pre><pre><strong>async</strong> <strong>def</strong> classify_url(https://medium.com/request):<br>   bytes <strong>=</strong> <strong>await</strong> get_bytes(request.query_params[&quot;url&quot;])<br>   img <strong>=</strong> open_image(BytesIO(bytes))<br>   _,_,losses <strong>=</strong> learner.predict(img)<br>   <strong>return</strong> JSONResponse({<br>&quot;predictions&quot;: sorted(zip(cat_learner.data.classes, map(float, losses)),key<strong>=lambda</strong> p: p[1],reverse<strong>=True</strong>)<br>})</pre><blockquote><em>Note: This code is displayed as a guide and is taken directly from the course mentioned above. It is not the scope of this article to explain it step by step or to validate it. In general, the code receives from the request as parameter the URL of the image, opens it, makes the prediction, and returns a JSON with the probabilities of each category. You can consult Simon Wilson complete code, </em><a href="https://github.com/simonw/cougar-or-not/blob/master/cougar.py"><em>thanks</em></a><em> him.</em></blockquote><h3>Summary</h3><p>We have seen how to create our own set of images from the Google search engine, or how to manipulate images from a server to unify them to our client can label them.</p><p>We have developed a resnet34 neural net obtaining very good initial results, better after tuning the learning rate, and excellent final results after cleaning the training images that can generate confusion or be duplicate.</p><p>Finally, we have seen a superficial guide on how to deploy the model to make predictions of new cases.</p><p>All this through fast.ai for Pytorch, in few and short lines of code.</p><p>Once we remember that this article is inspired by the course <a href="https://course.fast.ai/">https://course.fast.ai</a> lesson 2, on which we have carried out our tests, and from which we take the basis for our real case.</p><p>I hope this article was useful for you, I will be grateful for comments and reports if something could be doing better.</p><h3>References</h3><p>[1] Into fast.ai course referred, this technique is inspired by: Francisco Ingham and Jeremy Howard / [<a href="https://www.pyimagesearch.com/2017/12/04/how-to-create-a-deep-learning-dataset-using-google-images/">Adrian Rosebrock</a>]</p><p>[2] <a href="https://course.fast.ai/">https://course.fast.ai,</a> lesson 2, Jupyter Notebook: lesson2-download</p><p>[3] <a href="https://towardsdatascience.com/an-overview-of-resnet-and-its-variants-5281e2f56035">https://towardsdatascience.com/an-overview-of-resnet-and-its-variants-5281e2f56035</a></p><p>[4] <a href="https://medium.com/@14prakash/understanding-and-implementing-architectures-of-resnet-and-resnext-for-state-of-the-art-image-cf51669e1624">https://medium.com/@14prakash/understanding-and-implementing-architectures-of-resnet-and-resnext-for-state-of-the-art-image-cf51669e1624</a></p><p>[*] Lately, it has happened to me that confusion matrices with more than two class see strangely and erroneously, <a href="https://stackoverflow.com/questions/56942670/matplotlib-seaborn-first-and-last-row-cut-in-half-of-heatmap-plot">apparently is a subject of the version of matplotlib</a>, so I decided to include it anyway.</p><p>[5] <a href="https://www.uvicorn.org/">Uvicorn</a> is a lightning-fast ASGI server, built on <a href="https://github.com/MagicStack/uvloop">uvloop</a> and <a href="https://github.com/MagicStack/httptools">httptools</a>.</p><p>[6] <a href="https://www.starlette.io/">Starlette</a> is a lightweight <a href="https://asgi.readthedocs.io/en/latest/">ASGI</a> framework/toolkit, which is ideal for building high performance asyncio services</p><p>[7] Simon Willison make the structure of <a href="https://github.com/simonw/cougar-or-not">this code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30c3380ac284" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/fantastic-and-straightforward-image-classification-with-fastai-library-for-pytorch-30c3380ac284">Image classification and deploy with Pytorch</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>