<?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 Kanellis Georgios on Medium]]></title>
        <description><![CDATA[Stories by Kanellis Georgios on Medium]]></description>
        <link>https://medium.com/@kanellisg?source=rss-ef3648b35d09------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*TJBIWc5MB2stAZ5RCd1MKA.png</url>
            <title>Stories by Kanellis Georgios on Medium</title>
            <link>https://medium.com/@kanellisg?source=rss-ef3648b35d09------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:51:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kanellisg/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[Detect Greek language in text using Docker, & store in S3 without Boto3.]]></title>
            <link>https://medium.com/data-science/detect-greek-language-in-text-using-docker-store-in-s3-without-boto3-3c6d6b220639?source=rss-ef3648b35d09------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c6d6b220639</guid>
            <category><![CDATA[greek]]></category>
            <category><![CDATA[language-detection]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Kanellis Georgios]]></dc:creator>
            <pubDate>Tue, 15 Oct 2019 13:24:26 GMT</pubDate>
            <atom:updated>2019-10-15T17:33:23.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCkCbdsuoqu_H6CYhprrTw.jpeg" /></figure><p><strong><em>Hi, there! In this article we are going to build a small “application”, that has the ability to detect Greek language in text &amp; store some results in AWS S3.</em></strong></p><p>In more detail, the application will be a docker container which will accept an input filepath, will be able to fetch a file (e.g. from an AWS S3 bucket), use python scripts to process it, detect Greek language in text, keep only Greek text and finally upload the resulting .csv file of greek text back into an AWS S3 bucket.</p><p>As a first step, we will build a Docker image &amp; make sure all needed modules for the language detection, text processing, and AWS communication are installed in the image’s virtual OS, as long as that the environment variables that hold the credentials of AWS are passed into the Docker image properly.</p><p>To make this more interesting:</p><ul><li>We will not use the boto3 library, as it is not always functioning identically to the AWS CLI when the access rights for AWS S3 are strict.</li><li>We will use the <a href="https://fasttext.cc/">fastText</a> text classification library, which will actually be our language detection tool since it provides the tiny <a href="https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.ftz">lid.176.ftz</a> model; the compressed version of its corresponding main model, with a file size of 917kB only!</li></ul><h3>Needed Files</h3><p>We need to prepare some files before setting up our flow:</p><ul><li>. : Create a local folder in the directory in which the Dockerfile will be placed and used to built the image.</li><li>./init/: In the above main folder, create an ‘init’ folder, which will contain all files that need to be copied into the docker image.</li><li>./init/envs.py: The environment variables file:</li></ul><pre>envs = {<br>    &quot;LOCAL_FILE&quot;: &#39;temp.csv&#39;,<br>    &quot;LOCAL_OUT_FILE&quot;: &#39;output.csv&#39;,<br>    &quot;AWS_S3_PROFILE&quot;: &#39;my_aws_s3_profile_name&#39;<br>}</pre><ul><li>./init/s3.py: The script for the main functionality.</li><li>./init/lib_process.py: A helper library imported &amp; used by the s3.py file.</li><li>./init/lid.176.ftz: The language detection model.</li><li>./init/credentials: The AWS credentials file:</li></ul><pre>[my_aws_s3_profile_name]<br>aws_access_key_id = ABCDE<br>aws_secret_access_key = 12345</pre><ul><li>./init/config: The AWS config file:</li></ul><pre>[my_aws_s3_profile_name]<br>output=json<br>region=us-east-2</pre><p>where we assume that our AWS region is us-east-2.</p><ul><li>Dockerfile: The docker instructions for building the docker image.</li></ul><h3><strong>Docker Image</strong></h3><p>Let’s parse together the <strong>Dockerfile</strong>, line by line:</p><pre>1 FROM python:3.6.6-slim<br>2 WORKDIR .<br>3 COPY ./init/envs.py .<br>4 COPY ./init/s3.py .<br>5 COPY ./init/lib_process.py .<br>6 COPY ./init/lid.176.ftz .<br>7 RUN mkdir -p /.aws/<br>8 RUN apt-get update &amp;&amp; apt-get install -y \<br>9         python-dev \<br>10        python-numpy \<br>11        python-scipy \<br>12        &amp;&amp; rm -rf /var/cache/apk/*<br>13 COPY ./init/credentials /.aws/<br>14 COPY ./init/config /.aws/<br>15 ENV AWS_CONFIG_FILE=/.aws/config<br>16 ENV AWS_SHARED_CREDENTIALS_FILE=/.aws/credentials<br>17 RUN pip3 install --upgrade awscli<br>18 RUN pip3 install fasttext<br>19 RUN chmod u+x s3.py<br>20 ENTRYPOINT [&quot;python3&quot;,&quot;s3.py&quot;]<br>21 CMD [&#39;&#39;]</pre><p><em>Building the optimal docker image size-wise is out of scope; there are many good articles in Towards Data Science for this :-)</em></p><ul><li><strong>Line 1: </strong>We start from a python3.6 small image.</li><li><strong>Line 2: </strong>We set the current directory as the directory seen while building the image.</li><li><strong>Line 3:</strong> Move the envs into the image’s OS.</li><li><strong>Line 4 &amp; 5:</strong> Do the same with the python scripts.</li><li><strong>Line 6: </strong>Do the same with the language detection model.</li><li><strong>Line 7: </strong>Create the AWS-CLI settings directory.</li><li><strong>Line 8–12: </strong>Install through the docker image’s Ubuntu OS, some basic python modules, but without keeping their installation files.</li><li><strong>Line 13 &amp; 14:</strong> Move the AWS settings files (which include the AWS-CLI credentials) into the image’s OS default AWS-CLI settings directory.<br>✧<em> This is important. Instead of hardcoding the credentials in the Dockerfile or related source code, which is shared code, we inject it at building time.<br></em>✧<em> Making the running container ask for the credentials as input parameters would be even safer.<br></em>✧ <em>The above stand for the case we were passing credentials through the envs.py file, too.</em></li><li><strong>Line 15 &amp; 16: </strong>Refresh(set) the AWS environment variables that show the setting files paths.</li><li><strong>Line 17: </strong>Install AWS-CLI through python’s pip.</li><li><strong>Line 18: </strong>Install fasttext library through python’s pip.</li><li><strong>Line 19: </strong>Make the s3.py file executable.</li><li><strong>Lines 20 &amp; 21: </strong>Any container created by the above image will, by default, use the virtual OS’s python3 to run the python executable s3.py.</li></ul><h3>Using the docker image</h3><p>We can run the following commands, e.g. in Ubuntu:</p><ul><li>Build the image:</li></ul><pre>docker build --no-cache -t &lt;image_name&gt; .</pre><ul><li>Create &amp; run a container of the image:</li></ul><pre>docker run --rm -t --name &lt;container_name&gt; &lt;image_name&gt; \<br>&quot;s3://&lt;bucket_name&gt;/&lt;relative path to file&gt;/input.csv&quot; \ &quot;s3://&lt;bucket_name&gt;/&lt;relative path to file&gt;/output.csv&quot;</pre><p>In our case, the above means that we create &amp; run a container that will find the input file in the first s3 path &amp; will store the processed resulting file in the second s3 path.</p><ul><li>Debug the image by opening the virtual OS for manual exploration:</li></ul><pre>docker run --entrypoint &quot;/bin/bash&quot; -it \ <br>--name &lt;container_name&gt; &lt;image_name&gt;</pre><h3><strong>The Inner Flow</strong></h3><p>As we saw above, the container executes the s3.py script with some given parameters. The script:</p><ul><li>Reads the parameters.</li><li>Runs an aws-cli command through its host OS, meaning the docker image OS, and fetches from aws s3 the input .csv file.</li><li>Processes the input file &amp; produces an output one.</li><li>Runs an aws-cli command again and uploads it into s3 the output .csv file.</li><li>For this tutorial both .csv files are utf-8 encoded &amp; comma separated.</li></ul><p>The <strong>s3.py</strong> script:</p><pre>#!/usr/bin/python3</pre><pre>import os<br>import sys<br>from envs import envs<br>from lib_process import processing</pre><pre>if __name__ == &#39;__main__&#39;:<br>    print(os.uname())<br>    print(&quot;This is the name of the script: &quot;, sys.argv[0])<br>    print(&quot;Number of arguments: &quot;, len(sys.argv))<br>    print(&quot;The arguments are: &quot;, str(sys.argv))<br>    REMOTE_IN_FILE = sys.argv[1]<br>    LOCAL_FILE = &quot;./&quot; + envs[&quot;LOCAL_FILE&quot;]<br>    LOCAL_OUT_FILE = &quot;./&quot; + envs[&quot;LOCAL_OUT_FILE&quot;]<br>    REMOTE_OUT_FILE = sys.argv[2]<br>    print(&quot;Entered the python script.&quot;)<br>    print(&quot;Envs: REMOTE_IN_FILE:&quot;, REMOTE_IN_FILE)<br>    print(&quot;Envs: LOCAL_FILE:&quot;, LOCAL_FILE)<br>    print(&quot;Envs: REMOTE_OUT_FILE:&quot;, REMOTE_OUT_FILE)<br>    print(&quot;Envs: AWS_S3_PROFILE:&quot;, envs[&#39;AWS_S3_PROFILE&#39;])</pre><pre>    down_command = &quot;aws s3 cp &quot; + &quot;--profile &quot; + <br>        envs[&#39;AWS_S3_PROFILE&#39;] + &quot; &quot; + REMOTE_IN_FILE + &quot; &quot; <br>        + LOCAL_FILE<br>    print(down_command)<br>    os.system(down_command)</pre><pre>    processing(LOCAL_FILE, LOCAL_OUT_FILE)</pre><pre>    up_command = &quot;aws s3 cp &quot; + &quot;--profile &quot; + <br>        envs[&#39;AWS_S3_PROFILE&#39;] + &quot; &quot; + LOCAL_OUT_FILE + &quot; &quot; <br>        + REMOTE_OUT_FILE<br>    print(up_command)<br>    os.system(up_command)</pre><h3>Processing</h3><p>The s3.py script uses a helper library python file that contains the functions that do the processing.</p><p><strong>Let’s assume this format for the input file’s lines: “&lt;text_id&gt;,&lt;text&gt;\n”</strong></p><p>The <strong>lib_process.py</strong> library:</p><pre>import fasttext</pre><pre><br>def is_greek(txt, model):<br>    # Predict only the most dominant language in the text:<br>    pred = model.predict(txt, k=1)<br>    # Fetch the found language<br>    pred_langs = pred[0]<br>    pred_lang = pred_langs[0]<br>    # Compare the predicted language with the greek lang label:        <br>    return False if pred_lang != &#39;__label__el&#39; else True</pre><pre><br>def processing(local_file, out_file):<br>    # Open the file readers:        <br>    fin = open(local_file, mode=&#39;r&#39;)<br>    fout = open(out_file, mode=&#39;a&#39;)</pre><pre>    # Load the language detection model, once:<br>    model = fasttext.load_model(&#39;lid.176.ftz&#39;)</pre><pre>    line_count = 0    <br>    while True: # Loop over all input lines<br>        # Split text by sentence<br>        line = fin.readline()<br>        if not line:<br>            break # File ended<br>        line_count += 1</pre><pre>        # Split line(sentence) into tokens &amp; keep the text<br>        txt = line.strip().split(&quot;,&quot;)[1]<br>    <br>        # Keep Greek sentences<br>        if is_greek(txt, model):<br>            # Store in the output file the found greek sentence:            <br>            fout.write(line + &#39;\n&#39;)</pre><pre>    # Close the files:<br>    fin.close()<br>    fout.close()</pre><h3><strong>That was it! And I hope you liked it!</strong></h3><p>Thanks for reading and please don’t hesitate to leave any comments or share an opinion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c6d6b220639" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/detect-greek-language-in-text-using-docker-store-in-s3-without-boto3-3c6d6b220639">Detect Greek language in text using Docker, &amp; store in S3 without Boto3.</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[Proper Balancing for Cross Validation]]></title>
            <link>https://medium.com/data-science/proper-balancing-for-cross-validation-d95c17ff0ab4?source=rss-ef3648b35d09------2</link>
            <guid isPermaLink="false">https://medium.com/p/d95c17ff0ab4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[crossvalidation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[balancing]]></category>
            <dc:creator><![CDATA[Kanellis Georgios]]></dc:creator>
            <pubDate>Fri, 11 Oct 2019 14:13:40 GMT</pubDate>
            <atom:updated>2019-10-11T15:46:20.436Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*zUIylcXGRo01Lr5pejldVA.jpeg" /></figure><p>Who hasn’t come across the need of applying the cross validation technique, while the dataset in hand is imbalanced, in regards to the number of instances per target class value.</p><p><strong><em>The question here is, do we apply it properly?</em></strong></p><p><strong>The purpose of this article is to show a way to use the balancing methods in cross-validation, without forcing balancing on the CV test folds; thus to get more realistic CV evaluation results.</strong></p><p>One <strong>usually</strong> <strong>splits</strong> his data into train &amp; test (&amp; holdout) subsets,<br>balances the train subset, fits his model on it, and gets results on the imbalanced test &amp; holdout sets.</p><p>Alternatively, we use <strong>cross-validation</strong>, most probably with stratified folds,<br>so that the percentage of samples for each class is preserved per fold.</p><p>However, the pre-built functions like sickit-learn’s cross_validate <br>choose by default not to handle class imbalance.</p><p><strong>In this tutorial, we will play a bit first with some combined applications of data balancing &amp; Cross-Validation (CV). Then we will examine a way of producing evaluation metrics on the CV test folds, by keeping for the test folds, the same class distribution the holdout set (unknown test set) has.</strong></p><p>Let’s examine this train of thought with a simple <strong>python example</strong>.<br>I use here this <a href="https://www.kaggle.com/mlg-ulb/creditcardfraud/data">Credit Card Fraud Detection</a> Kaggle dataset,<br>following the steps below.</p><ul><li>We will keep a <strong>sample</strong> of the whole &amp; work on it.</li><li>Then <strong>split</strong> our data into train &amp; test set data.</li><li>We will treat this test set as the <strong>holdout</strong>/unknown set.</li><li>And will apply cross-validation on the train set only.</li><li>We will try out together under &amp; oversampling, <br>&amp; balancing before &amp; during cross-validation.</li><li>Since the most suitable credit frauds’ metric is <strong>precision</strong>,<br>we will compare the average precision on the CV test folds<br>against the model’s precision on the holdout set.</li></ul><p><strong><em>Heads up: </em></strong><em>The related code lies at the end of the article.</em></p><h4><strong>Section 1: No balancing</strong></h4><p>Here we plot the precision results of having no balancing at all:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*4T3vpTkePsQn76TKiz7mGA.png" /></figure><pre>Average Train Precision among C-V folds: 76.8 %<br>Average Test Precision among C-V folds: 71.98 %<br>Single Test set precision: 75.86 %<br>Single Test set Low Class(No-Fraud) Precision: 99.9 %<br>Single Test set High Class(Fraud) Precision: 75.9 %</pre><ul><li>Precision measurements of the CV folds seem quite unstable.</li><li>Some precision metrics are above their corresponding precision on the train set.</li><li>Big differences appear among the test set precision of the CV folds.</li><li>The average test set precision of the CV is not extremely away from the unknown’s fraud dataset, but still the difference is important.</li><li>Thus we shall examine balancing for our dataset.</li></ul><h4>Section 2: Balancing outside C-V (under-sampling)</h4><p>Here we plot the precision results of balancing, with under-sampling, only the train subset before applying CV on it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*hsyr1sBbo0QGskZtenQUzg.png" /></figure><pre>Average Train Precision among C-V folds: 99.81 %<br>Average Test Precision among C-V folds: 95.24 %<br>Single Test set precision: 3.38 %<br>Single Test set Low Class(No-Fraud) Precision: 100.0 %<br>Single Test set High Class(Fraud) Precision: 3.40 %</pre><ul><li>Like before:<br>- CV results seem mostly high, but unstable.<br>- Some precision metrics are above their corresponding precision on the train set.<br>- Big differences appear among the test set precision of the CV folds.</li><li>Additionally, any positive interpretation of some of the above high numbers is probably wrong,since the ‘unknown’ imbalanced test gives bad precision.</li><li>The above difference sources from the fact that:<br>- each fold’s test set is balanced,<br>- each fold’s model is fitted on balanced train fold data.</li><li>Thus the model goes well in CV, since it is trained &amp; tested on similar class distributions(balanced).</li><li>However an ‘unknown’ fraud dataset will not be balanced, thus we see very low precision on the test set.</li></ul><h4>Section 3: Balancing inside C-V (under-sampling)</h4><p>Here we plot the precision results of balancing, with under-sampling,<br>only the train set of each CV fold before fitting the model on it and<br>making predictions on the CV fold’s test set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*fRIpIn8YGOVrbYvIlUVoGQ.png" /></figure><pre>Average Train Precision among C-V folds: 99.21 %<br>Average Test Precision among C-V folds: 4.2 %<br>Single Test set precision: 3.38 %<br>Single Test set Low Class(No-Fraud) Precision: 100.0 %<br>Single Test set High Class(Fraud) Precision: 3.40 %</pre><ul><li>We see stable precision results among CV folds, but not efficient enough.</li><li>We see the precision on unknown data very close to the average precision of the CV folds.</li><li>What we have done here is, that we made each fold’s model recognize the existence of fraud transactions, and try to predict on a realistic, unbalanced version of unknown test (fold) data.</li><li>Still the precision is very bad, in contrast to the ~ 76% of the unbalanced version.</li><li>Does this mean we give up on balancing?</li><li>A next step could be to examine different balancing ratios.</li><li>But first let’s examine over-sampling instead of under-sampling, because our fraud transactions are too few.</li></ul><h4>Section 4: Balancing outside C-V with over-sampling</h4><p>Here we plot the precision results of balancing, with over-sampling,<br>only the train subset before applying CV on it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*L3qTao_hR6Ame4JDiqCnmg.png" /></figure><pre>Average Train Precision among C-V folds: 98.51 %<br>Average Test Precision among C-V folds: 98.52 %<br>Single Test set precision: 12.61 %<br>Single Test set Low Class(No-Fraud) Precision: 100.0 %<br>Single Test set High Class(Fraud) Precision: 12.6 %</pre><ul><li>Results are more stable than in Section 2, thanks to over-sampling; <br>under-sampling left too few instances.</li><li>Yet again, CV scores do not represent the reality of the unknown test set.</li></ul><h4>Section 5: Balancing inside C-V (over-sampling)</h4><p>Here we plot the precision results of balancing, with over-sampling,<br>only the train set of each CV fold before fitting the model on it and making predictions on the CV fold’s test set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*bZ5nYX9z9WX4wT_xbNNMQw.png" /></figure><pre>Average Train Precision among C-V folds: 98.38 %<br>Average Test Precision among C-V folds: 8.7 %<br>Single Test set precision: 12.61 %<br>Single Test set Low Class(No-Fraud) Precision: 100.0 %<br>Single Test set High Class(Fraud) Precision: 12.6 %</pre><ul><li>Thanks to oversampling precision score rises from that of Section 3.</li><li>Still though, we get in each CV fold prediction score results close enough to those that the model will produce on an unknown test dataset.</li></ul><p><strong>It is clear, that balancing so far did not help in getting good test results.<br>However, this is out of scope for this article ( :-) ) and the goal of this article is achieved:<br>To make the model produce, on each CV fold’s test set, evaluation metric scores similar to those that it would produce on an unknown one,<br>for the case that the train data are balanced.</strong></p><p>Finally, I wouldn’t recommend the adaption of the above in a strict way,<br>but for you to keep from the above a suggestion &amp; some food for thought!</p><p><strong><em>Thanks for reading this!<br>I am interested about any comments or suggestions.</em></strong></p><p><strong>PS:</strong> Below follows the related code, so that you can experiment on the above.</p><p>Importing &amp; splitting of the data:</p><pre>import pandas as pd<br>import numpy as np<br>from sklearn import datasets<br>from sklearn.model_selection import cross_validate<br>from sklearn.metrics import accuracy_score, precision_score<br>from sklearn.linear_model import LogisticRegression<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split,StratifiedKFold<br>from imblearn.over_sampling import SMOTE<br>from imblearn.under_sampling import RandomUnderSampler<br><br>df = pd.read_csv(&#39;creditcard.csv&#39;).sample(50000, random_state=0)<br>train, test = train_test_split(df, test_size=0.3, random_state=0, shuffle=True)<br>y_train = np.array(train[&quot;Class&quot;])<br>y_test = np.array(test[&quot;Class&quot;])<br>del train[&quot;Class&quot;]<br>del test[&quot;Class&quot;]<br>train = train.reset_index(drop=True)<br>test = test.reset_index(drop=True)</pre><p>The number of instances per class at this point is:</p><pre>Train Set Class 0:  34941<br>Train Set Class 1:  59<br><br>Test Set Class 0:  14967<br>Test Set Class 1:  33</pre><p>Now we will need some <strong>helper</strong> functions.</p><p>One to plot the precision scores:</p><pre>def <strong>plotit</strong>(tr,te):<br>    fig, ax = plt.subplots()<br>    r = range(1,11)<br>    ax.scatter(r, tr,label=&#39;cv train scores&#39;)<br>    ax.plot(r, tr, &#39;C3&#39;, lw=1)<br>    ax.scatter(r, te,label=&#39;cv test scores&#39;)<br>    ax.plot(r, te, &#39;C2&#39;, lw=1)<br>    ax.set_xlabel(&#39;CV Folds&#39;)<br>    ax.set_ylabel(&#39;Precision&#39;)<br>    ax.legend()<br>    plt.show()</pre><p>One for the per class value precision:</p><pre>def <strong>class_precisions</strong>(yt,yp):<br>    df = pd.DataFrame(np.transpose([yp,yt]),<br>    columns=(&#39;test_actual&#39;,&#39;test_preds&#39;))<br>    mask1 = (df[&#39;test_actual&#39;]==0)<br>    mask2 = (df[&#39;test_actual&#39;]==df[&#39;test_preds&#39;])<br>    low_CORRECT = df[mask1 &amp; mask2].count()[0]<br>    low_NOFRAUD = df[mask1].count()[0]<br>    print(&quot;Single Test set Low Class(No-Fraud) Precision:&quot;, <br>    np.round(low_CORRECT/low_NOFRAUD,3)*100,&quot;%&quot;)<br>    high_class_df = pd.DataFrame(np.transpose([yp,yt]),<br>    columns=(&#39;test_actual&#39;,&#39;test_preds&#39;))<br>    mask1 = (df[&#39;test_actual&#39;]==1)<br>    mask2 = (df[&#39;test_actual&#39;]==df[&#39;test_preds&#39;])<br>    high_CORRECT = df[mask1 &amp; mask2].count()[0]<br>    high_FRAUD = df[mask1].count()[0]<br>    print(&quot;Single Test set High Class(Fraud) Precision:&quot;, <br>    np.round(high_CORRECT/high_FRAUD,3)*100,&quot;%&quot;)</pre><p>And one that gathers the whole flow:</p><pre>def <strong>compare</strong>(x_train,y,x_test,yt,custom=False,method=&#39;over&#39;):<br>    if custom:<br>        tr,te = custom_balancing_cv(x_train, y,    <br>                cv=10,method=method)<br>    else:<br>        results = cross_validate( LogisticRegression(              <br>                  random_state=0, solver=&#39;liblinear&#39;,   <br>                  max_iter=10000), x_train, y, cv=10,<br>                  return_train_score=True,scoring=[&#39;precision&#39;])<br>        tr = results[&#39;train_precision&#39;]<br>        te = results[&#39;test_precision&#39;]<br>    plotit(tr,te)<br>    clf = LogisticRegression(random_state=0,solver=&#39;liblinear&#39;,                     <br>                             max_iter=10000)<br>    # If we customly balance train set of folds,<br>    # we need to compare with a balanced single prediction<br>    if custom:<br>        if method==&#39;under&#39;:<br>            s = RandomUnderSampler(random_state=0)<br>        else:<br>            s = SMOTE(random_state=0)<br>        x_train, y = s.fit_sample(x_train, y)<br>    clf.fit(x_train,y)<br>    y_pred = clf.predict(x_test)<br>    print(&quot;Average Train Precision among C-V            <br>          folds:&quot;,np.round(np.average(tr)*100,2),&quot;%&quot;)<br>    print(&quot;Average Test Precision among C-V <br>          folds:&quot;,np.round(np.average(te)*100,2),&quot;%&quot;)<br>    print(&quot;Single Test set   precision:&quot;, <br>          np.round(precision_score(yt, y_pred)*100,2),&quot;%&quot;)<br>    class_precisions(yt,y_pred)</pre><p><strong>Section 1</strong>: No balancing</p><pre>compare(train, y_train,test,y_test)</pre><p><strong>Section 2</strong>: Balancing outside C-V (undersampling)</p><pre>rus = RandomUnderSampler(random_state=0)<br>X_res, y_res = rus.fit_sample(train, y_train)<br>compare(X_res, y_res,test,y_test)</pre><p><strong>Section 3</strong>: Balancing inside C-V (undersampling)</p><pre>compare(train, y_train,test,y_test,custom=True, method=&#39;under&#39;)</pre><p><strong>Section 4</strong>: Balancing outside C-V (oversampling)</p><pre>sm = SMOTE(random_state=0)<br>X_res, y_res = sm.fit_sample(train, y_train)<br>compare(X_res, y_res,test,y_test)</pre><p><strong>Section 5</strong>: Balancing inside C-V (oversampling)</p><pre>compare(train, y_train,test,y_test,custom=True, method=&#39;over&#39;)</pre><p><strong>Thanks again for reading this, BB!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d95c17ff0ab4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/proper-balancing-for-cross-validation-d95c17ff0ab4">Proper Balancing for Cross Validation</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[Easier to Ask for Forgiveness than Permission: a short Python Example.]]></title>
            <link>https://medium.com/data-science/easier-to-ask-for-forgiveness-than-permission-a-short-python-example-e115566a3b8c?source=rss-ef3648b35d09------2</link>
            <guid isPermaLink="false">https://medium.com/p/e115566a3b8c</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[development-strategies]]></category>
            <category><![CDATA[python-dictionaries]]></category>
            <dc:creator><![CDATA[Kanellis Georgios]]></dc:creator>
            <pubDate>Wed, 25 Sep 2019 17:37:25 GMT</pubDate>
            <atom:updated>2019-09-25T17:37:25.667Z</atom:updated>
            <content:encoded><![CDATA[<p>A simple concept that can help you avoid parsing repeatedly all given data, when you just need to cross-check them with a small sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z_0GOuNo_ogum0og" /><figcaption>Photo by <a href="https://unsplash.com/@pisitheng?utm_source=medium&amp;utm_medium=referral">Pisit Heng</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine you have kept notes of the movies you have watched, and how many times you watched each one of them.</p><p>And for some strange reason you kept the notes in a python dictionary :-) ,<br>where the keys are the movie titles, and the values the number of times you watched the movies.</p><pre>movies = {<br>...<br>&#39;The Godfather&#39; : 5,<br>&#39;Pulp Fiction&#39; : 2,<br>...<br>}</pre><p>At some point you decide you only want to keep in your dictionary gangster movies, and nothing else.<br>So you have to cross-check your dictionary with a list of gangster movies.</p><p>One way to go would be to fetch the dictionary keys and look at whether they are contained in the given gangster list. <br>This results to <strong>O(k*n)</strong> actions in total, if we have <strong>k values</strong> in the gangster list, and <strong>n values</strong> in the movies dictionary.</p><pre>gangster_list = [..] # k values</pre><pre>for key in movies.keys(): # n values<br>    if movies[key] in gangster_list:<br>        continue<br>    else:<br>        del movies[key]</pre><pre># O(k*n) actions in total</pre><p>But what if the gangster movies list contains 1 million movies, where the gangster ones you have watched are near the end of the big gangster list?</p><p>Lets assume you have watched 10 gangster movies.<br>The ‘in’ check above would result into parsing almost the whole gangster list for each movie you have watched, resulting in:<br>O([1m values in list] * [10 gangster movies watched]) = O(10m) actions.</p><p>Instead, it is <strong>Easier to Ask for Forgiveness than Permission!</strong></p><p>We can take the cost of O(k) actions to produce a dummy dictionary out of the big gangster list:</p><pre>gangster_dic = {}<br>for movie in gangster_list:<br>    gangster_dic[movie] = None</pre><p>and the content of the gangster dictionary will be:</p><pre>{ # k keys without values<br>...<br>&#39;Goodfellas&#39; : None,<br>&#39;The Untouchables&#39; : None,<br>...<br>}<br>del gangster_list # To balance used memory</pre><p>Now we can go directly into searching each watched movie name:</p><pre>for key in movies.keys(): # n values<br>    # O(1) action<br>    try:<br>        gangster_dic[key]<br>        # do nothing: this is a gangster movie<br>    except KeyError:<br>        del movies[key]<br>        # delete the movie, since we did not find it in the   <br>        # gangster movies dictionary</pre><p>It is no big deal if we fail; We handle the exception.</p><p><strong>This is actually what we want:</strong> for the exception to happen and delete a movie that we watched, that is not a gangster one.</p><p>In total, the cost of actions is : <br>• O(k) for the dictionary, plus<br>• O(n * 1) for checking the existence, of the watched movies, in the gangster movies collection,<br>• Resulting in a total of <strong>O(k+m) </strong>actions.</p><p>If we assume again, that k=1m and n=10, then we get a total of (1m+10) = O(1m) actions.</p><p><strong>We lowered the actions needed down to 1 million, from the starting 10 millions! Or in general #n times less actions were needed!</strong></p><p><strong>`Easier to Ask for Forgiveness than Permission` </strong>concept has come in handy for me many times. I hope that you will find it useful, too!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e115566a3b8c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/easier-to-ask-for-forgiveness-than-permission-a-short-python-example-e115566a3b8c">Easier to Ask for Forgiveness than Permission: a short Python Example.</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>