AI-Driven Risk Assessment & Underwriting

Technologies Used:

  • Machine Learning Framework: Scikit-learn
  • Backend Framework: Flask (to provide an API)
  • Data: We’ll simulate data to train a basic risk prediction model.
  • Frontend: HTML/CSS for user input

Tutorial Overview:

  1. Data Collection and Preprocessing
  2. Train the Machine Learning Model
  3. Create the Flask API
  4. Develop the Frontend (HTML/CSS)
  5. Deploy the Application

Step 1: Data Collection and Preprocessing

For the purpose of this tutorial, we will simulate an insurance dataset with features such as age, health, lifestyle, and smoking status. We’ll use this dataset to train a model that predicts the risk level of an applicant.

1.1 Simulated Dataset

We’ll create a dataset where:

  • Age: Age of the applicant (in years)
  • Health: Health status of the applicant (1 = Healthy, 0 = Unhealthy)
  • Lifestyle: Lifestyle of the applicant (1 = Active, 0 = Sedentary)
  • Smoker: Whether the applicant smokes (1 = Yes, 0 = No)
  • Risk: The target variable (0 = Low Risk, 1 = High Risk)

You can generate this dataset programmatically or use a CSV file for more realistic data.

pythonCopy codeimport pandas as pd

# Simulated dataset
data = {
    "Age": [25, 45, 35, 60, 30, 50, 55, 40, 29, 70],
    "Health": [1, 0, 1, 0, 1, 0, 1, 1, 1, 0],
    "Lifestyle": [1, 0, 1, 0, 1, 1, 1, 1, 0, 0],
    "Smoker": [0, 1, 0, 1, 0, 1, 1, 0, 0, 1],
    "Risk": [0, 1, 0, 1, 0, 1, 1, 0, 0, 1]  # 0 = Low Risk, 1 = High Risk
}

df = pd.DataFrame(data)

# Save to CSV for later use
df.to_csv('insurance_data.csv', index=False)

Step 2: Train the Machine Learning Model

We’ll use Scikit-learn to create a basic machine learning model for risk assessment. For simplicity, we’ll use a Logistic Regression model, which is commonly used for binary classification problems.

2.1 Install Dependencies

You will need the following libraries:

  • Pandas for data manipulation.
  • Scikit-learn for machine learning.

You can install them with:

bashCopy codepip install pandas scikit-learn

2.2 Train the Model

Create a Python script to train the logistic regression model on our dataset:

pythonCopy codeimport pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import pickle

# Load the dataset
df = pd.read_csv('insurance_data.csv')

# Features and target
X = df[['Age', 'Health', 'Lifestyle', 'Smoker']]
y = df['Risk']

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Create and train the logistic regression model
model = LogisticRegression()
model.fit(X_train, y_train)

# Make predictions and evaluate the model
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy * 100:.2f}%")

# Save the model to a file
with open('risk_assessment_model.pkl', 'wb') as f:
    pickle.dump(model, f)

2.3 Explanation of the Code:

  • Train-Test Split: We divide the data into training and testing sets to evaluate the model’s performance.
  • Logistic Regression: We use logistic regression to predict the risk (low or high).
  • Accuracy: We check how well the model performs using accuracy.

After training, we save the model using pickle so we can load it in our Flask API.


Step 3: Create the Flask API

Now, we’ll create a Flask API that will:

  • Load the trained model.
  • Accept user input.
  • Make predictions using the trained model.

3.1 Install Flask

If you haven’t already, install Flask:

bashCopy codepip install flask

3.2 Flask API (server.py)

Create a server.py file to serve the model:

pythonCopy codefrom flask import Flask, request, jsonify
import pickle
import numpy as np

app = Flask(__name__)

# Load the trained model
with open('risk_assessment_model.pkl', 'rb') as f:
    model = pickle.load(f)

@app.route('/')
def home():
    return "Welcome to the AI Risk Assessment API!"

# Predict the risk of a new insurance applicant
@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json()
    
    # Extract features from the request data
    age = data['age']
    health = data['health']
    lifestyle = data['lifestyle']
    smoker = data['smoker']
    
    # Prepare the feature vector
    features = np.array([[age, health, lifestyle, smoker]])
    
    # Make prediction
    prediction = model.predict(features)
    
    # Return the result
    risk_level = 'High Risk' if prediction[0] == 1 else 'Low Risk'
    
    return jsonify({
        'prediction': risk_level
    })

if __name__ == "__main__":
    app.run(debug=True)

3.3 Explanation of the Flask API:

  • Home Route: A simple endpoint to check if the server is running.
  • Predict Route: A POST endpoint that accepts user data (age, health, lifestyle, smoker status) and returns the risk level (Low Risk or High Risk) based on the trained model.

The predict() function expects a JSON request with the following structure:

jsonCopy code{
  "age": 45,
  "health": 0,
  "lifestyle": 1,
  "smoker": 0
}

Step 4: Develop the Frontend (HTML/CSS)

Now, let’s create a simple frontend to interact with the Flask API. We’ll use basic HTML and JavaScript to capture user input and send it to the backend.

4.1 Frontend (index.html)

htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Risk Assessment</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <h1>AI Risk Assessment for Insurance</h1>
        <form id="riskForm">
            <label for="age">Age:</label>
            <input type="number" id="age" required>

            <label for="health">Health (1 = Healthy, 0 = Unhealthy):</label>
            <input type="number" id="health" required>

            <label for="lifestyle">Lifestyle (1 = Active, 0 = Sedentary):</label>
            <input type="number" id="lifestyle" required>

            <label for="smoker">Smoker (1 = Yes, 0 = No):</label>
            <input type="number" id="smoker" required>

            <button type="submit">Submit</button>
        </form>

        <h2>Risk Assessment Result:</h2>
        <div id="result"></div>
    </div>

    <script src="script.js"></script>
</body>
</html>

4.2 Styles (style.css)

cssCopy codebody {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
}

.container {
    width: 50%;
    margin: 50px auto;
    background-color: white;
    padding: 20px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

h1 {
    text-align: center;
}

form input, form button {
    width: 100%;
    padding: 10px;
    margin: 10px 0;
}

button {
    background-color: #4CAF50;
    color: white;
    border: none;
    cursor: pointer;

4o mini


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *