0% found this document useful (0 votes)
18 views23 pages

SVM and KNN Classification Examples

The document contains multiple assignments involving machine learning techniques, including SVM and KNN classification, as well as data manipulation using pandas. It provides code snippets for each task, detailing steps such as data loading, preprocessing, model training, and evaluation. Additionally, it includes practice questions on data structures and handling missing values in datasets.

Uploaded by

analrat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views23 pages

SVM and KNN Classification Examples

The document contains multiple assignments involving machine learning techniques, including SVM and KNN classification, as well as data manipulation using pandas. It provides code snippets for each task, detailing steps such as data loading, preprocessing, model training, and evaluation. Additionally, it includes practice questions on data structures and handling missing values in datasets.

Uploaded by

analrat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ASSIGNMENT

[Link] Classification on News Dataset


Code:
#SVM classification on News Dataset
import pandas as pd
import numpy as np
import seaborn as sns
import [Link] as plt
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from [Link] import SVC
from [Link] import
accuracy_score,classification_report,confusion_matrix
from [Link] import StandardScaler
from [Link] import hstack
#Load the dataset
file_path = "Google [Link]"
df = pd.read_csv(file_path)#encoding='ISO-8859-1'
#Drop missing values
df=[Link]()
#Extract features and labels
X_text =
df[['title','publisher','date','keyword','country']].astype(str).agg(''.join,axis=1)
y = df['category']
#Convert text to numerical features using TF-IDF
vectorizer = TfidfVectorizer(stop_words='english',max_features=5000)
X_tfidf=vectorizer.fit_transform(X_text)
#Standardize the TF-IDF features
scaler = StandardScaler(with_mean=False)
X_tfidf_scaled=scaler.fit_transform(X_tfidf)
#Split into training and testing sets(80%train,20%test)
X_train,X_test,y_train,y_test=train_test_split(X_tfidf_scaled,y,test_size=0.2,ran
dom_state=42)
#Train SVM model
svm_model=SVC(kernel='linear',random_state=42)
svm_model.fit(X_train,y_train)
#Predict on test data
y_pred=svm_model.predict(X_test)
#Evaluate modell performance
accuracy=accuracy_score(y_test,y_pred)
report=classification_report(y_test,y_pred,zero_division=1)
#Compute confusion matrix
conf_matrix=confusion_matrix(y_test,y_pred)
#Plot confusion matrix
[Link](figsize=(10,7))
[Link](conf_matrix,annot=True,fmt='d',cmap='Blues',xticklabels=[Link]
ue(y),yticklabels=[Link](y))
[Link]('Predicted Label')
[Link]('Confusion Matrix')
[Link]()
#Print the results
print(f"Accuracy: {accuracy:.4f}")
print("Classification Report:")
print(report)

Dataset:

Input:
Output:
[Link] Classification with Decision Boundary
Code:
import pandas as pd
import numpy as np
import [Link] as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from [Link] import KNeighborsClassifier
from [Link] import confusion_matrix,classification_report

#Load Dataset
df=pd.read_csv("student_pass.csv")

#Split into features (X) and target (y)


X = df[['Hours_Studied','Sleep_Hours']] #Features
y = df['Exam_Score'].map({'Fail':0,'Pass':1})

X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=4
2)
#Train KNN model(K=3)
knn = KNeighborsClassifier(n_neighbors=3)
[Link](X_train,y_train)

#Predict on test data


y_pred=[Link](X_test)
cm=confusion_matrix(y_test,y_pred)
print("Confusion Matrix:\n",cm)
print("\nClassification Report:\n",classification_report(y_test,y_pred))

#Plotting the decision boundary


[Link](figsize=(10,6))

#Create a mesh grid for decision boundary


x_min,x_max=X["Hours_Studied"].min()-1,X["Hours_Studied"].max()+1
y_min,y_max=X["Sleep_Hours"].min()-1,X["Sleep_Hours"].max()+1
xx,yy=[Link]([Link](x_min,x_max,100),[Link](y_min,y_max,10
0))

#Predict for each point in the grid


Z=[Link](np.c_[[Link](),[Link]()])
Z=[Link]([Link])

#Plot the decision boundary using contour


[Link](xx,yy,Z,alpha=0.3,cmap='coolwarm')

#Scatter plot of training data


[Link](x=X_train["Hours_Studied"],y=X_train["Sleep_Hours"],hue=y_tr
ain,palette={0:'red',1:'green'},s=100,edgecolor='black')

#Scatter plot of test data


[Link](x=X_test["Hours_Studied"],y=X_test["Sleep_Hours"],hue=y_pre
d,marker='s',palette={0:'orange',1:'blue'},s=150,edgecolor='black')

#Labels and title


