<?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 Zvika Segal on Medium]]></title>
        <description><![CDATA[Stories by Zvika Segal on Medium]]></description>
        <link>https://medium.com/@zvikasegal?source=rss-33ef13129216------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*IayqFtv6avJ8fQLv</url>
            <title>Stories by Zvika Segal on Medium</title>
            <link>https://medium.com/@zvikasegal?source=rss-33ef13129216------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:20:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zvikasegal/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[Part 5 — Calculating Trend Features]]></title>
            <link>https://medium.com/@zvikasegal/part-5-calculating-trend-features-2ce6622e3af9?source=rss-33ef13129216------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ce6622e3af9</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[medicine]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Zvika Segal]]></dc:creator>
            <pubDate>Sun, 06 Sep 2020 07:38:45 GMT</pubDate>
            <atom:updated>2020-09-06T07:38:45.248Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 5 — Calculating Trend Features</h3><p>In previous posts we have started multiprocessing our pre-designed features by dividing our sample to smaller batches, and calculating these batches in parallel. By using the diagnosis feature class as an example, we queried the custom SQLIte databases we have created in earlier steps from the raw CSV files, aggregated ICD9 codes to the meaningful diagnosis classes we have designed, and filtered out the unnecessary codes.</p><p>After all this work, the diagnoses dataframe for the patients in the current batch now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RIKIfBLmpOt7gRlj" /><figcaption>The raw diagnoses dataframe for a single batch</figcaption></figure><p>This diagnosis dataframe contains a single diagnosis assigned to a specific patient in our batch in every row, with the ICD9 code (DIAG_CODE columns) and diagnosis class (Group columns), and some additional information such as the date the diagnosis was assigned and prescribing physician, that we may want to use in the future. We used 2 diagnosis classes as examples — <a href="https://en.wikipedia.org/wiki/Hypertension">hypertension</a> and <a href="https://en.wikipedia.org/wiki/Pneumonia">pneumonia</a>.</p><p>When designing our features for the fibromyalgia prediction task (see project overview) , we speculated that patients with fibromyalgia may complain about pain-related symptoms, such as abdominal pain or headache, more after the onset of the disease as compared to before. This could be a valuable feature, as it captures a true change in a patient’s behavior, and it is less susceptible to confounders such as comorbidities and behavior<strong>. </strong>In order to capture that specific information in the data, we will need to calculate the <strong>trend </strong>of the count of every specific diagnosis class in the training time frame.</p><p>A quick reminder of the DiagnosisFeatures class -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b70a1a824b52a77ef75f4c975edc73e/href">https://medium.com/media/9b70a1a824b52a77ef75f4c975edc73e/href</a></iframe><p>After taking care of batching and multiprocessing in the base class BaseFeature, we will start calculating our current batch by loading the relevant diagnosis dataframes as explained in <a href="https://medium.com/@zvikasegal/part-4-feature-design-cf5b5244fc7f?source=friends_link&amp;sk=c82325792b01fa35f96cd2128475b426">previous posts</a>. We will have 3 different diagnosis dataframes — inpatient, outpatient and carrier, depending on the source database. Notice that the dataframes have have different columns names due to differences in the original CSV, so we will have to mind these differences when calling the different methods. For simplicity, we will calculate the trend features just for the outpatient table.</p><p>We’ll call the get_trends() function, the main method in the Trends class, which contains all of the relevant methods for calculating the trend features.<strong> We want to keep in mind that we are going to do these calculations many times , so we need to be as efficient as possible. </strong>We’ll pass the data frame, the name of the columns we want to make our calculation on (in this case, as we are working on the diagnoses group as was explained in previous posts, we will use the ‘Group’ column), the patient identifier column and the date identifier column.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62558a9e03d76eab509aa73d21e1776d/href">https://medium.com/media/62558a9e03d76eab509aa73d21e1776d/href</a></iframe><p>Although the data frame consists of many patients, with several different diagnosis classes prescribed for each patient, and will want to calculate the trend of each diagnosis class for every patient separately — we will have to reform our dataframe.</p><p>The most efficient way to reform the dataframe to our needs is the pandas groupby() method, a very useful method for reorganizing and extracting information efficiently from dataframes.</p><p>Groupby() basically splits the data to partial dataframes based on the values of a specified column or columns (for an in-depth discussion look at <a href="https://www.shanelynn.ie/summarising-aggregation-and-grouping-data-in-python-pandas/">this article</a>), and then performs some function on these dataframes, and returns the results as a new series or dataframe.</p><p>Since we want to calculate our trend features for a specific patient and diagnosis class, and we are only interested in the diagnosis dates for our analysis, we will groupby() using the patient columns and the diagnosis group columns on the dates column, which will return for further processing a dataframe that looks like this, with the dates a specific patients was diagnosis with a specific diagnosis class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*cCLmsbJ2FBWfRgiSejPPgw.png" /><figcaption>The sliced dates dataframe</figcaption></figure><p>The next step is to run some function on the sliced data frames. Although there are many available functions to be used on the groupby objects like mean() and sum(), we would want to create our own custom functions, and calculate them in a single run. For that, we will use the agg() function — the aggregation functionality provided by the agg() function allows multiple statistics to be calculated per group in one calculation. We need to pass the agg function a dictionary, with the columns we want to operate on as keys, and the functions we want to operate on the columns as items. In our case, since we are interested in trends, we will work on the date column, and perform 2 calculations- a. calculate the trend of the diagnoses in our training time frame, and b. the amount of the times the diagnosis was prescribed <strong>in the last 3 months before the index date</strong> as compared to th<strong>e mean of the times</strong> the diagnosis was prescribed, in standard deviation units. (for further discussion on the experimental setup see the <a href="https://medium.com/@zvikasegal/claimspredict-project-overview-fe75a07c3b32?source=friends_link&amp;sk=f8ab08e6a1d2e68caca4797e6ff4ec6d">project overview</a>) which will provide valuable information about the immediate time frame.</p><p>This is the <strong>trend </strong>calculating function, trend():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4189b5c423e0ede75eba4996c90fba62/href">https://medium.com/media/4189b5c423e0ede75eba4996c90fba62/href</a></iframe><p>The get_grouped_dates() method uses use the pd.grouper methods to sum the diagnosis prescribed in 3 months intervals on the dataframe -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6391d450e56d18d1adca0b9c3b1daab9/href">https://medium.com/media/6391d450e56d18d1adca0b9c3b1daab9/href</a></iframe><p>And return this dataframe, with the diagnosis class count in each time interval —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/0*8xsD9qBgkLzfw_Gs" /><figcaption>Grouped dataframe</figcaption></figure><p>There are 2 main problems with this dataframe — the first problem is that we don’t have data on the diagnosis counts for the first and last months of the timeframe — and we would want to assume they are zero. The second problem is that by the way the pd.grouper world, the 3 months time windows will be different for every patient, which will cause a lot of mess in the future</p><p>There is a quick-and-dirty, but effective, solution for both of the problems — we can add 2 dummy dates to our dataframe — the day before the beginning of our time frame and the day after the end of the time frame. This will force our grouped dataframe to look like this, for every patient in our batch —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/0*bRnkjR3iDvw2GGbm" /><figcaption>Processed dataframe</figcaption></figure><p>And now we can just return this dataframe without the first and last rows, which represents time windows outside of our experiment timeframe.</p><p>Now that we have an organized and uniformed diagnosis counts dataframe, we can easily fit the numpy.polyfit function to get the trend of the counts, and the value of the z score of the final interval for the std feature.</p><p>The groupby().agg() function, after iterating over all the patients and diagnoses groups, will return us this dataframe, with multilevel column names—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*QrUdcLr86gumKy6dYWefXw.png" /><figcaption>Results table with multilevel column names</figcaption></figure><p>Since we will want to merge this dataframe with other dataframes in the future, we will want to flatten the columns to a single level, with comprehensible column names. This simple task can be quite tricky to get right. We will first get rid of the patient id column and use it as an index. Then, we will first stack all of the columns, which will return this data frame -</p><p>And then unstack on levels 1 and 2 and drop level 0. We will get the right dataframe, but with names that will be hard to work with it in the future, so we can rename the columns by joining the 2 strings, and get our final dataframe -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/0*mQfvbZ0GssVMRH8m" /><figcaption>Final diagnosis trends dataframe</figcaption></figure><p>Notice that we have many nans — as patients that were not diagnosed with a specific diagnosis group, or diagnosed only once, can’t have a trend calculated. We will discuss different ways to impute these values in future posts.</p><p>We have now finished calculating the trends feature. There is still much more diagnosis related information we want to extract from our raw data — for example, we will want to count the times a certain diagnosis was prescribed, test the relations between different diagnoses, look for chronic conditions, and much more. We will continue extracting diagnosis features in the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ce6622e3af9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ClaimsPredict — Project Overview]]></title>
            <link>https://medium.com/@zvikasegal/claimspredict-project-overview-fe75a07c3b32?source=rss-33ef13129216------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe75a07c3b32</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[medicine]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Zvika Segal]]></dc:creator>
            <pubDate>Wed, 26 Aug 2020 15:35:07 GMT</pubDate>
            <atom:updated>2020-08-26T15:35:07.024Z</atom:updated>
            <content:encoded><![CDATA[<h3>ClaimsPredict — Project Overview</h3><p>In this project we will demonstrate a complete medical data science project, by building from scratch a machine learning model predicting clinical outcomes using an open access clinical database. We will go over the entire data science pipeline, from processing and cleaning raw CSV files,data preparation, feature engineering and data embedding, preprocessing, model design and training, up to the presentation and interpretation of the results.</p><p>This is a huge project. The project will be published here in different posts, each tackling a different segment of the project pipeline. As there is ALOT of code, each post will present only brief examples from the entire project code.The complete code is available in<a href="https://github.com/zhsegal/ClaimsPredict.git"> this github.</a></p><h3><strong>Introduction</strong></h3><p>AI is transforming the practice of medicine. It’s helping doctors diagnose patients more accurately, make predictions about patients’ future health, and recommend better treatments. Medical AI is one of the most interesting and diverse fields in AI. It’s diversity arises both from the multitude of different AI subfields that it encompasses, such as computer vision, audio analysis, NLP, time series analysis etc., and from the huge span of possible real world applications — from medical imaging to pathology, clinical decision support systems and precision medicine.</p><p>However, a major obstacle for the use of all of these applications and methods, is the difficulty in obtaining sufficient quality data. Medical data is scarce, and hard to get. As medical data is often held by health organizations, and is under severe privacy regulations, it is a scarce commodity that often requires significant resources and time from researchers to obtain. This is often regarded as the ‘chicken and egg’ problem by researchers and entrepreneurs in the medical AI domain — in order to get data access to data, one needs to show results, and needs the data in order to get these results.</p><p>There are only a few freely available datasets of good quality out there. A notable example is the<a href="https://mimic.physionet.org/"> MIMIC database</a> — MIMIC is an openly available dataset developed by the MIT Lab for Computational Physiology, comprising deidentified health data associated with ~60,000 intensive care unit admissions. It includes demographics, vital signs, laboratory tests, medications, and more.. There are also a few open resources in the medical imaging and <a href="https://www.itee.uq.edu.au/research/das/digital-pathology-datasets">pathology </a>domains , although they have their limitations.</p><p>A major limitation to these open access databases is that, aside from the MIMIC dataset ,none of them can offer us an in-depth information about a patient’s health status, both in and outside of hospitals, in order for us to perform critical medical-related tasks, such such as assessing risk for developing chronic conditions, assessing risk for latent undiagnosed diseases, identifying patients at increased risk for developing acute health events such as hospital admission or ER visits, and predicting the expected health costs and usage of health system resources for patients.</p><p>This work handles a unique exception — the <a href="https://www.cms.gov/Research-Statistics-Data-and-Systems/Downloadable-Public-Use-Files/SynPUFs/DESample01">CMS medical claims database</a>.</p><h3>The Dataset</h3><p>The CMS 2008–2010 Data Entrepreneurs’ Synthetic Public Use File (DE-SynPUF)open access medical claims database contains synthesized data taken from a 5% sample of 2008 Medicare beneficiaries and their medical claims from 2008, 2009, and 2010, representing 3 years of medical claims for about 2.4 million beneficiaries .</p><p>Medical claims is part of the payment practice in the USA health system, in which a healthcare provider submits a claim to a health insurance company in order to receive payment for services rendered; such as testing, treatments, and procedures. Various methods for medical coding are used to report what the diagnosis and treatment were, and prices are applied accordingly. In the common scenario in the USA where continuous EMR data about patients is not available, these claims provide a valuable proxy to a patient’s medical information over time.</p><p>An important note about this dataset is that it is fully “synthetic” — meaning no beneficiary in the data is an actual Medicare beneficiary. They are all synthetic beneficiaries meant to represent actual beneficiaries. In order to protect the privacy of beneficiaries and to greatly reduce the risk of re-identification, a significant amount of interdependence and co-variation among variables has been altered in the synthetic process — but, and most importantly for our cause — because the structure of the data is maintained, this dataset is useful for building data tools that could be used with the actual data.</p><p>The database is divided into 20 subsamples of the data. Each subsample contains eight (very big) CSV files: three beneficiary files (one for each year) carrying information about the beneficiary’s demographics and chronic conditions, one inpatient file containing three years of hospitalizations data, one outpatient file containing three years of outpatient clinics data, one medications file containing three years of all medication-related data, and two carrier files containing three years of data (segment A and segment B) regarding every other type of medical encounter.</p><h3><strong>Data Science Pipeline Architecture</strong></h3><p>We will use this dataset to demonstrate building a medical data science project pipeline from scratch. In future posts, our pipeline will take us from processing the raw data and up to predicting two clinical outcomes. The first target of the model will be to predict a patient’s risk for being diagnosed with <a href="https://en.wikipedia.org/wiki/Fibromyalgia">fibromyalgia </a>disease — a very common condition, which takes a long time to diagnose. We will train the model on clinical data from two out of three years in our data, and try to predict the diagnosis of fibromyalgia in the third year based on that information. The second target will try to predict in a similar design is the expected medical costs for each patient.</p><p>The general project pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*Y16QbdIytcZKSaPqQrNpvQ.png" /><figcaption>ClaimsPrerdict project pipeline</figcaption></figure><p>We will begin by ingesting the raw CSV files (someover a Gigabyte in size) to more efficient and convenient SQL database files — that will allow us to query processed information much more efficiently. We will then design a data preparation and extraction framework that will allow us to retrieve processed information efficiently from the database according to our needs.</p><p>Arguably the most important step in a data science pipeline is the careful use of domain knowledge for feature engineering — we will design and calculate features from the raw data, that will extract valuable information for our models.</p><p>We will engineer features in 6 different classe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*B3UT6cwoHZSJRuGz99PTiA.png" /></figure><p>In addition to the hand crafted features, we will provide more information for our model by using data embedding methods — we will represent our data in a way similar to the <a href="https://arxiv.org/abs/1602.05568">med2vec </a>method, and use it to construct a medical timeline embedding for each patient.</p><p>After a preprocessing step, mostly to impute missing data, we will try and compare several modeling approaches — 3 classical machine learning models (regression, random forest, SVM), and deep learning models. We will try 2 different types of deep learning models — the first deep model will be a simple DNN, using the engineers features and embeddings, and several different model architectures and hyperparameters. The second deep learning approach, will be to try and capture the temporal aspect of the data using a custom RNN. We will finish the project with model evaluation, with results analysis and presentation.</p><p>The <a href="https://medium.com/@zvikasegal/part-1-sqlite-db-creation-4d29aaa386bf?source=friends_link&amp;sk=2987e9b0d9a269b8ba49032a58f56d95">first post</a> in this project will discuss the first step of the data ingestion — processing the big CSVs, and converting them to clean and ready to use SQLIte database files for further preparations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe75a07c3b32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 4 — Feature Design]]></title>
            <link>https://medium.com/@zvikasegal/part-4-feature-design-cf5b5244fc7f?source=rss-33ef13129216------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf5b5244fc7f</guid>
            <dc:creator><![CDATA[Zvika Segal]]></dc:creator>
            <pubDate>Thu, 13 Aug 2020 06:53:16 GMT</pubDate>
            <atom:updated>2020-08-13T06:53:16.455Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 4 — Feature Design</h3><p>In previous posts, we have created our databases, and started our feature extraction pipeline by multiprocessing our sample in smaller batches, and loading the required dataframe for the specific feature class in each batch.</p><p>While working on the diagnosis feature class, we loaded this dataframe, based on all of the diagnoses the patients in our batch were assigned as outpatients:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKhWMGMjft4kk4Lei7fqbA.png" /></figure><p>We have a row for each diagnosis, with some additional information such as date and prescribing physician. The diagnoses are in<a href="https://en.wikipedia.org/wiki/International_Classification_of_Diseases"> ICD9 codes </a>— a globally accepted system of diagnostic codes for classifying diseases, including classifications of a wide variety of signs, symptoms, abnormal findings, complaints, social circumstances, and external causes of injury or disease. This system is designed to map health conditions to corresponding generic categories together with specific variations, assigning for these a designated code, up to six characters long.</p><p>We now want to extract some useful information from this dataframe, such as counting the amount or trend of certain diagnoses a patient was assigned in our training dataframe (number of pneumonia episodes for example). Before we can do that, we must first acknowledge 2 very important constraints:</p><p>1. there is a lot of noise in the data. A lot. Many of these diagnoses are irrelevant and we will not have any predictive value in our analysis. Just counting every possible diagnosis in the data will in fact just introduce noise into our model and interfere with our prediction. In order to prevent that, we must design our features with domain expertise, using medical reasoning to select the diagnoses we want to use</p><p>2. The ICD9 classification system is very sparse. Pneumonia, for example, has dozens of ICD9 assigned to, including various etiologies, causative agents, clinical features etc. As we are not interested usually in that level of detail, we will usually want to map all of the relevant ICD9 codes to a single diagnosis class</p><p>Let’s take our first prediction target as an example — we want to predict whether a patient is going to be diagnosed with <a href="https://en.wikipedia.org/wiki/Fibromyalgia">fibromyalgia</a>. Fibromyalgia is a disorder characterized by widespread musculoskeletal pain accompanied by fatigue, sleep, memory and mood issues. So, it makes sense for example to count the number of times a patient was diagnosed with pain-associated symptoms, such as abdominal pain or headache, mood or sleep related diagnoses etc. It will make less sense to include diagnoses related to skin disorders or trauma for example. This will be the heart of our feature design — we will use domain expertise to plan which diagnoses we want to use, and then filter the unnecessary diagnoses out.</p><p>We will use json files to keep track of our designed features in the diagnoses class. The json file will be organized like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a09dfb3fd03ad8a3368c18a905a8a79/href">https://medium.com/media/5a09dfb3fd03ad8a3368c18a905a8a79/href</a></iframe><p>We will take 3 diagnoses as an example: abdominal pain, pneumonia, and hypertension. Abdominal pain will be our positive example (we expect patients with fibromyalgia to have higher rates of abdominal pain), pneumonia will be our negative example (we expect no correlation between pneumonia and fibromyalgia) and hypertension will be an example of a categorical diagnosis class, as will be later explained.</p><p>Let’s look at the structure of the DiagnosisFeature class again. We begin every instance of the DiagnosisFeature class with loading this json:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b70a1a824b52a77ef75f4c975edc73e/href">https://medium.com/media/9b70a1a824b52a77ef75f4c975edc73e/href</a></iframe><p>After loading the outpatient diagnosis dataframe, we want to match every relevant ICD9 code in our dataframe with the relevant diagnoses class we have defined in our diagnosis json, and get rid of all of the unnecessary diagnoses. This will all happen in the merge_with_symptom_name method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48d0eb1a885473afe1480e5b3e2155fa/href">https://medium.com/media/48d0eb1a885473afe1480e5b3e2155fa/href</a></iframe><p>This method makes use of a very valuable resource: a mapping table between the ICD9 codes to diagnosis names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/0*1aULu9_LFOCOTEy8" /></figure><p>This mapping table is based on a csv file that can be downloaded here.</p><p>The first step will be to map the diagnosis names in this table to our diagnosis class -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d2d7f1fadbad82f0d3db0388ea33198/href">https://medium.com/media/0d2d7f1fadbad82f0d3db0388ea33198/href</a></iframe><p>For example, every diagnosis name which includes the word ‘pneumonia’ will be mapped to the ‘pneumonia’ diagnosis class. The returned dataframe will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/0*hwO5mHT0WoAO0WK0" /></figure><p>Now that we have a dataframe with ICD9 codes mapped to our diagnosis class, we can map this dataframe with our diagnosis dataframe on the ICD9 code columns, drop all of the diagnosis which are not mapped to any of the diagnosis classes, and get the dataframe we want:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CCLK1wm5NCAbb8xm" /></figure><p>Now that we have a dataframe with the relevant diagnoses mapped to the diagnosis classes we designed, we will be able to start calculating our features in the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf5b5244fc7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3 — Datasets]]></title>
            <link>https://medium.com/@zvikasegal/part-3-datasets-d3d533f7b5ac?source=rss-33ef13129216------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3d533f7b5ac</guid>
            <dc:creator><![CDATA[Zvika Segal]]></dc:creator>
            <pubDate>Wed, 12 Aug 2020 12:15:55 GMT</pubDate>
            <atom:updated>2020-08-12T12:15:55.701Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 3 — Datasets</h3><p>In previous posts, we have created SQLIte databases and started calculating our features. We have seen the BaseFeature class, the father class which all of the specific feature classes inherit from, and the base method in that class which controls chunking the patient sample to smaller batches and calculating the batches in parallel. In this post we will start exploring the way we compute each individual batch.</p><p>As an example we look at theDiagnosisFeature class.This feature class will include all of the features that are directly related to the diagnoses a patient was assigned in the study period — fever, pneumonia, abdominal pain etc. We will calculate features in this class in an attempt to capture as much data on these diagnoses as possible, as will be described in the future.</p><p>We will first look at the calculate_batch method in this class. As we have seen, the multiprocessing in the father BaseFeature class calls this method, which is not implemented in the father class but is implemented differently in each specific child class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b70a1a824b52a77ef75f4c975edc73e/href">https://medium.com/media/9b70a1a824b52a77ef75f4c975edc73e/href</a></iframe><p>In order for us to start our calculation, we first must load the revenant data. By now, we are quite specific in the data we want to load — we know the patient ids in our sample, and we know what kind of feature class we are currently working on (diagnosis). As we have described in the project overview, the general design of the project will be to train our models on the first 2 years of data, and use the third year for training our predictions — so we also know the timeframe we want to extract our data from.</p><p>In addition, we have to keep in mind that the relevant data for our specific feature class may be found in several different databases — in the diagnosis class case, we can find relevant diagnosis in the inpatient, outpatient and carrier tables — and these tables are all different in their structure and labels.</p><p>So in conclusion, in order to start our calculation, we must figure out a way to collect data according to patient id, feature class, and date, from several different databases — and do it in an organized and efficient manner. In order to do that, we will use the Datasets classes.</p><p>The Datasets classes are organized in a similar way to the rest of our project — a base BaseDataset class which holds some useful utility methods, and some core methods. These core methods will manage the core function of the Dataset classes — which is to extract specific data from the relevant SQL database.</p><p>Let’s look at the get_lines_from_sql_by_id_and_data method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f26dc4dffc03cd8a286560bb6794808/href">https://medium.com/media/4f26dc4dffc03cd8a286560bb6794808/href</a></iframe><p>This method connects to the database, creates an id query string using all of the ids in the batch, creates a time query string for the relevant sign and date, queries the database using the read_sql method from the pandas package, and returns the dataframe. This method is designed to be as flexible as possible, to allow us to use it for different databases, different feature classes, different time frames etc. — so we will have to explicitly tell it everything. We call this method in the father BaseDataset class from every specific child Dataset, with an instance which is specific to the feature class we are interested in. As this is quite overwhelming, let’s look at an example.</p><p>Let’s continue working on the diagnosis feature class. We want to get a dataframe which will include all of the diagnoses the patients in our sample got in an outpatient setting — so we will want to use the outpatient database.</p><p>We will use this line to get our dataframe:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baba63ea40c1c01f6b873da97fd2b650/href">https://medium.com/media/baba63ea40c1c01f6b873da97fd2b650/href</a></iframe><p>First, we create an instance of the OutpatientDataset class with the diagnosis feature class, and then we call the get patient_lines method. Let’s look at what happens in the OutpatientDataset method get_patient_lines_in_train_time we just called with the relevant patient ids -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c169772422ffbd7c0ed4325949819d4/href">https://medium.com/media/8c169772422ffbd7c0ed4325949819d4/href</a></iframe><p>Now we know the table type (outpatient), feature class (diagnosis), so we know which database to use (“OUTPATIENT_DIAGNOSIS_TABLE), and we assign it to self.table name. Since we are only fetching the diagnosis in the training time frame, we know in which time we want to get the data from, and we already got the patient ids, so we can finally call get_lines_from_sql_by_id_and_data with all of the required information.</p><p>The dataframe we just got looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKhWMGMjft4kk4Lei7fqbA.png" /></figure><p>We get in a single pandas dataframe all the data we need, in the structure we wanted — every diagnosis in a row.</p><p>In the next post, we will start extracting valuable information for our model from this dataframe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3d533f7b5ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2 — Multiprocess Feature Extraction]]></title>
            <link>https://medium.com/@zvikasegal/part-2-multiprocess-feature-extraction-193bac06f00a?source=rss-33ef13129216------2</link>
            <guid isPermaLink="false">https://medium.com/p/193bac06f00a</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[digital-health]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Zvika Segal]]></dc:creator>
            <pubDate>Tue, 11 Aug 2020 08:05:27 GMT</pubDate>
            <atom:updated>2020-08-11T08:05:27.635Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 2 — Multiprocess Feature Extraction</h3><p>In the previous post we have created SQLite databases from the raw CMS CSVs. We have designed the databases in such a way that feature extraction would be efficient and manageable, as we have multiple table types and multiple feature classes, which will require different processing and calculations.</p><p>In this post we will begin the feature extraction process. Although we are going to try and keep the calculations for our features as efficient as possible, they are still going to be quite heavy. As we will create many features for many patients, we will need to be as efficient as possible — and to achieve that, we are going to use <strong>multiprocessing</strong>. Instead of calculating the features for the entire sample of patients as a single, we will split our sample to smaller batches — and calculate the features for each of the batches in parallel.</p><p>Firse, let’s look at the general wrapper method that will control the caching and calculation for all of our different feature classes — the calculate_feature method. Each different specific feature class (e.g. diagnosis, procedures, medications etc.) will call this method from the parent BaseFeatrue class <strong>first</strong>. This method will take care of checking if the feature was already pre-calculated and cached, and calling the run_multiprocess method if it didn’t — which will then control the multiprocessing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1343986b1fa36d3357e3dd64e3111617/href">https://medium.com/media/1343986b1fa36d3357e3dd64e3111617/href</a></iframe><p>In the run_multiprocess method, we use the Pool class from the <a href="https://docs.python.org/2/library/multiprocessing.html">multiprocessing </a>module for the controlling the multiprocessing, and the tqdm module to show a progress bar for our calculations — as they might take some time to finish, we will want a convenient way to track our progress.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/073a1ea3e1041e84213ef5cdd47f6402/href">https://medium.com/media/073a1ea3e1041e84213ef5cdd47f6402/href</a></iframe><p>Using tqdm is generally very convenient — we just wrap any iterable with tqdm(iterable), and get a straightforward progress bar with very low-overhead.</p><p>Using the multiprocessing package requires some further discussion. There are 2 main classes in the multiprocessing package: Process and Pool. As can be seen in this <a href="https://www.ellicium.com/python-multiprocessing-pool-process/">great post</a>, although Pool and Process both execute the task parallely, their way of executing the task is different. The Pool distributes the tasks to the available processors using a FIFO scheduling. It maps the input to the different processors and collects the output from all the processors. After executing the calculation, it returns the output in the form of a list or array. It waits for all of the tasks to finish and then returns the output. The processes in execution are stored in memory and other non-executing processes are stored out of memory.</p><p>The Process class puts all the processes in memory and schedules execution using FIFO policy. When the process is suspended, it preempts and schedules a new process for execution. Generally, Pool is more convenient to use, and works better a large number of paralleled processes — and as we may have a large number of batches, we will use the Pool class.</p><p>Now we need to decide which method to use in the Pool class — Pool.map or Pool.imap. As described in this great <a href="https://stackoverflow.com/questions/26520781/multiprocessing-pool-whats-the-difference-between-map-async-and-imap">stackoverflow post</a>, there are 2 main differences between Pool.map and Pool.imap: the way they consume the iterable, and the way they return the results. Pool.map consumes the iterable by converting it to a list, breaking it into chunks, and sending those chunks to the worker processes. The Pool.imap just iterates over the iterable one element at a time. The other major difference is that the Pool.imap returns the results as soon as they are ready, and Pool.map only returns the results when all of the processes are done. As we want to use the tqdm module for tracking our progress, and save some memory by not storing the list the Pool.map methods creates, we will use the Pool.imap, with a chunkier — method that will generate iterable batches for us.The chunkeizer is a simple generator, which iterates over all of the patients in our data and generates batches according to the the batch size we have defined:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37f3f2a3975cf6f2c95fe13f3b88bf36/href">https://medium.com/media/37f3f2a3975cf6f2c95fe13f3b88bf36/href</a></iframe><p>The method we call in Pool.imap is calculate_batch method. This method is not implemented in the BaseFeature class, as it is implemented differently in every method in each feature class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2697dcf48b50878ea701ad7a29667a70/href">https://medium.com/media/2697dcf48b50878ea701ad7a29667a70/href</a></iframe><p>In the next post, we will start calculating our features. We will work on the caculate_batch method in the diagnosis feature class, and see how we can extract as much information as possible from our data, and do it as efficiently as possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=193bac06f00a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1 — SQLite DB creation]]></title>
            <link>https://medium.com/@zvikasegal/part-1-sqlite-db-creation-4d29aaa386bf?source=rss-33ef13129216------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d29aaa386bf</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[medicine]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Zvika Segal]]></dc:creator>
            <pubDate>Thu, 06 Aug 2020 13:12:01 GMT</pubDate>
            <atom:updated>2020-08-06T13:12:01.493Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 1 — SQLite DB creation</h3><p>In this post we will begin the preprocessing step of the medical claims data analysis pipeline.</p><p>As described in this project overview, the CMS free medical claims database is a unique database in the medical domain, as it’s the only freely available dataset which contains complete medical data for a significant sample size for a significant period of time, both in and outside of hospitals. This dataset can offer us deep insights to a patient’s health status and utilization of health-related resources. It’s important to keep in mind that this dataset is that it is synthetic — and as we will see in future posts, we have to be cautious in interpreting our results.</p><p>As most medical datasets, this data is very RAW, and needs A LOT of cleaning and preprocessing before it can be used for modeling and prediction, and we will go through this process in the following posts. In this first post of the series, we will face the first challenge of this dataset — multiple, huge csv files with 10M+ rows, structured in a way that will not fit our future feature extraction needs.</p><p>There are many ways to face this problem. In this project, we will conduct a multi step approach. First, we will create SQLite database files from the raw CSV. As the different feature classes (we have 5 different feature classes — diagnosis, procedures, costs, hospitalization and medication, see overview) will be extracted in a different manner, we will make different database files for each feature class for increased efficiency and usability in later stages of our feature creation pipeline, and allow future queries from the database to be as efficient as possible -we are going to query our database many time and for many samples in our features extraction pipeline, so it’s important to do this in an efficient way.</p><p>As this is a huge project, the entire code is presented in this github. Only a brief summary of the code will be presented here.</p><p>The DbRunner class will manage the SQLite database creation process(it inherits some usable methods from the BaseDB class). As each of the 5 main table types (inpatient, outpatient, beneficiary, carrier, medications, see overview) has a slightly different processing pipeline, the main method in the class will be run_dbs,is a simple wrapper method which will call all table-specific methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f186f3cc42835bfdaacaf59fbc9a7559/href">https://medium.com/media/f186f3cc42835bfdaacaf59fbc9a7559/href</a></iframe><p>Let’s look at an example of the one of the table specific methods which handles the creation of the outpatient databases from the outpatient csv. The create_inpatient_db method is a wrapper method which iterates over all the feature classes that are relevant for the outpatient table, and create and cache the database in the case it doesn’t exists:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eca1012f8d215ac6889c43868dbe6d80/href">https://medium.com/media/eca1012f8d215ac6889c43868dbe6d80/href</a></iframe><p>After several more steps of wrapping function, let’s look at the actual database creation method for the diagnosis feature class. The main idea of this method is to take the original csv which contains several diagnoses in each row (all originating from the same encounter), and transform it to a database in which every row represents a unique diagnosis. As we will filter specific diagnoses for feature extraction in the future, this step is crucial. This method iterates over the different diagnosis columns, creates a dataframe from the diagnosis columns and the columns containing necessary information such as date and provider ID, and concats all of the non empty rows to one huge database, which will serve us heavily in the future.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ba24cb00dfc131c25490924cee070c5/href">https://medium.com/media/0ba24cb00dfc131c25490924cee070c5/href</a></iframe><p>Then we use the convenient sqlite3 API to create the database from the pandas dataframe, and cache it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a3bc1b3c92f532e957edba3c4fc8695/href">https://medium.com/media/4a3bc1b3c92f532e957edba3c4fc8695/href</a></iframe><p>our final looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*il00OBtpWP5D0DTDuzpZRA.png" /></figure><p>Our wrapper methods make sure we carry out this procedure for every table, and every feature class. As we have 5 tables and 5 feature classes, all with specific uses and different variable names, this can be quite exhausting — especially as we have to keep track of all database and feature class names for future use. Luckily the entire process is carefully managed in the project, which can be found <a href="https://github.com/zhsegal/ClaimstoModels">in this github.</a></p><p>In the next post, we will begin to use the databases we created for feature extraction. The first step in our feature extraction process will allow us to multiprocessor our calculation, as will be described in the<a href="https://github.com/zhsegal/ClaimstoModels"> following post.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d29aaa386bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>