{
"cells": [
{
"cell_type": "markdown",
"id": "c01ffe8d-3916-478f-a9c5-f3b480e5e293",
"metadata": {},
"source": [
"# Copyright Rayyan Hodges, TAFE NSW, Gelos Enterprises, Indigo Community Services and Health Hub © 2026"
]
},
{
"cell_type": "markdown",
"id": "b9f47b2c-6f01-479a-a87b-e698effc6edf",
"metadata": {},
"source": [
"# Contact: rayyan.hodges@studytafensw.edu.au, rayyan.hodges@gelosmail.com.au indigoCSHH@hmail.com"
]
},
{
"cell_type": "markdown",
"id": "c49336b7-8ec3-4a18-8590-4cd6c02917cb",
"metadata": {},
"source": [
"# Program Name: HopsitalCancerClassification.ipynb"
]
},
{
"cell_type": "markdown",
"id": "59691122-a537-4615-8a65-f408eb6fcffb",
"metadata": {},
"source": [
"# Purpose: To train and evaluate an ML model to automate the task of classifying clients as high, medium or low risk of developing cancer."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "1092545b-8be3-487b-87df-d8829e0a00eb",
"metadata": {},
"outputs": [],
"source": [
"# Import required libraries\n",
"import joblib\n",
"import numpy\n",
"import pandas as pd\n",
"import sklearn # importing the scikit-learn project, different name due to syntax rules \n",
"import scipy\n",
"import threadpoolctl"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "3a05014a-200c-4bc6-9667-568898547852",
"metadata": {},
"outputs": [],
"source": [
"# Set appropriate display options in Pandas\n",
"pd.set_option('display.max_rows', 10000)\n",
"pd.set_option('display.max_columns', 10000)\n",
"pd.set_option('display.width', 10000)"
]
},
{
"cell_type": "markdown",
"id": "95ffdbd6-b7e7-41b9-990f-932a05cae2e6",
"metadata": {},
"source": [
"# Identify any datapoints with missing labels and remove them"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "10d93e7f-9ba8-45a4-831d-7ba48046fea7",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"np.int64(10)"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Load the data set into memory and define it for further analysis.\n",
"df = pd.read_csv(\"data.csv\")\n",
"# Check for missing values in the target column, count them, and display them in a total number.\n",
"df['cancer_risk'].isnull().sum()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "3434f6bb-7cdb-4434-a948-1dc7d9e7d260",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"np.int64(0)"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Remove the affected rows with missing data\n",
"df = df.dropna(subset=['cancer_risk'])\n",
"# Verify removal of said invalid data.\n",
"df['cancer_risk'].isnull().sum()"
]
},
{
"cell_type": "markdown",
"id": "44a9b1bc-0c6c-4e9e-95a7-03d3108b696b",
"metadata": {},
"source": [
"# Categorise ages as required."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "a8887198-0dbd-471d-bd1e-836d34def83a",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"
\n",
"\n",
"
\n",
" \n",
" \n",
" \n",
" age \n",
" age_group \n",
" \n",
" \n",
" \n",
" \n",
" 0 \n",
" 51 \n",
" 45-54 \n",
" \n",
" \n",
" 1 \n",
" 92 \n",
" 85+ \n",
" \n",
" \n",
" 2 \n",
" 14 \n",
" 0-14 \n",
" \n",
" \n",
" 3 \n",
" 71 \n",
" 65-74 \n",
" \n",
" \n",
" 4 \n",
" 60 \n",
" 55-64 \n",
" \n",
" \n",
"
\n",
"
"
],
"text/plain": [
" age age_group\n",
"0 51 45-54\n",
"1 92 85+\n",
"2 14 0-14\n",
"3 71 65-74\n",
"4 60 55-64"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Define age bins and labels for the groups\n",
"# Bins meaning boundaries \n",
"bins = [0, 14, 24, 34, 44, 54, 64, 74, 84, 120]\n",
"labels = ['0-14', '15-24', '25-34', '35-44', \n",
" '45-54', '55-64', '65-74', '75-84', '85+']\n",
"\n",
"# Categorise ages into age groups\n",
"df['age_group'] = pd.cut(df['age'], bins=bins, labels=labels, right=True)\n",
"\n",
"# Display the results in a table\n",
"df[['age', 'age_group']].head()\n"
]
},
{
"cell_type": "markdown",
"id": "b2751d18-2580-453a-b0d9-70bc956f73cc",
"metadata": {},
"source": [
"# Standardise numerical features using appropriate scaling techniques."
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "f9beff06-ce08-479d-b63d-56ca8aaf6338",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"\n",
"
\n",
" \n",
" \n",
" \n",
" bmi \n",
" blood_pressure \n",
" \n",
" \n",
" \n",
" \n",
" count \n",
" 9.900000e+02 \n",
" 9.900000e+02 \n",
" \n",
" \n",
" mean \n",
" 1.076580e-17 \n",
" 1.130409e-16 \n",
" \n",
" \n",
" std \n",
" 1.000505e+00 \n",
" 1.000505e+00 \n",
" \n",
" \n",
" min \n",
" -1.679483e+00 \n",
" -1.699762e+00 \n",
" \n",
" \n",
" 25% \n",
" -8.839714e-01 \n",
" -8.598235e-01 \n",
" \n",
" \n",
" 50% \n",
" 6.927133e-04 \n",
" -1.794981e-02 \n",
" \n",
" \n",
" 75% \n",
" 8.853568e-01 \n",
" 8.703721e-01 \n",
" \n",
" \n",
" max \n",
" 1.735732e+00 \n",
" 1.772241e+00 \n",
" \n",
" \n",
"
\n",
"
"
],
"text/plain": [
" bmi blood_pressure\n",
"count 9.900000e+02 9.900000e+02\n",
"mean 1.076580e-17 1.130409e-16\n",
"std 1.000505e+00 1.000505e+00\n",
"min -1.679483e+00 -1.699762e+00\n",
"25% -8.839714e-01 -8.598235e-01\n",
"50% 6.927133e-04 -1.794981e-02\n",
"75% 8.853568e-01 8.703721e-01\n",
"max 1.735732e+00 1.772241e+00"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Import the scaling component from the SciKit Learning Library\n",
"from sklearn.preprocessing import StandardScaler\n",
"\n",
"# Select numerical features from the datasheet.\n",
"numerical_features = ['bmi', 'blood_pressure']\n",
"\n",
"# Initialise scaler component\n",
"scaler = StandardScaler()\n",
"\n",
"# Apply scaling and transformation to standardise the numbers.\n",
"df[numerical_features] = scaler.fit_transform(df[numerical_features])\n",
"\n",
"# Display results from the scaling and transformation.\n",
"df[numerical_features].describe()\n"
]
},
{
"cell_type": "markdown",
"id": "2616a37d-bffd-4a8d-b648-24673a543e7d",
"metadata": {},
"source": [
"# Encode categorical data using appropriate encoding techniques."
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "8bc14115-e855-4233-9058-eff0ce5c9386",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"\n",
"
\n",
" \n",
" \n",
" \n",
" age \n",
" family_history \n",
" alcohol_consumption \n",
" bmi \n",
" blood_pressure \n",
" cholesterol_level \n",
" travelled_overseas \n",
" number_of_children \n",
" cancer_risk \n",
" age_group_15-24 \n",
" age_group_25-34 \n",
" age_group_35-44 \n",
" age_group_45-54 \n",
" age_group_55-64 \n",
" age_group_65-74 \n",
" age_group_75-84 \n",
" age_group_85+ \n",
" smoking_history_former \n",
" smoking_history_never \n",
" diet_good \n",
" diet_poor \n",
" exercise_frequency_low \n",
" exercise_frequency_moderate \n",
" exercise_frequency_none \n",
" \n",
" \n",
" \n",
" \n",
" 0 \n",
" 51 \n",
" no \n",
" low \n",
" 0.487601 \n",
" 1.629026 \n",
" 226.4 \n",
" no \n",
" 5 \n",
" moderate \n",
" False \n",
" False \n",
" False \n",
" True \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" True \n",
" False \n",
" True \n",
" False \n",
" False \n",
" True \n",
" \n",
" \n",
" 1 \n",
" 92 \n",
" no \n",
" moderate \n",
" -1.487463 \n",
" 1.396785 \n",
" 170.9 \n",
" yes \n",
" 2 \n",
" low \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" True \n",
" False \n",
" True \n",
" False \n",
" True \n",
" False \n",
" False \n",
" False \n",
" \n",
" \n",
" 2 \n",
" 14 \n",
" no \n",
" none \n",
" 0.528748 \n",
" 0.568459 \n",
" 279.9 \n",
" yes \n",
" 4 \n",
" high \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" True \n",
" \n",
" \n",
" 3 \n",
" 71 \n",
" yes \n",
" low \n",
" 1.667153 \n",
" -0.101170 \n",
" 280.7 \n",
" yes \n",
" 0 \n",
" moderate \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" True \n",
" False \n",
" False \n",
" True \n",
" False \n",
" False \n",
" True \n",
" False \n",
" False \n",
" False \n",
" \n",
" \n",
" 4 \n",
" 60 \n",
" no \n",
" none \n",
" -1.446316 \n",
" 0.649743 \n",
" 212.8 \n",
" yes \n",
" 5 \n",
" moderate \n",
" False \n",
" False \n",
" False \n",
" False \n",
" True \n",
" False \n",
" False \n",
" False \n",
" True \n",
" False \n",
" False \n",
" False \n",
" False \n",
" False \n",
" True \n",
" \n",
" \n",
"
\n",
"
"
],
"text/plain": [
" age family_history alcohol_consumption bmi blood_pressure cholesterol_level travelled_overseas number_of_children cancer_risk age_group_15-24 age_group_25-34 age_group_35-44 age_group_45-54 age_group_55-64 age_group_65-74 age_group_75-84 age_group_85+ smoking_history_former smoking_history_never diet_good diet_poor exercise_frequency_low exercise_frequency_moderate exercise_frequency_none\n",
"0 51 no low 0.487601 1.629026 226.4 no 5 moderate False False False True False False False False False True False True False False True\n",
"1 92 no moderate -1.487463 1.396785 170.9 yes 2 low False False False False False False False True False True False True False False False\n",
"2 14 no none 0.528748 0.568459 279.9 yes 4 high False False False False False False False False False False False False False False True\n",
"3 71 yes low 1.667153 -0.101170 280.7 yes 0 moderate False False False False False True False False True False False True False False False\n",
"4 60 no none -1.446316 0.649743 212.8 yes 5 moderate False False False False True False False False True False False False False False True"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Identify categorical features from the dataset file to be referenced.\n",
"categorical_features = ['age_group', 'smoking_history', 'diet', 'exercise_frequency']\n",
"\n",
"# Apply one-hot encoding to convert the text categories into dummy numerical categories (specifically true or false)\n",
"df_encoded = pd.get_dummies(df, columns=categorical_features, drop_first=True)\n",
"\n",
"# Print the results to ensure the categorical features have been converted to variables such as true or false correctly.\n",
"df_encoded.head()\n"
]
},
{
"cell_type": "markdown",
"id": "3b6926b7-31d0-4558-9695-c16570087104",
"metadata": {},
"source": [
"# Divide and randomise the dataset into training"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "a5174be9-c40b-457e-afd5-1ec97c70ed0a",
"metadata": {
"scrolled": true
},
"outputs": [
{
"data": {
"text/plain": [
"((693, 23), (148, 23), (149, 23))"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"\n",
"# Remove rows with missing target labels (specifically, the 'cancer_risk' label, as it has missing data) \n",
"df_encoded = df_encoded.dropna(subset=['cancer_risk'])\n",
"\n",
"#Import the splitting model from the scikit-learn model.\n",
"from sklearn.model_selection import train_test_split\n",
"\n",
"# Separate features and target\n",
"X = df_encoded.drop('cancer_risk', axis=1)\n",
"y = df_encoded['cancer_risk']\n",
"\n",
"# First split: 70% training, 30% temp\n",
"X_train, X_temp, y_train, y_temp = train_test_split(\n",
" X, y, test_size=0.30, random_state=42, stratify=y\n",
")\n",
"\n",
"# Second split: 15% validation, 15% test\n",
"X_val, X_test, y_val, y_test = train_test_split(\n",
" X_temp, y_temp, test_size=0.50, random_state=42, stratify=y_temp\n",
")\n",
"\n",
"# Print the results of said sizes to ensure it is working correctly.\n",
"X_train.shape, X_val.shape, X_test.shape\n"
]
},
{
"cell_type": "markdown",
"id": "b4c21ba9-b730-4150-8b38-dfb5b00f87c1",
"metadata": {},
"source": [
"# Select the most important features in the training dataset that may influence cancer risk, dropping 2 unnecessary features."
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "c94e2161-e95d-4a84-864d-bc1388bd4d48",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(693, 21)"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Drop two unnecessary features/columns that aren't relevant to cancer risk evaluation and wouldn't affect if someone would be likely to have cancer.\n",
"X_train = X_train.drop(['travelled_overseas', 'number_of_children'], axis=1)\n",
"X_val = X_val.drop(['travelled_overseas', 'number_of_children'], axis=1)\n",
"X_test = X_test.drop(['travelled_overseas', 'number_of_children'], axis=1)\n",
"\n",
"# Print the results to allow the user to determine the changes have worked\n",
"X_train.shape\n"
]
},
{
"cell_type": "markdown",
"id": "49174e92-2e15-461a-844f-ffa90c0d7c99",
"metadata": {},
"source": [
"# Part 3: Train and evaluate ML model - Task 1: Train ML model 1"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "b95cb28a-5312-4f55-8485-61c4e95e782e",
"metadata": {},
"outputs": [],
"source": [
"# Select an appropriate initial model size by setting the number of layers and neurons.\n",
"\n",
"\n",
"from sklearn.neural_network import MLPClassifier\n",
"\n",
"mlp_model_1 = MLPClassifier(\n",
" hidden_layer_sizes=(64, 32),\n",
" activation='relu',\n",
" solver='adam',\n",
" max_iter=300,\n",
" random_state=42\n",
")\n"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "9a44bcdd-8605-4e21-9a7a-1a3296f46909",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"age int64\n",
"family_history str\n",
"alcohol_consumption str\n",
"bmi float64\n",
"blood_pressure float64\n",
"cholesterol_level float64\n",
"age_group_15-24 bool\n",
"age_group_25-34 bool\n",
"age_group_35-44 bool\n",
"age_group_45-54 bool\n",
"age_group_55-64 bool\n",
"age_group_65-74 bool\n",
"age_group_75-84 bool\n",
"age_group_85+ bool\n",
"smoking_history_former bool\n",
"smoking_history_never bool\n",
"diet_good bool\n",
"diet_poor bool\n",
"exercise_frequency_low bool\n",
"exercise_frequency_moderate bool\n",
"exercise_frequency_none bool\n",
"dtype: object"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# BUG FIXING: List any non numerical rows\n",
"X_train.dtypes"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "f16e2e40-e065-44ca-b944-e9a2921d89db",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/tmp/ipykernel_82/146862157.py:2: Pandas4Warning: For backward compatibility, 'str' dtypes are included by select_dtypes when 'object' dtype is specified. This behavior is deprecated and will be removed in a future version. Explicitly pass 'str' to `include` to select them, or to `exclude` to remove them and silence this warning.\n",
"See https://pandas.pydata.org/docs/user_guide/migration-3-strings.html#string-migration-select-dtypes for details on how to write code that works with pandas 2 and 3.\n",
" X_train.select_dtypes(include=['object']).head()\n"
]
},
{
"data": {
"text/html": [
"\n",
"\n",
"
\n",
" \n",
" \n",
" \n",
" family_history \n",
" alcohol_consumption \n",
" \n",
" \n",
" \n",
" \n",
" 494 \n",
" yes \n",
" none \n",
" \n",
" \n",
" 379 \n",
" yes \n",
" high \n",
" \n",
" \n",
" 220 \n",
" yes \n",
" none \n",
" \n",
" \n",
" 732 \n",
" yes \n",
" high \n",
" \n",
" \n",
" 869 \n",
" no \n",
" low \n",
" \n",
" \n",
"
\n",
"
"
],
"text/plain": [
" family_history alcohol_consumption\n",
"494 yes none\n",
"379 yes high\n",
"220 yes none\n",
"732 yes high\n",
"869 no low"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# BUG FIXING: Check if the text value exists\n",
"X_train.select_dtypes(include=['object']).head()"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "f62a9503-664a-43d9-9afa-0029695acce8",
"metadata": {},
"outputs": [],
"source": [
"# BUG FIXING - Rayyan Hodges\n",
"\n",
"# Force all non-numeric columns to be one-hot encoded\n",
"X_train = pd.get_dummies(X_train)\n",
"X_val = pd.get_dummies(X_val)\n",
"X_test = pd.get_dummies(X_test)\n",
"\n",
"# Align columns so they match exactly\n",
"X_train, X_val = X_train.align(X_val, join=\"left\", axis=1, fill_value=0)\n",
"X_train, X_test = X_train.align(X_test, join=\"left\", axis=1, fill_value=0)\n"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "cfcddd52-1a78-4c07-8f5d-036682a8cad6",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"MLPClassifier(hidden_layer_sizes=(64, 32), max_iter=300, random_state=42) In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org. \n",
"
\n",
"
\n",
" Parameters \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" hidden_layer_sizes\n",
" hidden_layer_sizes: array-like of shape(n_layers - 2,), default=(100,) The ith element represents the number of neurons in the ith hidden layer. \n",
" \n",
" \n",
" (64, ...) \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" activation\n",
" activation: {'identity', 'logistic', 'tanh', 'relu'}, default='relu' Activation function for the hidden layer. - 'identity', no-op activation, useful to implement linear bottleneck, returns f(x) = x - 'logistic', the logistic sigmoid function, returns f(x) = 1 / (1 + exp(-x)). - 'tanh', the hyperbolic tan function, returns f(x) = tanh(x). - 'relu', the rectified linear unit function, returns f(x) = max(0, x) \n",
" \n",
" \n",
" 'relu' \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" solver\n",
" solver: {'lbfgs', 'sgd', 'adam'}, default='adam' The solver for weight optimization. - 'lbfgs' is an optimizer in the family of quasi-Newton methods. - 'sgd' refers to stochastic gradient descent. - 'adam' refers to a stochastic gradient-based optimizer proposed by Kingma, Diederik, and Jimmy Ba For a comparison between Adam optimizer and SGD, see :ref:`sphx_glr_auto_examples_neural_networks_plot_mlp_training_curves.py`. Note: The default solver 'adam' works pretty well on relatively large datasets (with thousands of training samples or more) in terms of both training time and validation score. For small datasets, however, 'lbfgs' can converge faster and perform better. \n",
" \n",
" \n",
" 'adam' \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" alpha\n",
" alpha: float, default=0.0001 Strength of the L2 regularization term. The L2 regularization term is divided by the sample size when added to the loss. For an example usage and visualization of varying regularization, see :ref:`sphx_glr_auto_examples_neural_networks_plot_mlp_alpha.py`. \n",
" \n",
" \n",
" 0.0001 \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" batch_size\n",
" batch_size: int, default='auto' Size of minibatches for stochastic optimizers. If the solver is 'lbfgs', the classifier will not use minibatch. When set to \"auto\", `batch_size=min(200, n_samples)`. \n",
" \n",
" \n",
" 'auto' \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" learning_rate\n",
" learning_rate: {'constant', 'invscaling', 'adaptive'}, default='constant' Learning rate schedule for weight updates. - 'constant' is a constant learning rate given by 'learning_rate_init'. - 'invscaling' gradually decreases the learning rate at each time step 't' using an inverse scaling exponent of 'power_t'. effective_learning_rate = learning_rate_init / pow(t, power_t) - 'adaptive' keeps the learning rate constant to 'learning_rate_init' as long as training loss keeps decreasing. Each time two consecutive epochs fail to decrease training loss by at least tol, or fail to increase validation score by at least tol if 'early_stopping' is on, the current learning rate is divided by 5. Only used when ``solver='sgd'``. \n",
" \n",
" \n",
" 'constant' \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" learning_rate_init\n",
" learning_rate_init: float, default=0.001 The initial learning rate used. It controls the step-size in updating the weights. Only used when solver='sgd' or 'adam'. \n",
" \n",
" \n",
" 0.001 \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" power_t\n",
" power_t: float, default=0.5 The exponent for inverse scaling learning rate. It is used in updating effective learning rate when the learning_rate is set to 'invscaling'. Only used when solver='sgd'. \n",
" \n",
" \n",
" 0.5 \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" max_iter\n",
" max_iter: int, default=200 Maximum number of iterations. The solver iterates until convergence (determined by 'tol') or this number of iterations. For stochastic solvers ('sgd', 'adam'), note that this determines the number of epochs (how many times each data point will be used), not the number of gradient steps. \n",
" \n",
" \n",
" 300 \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" shuffle\n",
" shuffle: bool, default=True Whether to shuffle samples in each iteration. Only used when solver='sgd' or 'adam'. \n",
" \n",
" \n",
" True \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" random_state\n",
" random_state: int, RandomState instance, default=None Determines random number generation for weights and bias initialization, train-test split if early stopping is used, and batch sampling when solver='sgd' or 'adam'. Pass an int for reproducible results across multiple function calls. See :term:`Glossary `. \n",
" \n",
" \n",
" 42 \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" tol\n",
" tol: float, default=1e-4 Tolerance for the optimization. When the loss or score is not improving by at least ``tol`` for ``n_iter_no_change`` consecutive iterations, unless ``learning_rate`` is set to 'adaptive', convergence is considered to be reached and training stops. \n",
" \n",
" \n",
" 0.0001 \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" verbose\n",
" verbose: bool, default=False Whether to print progress messages to stdout. \n",
" \n",
" \n",
" False \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" warm_start\n",
" warm_start: bool, default=False When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. See :term:`the Glossary `. \n",
" \n",
" \n",
" False \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" momentum\n",
" momentum: float, default=0.9 Momentum for gradient descent update. Should be between 0 and 1. Only used when solver='sgd'. \n",
" \n",
" \n",
" 0.9 \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" nesterovs_momentum\n",
" nesterovs_momentum: bool, default=True Whether to use Nesterov's momentum. Only used when solver='sgd' and momentum > 0. \n",
" \n",
" \n",
" True \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" early_stopping\n",
" early_stopping: bool, default=False Whether to use early stopping to terminate training when validation score is not improving. If set to True, it will automatically set aside ``validation_fraction`` of training data as validation and terminate training when validation score is not improving by at least ``tol`` for ``n_iter_no_change`` consecutive epochs. The split is stratified, except in a multilabel setting. If early stopping is False, then the training stops when the training loss does not improve by more than ``tol`` for ``n_iter_no_change`` consecutive passes over the training set. Only effective when solver='sgd' or 'adam'. \n",
" \n",
" \n",
" False \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" validation_fraction\n",
" validation_fraction: float, default=0.1 The proportion of training data to set aside as validation set for early stopping. Must be between 0 and 1. Only used if early_stopping is True. \n",
" \n",
" \n",
" 0.1 \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" beta_1\n",
" beta_1: float, default=0.9 Exponential decay rate for estimates of first moment vector in adam, should be in [0, 1). Only used when solver='adam'. \n",
" \n",
" \n",
" 0.9 \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" beta_2\n",
" beta_2: float, default=0.999 Exponential decay rate for estimates of second moment vector in adam, should be in [0, 1). Only used when solver='adam'. \n",
" \n",
" \n",
" 0.999 \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" epsilon\n",
" epsilon: float, default=1e-8 Value for numerical stability in adam. Only used when solver='adam'. \n",
" \n",
" \n",
" 1e-08 \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" n_iter_no_change\n",
" n_iter_no_change: int, default=10 Maximum number of epochs to not meet ``tol`` improvement. Only effective when solver='sgd' or 'adam'. .. versionadded:: 0.20 \n",
" \n",
" \n",
" 10 \n",
" \n",
" \n",
"\n",
" \n",
" \n",
" \n",
" \n",
" max_fun\n",
" max_fun: int, default=15000 Only used when solver='lbfgs'. Maximum number of loss function calls. The solver iterates until convergence (determined by 'tol'), number of iterations reaches max_iter, or this number of loss function calls. Note that number of loss function calls will be greater than or equal to the number of iterations for the `MLPClassifier`. .. versionadded:: 0.22 \n",
" \n",
" \n",
" 15000 \n",
" \n",
" \n",
" \n",
"
\n",
" \n",
"
\n",
"
"
],
"text/plain": [
"MLPClassifier(hidden_layer_sizes=(64, 32), max_iter=300, random_state=42)"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Train model 1 on generated data\n",
"mlp_model_1.fit(X_train, y_train)"
]
},
{
"cell_type": "markdown",
"id": "600e90f1-fc12-4300-ab60-76b4656bf5d8",
"metadata": {},
"source": [
"# Run the validation data through the ML model."
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "4d08a5ac-93cf-4da5-a266-7052ea31ac6a",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array(['low', 'high', 'high', 'moderate', 'low', 'high', 'high', 'high',\n",
" 'low', 'low'], dtype='