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
"""
return None
print("Minimum edit disctance = ", ldist("INTENTION", "EXECUTION"))
'''
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
"""
return None
# print("Minimum edit disctance = ", mod_ldist("INTENTION", "EXECUTION", 2))
'''
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.'''
return None
'''
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):
return None
# 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 ("Just a place holder")
# print("jaro(%r, %r) = %.4f and jaro-winkler(%r, %r) = %.4f" % (s, t, jaro(s, t), s, t, jaro_winkler(s, t)))
'''
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.
"""
return None
soundex('EDUCATE'), soundex('EVALUATE')
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 = ??? tokenize D1 into words
# S2 = ??? tokenize D2 into words
# S3 = ??? tokenize D3 into words
# S4 = ??? tokenize D4 into words
'''
TODO: Compute the pairwise Jaccard similarity for the sets S1, S2, S3, and S4.
'''
def jaccard_similarity(set1, set2):
return None
# 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))
'''
TODO: Compute the pairwise Sørensen Coefficient for the sets S1, S2, S3, and S4.
'''
def Sørensen_Coefficient(set1, set2):
return None
# 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))
'''
TODO: Compute the pairwise Tversky Index for the sets S1, S2, S3, and S4.
'''
def Tversky_Coefficient(set1, set2):
return None
# 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))
'''
TODO: Compute the pairwise Overlap Coefficient for the sets S1, S2, S3, and S4.
'''
def Overlap_Coefficient(set1, set2):
return None
# 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))
3. 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."
k = 5
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
'''
Now we use k = 3
'''
k = 3
# result_3sh = ???
# result_3sh
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:
'''
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'
'''
TODO:
* create a single list that contains all the sentences in D1, D2, D3, and D4
* find the list of 3-shingles from the full list of sentences
* Use the functions build_vocab and one_hot to create the documents-shinles matrix
(you can also use your own functions)
'''
k = 3
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):
return None
# 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)))
'''
TODO: Try the other set similarity metrics 'Sørensen Coefficient', 'Tversky Index' and 'Overlap Coefficient'
'''
4. Data Preparation
For this part, you need to install the following libraries:
matplotlib
sklearn
!pip install matplotlib
!pip install scikit-learn
from 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
#TODO: print the content of B
The mean is computed normally and missing values are ignored:
# TODO: Compute and print the mean value of A uing pandas library
# TODO: Compute and print the mean value of A using numpy library
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
# 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
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
# TODO: use the numpy library to add A and B
np.add(A, B)
First, 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
# TODO: Now, try the same function on the series A and B
# Print the values of attribute A before removing the null values
# TODO: now, print the values of A but without the null values
# TODO: do the same for B
However, 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
That actually works with any data type.
# TODO: fill the missing values with the string 'unknown' in attribute A
As 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
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
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
# TODO: display the dataframe. What do you see?
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
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)
We 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)
'''
We 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 and store it in a pandas DataFrame
'''
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):
# 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 None
# 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)
Now, we use the k-nearest neighbours method to detect the outliers
'''
TODO: 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):
# 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()
return None
'''
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))
Now, 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):
# 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()
return None
'''
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))