The Wayback Machine - https://web.archive.org/web/20240819110301/https://www.geeksforgeeks.org/autism-prediction-using-machine-learning/
Open In App

Autism Prediction using Machine Learning

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Autism is a neurological disorder that affects a person’s ability to interact with others, make eye contact with others, learn capacity, and other behavioral and social capabilities of a person.

But there is no ascertain way to tell whether a person has Autism or not because there are no such diagnostics methods available to diagnose this disorder. But what if we use machine learning to predict whether a person suffers from Autism or not? This is exactly what we’ll be learning in this article.

Importing Libraries and Dataset

Python libraries make it very easy for us to handle the data and perform typical and complex tasks with a single line of code.

  • Pandas – This library helps to load the data frame in a 2D array format and has multiple functions to perform analysis tasks in one go.
  • Numpy – Numpy arrays are very fast and can perform large computations in a very short time.
  • Matplotlib/Seaborn – This library is used to draw visualizations.
  • Sklearn – This module contains multiple libraries having pre-implemented functions to perform tasks from data preprocessing to model development and evaluation.
  • XGBoost – This contains the eXtreme Gradient Boosting machine learning algorithm which is one of the algorithms which helps us to achieve high accuracy on predictions.
  • Imblearn – This module contains a function that can be used for handling problems related to data imbalance.

Autism Prediction using Machine Learning Dataset : Link

Python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn import metrics
from sklearn.svm import SVC
from xgboost import XGBClassifier
from sklearn.linear_model import LogisticRegression
from imblearn.over_sampling import RandomOverSampler

import warnings
warnings.filterwarnings('ignore')

Now let’s load the dataset into the pandas data frame and print its first five rows.

Python
df = pd.read_csv('train.csv')
print(df.head())

Output:

First Five rows of the dataset

First Five rows of the dataset

Now let’s check the size of the dataset.

Python
df.shape

Output:

(800, 22)

Let’s check which column of the dataset contains which type of data.

Python
df.info()

Output:

Information regarding data in the columns

Information regarding data in the columns

As per the above information regarding the data in each column we can observe that there are no null values.

Python
df.describe().T

Output:

Descriptive statistical measures of the dataset

Descriptive statistical measures of the dataset

Data Cleaning

The data which is obtained from the primary sources is termed the raw data and required a lot of preprocessing before we can derive any conclusions from it or to some modeling on it. Those preprocessing steps are known as data cleaning and it includes, outliers removal, null value imputation, and removing discrepancies of any sort in the data inputs.

Python
df['ethnicity'].value_counts()

Output:

value_count of each unique value in the column

value_count of each unique value in the column

In the above two outputs we can observe some ambiguity that there are ‘?’, ‘others’, and ‘Others’ which all must be the same as they are unknown or we can say that null values have been substituted with some indicator.

Python
df['relation'].value_counts()

Output:

value_count of each unique value in the column

value_count of each unique value in the column

The same is the case with this column so, let’s clean this data, and along with this let’s convert ‘yes’ and ‘no’ to 0 and 1.

Python
df = df.replace({'yes':1, 'no':0, '?':'Others', 'others':'Others'})

Now we have cleaned the data a bit to derive insights from it.

Exploratory Data Analysis

EDA is an approach to analyzing the data using visual techniques. It is used to discover trends, and patterns, or to check assumptions with the help of statistical summaries and graphical representations. Here we will see how to check the data imbalance and skewness of the data.

Python
plt.pie(df['Class/ASD'].value_counts().values, autopct='%1.1f%%')
plt.show()

Output:

Pie chart for the number of data for each target

Pie chart for the number of data for each target

The dataset we have is highly imbalanced. If we will train our model using this data then the model will face a hard time predicting the positive class which is our main objective here to predict whether a person has autism or not with high accuracy.

Python
ints = []
objects = []
floats = []

for col in df.columns:
  if df[col].dtype == int:
    ints.append(col)
  elif df[col].dtype == object:
    objects.append(col)
  else:
    floats.append(col)

Now, we have columns segregated based on the type of data they contain hence now we’ll be able to perform suitable analysis depending upon the type of data.

Python
ints.remove('ID')
ints.remove('Class/ASD')

The ‘ID’ column will contain a unique value for each of the rows and for the column ‘Class/ASD’ we have already analyzed its distribution so, that is why they have been removed in the above code.