[Link]("Hours Studied")
[Link]("Sleep Hours")
[Link]("KNN Classification with Decision Boundary")
[Link](title="Legend",labels=["Fail(Train)","Pass(Train)","Fail(Test)","Pass(Te
st)"])
[Link](True)
[Link]()
Dataset:

Input:
Output:
[Link] Questions
3(a)
Code:
import pandas as pd
#Creating a series from a list
data = [10,20,30,40,50]
series1 = [Link](data)
print(series1)

Input:

Output:

3(b)
Code:
#Creating a pandas dataframe
import pandas as pd
#creating a dataframe froom a dictionary
data={
'Name':['Alice','Bob','Charlie'],
'Age':[25,30,35],
'Salary':[50000,60000,70000]
}
df=[Link](data)
print(df)
Input:
Output:

3(c)
Code:
#From a list of lists
data = [
['Alice',25,50000],
['Bob',30,60000],
['Charlie',35,70000]
]
df = [Link](data,columns=['Name','Age','Salary'])
print(df)
Input:

Output:
3(d)
Code:
#missing values
import pandas as pd
import numpy as np
#creating a dataset with some missing values
data = {
'Name': ['Alice','Bob','Charlie','David','Emma'],
'Age': [25,[Link],30,35,[Link]],
'Salary': [50000,60000,[Link],80000,75000],
'Department': ['HR','IT',[Link],'Finance','IT']
}
df = [Link](data)
print("Original Dataset with Missing Values:")
print(df)
Input:

Output:
3(e)
Code:
print("Missing Values in Each Column:")
print([Link]().sum()) #count missing values in each column
Input:

Output:

3(f)
Code:
import pandas as pd
import numpy as np
#Fill missing Age with the mean age
df['Age'].fillna(df['Age'].mean(),inplace=True)

#Fill missing salary with the median salary


df['Salary'].fillna(df['Salary'].median(),inplace=True)

#Fill missing department with the most frequent vzlue(mode)


df['Department'].fillna(df['Department'].mode()[0],inplace=True)

print("Dataset After filling missing values")


print(df)
Input:
Output:

3(g)
Code:
import pandas as pd
from [Link] import MinMaxScaler
#minmax normalization
#sample data
data = [Link]([[1,2],[3,4],[5,6],[7,8]])
#initialize the scaler
scaler = MinMaxScaler()
#fit and transform the data
print(data)
normalized_data = scaler.fit_transform(data)
print("Normalized Data (Min-Max Scaling)")
print(normalized_data)
Input:
Output:

3(h)
Code:
import pandas as pd
import numpy as np

#dictionary
data={
'Name':['Geek1','Geek2','Geek3','Geek4'],
'Salary':[18000,20000,15000,35000]
}
#create a dataframe
data = [Link](data,
columns=['Name',
'Salary'])
#show the dataframe
data
data['logarithm_base2'] = np.log2(data['Salary'])
#Show the dataframe
print(data)
Input:

Output:

3(i)
Code:
import pandas as pd
import numpy as np

#sample dataset
data = [50,60,70,80,90,100]

#convert to Pandas DataFrame


df = [Link](data,columns=['Values'])
#compute mean and standard deviation
mean = df['Values'].mean()
std_dev = df['Values'].std()

#Apply Z-score normalization


df['Z-Score'] = (df['Values']-mean)/std_dev

#display the results


print(df)
Input:

Output:
4. Naïve Bayes Classification
Code:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from [Link] import LabelEncoder
from sklearn.naive_bayes import GaussianNB
from [Link] import
accuracy_score,classification_report,confusion_matrix
#Sample weather Dataset
data = pd.read_csv("[Link]")
df=[Link](data)
#Encoding categorical features
label_enc=LabelEncoder()
df['Outlook'] = label_enc.fit_transform(df['Outlook']) #Convert
#'Sunny','Rain' etc. to numbets
df['Wind'] = label_enc.fit_transform(df['Wind']) #Covert 'Yes'
#No' to 1,0
df['Humidity'] = label_enc.fit_transform(df['Humidity']) #Convert 'Yes'
df['Temperature'] = label_enc.fit_transform(df['Humidity'])
#Splitting features and target
X=df[['Outlook','Temperature','Humidity','Wind']]
y=df['PlayTennis']
#Train test split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=4
2)
#Train Naive Bayes Classifier
model=GaussianNB()
[Link](X_train,y_train)
#Predictions
y_pred=[Link](X_test)
#Evaluate Model
print("Accuracy:",accuracy_score(y_test,y_pred))
print("Confusion Matrix:\n",confusion_matrix(y_test,y_pred))
print("Classification Report:\n",classification_report(y_test,y_pred))
Dataset:

