Web app to Predict Maternal Risk using IRIS IntegratedML
Tags: ai, programming, tutorial
Published: 2023-07-15 21:31:11

Maternal Risk can be measured from some parameters well known to the medical community. In this way, in order to help the medical community and computerized systems, especially AI, the scientist Yasir Hussein Shakir published a very useful dataset for training ML algorithms in the detection/prediction of Maternal Risk. This publication can be found on the largest and best known data repository for ML, Kaggle at https://www.kaggle.com/code/yasserhessein/classification-maternal-health-5-algorithms-ml.

## About the Dataset

Many pregnant women die from pregnancy issues as a result of a lack of information on maternal health care during and after pregnancy. It is more common in rural regions and among lower-middle-class families in emerging countries. During pregnancy, every minute should be observed to ensure the proper growth of the baby and the safe delivery (source: https://www.kaggle.com/code/yasserhessein/classification-maternal-health-5-algorithms-ml).

Data has been collected from different hospitals, community clinics, maternal health cares through the IoT based risk monitoring system.

  * Age: Age in years when a woman is pregnant.
  * SystolicBP: Upper value of Blood Pressure in mmHg, another significant attribute during pregnancy.
  * DiastolicBP: Lower value of Blood Pressure in mmHg, another significant attribute during pregnancy.
  * BS: Blood glucose levels is in terms of a molar concentration, mmol/L.
  * HeartRate: A normal resting heart rate in beats per minute.
  * Risk Level: Predicted Risk Intensity Level during pregnancy considering the previous attribute.

## Get the Maternal Risk data from Kaggle

The Maternal Risk data from Kaggle can be loaded into an IRIS table using the Health-Dataset application: https://openexchange.intersystems.com/package/Health-Dataset. To do this, from your module.xml project, set the dependency (ModuleReference for Health Dataset):

Module.xml with Health Dataset application reference
```
<?xml version="1.0" encoding="UTF-8"?>
<Export generator="Cache" version="25">
  <Document name="predict-diseases.ZPM">
    <Module>
      <Name>predict-diseases</Name>
      <Version>1.0.0</Version>
      <Packaging>module</Packaging>
      <SourcesRoot>src/iris</SourcesRoot>
      <Resource Name="dc.predict.disease.PKG"/>
      <Dependencies>
        <ModuleReference>
          <Name>swagger-ui</Name>
          <Version>1.*.*</Version>
        </ModuleReference>
        <ModuleReference>
          <Name>dataset-health</Name>
          <Version>*</Version>
        </ModuleReference>
      </Dependencies>
       <CSPApplication
        Url="/predict-diseases"
        DispatchClass="dc.predict.disease.PredictDiseaseRESTApp"
        MatchRoles=":{$dbrole}"
        PasswordAuthEnabled="1"
        UnauthenticatedEnabled="1"
        Recurse="1"
        UseCookies="2"
        CookiePath="/predict-diseases"
       />
       <CSPApplication
        CookiePath="/disease-predictor/"
        DefaultTimeout="900"
        SourcePath="/src/csp"
        DeployPath="${cspdir}/csp/${namespace}/"
        MatchRoles=":{$dbrole}"
        PasswordAuthEnabled="0"
        Recurse="1"
        ServeFiles="1"
        ServeFilesTimeout="3600"
        UnauthenticatedEnabled="1"
        Url="/disease-predictor"
        UseSessionCookie="2"
      />
    </Module>
   
  </Document>
</Export>
```
        
***Web Frontend and Backend Application to Predict Maternal Risk***

Go to Open Exchange  app link (https://openexchange.intersystems.com/package/Disease-Predictor) and follow these steps:

1.Clone/git pull the repo into any local directory

```
$ git clone https://github.com/yurimarx/predict-diseases.git
```

2.Open a Docker terminal in this directory and run:

```
$ docker-compose build
```

3.Run the IRIS container:

```
$ docker-compose up -d 
```

4.Go to Execute Query into Management Portal to train the AI model: http://localhost:52773/csp/sys/exp/%25CSP.UI.Portal.SQL.Home.zen?$NAMESPACE=USER

5.Create the VIEW used to train:

```
CREATE VIEW MaternalRiskTrain AS SELECT BS, BodyTemp, DiastolicBP, HeartRate, RiskLevel, SystolicBP, age FROM dc_data_health.MaternalHealthRisk 
```

6.Create the AI Model using the view:

```
CREATE MODEL MaternalRiskModel PREDICTING (RiskLevel) FROM MaternalRiskTrain 
```

7.Train the model:

```
TRAIN MODEL MaternalRiskModel
```

8.Go to http://localhost:52773/disease-predictor/index.html to use the Disease Predictor frontend and predict diseases like this:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ins2udstfst47huh797v.png)

**Behind the scenes**

***Backend ClassMethod to predict MaternalRisk Disease***
InterSystems IRIS allows you execute SELECT to predict using the previous model created.

Backend ClassMethod to predict Maternal Risk

```
/// Predict Maternal Risk
ClassMethod PredictMaternalRisk() As %Status
{
    Try {
      Set data = {}.%FromJSON(%request.Content)
      Set %response.Status = 200
      Set %response.Headers("Access-Control-Allow-Origin")="*"
     
      Set qry = "SELECT PREDICT(MaternalRiskModel) As PredictedMaternalRisk, "
                  _"age, BS, BodyTemp, DiastolicBP, HeartRate, SystolicBP "
                  _"FROM (SELECT "_data.BS_" AS BS, "
                  _data.BodyTemp_" As BodyTemp, "
                  _data.DiastolicBP_" AS DiastolicBP, "
                  _data.HeartRate_" AS HeartRate, "
                  _data.SystolicBP_" As SystolicBP, "
                  _data.Age_" AS age)"
      Set tStatement = ##class(%SQL.Statement).%New()
      Set qStatus = tStatement.%Prepare(qry)
      If qStatus'=1 {WRITE "%Prepare failed:" DO $System.Status.DisplayError(qStatus) QUIT}
      Set rset = tStatement.%Execute()
      Do rset.%Next()
 
      Set Response = {}
      Set Response.PredictedMaternalRisk = rset.PredictedMaternalRisk
      Set Response.Age = rset.Age
      Set Response.SystolicBP = rset.SystolicBP
      Set Response.DiastolicBP = rset.DiastolicBP
      Set Response.BS = rset.BS
      Set Response.BodyTemp = rset.BodyTemp
      Set Response.HeartRate = rset.HeartRate
 
      Write Response.%ToJSON()
      Return 1
     
    } Catch err {
      write !, "Error name: ", ?20, err.Name,
          !, "Error code: ", ?20, err.Code,
          !, "Error location: ", ?20, err.Location,
          !, "Additional data: ", ?20, err.Data, !
      Return 0
    }
}
```
Now, any web application can consume the prediction and show the results. See the source code into frontend folder to predict-diseases application.