AI-in-Healthcare1

Introduction

Artificial Intelligence (AI) is increasingly being used in healthcare to analyze large datasets, support clinical workflows, automate repetitive tasks, and identify patterns that may be difficult to detect manually.

For .NET developers, this creates opportunities to build healthcare applications using familiar technologies such as C#, ASP.NET Core, ML.NET, ONNX Runtime, and Azure AI services.

However, healthcare AI is different from a typical machine learning application. Patient information is sensitive, model predictions can affect clinical decisions, and accuracy, explainability, privacy, and validation are critical.

In this article, we will look at practical ways to integrate AI into healthcare applications using C# and .NET. We will start with a simple patient readmission prediction example using ML.NET, then look at ONNX model inference and clinical text analysis using Azure AI.

Important: The examples in this article are educational demonstrations. They are not medical diagnostic systems and should not be used to make clinical decisions without appropriate validation and regulatory review.

Why AI Matters in Healthcare

Healthcare systems generate large amounts of structured and unstructured information.

Examples include:

AI and machine learning can help process this information for specific, well-defined tasks.

Common applications include:

The important distinction is that AI should generally support healthcare professionals rather than replace clinical judgment.

adobestock_380560388.jpeg

Key AI Technologies Used in Healthcare

Different healthcare problems require different AI techniques.

Machine Learning

Machine learning can be used to identify patterns in historical data and generate predictions.

Examples include:

ML.NET allows .NET developers to train and consume machine learning models from C# applications. For binary classification, ML.NET supports trainers including LightGBM, SDCA, FastTree, and others.

Deep Learning

Deep learning models are commonly used for complex tasks such as image and signal analysis.

Potential healthcare applications include:

The model may be trained using a machine learning framework such as PyTorch or TensorFlow and exported to ONNX for deployment.

Natural Language Processing

Healthcare organizations generate a large amount of text through clinical notes, discharge summaries, reports, and other documents.

NLP can be used for:

Microsoft's current Azure AI Language tooling provides .NET support for text-analysis scenarios including sentiment analysis, entity recognition, PII recognition, summarization, and healthcare entity analysis.

Building a Patient Readmission Prediction Model with ML.NET

Let's create a small demonstration that predicts whether a patient may be readmitted.

This is a machine learning example, not a clinical prediction model. A real healthcare model would require a properly curated dataset, clinical validation, appropriate evaluation metrics, privacy controls, and domain-expert review.

Step 1: Create the Project

Create a console application:

dotnet new console -n HealthcareAiDemo
cd HealthcareAiDemo

Add ML.NET:

dotnet add package Microsoft.ML
dotnet add package Microsoft.ML.FastTree

Step 2: Define the Patient Data Model

Create a PatientData class:

public class PatientData
{
    public float Age { get; set; }

    public float BloodPressure { get; set; }

    public float Cholesterol { get; set; }

    public bool Readmitted { get; set; }
}

The Readmitted property is the label that the model will attempt to predict.

Step 3: Create the Prediction Model

Create a class to represent the prediction result:

public class ReadmissionPrediction
{
    public bool PredictedLabel { get; set; }

    public float Probability { get; set; }

    public float Score { get; set; }
}

Step 4: Load Training Data

For demonstration purposes, assume that patients.csv contains historical training data.

var mlContext = new MLContext(seed: 1);

IDataView data = mlContext.Data.LoadFromTextFile<PatientData>(
    "patients.csv",
    hasHeader: true,
    separatorChar: ',');

A real implementation should use a carefully prepared dataset rather than a small demonstration file.

The dataset should also be evaluated for missing values, class imbalance, data leakage, and representative coverage of the target population.

Step 5: Build the ML.NET Pipeline

The numerical columns can be combined into a feature vector:

var pipeline = mlContext.Transforms
    .Concatenate(
        "Features",
        nameof(PatientData.Age),
        nameof(PatientData.BloodPressure),
        nameof(PatientData.Cholesterol))
    .Append(
        mlContext.BinaryClassification.Trainers.LightGbm(
            labelColumnName: nameof(PatientData.Readmitted),
            featureColumnName: "Features"));

The pipeline defines how the input data is transformed before being supplied to the classifier.

Step 6: Train the Model

Train the model using the historical data:

var model = pipeline.Fit(data);

At this point, ML.NET has trained the classifier using the supplied training dataset.

Step 7: Make a Prediction

Create a prediction engine:

var predictionEngine =
    mlContext.Model.CreatePredictionEngine<
        PatientData,
        ReadmissionPrediction>(model);

Create a sample patient:

var patient = new PatientData
{
    Age = 65,
    BloodPressure = 140,
    Cholesterol = 220
};

Run the prediction:

var prediction = predictionEngine.Predict(patient);

Console.WriteLine(
    $"Predicted Readmission: {prediction.PredictedLabel}");

Console.WriteLine(
    $"Probability: {prediction.Probability:P2}");

Step 8: Expected Output

A sample console result may look like:

Predicted Readmission: True
Probability: 78.42%

The exact output depends on the training dataset and the model.

This is where the author's actual output screenshot should be added to satisfy the editor's request. The screenshot should show the application running with the real result generated from the author's POC.

What This Example Demonstrates

The complete flow is:

Patient Data
     |
     v
ML.NET Data Loading
     |
     v
Feature Transformation
     |
     v
LightGBM Classification
     |
     v
Trained Model
     |
     v
New Patient Data
     |
     v
Prediction

This architecture can be exposed through an ASP.NET Core API when the model needs to be consumed by a web or mobile application.

Evaluating a Healthcare ML Model

Generating a prediction is not enough for a real healthcare system.

A model should be evaluated using appropriate metrics and a dataset that represents the intended population.

For a binary classification problem, useful metrics can include:

For healthcare applications, accuracy alone can be misleading.

For example, if a dataset contains many more non-readmitted patients than readmitted patients, a model could achieve high accuracy while performing poorly at identifying patients in the minority class.

This is why model evaluation should be designed around the actual clinical or operational objective.

Running an ONNX Model with C#

Machine learning models do not always need to be trained inside .NET.

A common architecture is:

Python / ML Framework
        |
        v
   Train Model
        |
        v
    Export ONNX
        |
        v
.NET Application
        |
        v
 ONNX Runtime
        |
        v
    Prediction

ONNX Runtime provides a C# API for running ONNX models from .NET applications. Its current C# documentation recommends the OrtValue API for new development, while older APIs such as NamedOnnxValue are being deprecated.

Step 1: Install ONNX Runtime

Add the ONNX Runtime package:

dotnet add package Microsoft.ML.OnnxRuntime

The exact package version should be selected according to the application's supported .NET/runtime environment.

Step 2: Load the ONNX Model

A basic inference application can create an ONNX Runtime session:

using Microsoft.ML.OnnxRuntime;

using var session = new InferenceSession("xray_model.onnx");

The model must be compatible with the input data and tensor shape supplied by the application.

Step 3: Prepare the Model Input

For an image model, the application normally needs to:

  1. Load the image.

  2. Resize it according to the model requirements.

  3. Normalize pixel values if required.

  4. Convert the image into the expected tensor layout.

  5. Supply the tensor to the model.

For example, a model may expect:

Batch = 1
Channels = 1
Height = 224
Width = 224

The exact dimensions depend entirely on the model.

Important

The following example is intentionally schematic because the preprocessing requirements are model-specific:

Medical Image
     |
     v
Resize
     |
     v
Normalize
     |
     v
Tensor Conversion
     |
     v
ONNX Runtime
     |
     v
Model Output

Using the wrong image dimensions, normalization values, channel order, or tensor layout can produce incorrect predictions even when the model executes successfully.

Step 4: Run Inference

With the input tensor prepared according to the model's contract, the application can execute inference through ONNX Runtime.

The current C# API supports OrtValue-based inference:

using Microsoft.ML.OnnxRuntime;