Input:
Output:
[Link]-Model
Code:
#EM-Model
import pandas as pd
import numpy as np
import [Link] as plt
from [Link] import GaussianMixture
from [Link] import StandardScaler
from [Link] import confusion_matrix,accuracy_score

#Load dataset
df = pd.read_csv("student_data.csv")
#Extraxt features(Math Score, Science Score)
X = df[["Math_Score","Science_Score"]].values
y_true = df["Category"].values #True labels(0 or 1)

#Standardize data for better clustering


scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

#Apply Gaussian Mixture Model(EM Algorithm)


gmm =
GaussianMixture(n_components=2,covariance_type='full',random_state=42)
[Link](X_scaled)
y_pred=[Link](X_scaled) #Predicted clusters
#Adjust cluster labels to match true labels
if [Link](y_pred[y_true==1])< [Link](y_pred[y_true==0]):
y_pred = 1-y_pred #swap labels if necessary
#Compute Accuracy & Confusion Matrix
accuracy = accuracy_score(y_true,y_pred)
conf_matrix = confusion_matrix(y_true,y_pred)
print("Accuracy:",accuracy)
print("Confusion Matrix:\n",conf_matrix)

#Plot the clusters


[Link](figsize=(8,6))
[Link](X[:,0],X[:,1],c=y_pred,cmap='coolwarm',edgecolors='k',s=100)
[Link]("Math Score")
[Link]("Science Score")
[Link]("Student Clusters using EM(GMM)")
[Link](label="Cluster Label")
[Link]()
Dataset:
Input:
Output:

Common questions

Powered by AI

TF-IDF (Term Frequency-Inverse Document Frequency) is crucial in text classification tasks as it converts textual data into numerical features by reflecting the importance of a word in a document relative to a collection of documents (the corpus). In SVM classification, using TF-IDF helps in emphasizing important words while reducing the weight of commonly used words, thus improving the model's ability to classify and understand the context within the data .

Accuracy alone can be misleading, especially in imbalanced datasets. Classification report metrics like precision, recall, and F1-score provide deeper insights into the model's performance by showing the balance between true positive, false positive, and false negatives. They help evaluate how well a model distinguishes between classes, ensuring that it performs well across different aspects of the classification task .

Standardization ensures that the TF-IDF features are on a similar scale without altering the differences between values. In SVM classification, particularly when features vary greatly in range, standardization prevents features with larger ranges from dominating those with smaller ranges, allowing for a more balanced, efficient learning process .

Min-Max normalization scales data to a specific range, usually [0,1], which helps in handling numerical differences across features such as salary. This transformation is particularly effective in preventing numerical instability when dealing with algorithms sensitive to the scale of input features, ensuring that all variables contribute equally to the model's learning process .

The decision boundary in KNN classification illustrates the regions in the feature space where the classification of data points will change, offering a visual interpretation of how the model predicts classes based on the nearest neighbors. It is crucial because it visually demonstrates how well the model has segmented the feature space and highlights areas of potential overlap or misclassification among classes, which can be critical for understanding model performance and tuning K-values .

The choice of kernel in SVM models determines the decision boundary's complexity and ability to separate data points. A linear kernel is often used in text data due to its simplicity and efficiency in high-dimensional spaces like those created by TF-IDF transformations. It effectively handles text classification by assuming a linear relationship in the transformed feature space, leading to better performance with lower computational complexity .

Filling missing values with statistical measures like mean, median, or mode during data preprocessing ensures that all records are usable by replacing gaps with central tendencies, thus maintaining data completeness. However, this can reduce data variability and mask genuine trends within specific segments, potentially biasing model outcomes if the missing data's characteristics don't align well with the imputed statistics .

A linear decision boundary in high-dimensional spaces offers simplicity and reduced computational overhead, beneficial for large-scale text data. However, it may struggle to capture complex patterns and interactions between features that non-linear kernels could identify. The challenge lies in balancing model complexity with interpretability and computational efficiency, particularly when the data structure might inherently require a more sophisticated boundary .

Gaussian Naive Bayes is effective for categorical datasets where features can be encoded as numerical values. This statistical method assumes that features follow a Gaussian distribution, which can simplify the classification process and offer rapid predictions. Feature encoding transforms categorical variables into a numerical format, which is essential for Gaussian models but can introduce bias if not properly executed or if the encoded values do not reflect intrinsic relationships between categories .

The Expectation-Maximization (EM) algorithm iteratively refines the expected cluster assignments and updates the parameters of each cluster in Gaussian Mixture Models, allowing the model to converge on the optimal number of clusters. This iterative process efficiently identifies distinct groups by maximizing the likelihood of the observed data under the specified model, serving as a powerful method for uncovering the natural grouping of data points .

You might also like