0% found this document useful (0 votes)
5 views8 pages

Deep Learning and ML Model Evaluation

The document contains Python code for implementing various machine learning models, including deep neural networks and traditional classifiers like logistic regression, decision trees, random forests, and support vector machines. It utilizes libraries such as Keras, Scikit-learn, and Pandas for data handling, model training, and evaluation. The code also includes a graphical user interface using Tkinter for user interaction and data input.

Uploaded by

Aparna Arunpandi
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)
5 views8 pages

Deep Learning and ML Model Evaluation

The document contains Python code for implementing various machine learning models, including deep neural networks and traditional classifiers like logistic regression, decision trees, random forests, and support vector machines. It utilizes libraries such as Keras, Scikit-learn, and Pandas for data handling, model training, and evaluation. The code also includes a graphical user interface using Tkinter for user interaction and data input.

Uploaded by

Aparna Arunpandi
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

Sample code

Deep Neural Networks

import time
import pandas as pd
import numpy as np
import [Link] as plt
#import seaborn as sns
from [Link].vis_utils import plot_model
import tkinter as tk
from [Link] import askopenfilename
x=[Link]([569,30])
y=[Link]([569,1])
dataset=[Link]()
dataset=[Link](0)

def gettraindata():
global v
global allurlsdata
global dataset
global x,y
csv_file_path = askopenfilename()
print(csv_file_path)
[Link](csv_file_path)
dataset = pd.read_csv(csv_file_path)
x = [Link][:, 2:].values
y = [Link][:, 1].values

from tkinter import scrolledtext


txt = [Link](root,width=10,height=10,wrap=[Link])
[Link](column=1,row=1)
[Link]([Link],x)
from tkinter import scrolledtext
txt1 = [Link](root,width=10,height=10,wrap=[Link])
[Link](column=3,row=1)
[Link]([Link],y)

def ccdata():
global y
from [Link] import LabelEncoder
labelencoder_X_1 = LabelEncoder()
y = labelencoder_X_1.fit_transform(y)
from tkinter import scrolledtext
txt2 = [Link](root,width=10,height=10,wrap=[Link])
[Link](column=3,row=3)
[Link]([Link],y)
x_train=[]
x_test=[]
y_train=[]
y_test=[]
def tts():
global x,y,x_train,x_test,y_train,y_test
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.1, random_state
= 0)
def fs():
global x_train,x_test
from [Link] import StandardScaler
sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test = [Link](x_test)
from tkinter import scrolledtext
txt3 = [Link](root,width=10,height=10,wrap=[Link])
[Link](column=3,row=5)
[Link]([Link],x_train)
from tkinter import scrolledtext
txt4 = [Link](root,width=10,height=10,wrap=[Link])
[Link](column=4,row=5)
[Link]([Link],x_test)

def bm():
from [Link] import seed
seed(1)
import keras
from [Link] import Sequential
from [Link] import Dense, Dropout
global x,y,x_train,x_test,y_train,y_test

from tensorflow import set_random_seed


set_random_seed(2)
# Initialising the ANN
classifier = Sequential()
# Adding the input layer and the first hidden layer
[Link](Dense(output_dim=16, init='uniform', activation='relu',
input_dim=30))
# Adding dropout to prevent overfitting
[Link](Dropout(p=0.1))
[Link](Dense(output_dim=16, init='uniform', activation='relu'))
# Adding dropout to prevent overfitting
[Link](Dropout(p=0.1))
[Link](Dense(output_dim=1, init='uniform', activation='sigmoid'))
# Compiling the ANN
[Link](optimizer='adam', loss='binary_crossentropy',
metrics=['accuracy'])
# Fitting the ANN to the Training set
history=[Link](x_train, y_train, validation_split=0.1,batch_size=100,
nb_epoch=150)
plot_model(classifier, to_file='model_plot.png', show_shapes=True,
show_layer_names=True)
y_pred = [Link](x_test)
y_pred = (y_pred > 0.5)
from [Link] import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
print("Our accuracy is {}%".format(((cm[0][0] + cm[1][1])/57)*100))
acc=((cm[0][0] + cm[1][1])/57)*100 #[Link](cm,annot=True)
#[Link]('[Link]')
from [Link] import classification_report
cr=classification_report(y_test, y_pred)
from tkinter import scrolledtext
txt1ts = [Link](root,width=60,height=8,wrap=[Link])
[Link](row=2,column=9)
[Link]([Link],cr)
[Link](root, text=' Accuracy').grid(row=7, column=0)
v2 = [Link]()
entry1 = [Link](root, textvariable=v2).grid(row=7, column=5)
[Link](acc)
import [Link] as plt
[Link]([Link]['acc'])
[Link]([Link]['val_acc'])
[Link]('Model accuracy')
[Link]('Accuracy')
[Link]('Epoch')
[Link](['Train', 'Test'], loc='upper left')
[Link]()