using var session = new InferenceSession("xray_model.onnx");

// Prepare input according to the model's input specification.
// Create OrtValue objects for the actual tensor data.

using var results = session.Run(
    new Dictionary<string, OrtValue>
    {
        // "input" = inputOrtValue
    });

The exact implementation depends on the ONNX model's input and output definitions.

Expected Output

A medical imaging model might return a probability or classification score such as:

Model Output

Class: ExampleCondition
Probability: 0.91

This value should not automatically be presented to a patient as a diagnosis.

A production system needs appropriate validation, thresholds, clinical interpretation, auditability, and human oversight.

NLP for Clinical Text

Clinical documents contain valuable information that may not be stored in structured database fields.

For example:

Patient reports persistent elevated blood pressure.
History indicates diabetes.
Follow-up recommended.

An NLP system can process such text and identify relevant entities or other information.

Using Azure AI Language with C#

Azure AI Language provides .NET client libraries for text analysis.

Add the appropriate Azure AI Language package for the service functionality being used.

For the Azure AI Text Analytics SDK, a client can be created using an endpoint and credential:

using Azure;
using Azure.AI.TextAnalytics;

var endpoint = new Uri(
    Environment.GetEnvironmentVariable("AZURE_LANGUAGE_ENDPOINT")!);

var credential = new AzureKeyCredential(
    Environment.GetEnvironmentVariable("AZURE_LANGUAGE_KEY")!);

var client = new TextAnalyticsClient(
    endpoint,
    credential);

Microsoft's current .NET API exposes operations such as sentiment analysis and named-entity recognition through TextAnalyticsClient.

Analyzing Clinical Text

For example:

string text =
    "The patient reports persistent fatigue and elevated blood pressure.";

var response = await client.AnalyzeSentimentAsync(text);

Console.WriteLine(
    $"Sentiment: {response.Value.Sentiment}");

For a clinical system, sentiment analysis may not be the most useful NLP task. Entity recognition, PII detection, healthcare entity extraction, classification, or summarization may be more appropriate depending on the actual requirement.

The important point is to choose the NLP task based on the problem rather than adding AI simply because the technology is available.

Expected NLP Output

A sample output could look like:

Sentiment: Neutral

Again, the output depends on the supplied text and the selected model.

For a healthcare NLP implementation, the author's screenshot should show the actual application output from the POC.

Healthcare AI Architecture with ASP.NET Core

A practical .NET healthcare AI system could use ASP.NET Core as the application layer.

A simplified architecture is:

                    Healthcare Application
                             |
                             v
                     ASP.NET Core API
                             |
              +--------------+--------------+
              |              |              |
              v              v              v
           ML.NET       ONNX Runtime    Azure AI
              |              |              |
              +--------------+--------------+
                             |
                             v
                    Model / AI Results
                             |
                             v
                   Application Response

For example, an ASP.NET Core API could expose an endpoint such as:

POST /api/predictions/readmission

The API could receive appropriately structured input, execute the model, apply application-level validation, and return a prediction to an authorized client.

Protecting Healthcare Data

Healthcare applications must treat patient information as sensitive data.

Important security considerations include:

The exact legal and regulatory requirements depend on the country, organization, data type, and deployment scenario. HIPAA should not be treated as a universal compliance label for every healthcare application.

Model Security and Reliability

Protecting the database and API is only part of the problem.

AI models also need to be treated as production components.

Developers should consider:

A model that performs well on historical training data may behave differently when exposed to real-world data.

AI Should Support Clinical Decisions

A healthcare AI application should have clearly defined boundaries.

For example:

Patient Data
     |
     v
AI Model
     |
     v
Risk / Prediction
     |
     v
Clinical Review
     |
     v
Final Decision

The AI output should not automatically become a medical diagnosis or treatment recommendation without appropriate clinical validation and governance.

This distinction is especially important when developing demonstrations that could otherwise be mistaken for production medical systems.

Real-World Healthcare AI Use Cases

Patient Risk Prediction

Machine learning can help identify patients who may require additional attention based on historical and current data.

Medical Image Analysis

Computer vision models can assist trained professionals by highlighting patterns in medical images.

Clinical Text Processing

NLP can help extract structured information from unstructured documents.

Remote Patient Monitoring

AI systems can process data from connected devices and generate alerts when predefined conditions are detected.

Healthcare Operations

Machine learning can also support non-clinical workflows such as:

These operational applications can sometimes be easier to validate than systems making direct clinical recommendations.

Common Challenges

Data Quality

A model is only as reliable as the data used to train and evaluate it.

Missing values, inconsistent terminology, duplicated records, and biased datasets can affect model performance.

Privacy

Healthcare datasets can contain personally identifiable and highly sensitive information. Data minimization and appropriate security controls are essential.

Explainability

When an AI system produces an important prediction, users may need to understand why the prediction was generated.

Bias

A model trained on a limited population may not perform equally well across different populations.

Integration

Healthcare organizations often have existing applications, databases, and interoperability requirements. Connecting an AI system to those environments can be more difficult than building the model itself.

Clinical Validation

A technically accurate model is not automatically a clinically useful model.

Clinical experts should be involved in defining requirements, validating results, and determining how predictions should be used.

Best Practices for .NET Healthcare AI Projects

Start with a Specific Problem

Instead of starting with:

"We need AI."

start with:

"We need to predict a specific operational or clinical risk
using a defined set of validated data."

This makes it easier to define the model, data requirements, success metrics, and validation process.

Use Synthetic or De-Identified Data During Development

Developers should avoid using real patient information unnecessarily during development and testing.

Keep AI Separate from Business Logic

A useful architecture is to isolate model inference behind a service boundary.

For example:

ASP.NET Core API
      |
      v
Prediction Service
      |
      v
AI Model

This makes the model easier to test, replace, monitor, and version.

Validate Before Deployment

Do not deploy a healthcare model based only on a successful training run.

Evaluate the model using appropriate validation datasets and metrics, and involve relevant healthcare experts.

What the Author Should Add to the POC

Because the editor specifically requested a personal and practical implementation, the author should add genuine material from their own POC.

The revised submission should include screenshots such as:

  1. Creating the .NET project.

  2. Installing the ML.NET package.

  3. Loading the training dataset.

  4. Training the model.

  5. Running the prediction.

  6. Showing the actual prediction output.

  7. Running the ONNX model, if implemented.

  8. Showing the actual Azure AI text-analysis result.

  9. Showing the final application/API response.

The screenshots should come from the author's actual environment rather than generic or generated images.

The author should also add a short section explaining what they personally observed while implementing the example, such as:

These details should be written by the author from their actual experience.

Suggested POC Structure

A complete demonstration project could be organized like this:

HealthcareAiDemo
│
├── Data
│   └── patients.csv
│
├── Models
│   ├── PatientData.cs
│   └── ReadmissionPrediction.cs
│
├── Services
│   └── PredictionService.cs
│
├── Program.cs
└── HealthcareAiDemo.csproj

If the author implements multiple demonstrations, separate projects can be used:

HealthcareAI.sln
│
├── MLNetReadmissionDemo
├── OnnxInferenceDemo
└── AzureLanguageDemo

The complete source code can then be packaged as a ZIP file and attached to the article submission, as requested by the editor.

Conclusion

AI can help healthcare organizations process data, identify patterns, automate selected workflows, and support professionals with additional information.

For C# and .NET developers, technologies such as ML.NET, ONNX Runtime, ASP.NET Core, and Azure AI provide several ways to integrate machine learning and AI capabilities into applications.

The implementation itself is only one part of a healthcare AI solution. Data privacy, model validation, security, fairness, explainability, clinical oversight, and operational monitoring are equally important.

The strongest healthcare AI applications are not simply the ones that produce predictions. They are the ones that solve a clearly defined problem, use appropriate and validated data, provide understandable results, and fit safely into the workflow in which they are used.