Python
plt.subplots(figsize=(15,15))

for i, col in enumerate(ints):
  plt.subplot(4,3,i+1)
  sb.countplot(df[col], hue=df['Class/ASD'])
plt.tight_layout()
plt.show()

Output:

Countplots for each of the numerical column

Count plots for each of the numerical column

From these plots, we can conclude that if the score of some indicator is 0 then the chances of that person not having autism is quite high except in the case of A10_Score.

Python
plt.subplots(figsize=(15, 30))

for i, col in enumerate(objects):
    plt.subplot(5, 3, i+1)
    sb.countplot(df[col], hue=df['Class/ASD'])
    plt.xticks(rotation=60)
plt.tight_layout()
plt.show()

Output:

Countplots for the categorical columns

Count plots for the categorical columns

From the above plots we can draw the following observations:

  • Age_desc is the same for all the data points.
  • This used_app_before feature doesn’t seem to be useful or it will be the source of data leakage.
  • Here it seems like the chances of a male having autism is higher than a female but that is not true because we don’t have an equal number of examples of males and females.
Python
plt.figure(figsize=(15,5))
sb.countplot(data=df, x='country_of_res', hue='Class/ASD')
plt.xticks(rotation=90)
plt.show()

Output:

Countplots for different country's given in the dataset

Count plots for different country’s given in the dataset

In some places approximately 50% of the data available for that country have autism and in some places, this is quite low. This implies that the geography of a person also gives an idea of having autism.

Python
plt.subplots(figsize=(15,5))

for i, col in enumerate(floats):
  plt.subplot(1,2,i+1)
  sb.distplot(df[col])
plt.tight_layout()
plt.show()

Output:

Distribution plot for the columns with continuous data

Distribution plot for the columns with continuous data

Both of the continuous data are skewed left one is positive and the right one is negatively skewed.

Python
plt.subplots(figsize=(15,5))

for i, col in enumerate(floats):
  plt.subplot(1,2,i+1)
  sb.boxplot(df[col])
plt.tight_layout()
plt.show()

Output:

Box plots for the columns with continuous data

Box plots for the columns with continuous data 

Ah! some outliers in the result column. Let’s remove that as it doesn’t seem like too much loss of information.

Python
df = df[df['result']>-5]
df.shape

Output:

(798, 22)

So, here we lost only two data points.

Feature Engineering

Feature Engineering helps to derive some valuable features from the existing ones. These extra features sometimes help in increasing the performance of the model significantly and certainly help to gain deeper insights into the data.

Python
# This functions make groups by taking
# the age as a parameter
def convertAge(age):
    if age < 4:
        return 'Toddler'
    elif age < 12:
        return 'Kid'
    elif age < 18:
        return 'Teenager'
    elif age < 40:
        return 'Young'
    else:
        return 'Senior'

df['ageGroup'] = df['age'].apply(convertAge)

Now, let’s explore the number of cases for each age group.

Python
sb.countplot(x=df['ageGroup'], hue=df['Class/ASD'])
plt.show()

Output:

 

Here we can conclude that the Young and Toddler group of people have lower chances of having Autism.

Python
def add_feature(data):
  
  # Creating a column with all values zero
  data['sum_score'] = 0
  for col in data.loc[:,'A1_Score':'A10_Score'].columns:
    
    # Updating the 'sum_score' value with scores
    # from A1 to A10
    data['sum_score'] += data[col]

  # Creating a random data using the below three columns
  data['ind'] = data['austim'] + data['used_app_before'] + data['jaundice']

  return data

df = add_feature(df)

In the above code block, we have just summed up the clinical scores given from A1 to A10.

Python
sb.countplot(x=df['sum_score'], hue=df['Class/ASD'])
plt.show()

Output:

Comparison between scores and number of positive and negative cases

Comparison between scores and number of positive and negative cases

Another amazing observation higher the sum score higher the chances of having autism is higher as well and similarly for lower sum scores that are for less than 5 it is rare that the person has autism.

Python
# Applying log transformations to remove the skewness of the data.
df['age'] = df['age'].apply(lambda x: np.log(x))

The age data given to us is positively skewed. As we know that skewed data impacts the performance of the model, we will apply log transformations to remove the skewness of the data.

Python
sb.distplot(df['age'])
plt.show()

Output:

Normal distribution of the age values after log transformations

Normal distribution of the age values after log transformations

Now, the skewness of the data has been removed successfully by using the log transformations.

Python
def encode_labels(data):
    for col in data.columns:
      
      # Here we will check if datatype
      # is object then we will encode it
      if data[col].dtype == 'object':
        le = LabelEncoder()
        data[col] = le.fit_transform(data[col])
    
    return data

df = encode_labels(df)

# Making a heatmap to visualize the correlation matrix
plt.figure(figsize=(10,10))
sb.heatmap(df.corr() > 0.8, annot=True, cbar=False)
plt.show()

Output:

Heatmap for the highly correlated features

Heat map for the highly correlated features

From the above heat map, we can see that there are only one highly correlated features which we will remove before training the model on this data as highly correlated features do not help in learning useful patterns in the data.

Model Training

Now we will separate the features and target variables and split them into training and the testing data by using which we will select the model which is performing best on the validation data.

Python
removal = ['ID', 'age_desc', 'used_app_before', 'austim']
features = df.drop(removal + ['Class/ASD'], axis=1)
target = df['Class/ASD']

Let’s split the data into training and validation data. Also, the data was imbalanced earlier now we will balance it using the Random Over Sampler in this method we sample some points from the minority class and repeat it multiple times so, that the two classes get balanced.

Python
X_train, X_val, Y_train, Y_val = train_test_split(features, target, test_size = 0.2, random_state=10)

# As the data was highly imbalanced we will balance it by adding repetitive rows of minority class.
ros = RandomOverSampler(sampling_strategy='minority',random_state=0)
X, Y = ros.fit_resample(X_train,Y_train)
X.shape, Y.shape

Output:

((1026, 20), (1026,))

Now, let’s normalize the data to obtain stable and fast training.

Python
# Normalizing the features for stable and fast training.
scaler = StandardScaler()
X = scaler.fit_transform(X)
X_val = scaler.transform(X_val)

Now let’s train some state-of-the-art machine learning models and compare them which fit better with our data.

Python
models = [LogisticRegression(), XGBClassifier(), SVC(kernel='rbf')]

for model in models:
  model.fit(X, Y)

  print(f'{model} : ')
  print('Training Accuracy : ', metrics.roc_auc_score(Y, model.predict(X)))
  print('Validation Accuracy : ', metrics.roc_auc_score(Y_val, model.predict(X_val)))
  print()

Output:

Different state of the art model accuracy on the test data

Different state-of-the-art model accuracy on the test data

Model Evaluation

From the above accuracies, we can say that Logistic Regression and SVC() classifier perform better on the validation data with less difference between the validation and training data. Let’s plot the confusion matrix as well for the validation data using the Logistic Regression model.

Python
metrics.plot_confusion_matrix(models[0], X_val, Y_val)
plt.show()

Output:

Confusion matrix for the validation data

Confusion matrix for the validation data

Conclusion:

The machine learning model we have created is around 80% to 85% accurate. The disease for which there are no diagnostics methods machine learning models are able to predict whether the person has Autism or not. This is the power of machine learning by using which many of the real-world problems are being solved.



Previous Article
Next Article

Similar Reads