# Plot training & validation loss values


[Link]([Link]['loss'])
[Link]([Link]['val_loss'])
[Link]('Model loss')
[Link]('Loss')
[Link]('Epoch')
[Link](['Train', 'Test'], loc='upper left')
[Link]()
print("--- %s seconds ---" % ([Link]() - start_time))

root = [Link]()
start_time = [Link]()
#[Link](root, text='File Path').grid(row=0, column=0)
v = [Link]()
entry = [Link](root, textvariable=v).grid(row=0, column=0)
[Link](root, text='Select Data File',command=gettraindata).grid(row=0, column=2)
[Link](root, text='Convert Categorical Data',command=ccdata).grid(row=3,
column=2)
[Link](root, text='Train Test Split',command=tts).grid(row=4, column=2)
[Link](root, text='Feature Scaling',command=fs).grid(row=5, column=2)
[Link](root, text='Build Model',command=bm).grid(row=6, column=2)
[Link]()
Machine Learning Models
import time
import pandas as pd
import numpy as np
import [Link] as plt
import seaborn as sns
from [Link].vis_utils import plot_model
# Importing data
data = pd.read_csv('[Link]')
#del data['Unnamed: 32']
X = [Link][:, 2:].values
y = [Link][:, 1].values
from [Link] import LabelEncoder
labelencoder_X_1 = LabelEncoder()
y = labelencoder_X_1.fit_transform(y)

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state =
0)

#Feature Scaling
# from [Link] import StandardScaler
# sc = StandardScaler()
# X_train = sc.fit_transform(X_train)
# X_test = [Link](X_test)
print("==================LOGISTIC REGRESSION===============")
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
model= LogisticRegression()
[Link](X_train,y_train)
y_pred=[Link](X_test)
from [Link] import accuracy_score
acc_sco=accuracy_score(y_test, y_pred)
print("ACCURACY",acc_sco)
from [Link] import classification_report
cr=classification_report(y_test, y_pred)
print("Classification report",cr)

print("==========DECISION TREE================")
from [Link] import DecisionTreeClassifier
from sklearn import tree
model1= DecisionTreeClassifier()
[Link](X_train,y_train)
y_pred1=[Link](X_test)
from [Link] import accuracy_score
acc_sco1=accuracy_score(y_test, y_pred1)
print("ACCURACY",acc_sco1)
from [Link] import classification_report
cr=classification_report(y_test, y_pred1)
print("Classification report",cr)

print("====================Random Forest================")
from [Link] import RandomForestClassifier
model2= RandomForestClassifier()
[Link](X_train,y_train)
y_pred2=[Link](X_test)
from [Link] import accuracy_score
acc_sco2=accuracy_score(y_test, y_pred2)
print("ACCURACY",acc_sco2)
from [Link] import classification_report
cr=classification_report(y_test, y_pred2)
print("Classification report",cr)

print("=========Support vector Classifier==============")


from [Link] import SVC
model3= SVC(kernel='linear', C = 1.0)
[Link](X_train,y_train)
y_pred3=[Link](X_test)
from [Link] import accuracy_score
acc_sco3=accuracy_score(y_test, y_pred3)
print("ACCURACY",acc_sco3)
from [Link] import classification_report
cr=classification_report(y_test, y_pred3)
print("Classification report",cr)

Common questions

Powered by AI

The different machine learning models show varying performance in terms of accuracy. The logistic regression model achieves a certain level of accuracy (not specified in the excerpt). The decision tree classifier and random forest classifier also have their own respective accuracy scores. Among these, random forest is often expected to perform better due to its ensemble nature, which reduces overfitting and improves generalization. However, the actual effectiveness would depend on the specific accuracy scores which are not explicitly defined in the provided sources. Models like the support vector classifier, with its linear kernel, could offer competitive accuracy in scenarios where linear separation is feasible .

The ScrolledText widget in Tkinter provides a text area for display that is both scrollable and editable. In the given code, it displays various intermediate results such as the feature matrix `x`, label vector `y`, and transformed data. By enabling scrolling, it handles larger datasets conveniently within the GUI, allowing users to view outputs that exceed the default visible area .

Model validation is integrated through the use of a validation split within the training dataset during the fitting of the neural network. The code specifies `validation_split=0.1`, dedicating 10% of the training data for validation. This approach helps monitor the model's performance on unseen data throughout training and aids in early stopping and hyperparameter tuning by comparing training and validation metrics .

Using different classifiers on the same dataset allows for the comparison of models to determine which performs best under specific conditions. Each classifier has distinct strength and biases—Logistic Regression is simple with quick interpretation, Decision Trees capture complex relationships emphasizing interpretability, Random Forest reduces overfitting with ensemble techniques, and SVM focuses on maximizing margins for classification tasks. This diversity allows one to assess trade-offs related to accuracy, runtime, and interpretability .

The grid placement in Tkinter organizes GUI components into a grid-like structure, using rows and columns to control widgets' positioning. This system facilitates a structured and easily modifiable GUI layout where components can be added, removed, or adjusted without affecting other elements drastically. By employing `grid()` method calls, the code specifies each widget’s location, effectively arranging the interface into a coherent and user-friendly layout .

The introduction of dropout layers in a neural network model prevents overfitting by randomly dropping units along with their connections during training. This thins the network and creates an ensemble of smaller networks, which improves the model's generalization capacity by forcing it to rely on multiple representations rather than specific weights. In the code, dropout is added after each hidden layer to help prevent overfitting and improve validation accuracy .

The preprocessing steps include filling missing values with zeroes (`dataset.fillna(0)`), encoding categorical labels using `LabelEncoder`, splitting the dataset into training and testing sets using `train_test_split`, and standardizing feature scales with `StandardScaler`. These steps ensure that the dataset is cleaned, features are properly scaled for better convergence, and the proportions of train-test datasets are controlled to maintain unbiased model validation .

Setting the random seed in neural network training helps ensure reproducibility by fixing the randomness involved in weight initialization and other stochastic processes. By doing so, you can expect the same sequence of random numbers in every run, leading to consistent model initialization and similar training outcomes across different runs. In the given code, setting the random seed using `numpy.random.seed(1)` and `tensorflow.set_random_seed(2)` stabilizes the training output and allows for a fair comparison between model runs .

Feature scaling, implemented using `StandardScaler`, standardizes the dataset's features by removing the mean and scaling to unit variance. This is crucial for algorithms that rely on the distance between feature values, such as Logistic Regression, SVM, and neural networks. It ensures that each feature contributes equally to the result, thereby improving the convergence rate of gradient-based optimizers and leading to more stable and efficient learning outcomes .

While a single validation epoch history plot provides a quick visualization of accuracy and loss trends over time, it may overlook nuances such as stability and recovery from bad starts. Evaluating subtler metrics such as per-class accuracy, precision-recall curves, and F1 score would give deeper insights into misclassifications and class distributions, enabling fine-grained model assessments and improved hyperparameter tuning feedback. Comprehensive analysis leads to more informed decisions on model modifications and deployment strategies .

You might also like