<?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 Andrew Engel on Medium]]></title>
        <description><![CDATA[Stories by Andrew Engel on Medium]]></description>
        <link>https://medium.com/@engelanalytics?source=rss-610988231d93------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XSMHpHfajQxWDOOZuHSebg.jpeg</url>
            <title>Stories by Andrew Engel on Medium</title>
            <link>https://medium.com/@engelanalytics?source=rss-610988231d93------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:17:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@engelanalytics/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[Feature Engineering for Time Series Data]]></title>
            <link>https://medium.com/data-science/feature-engineering-for-time-series-data-f0cb1c1265d3?source=rss-610988231d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0cb1c1265d3</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-preparation]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Andrew Engel]]></dc:creator>
            <pubDate>Tue, 29 Mar 2022 17:42:46 GMT</pubDate>
            <atom:updated>2022-03-29T17:42:46.085Z</atom:updated>
            <content:encoded><![CDATA[<h4>Time series aggregations on the modern data stack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*poHa_4Zaq_gkKJNv" /><figcaption>Photo by <a href="https://unsplash.com/@donaldwuid?utm_source=medium&amp;utm_medium=referral">Donald Wu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In many business data science problems, data with a time series character (e.g., transactions, sensor readings, etc.) must be aggregated to an individual (e.g., customer, piece of equipment, etc.) level. Doing this in a modern machine learning environment can lead to trouble as traditional train-test and cross-validation splits will fail. This is because randomly splitting observations between training and test sets will almost always split related (and hence correlated) observations between the two sets. More problematically, observations will be split so that some training observations can be taken after the test observations. In other words, the model will be learning to predict the past from the future. This often leads to models failing when placed into production.</p><p>There are numerous ways to deal with this issue, and I discussed my preferred method <a href="https://www.rasgoml.com/post/selecting-the-right-data-for-your-ml-model">here</a>. A commonly used method is to take a single observation from each individual. This can be done either by randomly selecting one observation for each individual or picking a date and using only the observations from this date.</p><p>We will focus on creating a single record for each observation on a given date. In this example, we will use weather data and aggregate it to show the average high temperature at the county level over multiple periods of time. This can be challenging to do in pandas, but we will show how easily it can be done on the modern data stack with Rasgo.</p><h4>Single moment aggregations in pandas</h4><p>Given a dataframe df that contains a county code <em>FIPS</em>, a date <em>DATE</em>, and the high temperature in a county on a date <em>HIGH_TEMP</em>, rolling and groupby can be used to create rolling averages for all days. In this case, rolling averages over one, two, and four weeks will be created.</p><p>First, the rolling window should be created</p><pre>df[&#39;HIGH_TEMP_AVG_7D&#39;] = df.sort_values(<br>                              by=[&#39;FIPS&#39;, <br>                                 &#39;DATE&#39;]).set_index(<br>                                 &#39;DATE&#39;).groupby(<br>                                 &#39;FIPS&#39;)[<br>                                 &quot;HIGH_TEMP&quot;].rolling(&#39;7D&#39;,             <br>                                 closed=&#39;both&#39;).mean()<br>df[&#39;HIGH_TEMP_AVG_14D&#39;] = df.sort_values(<br>                              by=[&#39;FIPS&#39;, <br>                                 &#39;DATE&#39;]).set_index(<br>                                 &#39;DATE&#39;).groupby(<br>                                 &#39;FIPS&#39;)[<br>                                 &quot;HIGH_TEMP&quot;].rolling(&#39;14D&#39;,             <br>                                 closed=&#39;both&#39;).mean()<br>df[&#39;HIGH_TEMP_AVG_28D&#39;] = df.sort_values(<br>                              by=[&#39;FIPS&#39;, <br>                                 &#39;DATE&#39;]).set_index(<br>                                 &#39;DATE&#39;).groupby(<br>                                 &#39;FIPS&#39;)[<br>                                 &quot;HIGH_TEMP&quot;].rolling(&#39;28D&#39;,             <br>                                 closed=&#39;both&#39;).mean()</pre><p>The index can be reset to return the county code and date to being simple columns in the dataframe.</p><pre>df.reset_index(inplace=True)</pre><p>This approach has several issues. First, if the data is large, it can be quite time-consuming to download it to the workstation and process it. While this could be sped up by only downloading the data needed for the dates in question, additional computations would still be performed for all dates in the data. More importantly, only the aggregation to the current date is required for a production workflow and should be generated.</p><h4>RasgoQL and the modern data stack approach</h4><p>On the modern data stack, the open-source package RasgoQL resolves both of these problems in several ways. First, the processing is kept in the cloud data warehouse, so no data is moved to a workstation. Second, the RasgoQL transform timeseries_agg leverages the power of the data warehouse to work with much larger amounts of data than would be possible on a workstation.</p><p>To start, get a reference to the table in the data warehouse that holds the weather data.</p><pre>dataset = rql.dataset(&#39;WEATHER_TABLE_NAME&#39;)</pre><p>The rolling averages for every day can be generated with a call to the transform.</p><pre>tsagg = dataset.timeseries_agg(aggregations={<br>                                &#39;DAILY_HIGH_TEMP&#39;: [&#39;AVG&#39;]<br>                               },<br>                               group_by=[&#39;FIPS&#39;],<br>                               date=&#39;DATE&#39;<br>                               offsets=[7, 14, 28],<br>                               date_part=&#39;day&#39;)</pre><p>This data can be downloaded by calling to_df on tsagg to get a pandas dataframe for additional processing.</p><pre>tsagg_df = tsagg.to_df()</pre><p>Alternatively, this data can be published back to the cloud data warehouse to create a view that can be used by others both within RasgoQL and straight from the data warehouse through SQL.</p><pre>tsagg.save(table_name=&quot;ROLLING_WEATHER_SNAPSHOT&quot;)</pre><p>Using transformations from the open-source Python package RasgoQL on the modern data stack makes creating these sorts of rolling windows much simpler than they are to create within pandas. The package creates a SQL call that is executed in the database and the results can be saved back to the database to allow easy future reference within the existing project or in other projects that need the same data. By using SQL, the volume of data that is processed can be much higher. Finally, with pandas, using the aggregate function can allow multiple aggregations on multiple columns simultaneously. Except that only one time window (e.g. seven or fourteen days) can be considered in each step. This means to create a seven, a fourteen, and a twenty-eight day average, three different Python statements are needed. In RasgoQL, a single SQL call can generate all three simultaneously.</p><p>If you want to check out RasgoQL, the documentation can be found <a href="https://docs.rasgoql.com/">here</a> and the repository <a href="https://github.com/rasgointelligence/RasgoQL">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0cb1c1265d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/feature-engineering-for-time-series-data-f0cb1c1265d3">Feature Engineering for Time Series Data</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[Normalizing Features Within Groups]]></title>
            <link>https://medium.com/data-science/normalizing-features-within-groups-9873071f7e60?source=rss-610988231d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/9873071f7e60</guid>
            <category><![CDATA[data-preparation]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Andrew Engel]]></dc:creator>
            <pubDate>Tue, 22 Mar 2022 15:25:03 GMT</pubDate>
            <atom:updated>2022-03-22T15:25:03.253Z</atom:updated>
            <content:encoded><![CDATA[<h4>An alternative approach to standardization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l3hqB8JpUEDDZ2ms" /><figcaption>Photo by <a href="https://unsplash.com/@mroz?utm_source=medium&amp;utm_medium=referral">Filip Mroz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the most common feature engineering techniques for numerical features is to standardize those features. This is often accomplished either by subtracting the mean and dividing by the standard deviation or by subtracting the minimum and dividing by the difference between the maximum and the minimum. Either of these approaches can help both in the training of the model and the evaluation of the impact of the various features on the model. Further, these are trivial to perform either with scikit-learn or directly in pandas. These don’t contain new information, however.</p><h4>Normalize within groups</h4><p>There is a similar technique that can add information to the feature and help improve the performance of the model. Instead of using the global statistics (mean, standard deviation, minimum, maximum, etc.), use a statistic within a smaller group. For example, imagine building models around a customer’s credit card transactions. These could be fraud, credit risk, or churn models. Think about the amount on a single transaction. This could be normalized based on the global statistics across all transactions; however, there may be more interesting ways to standardize these amounts.</p><p>Consider normalizing this transaction across just the customer’s spending. Is this spent near the mean or three standard deviations from the mean? What does a transaction three standard deviations from the mean imply to fraud or churn risk? Further, consider normalizing the transaction across all transactions at that merchant, in that postal code, or in that merchant category. A transaction with three standard deviations from the customer’s usual patterns but near the mean at a jeweler seems very different from the same three standard deviation transaction that is also very far from the mean at a grocery store.</p><h4>Grouped statistics in pandas</h4><p>There are several ways to calculate these in-group statistics within pandas. One of the easiest ways is to use the pandas function pivot_table. For this example, using weather data, consider determining how unusual the high temperature is in a given region for a given weather pattern. In addition to location (<em>FIPS </em>the Federal Information Processing Standards county code), Our weather data reports the weather icon (is it cloudy, partly cloudy, sunny, etc.). To understand if the temperature is unusually high for a cloudy day, we need to know the mean and standard deviation of the temperature for cloudy days in that region. This can be done by pivoting on the weather icon (<em>column</em>), aggregating the high temperature (<em>value</em>) for each location (<em>index</em>).</p><pre>pd.pivot_table(weather_df, <br>               values=&#39;DAILY_HIGH_TEMP&#39;, <br>               index=[&#39;FIPS&#39;],<br>               columns=[&#39;WEATHER_ICON&#39;],<br>               aggfunc=[np.mean, np.std)</pre><p>The output of this call can be joined to the original dataset on <em>FIPS </em>and the appropriate mean and standard deviation used to calculate the normalized temperature.</p><h4>Pivots in the cloud data warehouse</h4><p>If the data sits in a data warehouse, this pivot and aggregation can also be performed in SQL without moving the data to your pandas environment. However, the SQL syntax for the pivot is tedious and requires identifying each value in the column that needs to be pulled out. With the open-source package <a href="https://github.com/rasgointelligence/RasgoQL">RasgoQL</a> <a href="https://docs.rasgoql.com/primitives/transform">transformations</a>, the <a href="https://docs.rasgoql.com/transforms/table-transforms/pivot">pivot transformation</a> does all of this for you.</p><p>Working with the daily weather data, this data can be used by calling rql.dataset</p><pre>dataset = rql.dataset(&#39;DAILY_WEATHER&#39;)</pre><p>The pivot transformation can be called to create the average high temperature by FIPS and WEATHER_ICON by calling pivot. In this case, the pandas index, columns, and values correspond to the RasgoQL pivot&#39;s dimensions, value_column and pivot_column respectively.</p><pre>t1 = dataset.pivot(dimensions=[&#39;FIPS&#39;],<br>                   pivot_column=&#39;DAILY_HIGH_TEMP&#39;,<br>                   value_column=&#39;WEATHER_ICON&#39;,<br>                   agg_method=&#39;AVG&#39;)</pre><p>The SQL can be checked by examining t1.sql() and a sample of the data can be examined by calling t1.preview(). Once the pivot looks correct, it can be saved to the data warehouse by calling save</p><pre>t1.save(table_name=&quot;WEATHER_AVG_HIGH_BY_FIPS&quot;)</pre><p>Similarly, the standard deviation can be calculated by running another transform and changing the <em>agg_method </em>from <strong>AVG </strong>to <strong>STDDEV</strong>.</p><pre>t2 = dataset.pivot(dimensions=[&#39;FIPS&#39;],<br>                   pivot_column=&#39;DAILY_HIGH_TEMP&#39;,<br>                   value_column=&#39;WEATHER_ICON&#39;,<br>                   agg_method=&#39;STDDEV&#39;)<br>t2.save(table_name=&quot;WEATHER_STD_HIGH_BY_FIPS&quot;)</pre><p>These can be joined together using the join transformation discussed <a href="https://docs.rasgoql.com/transforms/table-transforms/join">here</a>.</p><p>By performing these transformations in the data warehouse, the time spent moving data between the database and the server where feature engineering occurs is avoided. In addition, by processing the data in the data warehouse, all of the data can be used without the limitations imposed by the amount of memory on the server. Finally, by saving these transformations back to the database as views or tables, they are immediately available in production workflows without the need for the data engineering team to refactor them.</p><p>If you want to check out RasgoQL, the documentation can be found <a href="https://docs.rasgoql.com/">here</a> and the repository <a href="https://github.com/rasgointelligence/RasgoQL">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9873071f7e60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/normalizing-features-within-groups-9873071f7e60">Normalizing Features Within Groups</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[From Numerical to Categorical]]></title>
            <link>https://medium.com/data-science/from-numerical-to-categorical-3252cf805ea2?source=rss-610988231d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/3252cf805ea2</guid>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[data-preparation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Andrew Engel]]></dc:creator>
            <pubDate>Fri, 18 Mar 2022 13:30:39 GMT</pubDate>
            <atom:updated>2022-03-18T13:30:39.173Z</atom:updated>
            <content:encoded><![CDATA[<h4>Three ways to bin numeric features</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NMOXbLPyJABuQFX9" /><figcaption>Photo by <a href="https://unsplash.com/@frankiefoto?utm_source=medium&amp;utm_medium=referral">frank mckenna</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Binning numerical features into groups based on intervals the original value falls into can improve model performance. This can occur for several reasons. First, these bins can be defined based on domain knowledge to help the model better identify the patterns it is looking for. Second, data always has measurement errors, and binning can reduce the impact of these errors.</p><p>There are three common approaches outside of domain knowledge-based binning: equal widths, equal frequency, and a k-means approach. (The k-means approach is outside the scope of this article.) Equal widths takes the range of the numerical variable and divides it into equal-sized intervals. This means the size of the group is identical, but the count of observations in each bin can vary widely. An example of this is to divide the age of individuals into five or ten-year buckets. Equal frequency bins the feature to create roughly equal counts in each bin. In the age case, if most of the individuals are in their twenties and thirties, binning by ten or even five years can create bins that lack usefulness. Binning by frequency, these common ages will be better separated and more beneficial to the model.</p><h4>Binning in pandas</h4><p>Using weather data extracted from the database using the open-source package <a href="https://github.com/rasgointelligence/RasgoQL">RasgoQL</a>,</p><pre>dataset = rql.dataset(&#39;Table Name&#39;)<br>df = dataset.to_df()</pre><p>equal width bins can easily be created using the cut function from pandas. In this case, 4 even sized bins are created.</p><pre>df[&#39;HIGH_TEMP_EQ_BINS&#39;] = pd.cut(df.DAILY_HIGH_TEMP, bins=4,<br>                                 labels=False, include_lowest=True)</pre><p>Similarly, qcut can be used to create bins with approximately equal counts in each.</p><pre>df[&#39;HIGH_TEMP_FQ_BINS&#39;] = pd.qcut(df.DAILY_HIGH_TEMP, q=4, <br>                                  precision=1, labels=False)</pre><h4>Binning with scikit-learn</h4><p>These same bins can also be created using scikit-learn’s preprocessing function KBinsDiscretizer. To create equal with bins, we set the strategy to ‘uniform’.</p><pre>est = KBinsDiscretizer(n_bins=4, encode=&#39;ordinal&#39;, <br>                       strategy=&#39;uniform&#39;)<br>df[&#39;HIGH_TEMP_SK_EQ_BINS&#39;] = est.fit_transform(<br>                                         df[[&#39;DAILY_HIGH_TEMP&#39;]])</pre><p>Similarly, setting strategy to ‘quantile’ will create approximately equal frequency bins</p><pre>est = KBinsDiscretizer(n_bins=4, encode=&#39;ordinal&#39;, <br>                       strategy=&#39;quantile&#39;)<br>df[&#39;HIGH_TEMP_SK_FQ_BINS&#39;] = est.fit_transform(<br>                                         df[[&#39;DAILY_HIGH_TEMP&#39;]])</pre><p>In either case, to take models to production, these transformations will need to be rewritten for the production environment. In the case of the pandas versions, the cutoffs will need to be extracted from cut or qcut and hard coded into the production code. In the case of scikit-learn, either the cutoffs will need to be removed, and the entire transformation rewritten to use those cutoffs, or the preprocessing objects will need to be saved and reloaded into the production environment.</p><p>Beyond issues refactoring modeling code to production code, when working with vast amounts of data, this approach can be slow at best and nearly impossible at worst. With massive amounts of data, substantial amounts of time are wasted simply waiting for the data to transfer to the modeling environment. If the data is large enough, it may not fit into memory for pandas and not all of the data may be available for these transformations.</p><h4>Binning in the modern data stack</h4><p>By leveraging the open-source Python package <a href="https://github.com/rasgointelligence/RasgoQL">RasgoQL</a>, both of these issues can be avoided. First, because RasgoQL creates the bins directly in the database, it will work with any size data. Second, in creating these bins and examining them within Python, the underlying SQL code is saved in the database. This means that as new data arrives in the database, it will automatically be available with the bins applied.</p><p>To create the equal width bins, the RasgoQL function bin can be called with a type of ‘equalwidth’.</p><pre>eq_bin = dataset.bin(type=&#39;equalwidth&#39;,<br>                     bin_count=4,<br>                     column=&#39;DAILY_HIGH_TEMP&#39;)<br>eq_bin.save(table_name=&quot;HIGH_TEMP_EWB&quot;)</pre><p>Alternatively, setting type to ‘ntile’ will create equal count bins.</p><pre>fq_bin = dataset.bin(type=&#39;ntile&#39;,<br>                     bin_count=4,<br>                     column=&#39;DAILY_HIGH_TEMP&#39;)<br>fq_bin.save(table_name=&quot;HIGH_TEMP_NTB&quot;)</pre><p>At this point, these datasets are published back to the database and available for use in both a modeling and production environment.</p><p>While binning the data directly in pandas or using scikit-learn’s binning functions is easy to implement in traditional Python machine learning workflows, when working with big data stored in a database converting to a SQL approach has advantages in speed and ease of promotion to production. SQL based feature engineering allows for faster processing, an easier path to production, and reuse of the features across multiple projects. However, most data scientists are more comfortable in Python (or R) than SQL, and, for many calculations, the SQL is complicated. The open-source package RasgoQL allows data scientists to continue working in Python but execute the calculations in the database.</p><p>If you want to check out RasgoQL, the documentation can be found <a href="https://docs.rasgoql.com/">here</a> and the repository <a href="https://github.com/rasgointelligence/RasgoQL">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3252cf805ea2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/from-numerical-to-categorical-3252cf805ea2">From Numerical to Categorical</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[Categorical Variables for Machine Learning Algorithms]]></title>
            <link>https://medium.com/data-science/categorical-variables-for-machine-learning-algorithms-d2768d587ab6?source=rss-610988231d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2768d587ab6</guid>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-preparation]]></category>
            <dc:creator><![CDATA[Andrew Engel]]></dc:creator>
            <pubDate>Wed, 16 Mar 2022 18:06:19 GMT</pubDate>
            <atom:updated>2022-03-16T18:06:19.382Z</atom:updated>
            <content:encoded><![CDATA[<h4>One-hot encoding in Python and on the data warehouse</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jOXXRAQGuEe4U8as" /><figcaption>Photo by <a href="https://unsplash.com/@burst?utm_source=medium&amp;utm_medium=referral">Burst</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>While most machine learning algorithms only work with numeric values, many important real-world features are not numeric but rather categorical. As categorical features, they take on levels or values. These can be represented as various categories such as age, state, or customer type for example. Alternatively, these can be created by binning underlying numeric features, such as identifying individuals by age ranges (e.g., 0–10, 11–18, 19–30, 30–50, etc.). Finally, these can be numeric identifiers where the relationship between the values is not meaningful. ZIP codes are a common example of this. Two ZIP codes close numerically may be farther apart than another ZIP code that is distant numerically.</p><p>Since these categorical features cannot be directly used in most machine learning algorithms, the categorical features need to be transformed into numerical features. While numerous techniques exist to transform these features, the most common technique is one-hot encoding.</p><p>In one-hot encoding, a categorical variable is converted into a set of binary indicators (one per category in the entire dataset). So in a category that contains the levels clear, partly cloudy, rain, wind, snow, cloudy, fog, seven new variables will be created that contain either <em>1</em> or <em>0</em>. Then, for each observation, the variable that matches the category will be set to <em>1 </em>and all other variables set to <em>0.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/791c6d174a7d011c988337db4657fd69/href">https://medium.com/media/791c6d174a7d011c988337db4657fd69/href</a></iframe><h4>Encoding with scikit-learn</h4><p>One-hot encoding is easy to perform with the scikit-learn preprocessing library. In this code, we will one-hot encode the column stored in the variable <em>column</em> from the dataframe <em>df.</em></p><pre>from sklearn.preprocessing import OneHotEncoder<br>encoder = OneHotEncoder()<br>onehotarray = encoder.fit_transform(df[[column]]).toarray()<br>items = [f&#39;{column}_{item}&#39; for item in encoder.categories_[0]]<br>df[items] = onehotarray</pre><p>This adds the columns created by the one-hot encoder back into the original dataframe and names each of the added column by the original column name along with the category level.</p><h4>One-hot encoding in the database</h4><p>Suppose the data already exists in a data warehouse. Instead of extracting the data to pandas on your system and converting it to push the data back to the warehouse, the open-source Python package RasgoQL can perform this encoding directly on the warehouse without needing to move the data at all. This approach saves the time and expense of moving the data, can work with datasets too large to fit into memory on a single machine, and automatically generates the encoded variables as new data arrives in the warehouse. This means the encoding works not just for existing data and modeling pipelines but is automatically available for production pipelines.</p><p>To perform the one-hot encoding using RasgoQL, the following code can be used.</p><pre>onehotset = dataset.one_hot_encode(column=column)</pre><p>Again, the column to be encoded is stored in the Python variable <em>column.</em></p><p>This data can be downloaded to the python environment as a sample of ten rows in a dataframe by running preview:</p><pre>onehot_df = onehotset.preview()</pre><p>Or the full data can be downloaded as:</p><pre>onehot_df = onehotset.to_df()</pre><p>To make this data available to everyone as a view on the data warehouse, it can be published using save:</p><pre>onehotset.save(table_name=&#39;&lt;One hot Tablename&gt;&#39;,<br>               table_type=&#39;view&#39;)</pre><p>Alternatively, to save this as a table, change <strong>table_type</strong> from <strong>‘view’</strong> to <strong>‘table’</strong>. If you’d like to check the SQL RasgoQL uses to create this table or view, run sql:</p><pre>print(onehotset.sql())</pre><p>Finally, if you use dbt in production and would like to export this work as a dbt model for use by your data engineering team, call to_dbt:</p><pre>onehotset.to_dbt(project_directory=&#39;&lt;path to dbt project&gt;&#39;</pre><p>One-hot encoding is one of the most common feature engineering techniques that is applied in many machine learning pipelines. It is easy to apply using scikit-learn, but, unless the production system is running Python, it will require rewriting to migrate the step to the production system. In the modern data stack, this migration often involves rewriting the code into SQL.</p><p>In order to perform one-hot encoding in SQL, one most first identify all of the levels in the categorical variable and then generate case statements to populate binary indicator variables for each level. This can be very tedious. Using RasgoQL, the SQL code is generated automatically and saved into the data warehouse. This means that while still working in Python and pandas, the data scientist has already generated code that can be used directly in production.</p><p>The process of converting the code developed during the modeling process to production ready code can be among the most time consuming steps of the entire data science lifecycle. Using a tool that makes it easy to transfer the modeling code into production can be a huge time saver. In addition, by moving the data preparation tasks to the data warehouse, the data scientists is allowed to work with the full data stored in the data warehouse and is no longer limited by both the time it takes to transfer the data to their computational environment, nor by the size limitation imposed by the environments memory.</p><p>If you want to check out RasgoQL, the documentation can be found <a href="https://docs.rasgoql.com/">here</a> and the repository <a href="https://github.com/rasgointelligence/RasgoQL">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2768d587ab6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/categorical-variables-for-machine-learning-algorithms-d2768d587ab6">Categorical Variables for Machine Learning Algorithms</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[Three Techniques for Scaling Features for Machine Learning]]></title>
            <link>https://medium.com/data-science/three-techniques-for-scaling-features-for-machine-learning-a7bc063ecd69?source=rss-610988231d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7bc063ecd69</guid>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[feature-scaling]]></category>
            <dc:creator><![CDATA[Andrew Engel]]></dc:creator>
            <pubDate>Thu, 10 Mar 2022 19:15:40 GMT</pubDate>
            <atom:updated>2022-03-10T19:15:40.624Z</atom:updated>
            <content:encoded><![CDATA[<h4>Scaling features on the modern data stack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ugnq6J0fRsbHz9nt" /><figcaption>Photo by <a href="https://unsplash.com/@julensan09?utm_source=medium&amp;utm_medium=referral">Julentto Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>While the scaling of numeric features does not always need to be done as explained by <a href="https://medium.com/@praveenmec67">Praveen Thenraj</a> in his <a href="https://towardsdatascience.com/do-decision-trees-need-feature-scaling-97809eaa60c6">post on Towards Data Science</a> for tree-based machine learning techniques, it does benefit linear and logistic regressions, support vector machines and neural networks. Many data scientists have created modeling scripts that automate the building and testing of many different types of modeling algorithms. These scripts allow the data scientist to select the best performing model for that data. Scaling of features is commonly performed in these scripts.</p><p>There are two primary scaling techniques used. The first is standard scaling (or z-scaling) and is calculated by subtracting the mean and dividing by the standard deviation. The second is min-max scaling and is calculated by subtracting by the minimum value and dividing by the difference between the maximum and minimum values.</p><h4>Scikit-learn based scaling</h4><p>The standard scaler can be applied to scale a list of columns scale_columns by importing StandardScaler from the preprocessing module and applying it to the dataframe as</p><pre>from sklearn.preprocessing import StandardScaler<br>scaler = StandardScaler()<br>df[scale_columns] = scaler.fit_transform(df[scale_columns])</pre><p>Similarly, the min-max scaler can be applied to the same list of columns as</p><pre>from sklearn.preprocessing import MinMaxScaler<br>scaler = MinMaxScaler()<br>df[scale_columns] = scaler.fit_transform(df[scale_columns])</pre><h4>Pandas only based scaling</h4><p>As the scikit-learn module is rather large, if it is only going to be used to scale the feature, it can be easier to do the scaling using pandas. To scale each feature by the mean and standard deviation, call</p><pre>df[scale_columns] = (df[scale_columns] - df[scale_columns].mean()) /<br>                     df[scale_columns].std()</pre><p>Note that this does not duplicate the results from StandardScaler. This is because scikit-learn uses numpy’s std function. By default, this function uses 0 degrees of freedom. On the other hand, pandas’ std is the unbiased estimator by default. To get the same value, run</p><pre>df[scale_columns] = (df[scale_columns] - df[scale_columns].mean()) /<br>                     df[scale_columns].std(ddof=1)</pre><p>Similarly, to get the min-max scaler, run</p><pre>df[scale_columns] = (df[scale_columns] - df[scale_columns].min()) /<br>                 (df[scale_columns].max() - df[scale_columns].min())</pre><h4>RasgoQL scaling in the data warehouse</h4><p>Instead of extracting the data from the data warehouse, the open-source Python package <a href="https://github.com/rasgointelligence/RasgoQL">RasgoQL</a> can create the scaled variables directly in the warehouse. First, this will save time extracting the data and pushing it back to the warehouse after scaling. Second, by leveraging the power of the warehouse, much larger dataset sizes can be transformed at once.</p><p>The standard scaler can be applied as</p><pre>scaledset = dataset.standard_scaler(<br>                       columns_to_scale=[&#39;DS_DAILY_HIGH_TEMP&#39;, <br>                                         &#39;DS_DAILY_LOW_TEMP&#39;,<br>                                         &#39;DS_DAILY_TEMP_VARIATION&#39;,<br>                                         &#39;DS_DAILY_TOTAL_RAINFALL&#39;])</pre><pre>scaledset.save(table_name=&#39;DS_STANDARD_SCALED&#39;)</pre><p>Similarly, the min-max scaler can be applied as</p><pre>scaledset = dataset.min_max_scaler(<br>                       columns_to_scale=[&#39;DS_DAILY_HIGH_TEMP&#39;, <br>                                         &#39;DS_DAILY_LOW_TEMP&#39;,<br>                                         &#39;DS_DAILY_TEMP_VARIATION&#39;,<br>                                         &#39;DS_DAILY_TOTAL_RAINFALL&#39;])</pre><pre>scaledset.save(table_name=&#39;DS_MIN_MAX_SCALED&#39;)</pre><p>These scaled features are now available for use either by joining to the original data or with any other data. They can also be used in modeling pipelines, data visualizations, and predictions in production pipelines. This scaled data can be downloaded into pandas for use in modeling by calling to_df</p><pre>df = scaledset.to_df()</pre><p>If you’d like to check the SQL RasgoQL uses to create this table or view, run sql:</p><pre>print(scaledset.sql())</pre><p>Finally, if you use dbt in production and would like to export this work as a dbt model for use by your data engineering team, call to_dbt:</p><pre>scaledset.to_dbt(project_directory=&#39;&lt;path to dbt project&gt;&#39;</pre><p>When working with small amounts of data on a single machine, the scikit-learn and pandas approaches will work well for scaling features before modeling. However, if the data is large or already stored in a database, performing the scaling in the database (using RasgoQL or SQL) can save significant time during data preparation. More importantly, the code used to scale the data can easily be put into a production workflow potentially saving weeks of effort moving models into production.</p><p>If you want to check out RasgoQL, the documentation can be found <a href="https://docs.rasgoql.com/">here</a> and the repository <a href="https://github.com/rasgointelligence/RasgoQL">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7bc063ecd69" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/three-techniques-for-scaling-features-for-machine-learning-a7bc063ecd69">Three Techniques for Scaling Features for Machine Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Weekly aggregation of time series data]]></title>
            <link>https://medium.com/data-science/weekly-aggregation-of-time-series-data-f9bdcc495a58?source=rss-610988231d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9bdcc495a58</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[data-preparation]]></category>
            <dc:creator><![CDATA[Andrew Engel]]></dc:creator>
            <pubDate>Tue, 08 Mar 2022 14:27:45 GMT</pubDate>
            <atom:updated>2022-03-08T14:27:45.941Z</atom:updated>
            <content:encoded><![CDATA[<h3>Weekly Aggregation of time series data</h3><h4>Aggregation in the Modern Data Stack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zcDm7_94UGRfCYBt" /><figcaption>Photo by <a href="https://unsplash.com/@jamesamolnar?utm_source=medium&amp;utm_medium=referral">James A. Molnar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the most common feature engineering tasks is to aggregate multiple records into a single record. This could be customer transactions aggregated into a single record per customer. These sorts of aggregations often have a time-series like aspect. For example, instead of aggregating all customer transactions, often only the transactions prior to a certain date or transaction need to be aggregated. Alternatively, only transactions within a certain period of time before a given transaction need to be combined. Other aggregations occur across dimensions other than time. These could be aggregating biometrics for all patients with a certain disease, transaction details for all fraudulent transactions, etc.</p><p>In this article, we will focus on aggregating data over time with both Python and on the modern data stack with the open-source package <a href="https://github.com/rasgointelligence/RasgoQL">RasgoQL</a>. In particular, we will create weekly aggregations of the underlying data.</p><h4>Aggregation in pandas</h4><p>In pandas, aggregation can be performed by calling aggregate (or agg as an alias. The arguments to agg can be a function (max), string containing the function name (‘max’), a list of functions or function names ([max, ‘mean’]), or a dictionary of labels (usually column names) and functions, functions names, or lists:</p><pre>df.agg({&#39;column_A&#39;: max,<br>        &#39;column_B&#39;: np.sum,<br>        &#39;column_C&#39;: [max, &#39;mean&#39;, np.sum]})</pre><p>Aggregations are not usually directly applied to dataframes, rather they are applied to groups. Most often, these groups are created by a call to groupby</p><pre>group = df.groupby(by=[&#39;column_A&#39;])</pre><p>followed by a call to agg.</p><h4>Aggregation over time windows</h4><p>In this case, to aggregate over a time window, the function resample is used instead of groupby. In order to use resample, the index of the dataframe needs to be a date or time. Use set_index to set the index to be the <em>DATE</em>.</p><pre>df.set_index(&#39;DATE&#39;, inplace=True)</pre><p>Then create the weekly group</p><pre>weekly_group = df.resample(&#39;7D&#39;)</pre><p>Finally, call agg to aggregate the features to a weekly level</p><pre>weekly_df = weekly_group.agg({&#39;COLUMN_A&#39;: [&#39;min&#39;, &#39;max&#39;],<br>                              &#39;COLUMN_B&#39;: [&#39;mean&#39;, &#39;sum&#39;]})</pre><p>This approach works well on a single machine with data that fits within memory. However, this often needs to be rewritten to work in a production environment or to create a shared version that the rest of the company can leverage.</p><h4>Aggregation with RasgoQL</h4><p>Leveraging RasgoQL will allow the data scientist to create the same weekly aggregation from their notebook or computer but will leverage the power of the modern data stack to create these features on the cloud data warehouse directly. Unlike pandas, instead of resampling to the weekly level, we need to create the feature we want to group by. In this case, the <em>DATE</em> needs to be converted to a weekly variable. This can be done by the datetrunc transform to truncate the date to the week.</p><pre>dataset.datetrunc(dates={&#39;DATE&#39;: &#39;week&#39;})</pre><p>This creates a new variable <em>DATE_WEEK</em>. To make this clearer, use the rename transform to rename this new variable to <em>WEEK</em>.</p><pre>dataset.datetrunc(dates={&#39;DATE&#39;: &#39;week&#39;}).rename(<br>                  renames={&#39;DATE_WEEK&#39;: &#39;WEEK})</pre><p>Now, applying the aggregate transform with the same dictionary as used in the pandas agg function will aggregate the data to the weekly level just like was done with pandas.</p><pre>dataset.datetrunc(dates={&#39;DATE&#39;: &#39;week&#39;}).rename(<br>                  renames={&#39;DATE_WEEK&#39;: &#39;WEEK}).aggregate(<br>                  aggregations={&#39;COLUMN_A&#39;: [&#39;min&#39;, &#39;max&#39;],<br>                                &#39;COLUMN_B&#39;: [&#39;mean&#39;, &#39;sum&#39;]})</pre><p>The result of this transformation can be published back to the cloud data warehouse by calling the save function.</p><pre>wkds = dataset.datetrunc(dates={&#39;DATE&#39;: &#39;week&#39;}).rename(<br>                         renames={&#39;DATE_WEEK&#39;: &#39;WEEK}).aggregate(<br>                         aggregations={&#39;COLUMN_A&#39;: [&#39;min&#39;, &#39;max&#39;],<br>                                       &#39;COLUMN_B&#39;: [&#39;mean&#39;, &#39;sum&#39;]})</pre><pre>wkds.save(table_name=&#39;WEEKLYAGGDATA&#39;)</pre><p>This data is available within Python as a pandas dataframe by calling to_df.</p><pre>weekly_df = wkds.to_df()</pre><p>This data can now be used for modeling, ad hoc analysis, or dashboard development. In addition, as the original data is updated on the data warehouse, RasgoQL will keep this weekly aggregation up to date automatically. This means that the aggregations performed during the development of this project are simultaneously made in the production environment and immediately available to production systems.</p><p>For most of my career, after building my features in Python and pandas I would hand off the code to software engineering where they would refactor it. This process took weeks, if not months, to complete. I’ve seen models fail to perform, because, by the time they were put into production, the modeling data was no longer reflective of the current production data. With RasgoQL, I can still work in Python, but save my feature engineering in my database and hand of dbt models that software engineering can more easily implement. This can save months of development effort before models can be deployed.</p><p>If you want to check out RasgoQL, the documentation can be found <a href="https://docs.rasgoql.com/">here</a> and the repository <a href="https://github.com/rasgointelligence/RasgoQL">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9bdcc495a58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/weekly-aggregation-of-time-series-data-f9bdcc495a58">Weekly aggregation of time series data</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[Merging Multiple Datasets at Scale]]></title>
            <link>https://medium.com/data-science/merging-multiple-datasets-at-scale-6a2424d5ea57?source=rss-610988231d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a2424d5ea57</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Andrew Engel]]></dc:creator>
            <pubDate>Fri, 04 Mar 2022 19:59:29 GMT</pubDate>
            <atom:updated>2022-03-04T20:48:34.303Z</atom:updated>
            <content:encoded><![CDATA[<h4>Joining data on the modern data stack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a6vRFR4Hbt1AJu0D" /><figcaption>Photo by <a href="https://unsplash.com/@timberfoster?utm_source=medium&amp;utm_medium=referral">Tim Foster</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When working in data science, rarely will a data scientist be able to find all of the necessary data for their project in a single file. Even if the data is always available in a single file, feature-engineering techniques often create additional data sets which means that the data will need to be joined together. On the modern data stack, this can be done using SQL as detailed <a href="https://towardsdatascience.com/sql-join-8212e3eb9fde">here</a> and <a href="https://towardsdatascience.com/the-world-of-sql-joins-c70ca7f36f04">here</a>. For data scientists who are working in Python, this can be done with the merge command in pandas.</p><p>Using <a href="https://github.com/microsoft/sql-server-samples/tree/master/samples/databases/adventure-works">AdventureWorks</a> data (released under the MIT license and with further documentation found <a href="https://docs.microsoft.com/en-us/sql/samples/adventureworks-install-configure?view=sql-server-ver15&amp;tabs=ssms">here</a>), consider the problem of understanding the impact of promotions on internet sales. A Jupyter notebook that shows how to read all of the AdventureWork data into pandas dataframes can be found <a href="https://github.com/rasgointelligence/RasgoQL/blob/main/tutorials/import_datasets.ipynb">here</a>. Examining the internet_sales dataframe (called <em>import_sales</em> in the notebook), it looks promising as it contains both the purchase information, a promotion key to show promotions, the discount amount on the purchase and the total sales amount. Unfortunately, the data seems to be bad. Whether or not a promotion was in place, the discount amount is always zero and the sales amount is the same despite the various promotions.</p><p>It is not uncommon to experience these sorts of data errors with real data. While this may be an artifact of original use of the AdventureWorks data, in the real world this often occurs due to an issue in the software and a failure to apply the promotion details correctly before the invoice is saved. As is often the case in data science, a workaround will need to be found. Fortunately, a promotion dataframe (called <em>import_promotion</em> in the notebook above) exists that contains information on each promotion and the discount percentage. This data will need to be joined to the sales data and an actual sale price calculated.</p><h4>pandas merge</h4><p>Using the AdventureWorks sales and promotion data extracted as import_sales and import_promotion for the internet sales and promotion data respectively. First, we can create a simplified promotion dataset containing just the *PROMOTIONKEY* and *DISCOUNTPCT*.</p><pre>promotiondf = import_promotion[[&#39;PROMOTIONKEY&#39;, <br>                                &#39;DISCOUNTPCT&#39;]].copy()</pre><p>This promotion dataframe can be joined to the original sales dataframe as:</p><pre>sales = pd.merge(import_sales, <br>                 lean_promo,<br>                 on=&#39;PROMOTIONKEY&#39;,<br>                 how=&#39;left&#39;)</pre><p>Alternatively, this can be calculated as:</p><pre>sales = import_sales.merge(import_sales, <br>                           lean_promo,<br>                           on=&#39;PROMOTIONKEY&#39;,<br>                           how=&#39;left&#39;)</pre><p>The dataframe sales now contains both the price before discount and the discount percentage that should be applied. The actual sales price can be calculated as:</p><pre>sales[&#39;ACTUALSALESAMT&#39;] = (1 - sales[&#39;DISCOUNTPCT&#39;]) *<br>                               sales[&#39;SALESAMOUNT&#39;]</pre><p>Now, further analysis of the impact of discounts can be completed with the actual sales amount.</p><p>While using pandas in this way is both common and effective, it is not without its drawbacks. In particular, using pandas requires the data to be extracted from the data warehouse and moved to the machine where the computation and merging can happen and then sent back to the data warehouse for storage. In the case of massive data sets, this can be infeasible. Even in the case of moderate sized data that fits into a server’s memory, the time to extract the data into pandas and push it back into the warehouse can exceed the time to do the analysis itself.</p><h4>Using RasgoQL to perform this in the data warehouse</h4><p>Instead of moving the data to use pandas, the same join and calculation can be done within the data warehouse. Not all data scientists are comfortable in working in SQL or would like to continue working in Python. This is because of the better IDEs available or the ability to quickly profile data during this work. The open-source package RasgoQL helps bridge this gap by allowing data scientists to work in Python, but execute the code in the data warehouse.</p><p>First, RasgoQL needs a handle on the tables in the cloud. This is done with the datasetfunction:</p><pre>salesds = rql.dataset(&#39;ADVENTUREWORKS.PUBLIC.FACTINTERNETSALES&#39;)<br>promotionds = rql.dataset(&#39;ADVENTUREWORKS.PUBLIC.DIMPROMOTION&#39;)</pre><p>Next, join the promotion data with the sales data:</p><pre>sales = sales_ds.join(join_table=promotion_ds.fqtn, <br>                      join_type=&#39;RIGHT&#39;,<br>                      join_columns={&#39;PROMOTIONKEY&#39;:&#39;PROMOTIONKEY&#39;})</pre><p>The math function can be applied to create the actual sales amount:</p><pre>sales = sales.math(math_ops=[&#39;(1 - DISCOUNTPCT) * SALESAMOUNT&#39;],<br>                             names=[&#39;ACTUALSALESAMT&#39;])</pre><p>This data can be downloaded to the python environment as a sample of ten rows in a dataframe by running preview:</p><pre>sales_sample_df = sales.preview()</pre><p>Or the full data can be downloaded as:</p><pre>sales_df = sales.to_df()</pre><p>To make this data available to everyone as a view on the data warehouse, it can be published using save:</p><pre>sales.save(table_name=&#39;&lt;Actual Sales Data Tablename&gt;&#39;,<br>           table_type=&#39;view&#39;)</pre><p>Alternatively, to save this as a table, change <strong>table_type</strong> from <strong>‘view’</strong> to <strong>‘table’</strong>. If you’d like to check the SQL RasgoQL uses to create this table or view, run sql:</p><pre>print(sales.sql())</pre><p>Finally, if you use dbt in production and would like to export this work as a dbt model for use by your data engineering team, call to_dbt:</p><pre>sales.to_dbt(project_directory=&#39;&lt;path to dbt project&gt;&#39;</pre><p>This approach causes a SQL join to be generated and executed on the data warehouse allowing all of the data to be joined without needing to move the data to the workstation. In addition, as this creates SQL that is run on the warehouse, the features are automatically ready for use in production without needing to translate the Python code into SQL.</p><p>When dealing with small amounts of data, pandas can be a useful tool. As the dataset size gets larger, it can be hard if not impossible, to continue using pandas. Numerous Python packages can help, but with the processing power available in the data warehouse, the best solution can be to perform as much of the calculation there.</p><p>Migrating the data preparation process to the data warehouse can be challenging and often requires the help of data engineering. With the open-source package, RasgoQL, data scientists can leverage the power of SQL in the data warehouse without the need for additional resources.</p><p>If you want to check out RasgoQL, the documentation can be found <a href="https://docs.rasgoql.com/">here</a> and the repository <a href="https://github.com/rasgointelligence/RasgoQL">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a2424d5ea57" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/merging-multiple-datasets-at-scale-6a2424d5ea57">Merging Multiple Datasets at Scale</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[Imputation on the Modern Data Stack]]></title>
            <link>https://medium.com/data-science/imputation-on-the-modern-data-stack-6c0e37e20e7a?source=rss-610988231d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c0e37e20e7a</guid>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[imputation]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Andrew Engel]]></dc:creator>
            <pubDate>Thu, 03 Mar 2022 18:14:43 GMT</pubDate>
            <atom:updated>2022-03-03T18:14:43.857Z</atom:updated>
            <content:encoded><![CDATA[<h4>Imputation at scale</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i__5i2gp2gxtT4wK" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Since the majority of machine learning algorithms do not handle null values, missing value imputation is a standard part of feature engineering pipelines. There are multiple techniques for this imputation ranging from the very simple to the creation of complicated models to infer what the value should be.</p><p>The simplest method is to impute a single value for the missing value, most commonly the mean or median of the feature. For tree based methods, imputing an extreme value (larger than the maximum or smaller than the minimum for the feature) also works. Often, data scientist feel that these simple techniques do not adequately replace the missing value. In these cases, a model can be created to impute the value based on the other features for that observation. This can range from relatively simple (kNN models) to complicated models similar in scope to the original machine learning effort. While this model-based approach can be appealing, the power of modern machine learning algorithms mean that imputing a single value and creating a missing indicator can perform as well with much lower effort. In this blog, we will impute the mean, but simple changes to the code would allow us to impute other values instead.</p><h4>Imputation in Python</h4><p>Within Python, there are two common ways to perform this imputation. First, this imputation can be done with pandas.</p><pre>df[&#39;varname&#39;] = df[&#39;varname&#39;].fillna(df[&#39;varname&#39;].mean())</pre><p>In order to create the missing indicator, it needs to be created first</p><pre>df[&#39;varname_mi&#39;] = df[&#39;varname&#39;].isna()<br>df[&#39;varname&#39;] = df[&#39;varname&#39;].fillna(df[&#39;varname&#39;].mean())</pre><p>Often, this is done in Scikit-learn as part of the feature engineering pipeline. Using train_test_split to create the training and test partitions, a SimpleImputer can be created to replace missing values.</p><pre>from sklearn.impute import SimpleImputer<br>from sklearn.model_selection import train_test_split</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=1066)</pre><pre>imp = SimpleImputer(missing_values=np.NaN, strategy=&#39;mean&#39;)<br>X_train = imp.fit_transform(X_train)<br>X_test = imp.transform(X_test)</pre><p>Unlike with pandas, SimpleImputer can simultaneously create a missing value indicator by changing the call to include setting the parameter <em>add_indicator </em>to <em>True.</em></p><pre>imp = SimpleImputer(missing_values=np.NaN, <br>                    strategy=&#39;mean&#39;,<br>                    add_indicator=True)</pre><h4>Challenges</h4><p>In both of these cases, these methods work for datasets that are manageable on individual workstations. In problems where the datasets contain hundreds of gigabytes or terabytes of data, this approach no longer works. While packages such as Dask can allow you to process these massive datasets, you will still need to move the data to your machine or cluster. With these size datasets, the time to move the data can be significant. Even with manageable data sizes, these Python based approaches can still cause problems when the final model goes into production, as these imputations will need to be duplicated in the production code. This can be challenging when the production environment isn’t in Python or doesn’t support loading Python objects.</p><h4>Imputation using the power of the cloud data warehouse</h4><p>Using RasgoQL can alleviate both of these issues. RasgoQL performs the imputation within the data warehouse and allows you to save all feature engineering steps so they can be rerun in the warehouse at the time of prediction.</p><p>To use RasgoQL’s transforms, first connect to the system with RasgoQL.</p><pre>import rasgoql<br>creds = rasgoql.SnowflakeCredentials.from_env()<br>rql = rasgoql.connect(creds)</pre><p>And get the dataset (a table or view in the data warehouse) that needs missing value imputation performed on it with rql.dataset(fqtn=&lt;Fully Qualified Table Name&gt;). All supported transforms can be found <a href="https://docs.rasgoql.com/primitives/transform">here</a> or by listing them programmatically:</p><pre>transforms = rql.list_transforms()<br><strong>print(transforms)</strong></pre><p>To transform the data, call the transform name on the dataset.</p><pre>newset = dataset.impute(imputations={&#39;VARIABLE_1&#39;: &#39;mean&#39;,<br>                                     &#39;VARIABLE_2&#39;: &#39;mean&#39;},<br>                                     flag_missing_vals=False)</pre><p>Note that the imputation transformation takes a dictionary of the fields that need imputation and allow different methods for the imputation: <em>mean, median, mode </em>or a single value. In addition, setting <em>flag_missing_vals</em> to <em>True </em>will cause missing indicator features to be created for each field in the imputation dictionary.</p><h4>Transformation chaining</h4><p>Multiple transformations can be chained to one another, either by appending multiple calls to transformation functions or by running a transformation function on the output of a prior transformation. This allows you to build up more complicated transformations from relatively simple ones and create your final dataset with a single SQL call. The results of the chain of transformations can be viewed as a dataframe with:</p><pre>df_transform = newset.preview()<br>print(df_transform)</pre><p>By default, preview returns ten rows. To download the entire data as a dataframe, call to_df.</p><p>Since these transformations are running on the cloud data warehouse, it is running SQL code. The SQL statements for the transformation chain can be viewed by running</p><pre>print(newset.sql())</pre><p>While this code creates the transformation chain, it has not yet been executed with the results saved in the warehouse. To save it, a new table needs to be created by calling save on the chain.</p><pre>newset.save(table_name=&#39;&lt;NEW TABLE NAME&gt;&#39;,<br>            table_type=&#39;view&#39;)</pre><p>This data is saved as a view. In order to save it as a table instead, change <strong>table_type</strong> to <strong>‘table’</strong> instead.</p><p>At this point, Rasgo has run the missing value imputation against the full data stored in the data warehouse and returned the results as a dataframe in any Python environment and can be used for modeling or visualization using standard tools. In addition, if this was saved as a view, when new data is added to the underlying table in the data warehouse, the data preparation phase doesn’t need to be rerun as the imputed data is automatically run and available for download.</p><p>The fact that this preparation is automatically run impacts the ability to place the data preparation pipeline into production. Instead of either packaging up the python code or rewriting it into the language used in the production system, the data is automatically kept up to date in the warehouse and the relevant rows of data can be extracted with the imputation already created.</p><p>Now, instead of losing weeks or months of time rewriting (or waiting for software engineering to rewrite) and testing the output of the code, the data is immediately available.</p><p>Finally, as this imputation is immediately available in the data warehouse means that other data scientists and analysts no longer need to extract the original data and prepare it for their own use. Instead, the final, transformed data can be extracted directly from the warehouse and used for modeling, visualization or reporting.</p><p>To understand the power of these tools, a dataset was created that included missing data in several key fields and uploaded to our data warehouse. The mean was imputed for the missing fields both with and without creating a missing indicator. Finally, a <a href="https://catboost.ai/">CatBoost</a> classifier was trained for both cases and the log loss and AUC were both calculated.</p><pre>y = transformed_df[target]<br>X = transformed_df.drop(columns=[target])<br>X_train, X_test, y_train, y_test = train_test_split(X, y,     <br>                                                    test_size=.2,                  <br>                                                  random_state=1066)</pre><pre>categorical_features = X_train.select_dtypes(exclude=[np.number])</pre><pre>train_pool = Pool(X_train, y_train, categorical_features)<br>test_pool = Pool(X_test, y_test, categorical_features)</pre><pre>model = CatBoostClassifier(iterations=1000, <br>                           max_depth=5,<br>                           learning_rate=0.05,<br>                           random_seed=1066,<br>                           logging_level=&#39;Silent&#39;, <br>                           loss_function=&#39;Logloss&#39;)</pre><pre>model.fit(X_train, <br>          y_train, <br>          eval_set=test_pool, <br>          cat_features=categorical_features, <br>          use_best_model=True, <br>          early_stopping_rounds=50)</pre><pre>y_predict = model.predict_proba(X_test)</pre><pre>logloss = log_loss(y_test, y_predict[:, 1])<br>auc = roc_auc_score(y_test, y_predict[:, 1])</pre><pre>print(logloss, auc)</pre><p>This gives the final results</p><ul><li>Without missing indicator: AUC: 0.6881, Log loss: 0.2574</li><li>With missing indicator: AUC: 0.7045, Log loss 0.2563</li></ul><p>In this case, using CatBoost, the model with the missing indicator slightly outperformed the model without the indicator</p><p>If you want to check out RasgoQL, the documentation can be found <a href="https://docs.rasgoql.com/">here</a> and the repository <a href="https://github.com/rasgointelligence/RasgoQL">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c0e37e20e7a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/imputation-on-the-modern-data-stack-6c0e37e20e7a">Imputation on the Modern Data Stack</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 in Python]]></title>
            <link>https://medium.com/data-science/feature-engineering-in-python-2fdb9bb8ee7a?source=rss-610988231d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fdb9bb8ee7a</guid>
            <category><![CDATA[pandas-tutorial]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Andrew Engel]]></dc:creator>
            <pubDate>Thu, 18 Nov 2021 19:03:04 GMT</pubDate>
            <atom:updated>2021-11-30T16:54:21.736Z</atom:updated>
            <content:encoded><![CDATA[<h4>Beyond the basics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6VNq4rMMyDwzr-N-hgf7ow.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@antoine1003">Antoine Dautry</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>In my decade plus as a data scientist, my experience largely agrees with Andrew Ng’s statement, “Applied machine learning is basically feature engineering.” From the very start of my career, building credit card fraud models at SAS, most of my value as a data scientist came from my ability to engineer new features and capture both business insights and behavior observed in the data to help the model identify the target. Also aligning with this sentiment is Dr. Pedro Domingos’ statement, “At the end of the day, some machine learning projects succeed and some fail. What makes the difference? Easily the most important factor is the features used.”</p><h4>Common feature engineering content</h4><p>Despite both this experience and the statements by leaders in the field, feature engineering content is still lacking. While a search for “feature engineering” on Google returns many pages, the underlying content is very similar and focuses on only a few topics:</p><ul><li>handling missing values</li><li>handling outliers</li><li>binning numeric variables</li><li>encoding categorical features</li><li>numerical transformations</li><li>scaling numerical features</li><li>extracting parts of a date</li></ul><h4>The problem with this content</h4><p>These are important topics and, in many cases, necessary for the underlying machine learning algorithm to even be able to process the data. However, they are lacking in three primary ways. First, in some cases, they blindly apply the techniques without understanding why. Many blogs discuss how numeric features need to be scaled before modeling. This is not true. Tree-based methods, e.g. XGBoost, LightGBM, etc. are invariant to scaling. <a href="https://medium.com/@praveenmec67">Praveen Thenraj</a> gave a nice example of this in his <a href="https://towardsdatascience.com/do-decision-trees-need-feature-scaling-97809eaa60c6">post on Towards Data Science</a>.</p><p>Second, while the technique is needed, there are large classes of problems where the technique will not be practical and other techniques are needed. An example of this is encoding categorical features. Most discussions of feature engineering explain one-hot or dummy encoding and often explain label encoding. Rarely do they discuss the challenge of high cardinality categorical variables. Most often, I have seen this occur when dealing with ZIP codes or Postcodes, but this can also occur when working with medical data and ICD-9 or ICD-10 diagnosis codes. One-hot encoding ZIP codes could result in over 40,000 new features. This is not a practical solution. Understanding the structure of these codes can allow them to be rolled up to higher levels of aggregation. Even after aggregation, there may be too many categories for either one-hot or label encoding to be useful. Further, some categorical variables do not have an easily identifiable aggregation that can reduce the number of categories needed. Target encoding or leave-one-out encoding can handle these high cardinality categorical features. While some feature engineering blogs discuss these techniques, they often fail to highlight their usefulness in this case or the impracticality of one-hot encoding.</p><h4>Feature engineering is more than this.</h4><p>Finally, and most crucially, feature engineering is far more than this. When people talk about the power of feature engineering or the art of feature engineering, they are not referring to these standard techniques. Instead, it is the work recognizing that ZIP codes can be aggregated to cities, states, DMAs, etc. and performing those aggregations. This engineering can be further performed by combining these aggregations with all purchases in that location to capture a better sense of the local market. Finally, comparisons between an individual’s purchases and the local market overall. This is just the tip of the iceberg and is my favorite part of the data science process.</p><p>To be fair, it is hard to show examples of this sort of feature engineering without also discussing an actual modeling problem. But to neglect it altogether when discussing feature engineering may leave a false sense of its scope. In addition, many powerful techniques exist that can be applied across a broad set of problems.</p><h4>Feature engineering with time series data</h4><p>For example, many data science problems have a time series character. This is not to say that the problems are time series problems, rather there are repeated observations that need to be aggregated together to represent the underlying behavior of interest. In building models for customer analytics (e.g. churn, lifetime value), the individual transaction and the way they change over time are important. A feature engineering blog could share code showing how to calculate common features for this as follows.</p><p>When working with data about a single customer with multiple observations over time, one of the most common techniques to aggregate this data is through rolling windows followed by an aggregation in pandas. In this case, a weekly aggregation is created and the minimum, mean, maximum and standard deviation are created.</p><pre>weekly_resample = df.rolling(&#39;7D&#39;)<br>aggregated_df = weekly_resample.agg([&#39;min&#39;, &#39;mean&#39;, &#39;max&#39;, &#39;std&#39;])<br>aggregated_df.columns = [&#39;_&#39;.join(col).strip() + &#39;_week&#39; <strong>for</strong> col <strong>in</strong> <br>                         aggregated_df.columns.values]</pre><p>Note that for this to work, the dataframe df needs the date set as its index.</p><pre>df.set_index(&#39;date&#39;, inplace=<strong>True</strong>)</pre><p>Using rolling windows, aggregated_df contains a record for each transaction with the aggregation of all transactions from the prior seven days. If, instead, a prediction was needed after every week, additional work would be needed to filter out just the last record prior to that week. pandas supports this use case with resample. If the following code is run instead, one record per week is returned.</p><pre>weekly_resample = df.resample(&#39;7D&#39;, <br>                              origin=pd.to_datetime(&#39;2021-01-03&#39;))<br>aggregated_df = weekly_resample.agg([&#39;min&#39;, &#39;mean&#39;, &#39;max&#39;, &#39;std&#39;])<br>aggregated_df.columns = [&#39;_&#39;.join(col).strip() + &#39;_week&#39; <strong>for</strong> col <strong>in<br>                         </strong>aggregated_df.columns.values]</pre><p>Since January 3, 2021 is a Sunday, the aggregation starts on each Sunday and includes all transactions in the rest of the week. If the seven days prior to Sunday was desired, the following change could be made.</p><pre>weekly_resample = df.resample(&#39;7D&#39;, <br>                              origin=pd.to_datetime(&#39;2021-01-03&#39;),<br>                              lavel=&#39;right&#39;)</pre><p>Once these weekly aggregations are created (of either type), rate of change of these aggregations can be exceedingly powerful. From a physics point of view, this is the velocity of the underlying feature and we can look at the rate of change over multiple time periods.</p><pre>aggregated_df[&#39;velocity_1wk&#39;] = (aggregated_df[&#39;mean_week&#39;] - <br>                              aggregated_df[&#39;mean_week&#39;].shift(1))/7 aggregated_df[&#39;velocity_4wk&#39;] = (aggregated_df[&#39;mean_week&#39;] - <br>                             aggregated_df[&#39;mean_week&#39;].shift(4))/28</pre><p>This gives us the rate of change of the weekly mean over one week and four weeks. Next, the rate of change of this rate of change (acceleration) can be calculated.</p><pre>aggregated_df[&#39;acceleration_1wk&#39;] = (aggregated_df[&#39;velocity_1wk&#39;] - <br>                           aggregated_df[&#39;velocity_1wk&#39;].shift(1))/7</pre><h4>50+ Free Feature Engineering Tutorials</h4><p>Techniques like these can be used to build features that can represent the underlying behavior of interest. At <a href="https://www.rasgoml.com/">Rasgo</a>, we wanted to help the data science community by sharing these techniques. To do this, we created a <a href="https://hubs.la/Q0100qK30">free repository devoted to feature engineering tutorials</a> that contains feature engineering code, including the examples above, as Jupyter notebooks. In addition to feature engineering, there are examples for:</p><ul><li>Feature Profiling and EDA</li><li>Data Cleaning</li><li>Train-Test Splits</li><li>Feature Importance</li><li>Feature Selection</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fdb9bb8ee7a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/feature-engineering-in-python-2fdb9bb8ee7a">Feature Engineering in 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[Refined Data is the New Fuel part 2]]></title>
            <link>https://medium.com/rasgoml/refined-data-is-the-new-fuel-part-2-dda2025adbbd?source=rss-610988231d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/dda2025adbbd</guid>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Andrew Engel]]></dc:creator>
            <pubDate>Tue, 16 Nov 2021 20:17:13 GMT</pubDate>
            <atom:updated>2021-11-16T20:17:13.230Z</atom:updated>
            <content:encoded><![CDATA[<h4>Best Practices For Transforming Dirty Data Into a Renewable Resource</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-x8O-GQrvyaLLNIotZufw.png" /><figcaption>Photo by hxdyl from Getty Images via Canva</figcaption></figure><p>In part one, we discussed the quote “Data is the new oil” and used it to discuss the state of data science and the lack of investment in the tools to improve the data slog. This lack of investment exists despite the fact that 50% to 80% of a data scientist’s time is spent performing data preparation and feature engineering. Even Andrew Ng has begun talking about shifting priorities to this portion of the machine learning lifecycle, “If 80 percent of our work is data preparation, then ensuring data quality is the important work of a machine learning team.” More damning, despite a massive investment in tools for the rest of the data science lifecycle, data science projects still commonly fail to produce significant ROI.</p><h4>The data preparation process.</h4><p>The data slog is not just the technical aspect of extracting data, profiling data, handling outliers, and creating new features from existing data. A large part of the work requires soft skills to complete. It includes meetings to find the necessary data, get access to the data and work with the business and data owners to understand what is in the data. Once the profiling is done, the knowledge gained needs to be shared back with the business, both to validate the data scientist’s understanding, but also to provide value to the business based on their existing data.</p><p>At the beginning of the process, the data scientist has an initial list of data sources to perform the above work on. However, during this initial data preparation work, gaps in the data may be identified. This identification leads to additional meetings and work for the data scientist.</p><p>Once all of the data has been collected and analyzed, the data scientist needs to focus on how to merge the data. While some of the information necessary to do this merge will have already been captured, often additional context is needed. This leads to more meetings with the data owner to be able to do the technical work necessary before they can even begin to create models.</p><h4>Why data preparation is a slog?</h4><p>To make matters even worse, anytime something changes in the source data warehouse, the data scientist needs to identify it and find a solution. This could involve working with the data owner to fix the data in the data warehouse, create new feature engineering code to transform the data back into the form it originally was in, or rebuilding the models to use the new data.</p><p>This means that in order to build and deploy models, A lot of technical work needs to be done. Often, however, the vast majority of the time spent in data preparations is spent in meetings: finding, getting access to, and understanding the data, and developing the domain expertise to even do the data preparation. While most data scientists have the technical skills to perform the data preparation tasks, most are trained to build models and believe that is the primary purpose of being a data scientist. A much more limited number of data scientists are interested in either the development of domain expertise or the necessary interactions with the rest of the business.</p><p>Is it any wonder that data scientists complain about data preparation and would rather spend their time building models? This causes the data science community to put model building above feature engineering and data preparation in importance even though without quality features, the models will not perform.</p><p>This data slog does not just impact the data scientist working on the initial project. Because of the difficulty of the data preparation process and the capture of domain knowledge, the data scientist tasked with rebuilding or improving an existing model will need to repeat much of the data preparation process. Even if the code exists, understanding what it does and modifying it to handle changes to the data sources can be a laborious process. More importantly, even to do this, the new data scientist must develop the domain knowledge to understand the data and why the data preparation code works the way it does. This involves the same set of meetings and conversations with the business and data owners as the original project needed.</p><p>This necessity of repeated work doesn’t just impact the data scientist working on a model refresh. It can impact the business in much more serious ways. Because the knowledge on how to create a feature or metric is embedded in the data preparation and feature engineering code, it is difficult for others to even know it exists. This means two different data scientists, working on different projects, but needing the same metric will often create two slightly different versions. This can lead to different portions of the business having different views of the business and multiple answers to the same question.</p><h4>Data science needs to focus on the features not the models.</h4><p>To resolve this problem, we believe we need to turn the data preparation process on its side and focus on the features, not the models. It is the features that result from refining the data and it is the features that contain the valuable signal. In the end, the output of a model is just another feature that itself can become an input into another model.</p><p>When we focus on the feature, we see all of data preparation, from data catalogs to feature engineering as a process to extract signals from the data. It turns out, data preparation is not a menial task, it is a critical and valuable part of the process of extracting signals from data. And finding and utilizing these valuable signals is the point of data science. Without these signals, data-driven decisions will be blind.</p><p>Finally, when we focus on the feature, we realize data preparation and feature engineering tools need to focus on the feature and consider each feature as a column of data that contains a signal of some behavior. This implies that instead of focusing on data in tables or files, data science needs to focus on the features independent of the underlying storage mechanism. Tools need to abstract away the technical details of where the data resides, how it can be joined to other data and even how it can be aggregated to different levels of granularity.</p><p>Beyond that, all features can be stored in one central repository along with metadata that documents where the data came from, who owns it, what processing has been performed on it, the domain knowledge needed to understand it, its statistical profile and relationship to other features and where it is being used. By allowing all this metadata to be easily searched, data scientists can easily find and understand existing features both from prior versions of their project and other unrelated projects. This, in turn, makes it easy for data scientists to gather all relevant features for their machine learning models and execute (and document) additional feature engineering approaches they have used.</p><p>This allows data scientists to focus on what really matters, the features. Tools that focus on the feature will make it easy for data scientists to pull only the features they want, aggregated at the level they want into their models. Further, by focusing on the features, data scientists are equipped to find and capture the signal, develop better features, and easily share these features with the entire organization.</p><h4>The feature is the future.</h4><p>The feature is the future of data science. Despite data preparation and feature engineering being the portion of the data science lifecycle where most time is spent, the data science community has focused its efforts on optimizing either side of the process. Unless we fix the data preparation and feature engineering experience, data science will continue to fail to deliver significant returns on the investments being made.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dda2025adbbd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rasgoml/refined-data-is-the-new-fuel-part-2-dda2025adbbd">Refined Data is the New Fuel part 2</a> was originally published in <a href="https://medium.com/rasgoml">Rasgoml</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>