Gold Price Prediction using Machine Learning
In This article, We will be making a project from scratch about Gold price prediction. To build any data science project We have to follow certain steps that need not be in the same order. In our project, We will go through these steps sequentially. Problem Formulation Data preprocessing Data wranglingModel DevelopmentModel ExplainabilityModel Depl
15+ min read
House Price Prediction using Machine Learning in Python
We all have experienced a time when we have to look up for a new house to buy. But then the journey begins with a lot of frauds, negotiating deals, researching the local areas and so on. House Price Prediction using Machine Learning So to deal with this kind of issues Today we will be preparing a MACHINE LEARNING Based model, trained on the House P
6 min read
Loan Approval Prediction using Machine Learning
LOANS are the major requirement of the modern world. By this only, Banks get a major part of the total profit. It is beneficial for students to manage their education and living expenses, and for people to buy any kind of luxury like houses, cars, etc. But when it comes to deciding whether the applicant's profile is relevant to be granted with loan
5 min read
Waiter's Tip Prediction using Machine Learning
If you have recently visited a restaurant for a family dinner or lunch and you have tipped the waiter for his generous behavior then this project might excite you. As in this article, we will try to predict what amount of tip a person will give based on his/her visit to the restaurant using some features related to the same. Let's start by importin
6 min read
Bitcoin Price Prediction using Machine Learning in Python
Machine learning proves immensely helpful in many industries in automating tasks that earlier required human labor one such application of ML is predicting whether a particular trade will be profitable or not. In this article, we will learn how to predict a signal that indicates whether buying a particular stock will be helpful or not by using ML.
7 min read
Medical Insurance Price Prediction using Machine Learning - Python
You must have heard some advertisements regarding medical insurance that promises to help financially in case of any medical emergency. One who purchases this type of insurance has to pay premiums monthly and this premium amount varies vastly depending upon various factors. Medical Insurance Price Prediction using Machine Learning in PythonIn this
7 min read
Parkinson Disease Prediction using Machine Learning - Python
Parkinson's disease is a progressive disorder that affects the nervous system and the parts of the body controlled by the nerves. Symptoms are also not that sound to be noticeable. Signs of stiffening, tremors, and slowing of movements may be signs of Parkinson's disease. But there is no ascertain way to tell whether a person has Parkinson's diseas
6 min read
Loan Eligibility prediction using Machine Learning Models in Python
Have you ever thought about the apps that can predict whether you will get your loan approved or not? In this article, we are going to develop one such model that can predict whether a person will get his/her loan approved or not by using some of the background information of the applicant like the applicant's gender, marital status, income, etc. I
5 min read
Flight Fare Prediction Using Machine Learning
In this article, we will develop a predictive machine learning model that can effectively predict flight fares. Why do we need to predict flight fares?There are several use cases of flight fare prediction, which are discussed below: Trip planning apps: Several Travel planning apps use airfare calculators to help users find the best time to book fli
5 min read
Click-Through Rate Prediction using Machine Learning
Predicting the click-through Rate (CTR) is crucial for optimizing online advertising campaigns. By accurately estimating the likelihood of a user clicking on an ad, businesses can make informed decisions about ad placement and design, ultimately maximizing their return on investment (ROI). In this article, we will explore how to use the eXtreme Gra
5 min read
Netflix Stock Price Prediction & Forecasting using Machine Learning in R
Recently, many people have been paying attention to the stock market as it offers high risks and high returns. In simple words, "Stock" is the ownership of a small part of a company. The more stock you have the bigger the ownership is. Using machine learning algorithms to predict a company's stock price aims to forecast the future value of the comp
9 min read
Disease Prediction Using Machine Learning
This article aims to implement a robust machine-learning model that can efficiently predict the disease of a human, based on the symptoms that he/she possesses. Let us look into how we can approach this machine-learning problem: Approach: Gathering the Data: Data preparation is the primary step for any machine learning problem. We will be using a d
10 min read
Titanic Survival Prediction Using Machine Learning
In this article, we will learn to predict the survival chances of the Titanic passengers using the given information about their sex, age, etc. As this is a classification task we will be using random forest. There will be three main steps in this experiment: Feature EngineeringImputationTraining and PredictionDataset The dataset for this experimen
7 min read
Stock Price Prediction using Machine Learning in Python
Machine learning proves immensely helpful in many industries in automating tasks that earlier required human labor one such application of ML is predicting whether a particular trade will be profitable or not. In this article, we will learn how to predict a signal that indicates whether buying a particular stock will be helpful or not by using ML.
8 min read
Calories Burnt Prediction using Machine Learning
In this article, we will learn how to develop a machine learning model using Python which can predict the number of calories a person has burnt during a workout based on some biological measures. Importing Libraries and DatasetPython libraries make it easy for us to handle the data and perform typical and complex tasks with a single line of code. P
5 min read
Rainfall Prediction using Machine Learning - Python
Today there are no certain methods by using which we can predict whether there will be rainfall today or not. Even the meteorological department's prediction fails sometimes. In this article, we will learn how to build a machine-learning model which can predict whether there will be rainfall today or not based on some atmospheric factors. This prob
6 min read
Wine Quality Prediction - Machine Learning
Here we will predict the quality of wine on the basis of given features. We use the wine quality dataset available on Internet for free. This dataset has the fundamental features which are responsible for affecting the quality of the wine. By the use of several Machine learning models, we will predict the quality of the wine. Importing libraries an
4 min read
Microsoft Stock Price Prediction with Machine Learning
In this article, we will implement Microsoft Stock Price Prediction with a Machine Learning technique. We will use TensorFlow, an Open-Source Python Machine Learning Framework developed by Google. TensorFlow makes it easy to implement Time Series forecasting data. Since Stock Price Prediction is one of the Time Series Forecasting problems, we will
5 min read
Dogecoin Price Prediction with Machine Learning
Dogecoin is a cryptocurrency, like Ethereum or Bitcoin — despite the fact that it's totally different than both of these famous coins. Dogecoin was initially made to some extent as a joke for crypto devotees and took its name from a previously well-known meme. In this article, we will be implementing a machine learning model which can predict the p
4 min read
Django - Machine Learning Placement Prediction Project
In this article, we will create  Placement Prediction Project using the Django framework using Python. In this project, we are using logistic regression algorithm of Python machine learning to predict the Placement of students by observing the input values filled by students according to their study background. Placement Prediction Project in Djang
7 min read
Machine Learning Diabetes Prediction Project in Django
In this article, we will create Diabetes Prediction Project using the Django framework using Python. In this project, we are using a logistic regression algorithm of Python machine learning to predict Diabetes diseases in a person by observing the input values filled by the person according to their health. Diabetes Prediction Project in Django Bas
8 min read
Machine Learning Heart Disease Prediction Project in Django
Introduction-In this article, we will implement a Machine Learning Heart disease Prediction Project using the Django framework using Python. Here, we will convert the code of the heart diseases prediction into a web form with the help of the Django framework basically we will create a form by using the Django framework and add the dataset of heart
9 min read
Prediction Intervals for Machine Learning
Prediction intervals are an essential concept in machine learning and statistics, providing a range within which a future observation is expected to fall with a certain probability. Unlike confidence intervals, which estimate the uncertainty of a population parameter, prediction intervals focus on the uncertainty of individual predictions. This art
9 min read
Heart Disease Prediction using Support Vector Machine
Heart disease is a significant health concern worldwide, and early detection plays a crucial role in effective treatment and prevention. Machine learning algorithms, such as Support Vector Machines (SVM), have shown promising results in predicting heart disease based on patient data. SVM stands for Support Vector Machine are a set of supervised lea
4 min read
Prediction of Wine type using Deep Learning
We use deep learning for the large data sets but to understand the concept of deep learning, we use the small data set of wine quality. You can find the wine quality data set from the UCI Machine Learning Repository which is available for free. The aim of this article is to get started with the libraries of deep learning such as Keras, etc and to b
4 min read
Flight Delay Prediction using Deep Learning
Air travel has become an important part of our lives, and with this comes the problem of flights being delayed. Deep learning models can automatically learn hierarchical representations from data, making them best for flight delay prediction. In the article, we will build a flight delay predictor using TensorFlow framework. How can we use deep lear
5 min read
IPL Score Prediction using Deep Learning
In the modern era of cricket analytics, where each run and decision can change the outcome, the application of Deep Learning for IPL score prediction stands at the forefront of innovation. This article explores the cutting-edge use of advanced algorithms to forecast IPL score in live matches with unprecedented accuracy. Exploring the analysis of hi
9 min read
Automated Machine Learning for Supervised Learning using R
Automated Machine Learning (AutoML) is an approach that aims to automate various stages of the machine learning process, making it easier for users with limited machine learning expertise to build high-performing models. AutoML is particularly useful in supervised learning, where you have labeled data and want to create models that can make predict
8 min read
Support vector machine in Machine Learning
In this article, we are going to discuss the support vector machine in machine learning. We will also cover the advantages and disadvantages and application for the same. Let's discuss them one by one. Support Vector Machines : Support vector machine is a supervised learning system and is used for classification and regression problems. Support vec
9 min read
Azure Virtual Machine for Machine Learning
Prerequisites: About Microsoft Azure, Cloud Based Services Some of the Machine Learning and Deep Learning algorithms may require high computation power which may not be supported by your local machine or laptop. In that case, creating a Virtual Machine on a cloud platform can provide you the expected computation power. We can have a system with hig
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg