Heterogeneous Data Analysis & String Similarity and Data Cleaning
Overview
In this lab, you will compute the similairty between different strings and sets. You will use different atomic similarity measures. Moreover, you will practice to find the similarity between different sets using traditional similarity (Jaccard similarity, Sørensen Coefficient, Tversky Index and the Overlap Coefficient). Furthermore, you will handle data quality problems such as missing values, noisy data and outliers.
1. Atomic String Similarity
In the following exercises, you will learn about finding the simiarity between atomic values using Edit-Distance, Jaro Similarity, Jaro-Winkler Similarity and Soundex). We will start by importing the required libraries.
import pandas as pd
import csv
import numpy as np
'''
TODO: find an implementation of the Levenshtein minimum edit distance and use it
to find the similarity between INTENTION and EXECUTION
'''
def ldist(s, t):
"""
iterative_levenshtein(s, t) -> ldist
ldist is the Levenshtein distance between the strings
s and t.
For all i and j, dist[i,j] will contain the Levenshtein
distance between the first i characters of s and the
first j characters of t
"""
rows = len(s)+1
cols = len(t)+1
dist = [[0 for x in range(cols)] for x in range(rows)]
# source prefixes can be transformed into empty strings
# by deletions:
for i in range(1, rows):
dist[i][0] = i
# target prefixes can be created from an empty source string
# by inserting the characters
for i in range(1, cols):
dist[0][i] = i
for col in range(1, cols):
for row in range(1, rows):
if s[row-1] == t[col-1]:
c = 0
else:
c = 2
dist[row][col] = min(dist[row-1][col] + 1, # deletion
dist[row][col-1] + 1, # insertion
dist[row-1][col-1] + c) # substitution
for r in range(rows):
print(dist[r])
return dist[row][col]
print("Minimum edit disctance = ", ldist("INTENTION", "EXECUTION"))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 6, 7, 8]
[2, 3, 4, 5, 6, 7, 8, 7, 8, 7]
[3, 4, 5, 6, 7, 8, 7, 8, 9, 8]
[4, 3, 4, 5, 6, 7, 8, 9, 10, 9]
[5, 4, 5, 6, 7, 8, 9, 10, 11, 10]
[6, 5, 6, 7, 8, 9, 8, 9, 10, 11]
[7, 6, 7, 8, 9, 10, 9, 8, 9, 10]
[8, 7, 8, 9, 10, 11, 10, 9, 8, 9]
[9, 8, 9, 10, 11, 12, 11, 10, 9, 8]
Minimum edit disctance = 8'''
TODO: Modify the ldist function to accept a new parameter which specifies the substitution cost
Test your implementation with the call mod_ldist("Intention", "execution", 1) -- You should get 5
and mod_ldist("Intention", "execution", 2) -- You should get 8
'''
def mod_ldist(s, t, substitution_cost):
"""
iterative_levenshtein(s, t) -> ldist
ldist is the Levenshtein distance between the strings
s and t.
For all i and j, dist[i,j] will contain the Levenshtein
distance between the first i characters of s and the
first j characters of t
"""
rows = len(s)+1
cols = len(t)+1
dist = [[0 for x in range(cols)] for x in range(rows)]
# source prefixes can be transformed into empty strings
# by deletions:
for i in range(1, rows):
dist[i][0] = i
# target prefixes can be created from an empty source string
# by inserting the characters
for i in range(1, cols):
dist[0][i] = i
for col in range(1, cols):
for row in range(1, rows):
if s[row-1] == t[col-1]:
c = 0
else:
c = substitution_cost
dist[row][col] = min(dist[row-1][col] + 1, # deletion
dist[row][col-1] + 1, # insertion
dist[row-1][col-1] + c) # substitution
return dist[row][col]
print("Minimum edit disctance = ", mod_ldist("INTENTION", "EXECUTION", 2))
Minimum edit disctance = 8'''
TODO: find an implementation of the Jaro similarity algorithm and use it
to find the similarity between the follwing pairs of strings:
('nichlseon','niechlson'),
('MARTHA', 'MARHTA'),
('DIXON', 'DICKSONX'),
('JELLYFISH', 'SMELLYFISH'),
('cunningham', 'cunnigham'),
('shackleford', 'shackelford'),
('nichleson', 'nichulson'),
('arnab', 'urban'),
('DATASCIENCE','SCIENCEDATA')
'''
def jaro(s, t):
'''Jaro similarity between two strings.'''
s_len = len(s)
t_len = len(t)
if s_len == 0 and t_len == 0:
return 1
match_distance = (max(s_len, t_len) // 2) - 1
s_matches = [False] * s_len
t_matches = [False] * t_len
matches = 0
transpositions = 0
for i in range(s_len):
start = max(0, i - match_distance)
end = min(i + match_distance + 1, t_len)
for j in range(start, end):
if t_matches[j]:
continue
if s[i] != t[j]:
continue
s_matches[i] = True
t_matches[j] = True
matches += 1
break
if matches == 0:
return 0
k = 0
for i in range(s_len):
if not s_matches[i]:
continue
while not t_matches[k]:
k += 1
if s[i] != t[k]:
transpositions += 1
k += 1
return ((matches / s_len) +
(matches / t_len) +
((matches - transpositions / 2) / matches)) / 3
'''
TODO: find an implementation of the Jaro-Winkler similarity algorithm and use it
to find the similarity between the pairs of strings in the previous exercise.
Compare the results and comment on them.
'''
def jaro_winkler(s, t, p = 0.1):
# Compute the Jaro similarity
jaro_sim = jaro(s, t)
ls = len(s)
lt = len(t)
# Initialize the upper bound for the no. of prefixes.
min_l = min(ls, lt)
# Compute the prefix matches.
l = 0
for i in range(min_l):
if s[i] == t[i]:
l += 1
else:
break
# Return the similarity value.
L = min(l, 4)
return (jaro_sim + ( L * p * (1 - jaro_sim) ))
# Test the functions on a set of strings
for s, t in [('nichlseon','niechlson'),
('MARTHA', 'MARHTA'),
('DIXON', 'DICKSONX'),
('JELLYFISH', 'SMELLYFISH'),
('cunningham', 'cunnigham'),
('shackleford', 'shackelford'),
('nichleson', 'nichulson'),
('arnab', 'urban'),
('DATASCIENCE','SCIENCEDATA')
]:
print("jaro(%r, %r) = %.4f and jaro-winkler(%r, %r) = %.4f" % (s, t, jaro(s, t), s, t, jaro_winkler(s, t)))
jaro('nichlseon', 'niechlson') = 0.9259 and jaro-winkler('nichlseon', 'niechlson') = 0.9407
jaro('MARTHA', 'MARHTA') = 0.9444 and jaro-winkler('MARTHA', 'MARHTA') = 0.9611
jaro('DIXON', 'DICKSONX') = 0.7667 and jaro-winkler('DIXON', 'DICKSONX') = 0.8133
jaro('JELLYFISH', 'SMELLYFISH') = 0.8963 and jaro-winkler('JELLYFISH', 'SMELLYFISH') = 0.8963
jaro('cunningham', 'cunnigham') = 0.9667 and jaro-winkler('cunningham', 'cunnigham') = 0.9800
jaro('shackleford', 'shackelford') = 0.9697 and jaro-winkler('shackleford', 'shackelford') = 0.9818
jaro('nichleson', 'nichulson') = 0.9259 and jaro-winkler('nichleson', 'nichulson') = 0.9556
jaro('arnab', 'urban') = 0.6000 and jaro-winkler('arnab', 'urban') = 0.6000
jaro('DATASCIENCE', 'SCIENCEDATA') = 0.7576 and jaro-winkler('DATASCIENCE', 'SCIENCEDATA') = 0.7576'''
TODO: find an implementation of the soundex algorithm and use it
to find the representation of EDUCATE and EVALUATE
'''
def soundex(name):
"""
The Soundex algorithm assigns a 1-letter + 3-digit code to strings,
the intention being that strings pronounced the same but spelled
differently have identical encodings; words pronounced similarly
should have similar encodings.
"""
soundexcoding = [' ', ' ', ' ', ' ']
soundexcodingindex = 1
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
mappings = "01230120022455012623010202"
soundexcoding[0] = name[0].upper()
for i in range(1, len(name)):
c = ord(name[i].upper()) - 65
if c >= 0 and c <= 25:
if mappings[c] != '0':
if mappings[c] != soundexcoding[soundexcodingindex-1]:
soundexcoding[soundexcodingindex] = mappings[c]
soundexcodingindex += 1
if soundexcodingindex > 3:
break
if soundexcodingindex <= 3:
while(soundexcodingindex <= 3):
soundexcoding[soundexcodingindex] = '0'
soundexcodingindex += 1
return ''.join(soundexcoding)
soundex('EDUCATE'), soundex('EVALUATE')
('E323', 'E143')2. Similarity of Sets
For this exercise, you may use a tokenizing function that convert the following sentences into sets of words (words are separated by spaces). After that, apply Jaccard, Sørensen Coefficient, Tversky Index, Overlap Cooficient).
D1 = People wearing costumes are gathering in a forest and are looking in the same direction
D2 = People wearing costumes are scattering in a forest and are looking in different directions
D3 = People wearing costumes are gathering in a forest and are looking in the same direction
D4 = Masked people are looking in the same direction in a forest
Compute the pairwise similarity between the documents using the four measures.
'''
TODO: first step is to tokenize the documents
'''
D1 = 'People wearing costumes are gathering in a forest and are looking in the same direction'
D2 = 'People wearing costumes are scattering in a forest and are looking in different directions'
D3 = 'People wearing costumes are gathering in the wood and are looking in the same direction'
D4 = 'Masked people are looking in the same direction in a forest'
S1 = D1.split()
S2 = D2.split()
S3 = D3.split()
S4 = D4.split()
'''
TODO: Compute the pairwise Jaccard similarity for the sets S1, S2, S3, and S4.
'''
def jaccard_similarity(set1, set2):
intersection_size = len(set1.intersection(set2))
union_size = len(set1.union(set2))
return intersection_size / union_size if union_size != 0 else 0.0
strings = [S1, S2, S3, S4]
for i in range(len(strings)):
s1 = set(strings[i])
# loop over the columns of the second table
s2 = set()
for j in range(i+1,len(strings)):
s2 = set(strings[j])
JSim = jaccard_similarity(s1, s2)
# display the Similarities
print ("Jacard similarity between S{} and S{} = {:2.3}"\
.format(i+1, j+1, JSim))
Jacard similarity between S1 and S2 = 0.562
Jacard similarity between S1 and S3 = 0.786
Jacard similarity between S1 and S4 = 0.533
Jacard similarity between S2 and S3 = 0.412
Jacard similarity between S2 and S4 = 0.294
Jacard similarity between S3 and S4 = 0.375'''
TODO: Compute the pairwise Sørensen Coefficient for the sets S1, S2, S3, and S4.
'''
def Sørensen_Coefficient(set1, set2):
intersection_size = len(set1.intersection(set2))
total_size = (len(set1) + len(set2))
return (2 * intersection_size) / total_size if total_size != 0 else 0.0
strings = [S1, S2, S3, S4]
for i in range(len(strings)):
s1 = set(strings[i])
# loop over the columns of the second table
s2 = set()
for j in range(i+1,len(strings)):
s2 = set(strings[j])
SCoef = Sørensen_Coefficient(s1, s2)
# display the Similarities
print ("Sørensen Coefficient between S{} and S{} = {:2.3}"\
.format(i+1, j+1, SCoef))
Sørensen Coefficient between S1 and S2 = 0.72
Sørensen Coefficient between S1 and S3 = 0.88
Sørensen Coefficient between S1 and S4 = 0.696
Sørensen Coefficient between S2 and S3 = 0.583
Sørensen Coefficient between S2 and S4 = 0.455
Sørensen Coefficient between S3 and S4 = 0.545'''
TODO: Compute the pairwise Tversky Index for the sets S1, S2, S3, and S4.
'''
def Tversky_Coefficient(set1, set2):
intersection_size = len(set1.intersection(set2))
S1_diff_S2 = len(set1.difference(set2))
S2_diff_S1 = len(set2.difference(set1))
alpha = 0.2
beta = 0.8
denominator = intersection_size + (alpha * S1_diff_S2) + (beta * S2_diff_S1)
return intersection_size / denominator if denominator != 0 else 0.0
strings = [S1, S2, S3, S4]
for i in range(len(strings)):
s1 = set(strings[i])
# loop over the columns of the second table
s2 = set()
for j in range(i+1,len(strings)):
s2 = set(strings[j])
TCoef = Tversky_Coefficient(s1, s2)
# display the Similarities
print ("Tversky Coefficient between S{} and S{} = {:2.3}"\
.format(i+1, j+1, TCoef))
Tversky Coefficient between S1 and S2 = 0.738
Tversky Coefficient between S1 and S3 = 0.902
Tversky Coefficient between S1 and S4 = 0.755
Tversky Coefficient between S2 and S3 = 0.583
Tversky Coefficient between S2 and S4 = 0.481
Tversky Coefficient between S3 and S4 = 0.577'''
TODO: Compute the pairwise Overlap Coefficient for the sets S1, S2, S3, and S4.
'''
def Overlap_Coefficient(set1, set2):
intersection_size = len(set1.intersection(set2))
min_size = min(len(set1), len(set2))
return intersection_size / min_size if min_size != 0 else 0.0
strings = [S1, S2, S3, S4]
for i in range(len(strings)):
s1 = set(strings[i])
# loop over the columns of the second table
s2 = set()
for j in range(i+1,len(strings)):
s2 = set(strings[j])
OCoef = Overlap_Coefficient(s1, s2)
# display the Similarities
print ("Overlap Coefficient between S{} and S{} = {:2.3}"\
.format(i+1, j+1, OCoef))
Overlap Coefficient between S1 and S2 = 0.75
Overlap Coefficient between S1 and S3 = 0.917
Overlap Coefficient between S1 and S4 = 0.8
Overlap Coefficient between S2 and S3 = 0.583
Overlap Coefficient between S2 and S4 = 0.5
Overlap Coefficient between S3 and S4 = 0.63. Similarity of Documents
To compute the similarity between two documents, we studied simple techniques where we convert the text into sparse vectors using k-shingling. After that we create the shingle-Document matrix using one-hot encoding. Finally, we compare two documents using one of the similarity of sets metrics.
k-Shingling, often referred to as shingling, involves the transformation of a text string into a collection of 'shingles.' This procedure resembles sliding a window of length k along our text string and capturing a snapshot at each step. We aggregate all these snapshots to form our set of shingles.
def shingle(text: str, k: int)->set:
"""
Create a set of 'shingles' from the input text using k-shingling.
Parameters:
text (str): The input text to be converted into shingles.
k (int): The length of the shingles (substring size).
Returns:
set: A set containing the shingles extracted from the input text.
"""
shingle_set = []
for i in range(len(text) - k+1):
shingle_set.append(text[i:i+k])
return set(shingle_set)
def build_vocab(shingle_sets: list)->dict:
"""
Constructs a vocabulary dictionary from a list of shingle sets.
This function takes a list of shingle sets and creates a unified vocabulary
dictionary. Each unique shingle across all sets is assigned a unique integer
identifier.
Parameters:
- shingle_sets (list of set): A list containing sets of shingles.
Returns:
- dict: A vocabulary dictionary where keys are the unique shingles and values
are their corresponding unique integer identifiers.
Example:
sets = [{"apple", "banana"}, {"banana", "cherry"}]
build_vocab(sets)
{'apple': 0, 'cherry': 1, 'banana': 2} # The exact order might vary due to set behavior
"""
full_set = {item for set_ in shingle_sets for item in set_}
vocab = {}
for i, shingle in enumerate(list(full_set)):
vocab[shingle] = i
return vocab
Simple example of shingling
'''
TODO: using the function 'shingle', find the list of 5-shingles in the document:
D = "This is an example of text shingling using k-shingling."
After that, find the 5-shingles manually and check if the computed ones are corret or not.
If you don't see the message "Assertion failed: The result does not match the expected shingles.",
then the function that computes the shingles provides correct results
'''
text = "This is an example of text shingling using k-shingling."
k = 5
result_5sh = shingle(text, k)
# We find all the shingles and use the set class to remove the duplicates
expected_result = {'This ', 'his i', 'is is', 's is ', ' is a', 'is an', 's an ', ' an e', 'an ex',
'n exa', ' exam', 'examp', 'xampl', 'ample', 'mple ', 'ple o', 'le of', 'e of ',
' of t', 'of te', 'f tex', ' text', 'text ', 'ext s', 'xt sh', 't shi', ' shin',
'shing', 'hingl', 'ingli', 'nglin', 'gling', 'ling ', 'ing u', 'ng us', 'g usi',
' usin', 'using', 'sing ', 'ing k', 'ng k-', 'g k-s', ' k-sh', 'k-shi', '-shin',
'shing', 'hingl', 'ingli', 'nglin', 'gling', 'ling.', }
assert result_5sh == set(expected_result), "Assertion failed: The result does not match the expected shingles."
result_5sh
{' an e',
' exam',
' is a',
' k-sh',
' of t',
' shin',
' text',
' usin',
'-shin',
'This ',
'ample',
'an ex',
'e of ',
'examp',
'ext s',
'f tex',
'g k-s',
'g usi',
'gling',
'hingl',
'his i',
'ing k',
'ing u',
'ingli',
'is an',
'is is',
'k-shi',
'le of',
'ling ',
'ling.',
'mple ',
'n exa',
'ng k-',
'ng us',
'nglin',
'of te',
'ple o',
's an ',
's is ',
'shing',
'sing ',
't shi',
'text ',
'using',
'xampl',
'xt sh'}'''
Now we use k = 3
'''
k = 3
result_3sh = shingle(text, k)
result_3sh
{' an',
' ex',
' is',
' k-',
' of',
' sh',
' te',
' us',
'-sh',
'Thi',
'amp',
'an ',
'e o',
'exa',
'ext',
'f t',
'g k',
'g u',
'gli',
'hin',
'his',
'ing',
'is ',
'k-s',
'le ',
'lin',
'mpl',
'n e',
'ng ',
'ng.',
'ngl',
'of ',
'ple',
's a',
's i',
'shi',
'sin',
't s',
'tex',
'usi',
'xam',
'xt '}Once the set of shingles are identified, we create a matrix (table) where each represent a shingle and each column represent a document. The value of each cell $c_{ij}$ of this matrix is 1 if Shingle $Sh_i$ exists in Document $D_j$
def one_hot(shingles: set, vocab: dict):
vec = np.zeros(len(vocab))
for shingle in shingles:
idx = vocab[shingle]
vec[idx] = 1
return vec
'''
GIVEN:
D1 = People wearing costumes are gathering in a forest and are looking in the same direction
D2 = People wearing costumes are scattering in a forest and are looking in different directions
D3 = People wearing costumes are gathering in a forest and are looking in the same direction
D4 = Masked people are looking in the same direction in a forest
TODO:
1. create a single list that contains all the sentences in D1, D2, D3, and D4
2. find the list of 3-shingles from the full list of sentences
3. Use the functions build_vocab and one_hot to create the documents-shinles matrix
(you can also use your own functions)
'''
k = 3
D1 = 'People wearing costumes are gathering in a forest and are looking in the same direction'
D2 = 'People wearing costumes are scattering in a forest and are looking in different directions'
D3 = 'People wearing costumes are gathering in a forest and are looking in the same direction'
D4 = 'Masked people are looking in the same direction in a forest'
sentences = [D1, D2, D3, D4]
print(f"the number of sentences (documents):{len(sentences)}")
shingles = []
for sentence in sentences:
shingles.append(shingle(sentence,k))
vocab = build_vocab(shingles)
print(f"Number of vocabulary is:{len(vocab)}")
shingles_1hot = []
for shingle_set in shingles:
shingles_1hot.append(one_hot(shingle_set,vocab))
shingles_1hot = np.stack(shingles_1hot)
shingles_1hot
the number of sentences (documents):4
Number of vocabulary is:101array([[1., 1., 1., 1., 1., 0., 0., 0., 1., 0., 1., 0., 1., 1., 1., 0.,
0., 1., 1., 1., 1., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
0., 1., 1., 0., 1., 1., 0., 1., 1., 1., 0., 0., 1., 0., 1., 1.,
0., 1., 1., 1., 0., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 1.,
1., 0., 1., 1., 1., 1., 1., 1., 0., 1., 1., 1., 1., 1., 1., 1.,
1., 0., 1., 1., 1., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 0.,
1., 1., 1., 0., 1.],
[1., 1., 1., 1., 0., 0., 1., 0., 1., 0., 1., 0., 1., 0., 1., 1.,
0., 1., 0., 0., 0., 1., 1., 0., 1., 1., 1., 1., 1., 1., 0., 1.,
1., 1., 1., 1., 1., 1., 1., 0., 1., 1., 0., 1., 1., 0., 1., 0.,
1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 1., 1., 0., 0., 1.,
1., 0., 1., 1., 1., 1., 1., 0., 0., 1., 0., 1., 1., 1., 1., 1.,
1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 1., 1., 1., 1.,
1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 0., 0., 0., 1., 0., 1., 0., 1., 1., 1., 0.,
0., 1., 1., 1., 1., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
0., 1., 1., 0., 1., 1., 0., 1., 1., 1., 0., 0., 1., 0., 1., 1.,
0., 1., 1., 1., 0., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 1.,
1., 0., 1., 1., 1., 1., 1., 1., 0., 1., 1., 1., 1., 1., 1., 1.,
1., 0., 1., 1., 1., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 0.,
1., 1., 1., 0., 1.],
[1., 1., 0., 0., 0., 1., 0., 1., 1., 1., 1., 1., 0., 1., 1., 0.,
1., 1., 0., 1., 1., 0., 1., 0., 0., 0., 1., 1., 1., 1., 1., 1.,
0., 0., 1., 0., 1., 0., 0., 1., 0., 1., 1., 0., 0., 1., 1., 1.,
0., 1., 1., 1., 0., 0., 0., 0., 1., 1., 1., 0., 0., 1., 1., 1.,
0., 1., 1., 1., 0., 1., 0., 0., 1., 1., 1., 1., 1., 1., 0., 0.,
1., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 1., 0., 0.,
1., 0., 0., 0., 1.]])'''
Since the one hot encoding results in numpy arrays instead of sets,
our earlier implementation of jaccard_similarity wouldn't work.
We need to modify the function slightly
'''
def jaccard_similarity_arrays(a, b):
a = np.asarray(a).astype(bool)
b = np.asarray(b).astype(bool)
if a.shape != b.shape:
raise ValueError("The arrays must have the same shape.")
intersection = np.logical_and(a, b).sum()
union = np.logical_or(a, b).sum()
return intersection / union if union != 0 else 1.0
for i in range(len(shingles_1hot)):
for j in range(i+1, len(shingles_1hot)):
print('Jaccard similarity between D{} and D{} is {}'.
format(i+1, j+1, round(jaccard_similarity_arrays(shingles_1hot[i], shingles_1hot[j]), 2)))
Jaccard similarity between D1 and D2 is 0.66
Jaccard similarity between D1 and D3 is 1.0
Jaccard similarity between D1 and D4 is 0.52
Jaccard similarity between D2 and D3 is 0.66
Jaccard similarity between D2 and D4 is 0.36
Jaccard similarity between D3 and D4 is 0.52'''
TODO: Try the other set similarity metrics 'Sørensen Coefficient', 'Tversky Index' and 'Overlap Coefficient'
'''
"\nTODO: Try the other set similarity metrics 'Sørensen Coefficient', 'Tversky Index' and 'Overlap Coefficient'\n"4. Data Preparation
For this part, you need to install the following libraries:
matplotlib
sklearn
!pip install matplotlib
Requirement already satisfied: matplotlib in /Users/hakim/Documents/gen_env/lib/python3.10/site-packages (3.10.9)
Requirement already satisfied: contourpy>=1.0.1 in /Users/hakim/Documents/gen_env/lib/python3.10/site-packages (from matplotlib) (1.3.2)
Requirement already satisfied: cycler>=0.10 in /Users/hakim/Documents/gen_env/lib/python3.10/site-packages (from matplotlib) (0.12.1)
Requirement already satisfied: fonttools>=4.22.0 in /Users/hakim/Documents/gen_env/lib/python3.10/site-packages (from matplotlib) (4.65.0)
Requirement already satisfied: kiwisolver>=1.3.1 in /Users/hakim/Documents/gen_env/lib/python3.10/site-packages (from matplotlib) (1.5.1)
Requirement already satisfied: numpy>=1.23 in /Users/hakim/Documents/gen_env/lib/python3.10/site-packages (from matplotlib) (2.1.2)
Requirement already satisfied: packaging>=20.0 in /Users/hakim/Documents/gen_env/lib/python3.10/site-packages (from matplotlib) (24.1)
Requirement already satisfied: pillow>=8 in /Users/hakim/Documents/gen_env/lib/python3.10/site-packages (from matplotlib) (12.3.0)
Requirement already satisfied: pyparsing>=3 in /Users/hakim/Documents/gen_env/lib/python3.10/site-packages (from matplotlib) (3.3.3)
Requirement already satisfied: python-dateutil>=2.7 in /Users/hakim/Documents/gen_env/lib/python3.10/site-packages (from matplotlib) (2.9.0.post0)
Requirement already satisfied: six>=1.5 in /Users/hakim/Documents/gen_env/lib/python3.10/site-packages (from python-dateutil>=2.7->matplotlib) (1.16.0)
[1m[[0m[34;49mnotice[0m[1;39;49m][0m[39;49m A new release of pip is available: [0m[31;49m24.2[0m[39;49m -> [0m[32;49m26.2.2[0m
[1m[[0m[34;49mnotice[0m[1;39;49m][0m[39;49m To update, run: [0m[32;49mpip install --upgrade pip[0mfrom sklearn.neighbors import NearestNeighbors
import matplotlib.pyplot as plt
We begin by defining a pandas dataframe that contains some cells with missing values. Note that pandas, in addition to allowing us to create dataframes from a variety of files, also supports explicit declaration.
incomplete_df = pd.DataFrame({'id': [1,2,3,2,2,3,1,1,1,2,4],
'type': ['one', 'one', 'two', 'three', 'two', 'three', 'one', 'two', 'one', 'three','one'],
'amount': [345,928,np.nan,645,113,942,np.nan,539,np.nan,814,np.nan]
}, columns=['id','type','amount'])
Column 'amount' is the only one with missing values. Now we display the dataframe
Recall that summary statistics and arithmetic with missing data is natively supported by pandas. Let's define two series, both containing some missing values.
A = incomplete_df['amount']
B = pd.Series(data=[np.nan,125,335,345,312,np.nan,np.nan,129,551,800,222])
#TODO: print the content of A
print("The values of attr. A = ", A)
print ('\n')
#TODO: print the content of B
print(B)
The values of attr. A = 0 345.0
1 928.0
2 NaN
3 645.0
4 113.0
5 942.0
6 NaN
7 539.0
8 NaN
9 814.0
10 NaN
Name: amount, dtype: float64
0 NaN
1 125.0
2 335.0
3 345.0
4 312.0
5 NaN
6 NaN
7 129.0
8 551.0
9 800.0
10 222.0
dtype: float64The mean is computed normally and missing values are ignored:
'''
TODO: Compute and print the mean value of A using pandas library
'''
A.mean()
np.float64(618.0)'''
TODO: Compute and print the mean value of A using numpy library
'''
np.mean(A)
np.float64(618.0)Min, Max, STD and Variance all work even when data are missing:
'''
TDOD: Compute and display the min, max, standard deviation and variance of B
'''
print(B.min())
print(B.max())
print(B.std())
print(B.var())
print(np.min(B))
125.0
800.0
226.90459763647678
51485.69642857143
125.0# We can also display multiple variable by listing their in a comma separated format e.g.
# x, y will display the values of x and y.
# Use the same format to display the computed quantities
B.min(), B.max(), B.std(), B.var()
(np.float64(125.0),
np.float64(800.0),
np.float64(226.90459763647678),
np.float64(51485.69642857143))We can also perform element-wise arithmetic operations between series with missing data.
Remember: by definition, the result of any operation that involves missing values is NaN.
# TODO: Perform element-wise addition between the values in A and B
A + B
0 NaN
1 1053.0
2 NaN
3 990.0
4 425.0
5 NaN
6 NaN
7 668.0
8 NaN
9 1614.0
10 NaN
dtype: float64np.add(A, B)
0 NaN
1 1053.0
2 NaN
3 990.0
4 425.0
5 NaN
6 NaN
7 668.0
8 NaN
9 1614.0
10 NaN
dtype: float64First, deleting the records that contain missing values
Pandas has a function that allows deleting the rows in a dataframe (or elements in a series) that contain missing values.
'''
TODO: Copy the incomplete dataframe and
use a Python function to delete the records with missing values
'''
idf_copy = incomplete_df.copy()
idf_copy.dropna()
| id | type | amount | |
|---|---|---|---|
| 0 | 1 | one | 345.0 |
| 1 | 2 | one | 928.0 |
| 3 | 2 | three | 645.0 |
| 4 | 2 | two | 113.0 |
| 5 | 3 | three | 942.0 |
| 7 | 1 | two | 539.0 |
| 9 | 2 | three | 814.0 |
'''
TODO: Now, try the same function on the series A and B
Print the values of attribute A before removing the null values
'''
print("original\n", A)
# TODO: now, print the values of A but without the null values
print("A after deleting the missing values = \n", A.dropna())
# TODO: do the same for B
print("original\n", B)
print("B after deleting the missing values = \n", B.dropna())
original
0 345.0
1 928.0
2 NaN
3 645.0
4 113.0
5 942.0
6 NaN
7 539.0
8 NaN
9 814.0
10 NaN
Name: amount, dtype: float64
A after deleting the missing values =
0 345.0
1 928.0
3 645.0
4 113.0
5 942.0
7 539.0
9 814.0
Name: amount, dtype: float64
original
0 NaN
1 125.0
2 335.0
3 345.0
4 312.0
5 NaN
6 NaN
7 129.0
8 551.0
9 800.0
10 222.0
dtype: float64
B after deleting the missing values =
1 125.0
2 335.0
3 345.0
4 312.0
7 129.0
8 551.0
9 800.0
10 222.0
dtype: float64However, very often you may wish to fill in those missing values rather than simply dropping them. Of course, pandas also has that functionality. For example, we could fill missing values with a constant. We do this for exercise only but you will learn later about different techniques for data imputation.
'''
TODO: replace the missing value with -99 in attribute A
'''
A.fillna(-99)
0 345.0
1 928.0
2 -99.0
3 645.0
4 113.0
5 942.0
6 -99.0
7 539.0
8 -99.0
9 814.0
10 -99.0
Name: amount, dtype: float64That actually works with any data type.
'''
TODO: fill the missing values with the string 'unknown' in attribute A
'''
print(A.fillna("unknown"))
A
0 345.0
1 928.0
2 unknown
3 645.0
4 113.0
5 942.0
6 unknown
7 539.0
8 unknown
9 814.0
10 unknown
Name: amount, dtype: object0 345.0
1 928.0
2 NaN
3 645.0
4 113.0
5 942.0
6 NaN
7 539.0
8 NaN
9 814.0
10 NaN
Name: amount, dtype: float64As such, we can use this functionality to fill in the gaps with the average value computed across the non-missing values.
'''
TODO: replace the missing values with the average value of the non-missing values
'''
A.fillna(A.mean())
0 345.0
1 928.0
2 618.0
3 645.0
4 113.0
5 942.0
6 618.0
7 539.0
8 618.0
9 814.0
10 618.0
Name: amount, dtype: float64'''
TODO: Use the same technique to replace the missing values
in the amount attribute of the incomplete dataframe
We create a new copy of the dataframe and work with the copy
so we can replace the values in the dataframe
'''
idf = incomplete_df.copy()
idf["amount"].fillna(incomplete_df["amount"].mean(), inplace = True)
idf
/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/1078432112.py:8: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.
The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.
For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.
idf["amount"].fillna(incomplete_df["amount"].mean(), inplace = True)| id | type | amount | |
|---|---|---|---|
| 0 | 1 | one | 345.0 |
| 1 | 2 | one | 928.0 |
| 2 | 3 | two | 618.0 |
| 3 | 2 | three | 645.0 |
| 4 | 2 | two | 113.0 |
| 5 | 3 | three | 942.0 |
| 6 | 1 | one | 618.0 |
| 7 | 1 | two | 539.0 |
| 8 | 1 | one | 618.0 |
| 9 | 2 | three | 814.0 |
| 10 | 4 | one | 618.0 |
incomplete_df
| id | type | amount | |
|---|---|---|---|
| 0 | 1 | one | 345.0 |
| 1 | 2 | one | 928.0 |
| 2 | 3 | two | NaN |
| 3 | 2 | three | 645.0 |
| 4 | 2 | two | 113.0 |
| 5 | 3 | three | 942.0 |
| 6 | 1 | one | NaN |
| 7 | 1 | two | 539.0 |
| 8 | 1 | one | NaN |
| 9 | 2 | three | 814.0 |
| 10 | 4 | one | NaN |
Even better, if we want to fill in the gaps with mean values of corresponding id's (recall our initial dataframe printed below), the following two lines of code perform that seemingly complex task.
'''
TODO: Fill in gaps in the 'amount' column with means obtained from corresponding id's in the first column
'''
idf2 = incomplete_df.copy()
idf2["amount"].fillna(idf2.groupby("id")["amount"].\
transform("mean"),inplace=True)
# TODO: display the dataframe. What do you see?
idf2
/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/520625319.py:5: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.
The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.
For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.
idf2["amount"].fillna(idf2.groupby("id")["amount"].\| id | type | amount | |
|---|---|---|---|
| 0 | 1 | one | 345.0 |
| 1 | 2 | one | 928.0 |
| 2 | 3 | two | 942.0 |
| 3 | 2 | three | 645.0 |
| 4 | 2 | two | 113.0 |
| 5 | 3 | three | 942.0 |
| 6 | 1 | one | 442.0 |
| 7 | 1 | two | 539.0 |
| 8 | 1 | one | 442.0 |
| 9 | 2 | three | 814.0 |
| 10 | 4 | one | NaN |
'''
TODO: If there is no corresponding id and the cell is still null,
simply use the overall mean
This step should follow the previous step
'''
idf2["amount"].fillna(idf2["amount"].mean(), inplace=True)
idf2
/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/3768350549.py:6: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.
The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.
For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.
idf2["amount"].fillna(idf2["amount"].mean(), inplace=True)| id | type | amount | |
|---|---|---|---|
| 0 | 1 | one | 345.0 |
| 1 | 2 | one | 928.0 |
| 2 | 3 | two | 942.0 |
| 3 | 2 | three | 645.0 |
| 4 | 2 | two | 113.0 |
| 5 | 3 | three | 942.0 |
| 6 | 1 | one | 442.0 |
| 7 | 1 | two | 539.0 |
| 8 | 1 | one | 442.0 |
| 9 | 2 | three | 814.0 |
| 10 | 4 | one | 615.2 |
You can fill values forwards and backwards with the flags pad / ffill and bfill / backfill
'''
TODO: fill the missing values in B with the values in the previous records (no limit)
'''
print (B)
print ('\n') # line to separate the output
B.fillna(method = 'pad')
0 NaN
1 125.0
2 335.0
3 345.0
4 312.0
5 NaN
6 NaN
7 129.0
8 551.0
9 800.0
10 222.0
dtype: float64/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/699988559.py:6: FutureWarning: Series.fillna with 'method' is deprecated and will raise in a future version. Use obj.ffill() or obj.bfill() instead.
B.fillna(method = 'pad')0 NaN
1 125.0
2 335.0
3 345.0
4 312.0
5 312.0
6 312.0
7 129.0
8 551.0
9 800.0
10 222.0
dtype: float64We can set a limit if we only want to replace consecutive gaps.
'''
TODO: fill the missing values in B with the value in the next record
(the value of a record can be used in the previous record only)
'''
print (B)
print ('\n') # line to separate the output
B.fillna(method = 'bfill', limit = 1)
0 NaN
1 125.0
2 335.0
3 345.0
4 312.0
5 NaN
6 NaN
7 129.0
8 551.0
9 800.0
10 222.0
dtype: float64/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/2204456688.py:7: FutureWarning: Series.fillna with 'method' is deprecated and will raise in a future version. Use obj.ffill() or obj.bfill() instead.
B.fillna(method = 'bfill', limit = 1)0 125.0
1 125.0
2 335.0
3 345.0
4 312.0
5 NaN
6 129.0
7 129.0
8 551.0
9 800.0
10 222.0
dtype: float64We can use the Pima Indians Diabetes Dataset "diabetes.csv" (https://www.kaggle.com/datasets/iammustafatz/diabetes-prediction-dataset) to practice on outlier detection
'''
TODO: read the csv file
'''
df_pid = pd.read_csv('diabetes.csv', header = 0,
quotechar = '"',sep = ",",
na_values = ['na', '-', '.', ''])
df_pid
| gender | age | hypertension | heart_disease | smoking_history | bmi | HbA1c_level | blood_glucose_level | diabetes | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | Female | 80.0 | 0 | 1 | never | 25.19 | 6.6 | 140 | 0 |
| 1 | Female | 54.0 | 0 | 0 | No Info | 27.32 | 6.6 | 80 | 0 |
| 2 | Male | 28.0 | 0 | 0 | never | 27.32 | 5.7 | 158 | 0 |
| 3 | Female | 36.0 | 0 | 0 | current | 23.45 | 5.0 | 155 | 0 |
| 4 | Male | 76.0 | 1 | 1 | current | 20.14 | 4.8 | 155 | 0 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 99995 | Female | 80.0 | 0 | 0 | No Info | 27.32 | 6.2 | 90 | 0 |
| 99996 | Female | 2.0 | 0 | 0 | No Info | 17.37 | 6.5 | 100 | 0 |
| 99997 | Male | 66.0 | 0 | 0 | former | 27.83 | 5.7 | 155 | 0 |
| 99998 | Female | 24.0 | 0 | 0 | never | 35.42 | 4.0 | 100 | 0 |
| 99999 | Female | 57.0 | 0 | 0 | current | 22.43 | 6.6 | 90 | 0 |
100000 rows × 9 columns
df_pid[df_pid.columns[1]]
0 80.0
1 54.0
2 28.0
3 36.0
4 76.0
...
99995 80.0
99996 2.0
99997 66.0
99998 24.0
99999 57.0
Name: age, Length: 100000, dtype: float64'''
TODO: for each column except the label column, compute the standard deviation of the columns
report all the values that are at distance > 3 * std from the mean value as outliers.
'''
%matplotlib inline
def stat_outliers (col):
outliers = set()
m = col.mean()
s = col.std()
for p in col.unique():
if (abs(p-m) > 3 * s):
outliers.add(p.item())
outliers_indexes = col.isin(outliers)
plt.plot(col, color='blue', marker='o', ms = 2, linewidth = 0)
plt.plot(col, color='red', markevery = outliers_indexes, marker='*', ms = 6, linewidth = 0)
plt.show()
return outliers
dataTypeSeries = df_pid.dtypes
for col_idx in range(len(df_pid.columns)-1):
if (not (dataTypeSeries[col_idx] == 'object')):
outliers = stat_outliers(df_pid[df_pid.columns[col_idx]])
print("Outliers in column ", df_pid.columns[col_idx], " are: ", outliers)
/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/624712760.py:20: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
if (not (dataTypeSeries[col_idx] == 'object')):Outliers in column age are: set()Outliers in column hypertension are: {1}Outliers in column heart_disease are: {1}Outliers in column bmi are: {47.67, 47.43, 47.93, 58.05, 60.52, 48.17, 47.44, 48.93, 48.18, 48.68, 47.92, 47.42, 49.15, 50.14, 47.68, 52.12, 49.41, 54.09, 55.95, 48.92, 50.15, 58.54, 53.63, 53.13, 56.33, 53.3, 54.87, 55.85, 56.73, 57.21, 59.99, 60.2, 60.26, 63.48, 65.93, 65.56, 69.37, 68.1, 69.39, 69.66, 73.77, 72.28, 79.48, 72.89, 50.42, 75.78, 83.74, 49.94, 79.46, 81.73, 87.51, 88.72, 87.7, 88.76, 91.82, 95.22, 95.69, 51.67, 51.17, 50.44, 50.94, 50.69, 64.26, 50.19, 51.68, 48.44, 51.69, 51.19, 51.94, 52.68, 53.17, 52.44, 50.25, 50.0, 53.18, 64.8, 54.93, 54.68, 54.43, 55.18, 47.97, 47.47, 47.72, 47.5, 47.25, 48.0, 48.5, 48.31, 47.94, 48.72, 49.44, 49.97, 49.0, 49.25, 49.75, 50.5, 50.78, 49.28, 50.53, 49.56, 51.66, 51.44, 51.41, 51.22, 51.84, 52.72, 52.69, 52.22, 52.03, 51.81, 53.44, 53.94, 53.22, 53.78, 53.03, 54.22, 54.69, 54.91, 54.0, 54.25, 55.19, 55.75, 55.28, 54.06, 54.66, 56.94, 56.47, 56.5, 56.25, 56.81, 57.22, 51.75, 57.34, 47.31, 47.81, 58.16, 58.06, 58.66, 58.31, 58.22, 59.03, 59.56, 59.59, 59.22, 58.75, 60.53, 60.03, 59.06, 60.75, 47.57, 61.56, 61.31, 60.0, 47.82, 59.42, 62.22, 62.19, 62.09, 48.06, 48.81, 62.72, 48.56, 62.81, 62.53, 47.83, 64.18, 64.31, 64.56, 64.5, 65.91, 65.59, 48.32, 66.88, 66.37, 66.84, 67.53, 49.06, 49.31, 68.53, 68.0, 68.47, 48.33, 48.58, 48.83, 69.32, 48.08, 49.57, 49.32, 72.03, 50.56, 50.31, 50.06, 49.58, 49.33, 49.83, 49.08, 49.29, 49.79, 50.57, 50.82, 51.56, 50.83, 50.33, 51.57, 51.32, 52.25, 52.56, 51.08, 51.58, 52.82, 53.31, 53.06, 53.07, 53.57, 54.81, 58.41, 53.58, 53.08, 53.33, 54.82, 55.58, 56.83, 58.56, 47.45, 59.91, 47.46, 47.96, 58.58, 48.95, 48.7, 48.21, 49.45, 49.95, 48.47, 48.22, 49.71, 49.46, 48.73, 48.98, 50.45, 50.7, 49.72, 49.47, 49.22, 50.46, 50.21, 49.98, 49.48, 51.45, 51.7, 50.22, 50.97, 50.47, 51.46, 51.71, 51.21, 50.98, 52.7, 52.2, 52.45, 51.23, 51.98, 53.45, 53.2, 53.7, 52.97, 47.98, 47.48, 47.54, 47.29, 47.76, 48.04, 48.23, 47.26, 47.73, 48.82, 49.23, 48.57, 49.04, 48.07, 49.07, 50.26, 50.73, 50.48, 50.13, 50.29, 51.73, 51.76, 51.04, 50.07, 50.1, 52.1, 52.07, 52.54, 52.04, 52.57, 53.38, 53.29, 53.26, 53.76, 52.35, 54.26, 54.48, 54.79, 54.04, 54.85, 55.98, 55.26, 55.1, 55.6, 55.76, 56.48, 56.85, 55.57, 56.35, 55.38, 57.79, 57.07, 57.32, 57.1, 54.98, 58.82, 58.26, 58.23, 58.1, 58.32, 59.6, 58.13, 58.73, 59.88, 58.98, 60.29, 61.85, 61.79, 61.04, 61.29, 62.88, 48.53, 48.03, 48.78, 63.85, 63.29, 63.82, 49.93, 49.68, 57.95, 57.45, 57.2, 47.59, 47.6, 47.35, 47.85, 58.97, 48.34, 48.59, 48.09, 47.36, 48.1, 48.85, 48.6, 48.35, 59.72, 47.62, 49.59, 49.34, 49.09, 48.36, 48.11, 48.86, 49.6, 49.1, 49.35, 48.62, 48.12, 50.84, 49.86, 49.11, 49.36, 49.78, 49.61, 50.35, 50.85, 50.6, 49.12, 49.87, 51.59, 51.09, 52.98, 52.23, 52.48, 50.11, 50.61, 51.35, 51.1, 52.24, 52.74, 50.12, 52.34, 51.86, 51.62, 53.59, 53.84, 53.34, 52.11, 53.35, 54.34, 54.59, 54.84, 53.11, 53.61, 54.35, 54.6, 53.12, 53.37, 55.34, 55.59, 54.62, 53.23, 56.1, 55.87, 57.84, 57.6, 56.87, 56.12, 58.09, 57.62, 48.54, 47.24, 48.79, 47.99, 47.74, 47.75, 48.49, 48.74, 47.51, 48.25, 48.75, 49.24, 49.99, 48.26, 48.51, 48.01, 49.5, 50.74, 50.49, 49.01, 49.26, 49.51, 47.64, 47.3, 47.7, 47.33, 47.61, 48.61, 48.3, 48.2, 48.55, 48.05, 49.17, 49.2, 49.7, 49.55, 49.8, 50.36, 50.3, 50.86, 50.2, 50.8, 51.39, 51.61, 51.36, 51.64, 50.08, 52.67, 52.83, 52.89, 52.14, 52.39, 53.89, 53.42, 53.39, 52.3, 53.05, 54.86, 54.39, 54.61, 54.7, 54.45, 55.11, 55.92, 55.17, 55.55, 55.61, 56.14, 56.36, 56.89, 51.51, 55.33, 57.17, 57.7, 52.5, 56.7, 56.45, 58.45, 58.8, 58.95, 57.39, 57.14, 59.7, 59.11, 59.92, 59.45, 59.33, 60.89, 52.51, 52.01, 60.36, 60.83, 61.67, 61.33, 61.92, 61.11, 62.55, 53.5, 53.0, 62.8, 63.3, 63.55, 64.23, 64.61, 64.73, 64.49, 64.36, 65.45, 53.01, 64.7, 64.52, 65.36, 66.48, 66.36, 65.11, 67.54, 67.39, 67.92, 67.27, 54.97, 68.61, 67.49, 69.55, 70.96, 71.55, 72.21, 56.49, 56.24, 49.92, 49.42, 49.67, 51.0, 57.51, 47.38, 58.5, 58.0, 47.89, 48.13, 48.38, 47.4, 48.39, 48.89, 47.41, 47.91, 49.38, 49.88, 47.66, 48.65, 48.4, 48.9, 49.14, 49.89, 49.02, 49.52, 48.16, 48.41, 48.91, 48.66, 50.88, 50.17, 49.4, 49.65, 49.91, 50.9, 50.4, 50.91, 50.66, 52.63, 50.41, 52.88, 52.13, 47.55, 51.91, 51.16, 53.88, 52.9, 53.64, 52.91, 54.88, 50.76, 54.63, 54.38, 53.65, 53.9, 64.27, 54.89, 50.27, 53.66, 53.16, 53.41, 55.88, 54.15, 53.97, 53.72, 54.16, 56.88, 55.65, 55.4, 56.39, 55.41, 56.18, 56.15, 56.65, 48.8, 56.91, 58.38, 57.9, 57.65, 47.77, 47.27, 57.16, 57.41, 51.26, 47.28, 47.53, 48.27, 47.9, 47.37, 47.87, 47.65, 47.49, 48.43, 48.96, 48.71, 48.46, 48.99, 48.24, 49.74, 49.49, 48.02, 49.27, 50.18, 50.96, 49.62, 49.43, 49.18, 51.93, 51.4, 51.65, 51.9, 50.77, 52.43, 52.49, 51.49, 51.87, 49.77, 53.21, 53.02, 52.15, 52.62, 52.96, 54.12, 53.27, 53.4, 53.77, 49.03, 55.52, 55.37, 55.62, 55.02, 55.27, 56.43, 55.12, 55.96, 55.99, 55.24, 57.15, 57.43, 56.4, 57.02, 56.21, 58.12, 58.4, 58.24, 58.93, 57.68, 59.4, 59.27, 59.96, 59.15, 50.03, 60.27, 60.12, 60.18, 59.62, 59.71, 61.02, 61.99, 61.68, 61.77, 51.27, 62.99, 49.3, 51.52, 51.77, 63.74, 63.18, 63.15, 63.27, 50.54, 50.04, 51.78, 51.03, 50.05, 52.52, 52.27, 52.78, 51.8, 51.05, 51.55, 53.28, 52.55, 52.8, 53.79, 54.53, 54.03, 54.29, 58.43, 55.78, 54.05, 54.3, 55.04, 56.04, 57.78, 56.55, 56.8, 58.78}Outliers in column HbA1c_level are: {8.8, 9.0}Outliers in column blood_glucose_level are: {280, 300}Now, we use the k-nearest neighbours method to detect the outliers
'''
First, we define a function to find the outlier and
plot the data after highlighting the outliers
'''
%matplotlib inline
def knn_outliers(data, threshold, n_neighbors):
nbrs = NearestNeighbors(n_neighbors = 10)
X = data.reshape(-1, 1)
# fit model
nbrs.fit(X)
# distances and indexes of k-neaighbors from model outputs
distances, indexes = nbrs.kneighbors(X)
# plot mean of k-distances of each observation
plt.plot(distances.mean(axis = 1))
# visually determine cutoff values > 0.15
outlier_index = np.where(distances.mean(axis = 1) > threshold)
knn_outliers = list(outlier_index[0])
plt.plot(data, color='blue', marker='o', ms = 2, linewidth = 0)
plt.plot(data, markevery = knn_outliers, color='green', marker='s', ms=7, fillstyle='none', linewidth=0)
plt.show()
outliers = X[knn_outliers]
return np.unique(outliers)
'''
TODO: now, we iterate over the columns and find the outliers in each column
'''
dataTypeSeries = df_pid.dtypes
for col_idx in range(len(df_pid.columns)-1):
if (not (dataTypeSeries[col_idx] == 'object')):
current_attribute = df_pid.columns[col_idx]
cur_att_values = np.array(df_pid[current_attribute])
outliers = knn_outliers(cur_att_values, 0.75, 10)
print("Attribute {} has {} as outliers".format(current_attribute, outliers))
/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/1748342502.py:6: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
if (not (dataTypeSeries[col_idx] == 'object')):Attribute age has [] as outliers/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/1748342502.py:6: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
if (not (dataTypeSeries[col_idx] == 'object')):Attribute hypertension has [] as outliers/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/1748342502.py:6: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
if (not (dataTypeSeries[col_idx] == 'object')):Attribute heart_disease has [] as outliers/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/1748342502.py:6: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
if (not (dataTypeSeries[col_idx] == 'object')):Attribute bmi has [70.96 71.55 72.03 72.21 72.28 72.89 73.77 75.78 79.46 79.48 81.73 83.74
87.51 87.7 88.72 88.76 91.82 95.22 95.69] as outliers/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/1748342502.py:6: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
if (not (dataTypeSeries[col_idx] == 'object')):Attribute HbA1c_level has [] as outliers/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/1748342502.py:6: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
if (not (dataTypeSeries[col_idx] == 'object')):Attribute blood_glucose_level has [] as outliersNow, we use the LOF method to detect the outliers
'''
TODO: Apply LOF to find outliers in all the columns in the dataframe except the label
'''
from sklearn.neighbors import LocalOutlierFactor
%matplotlib inline
def lof_outliers(data, threshold):
clf = LocalOutlierFactor(n_neighbors = 10)
X = data.reshape(-1, 1)
clf.fit_predict(X)
lofOutiers = []
for cc in range(len(clf.negative_outlier_factor_)):
if clf.negative_outlier_factor_[cc] < -threshold:
lofOutiers.append(cc)
plt.plot(data, color='blue', marker='*', ms=6, linewidth=0)
plt.plot(data, markevery = lofOutiers, color='red', marker='s', ms=9, \
fillstyle='none', linewidth=0)
plt.show()
outliers = X[lofOutiers]
return np.unique(outliers)
'''
TODO: now, we iterate over the columns and find the outliers in each column
'''
dataTypeSeries = df_pid.dtypes
for col_idx in range(len(df_pid.columns)-1):
if (not (dataTypeSeries[col_idx] == 'object')):
current_attribute = df_pid.columns[col_idx]
cur_att_values = np.array(df_pid[current_attribute])
outliers = lof_outliers(cur_att_values, 1.0)
print("Attribute {} has {} as outliers".format(current_attribute, outliers))
/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/2169311699.py:6: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
if (not (dataTypeSeries[col_idx] == 'object')):Attribute age has [] as outliers/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/2169311699.py:6: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
if (not (dataTypeSeries[col_idx] == 'object')):Attribute hypertension has [] as outliers/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/2169311699.py:6: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
if (not (dataTypeSeries[col_idx] == 'object')):Attribute heart_disease has [] as outliers/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/2169311699.py:6: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
if (not (dataTypeSeries[col_idx] == 'object')):
/Users/hakim/Documents/gen_env/lib/python3.10/site-packages/sklearn/neighbors/_lof.py:322: UserWarning: Duplicate values are leading to incorrect results. Increase the number of neighbors for more accurate results.
warnings.warn(/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/2169311699.py:6: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
if (not (dataTypeSeries[col_idx] == 'object')):Attribute bmi has [10.01 10.08 10.14 ... 91.82 95.22 95.69] as outliersAttribute HbA1c_level has [] as outliers/var/folders/7c/thwjjxtx3_n8jl9xncdtz7rc0000gq/T/ipykernel_28959/2169311699.py:6: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
if (not (dataTypeSeries[col_idx] == 'object')):Attribute blood_glucose_level has [] as outliers