SlideShare a Scribd company logo
File: /home/andres/Dropbox/Classes/…es/Data/SimpleNeuralNetwork.py Page 1 of 3
import matplotlib.pyplot as plt
import numpy as np
from scipy.special import expit
def sigmoid(eval):
return expit(eval)
def Neural_Training(Y01, Labels01 , eta , Epochs):
d,samplenumb = Y01.shape
# Random [-1,1] init from Haykin
WIH = 2*np.mat(np.random.rand(2*d,d)) -1.0
WHO = 2*np.mat(np.random.rand(1,2*d)) -1.0
difft = Labels01.astype(np.float64)
for i in xrange(1,Epochs):
#Get the input to the output layer
y_j_temp = sigmoid(WIH*Y01)
netk = WHO*y_j_temp
zk = sigmoid(netk)
# Creating Delta Wk
diff1 = difft - zk
tDeltaWk = eta*np.multiply(diff1,np.multiply(sigmoid(netk),1.0-sigmoid(netk)))
tDeltaWk = np.tile(tDeltaWk,(2*d,1))
DeltaWk = np.multiply( y_j_temp,tDeltaWk)
DeltaWk = np.transpose(np.sum(DeltaWk,1))
# New Weights
WHO = WHO + DeltaWk
#Creating Delta Wj
dnetj = np.multiply(y_j_temp,1.0-y_j_temp)
tprodsumk = np.multiply(np.transpose(DeltaWk),np.transpose(WHO))
tprodsumk = np.tile(tprodsumk, (1,samplenumb) )
tprodsumk = eta*np.multiply(tprodsumk,dnetj)
DeltaWj = tprodsumk * np.transpose(Y01)
# New Weights
WIH = WIH + DeltaWj
return WIH, WHO
# Number of samples
N= 60000
#Number of Epochs
Epochs = 20
#Learning Rate
eta = 0.001
# opening images for [r]eading as [b]inary
in_file = open("train-images.idx3-ubyte", "rb")
in_file.read(16)
Data = in_file.read()
in_file.close()
# Transform the data stream
X = np.fromstring(Data, dtype=np.uint8)
X = X.astype(np.float64)
X = np.mat(X)
File: /home/andres/Dropbox/Classes/…es/Data/SimpleNeuralNetwork.py Page 2 of 3
X = X.reshape(N,784)
X = np.transpose(X)
# Now the labels:
in_file = open("train-labels.idx1-ubyte", "rb")
in_file.read(8)
DLabel = in_file.read()
in_file.close()
# Transform the label
Labels = np.fromstring(DLabel, dtype=np.uint8)
Labels01 = Labels[ np.logical_or(Labels[:]==0 , Labels[:]==1) ]
#Extract Data 01
X01 = X[:, Labels[ np.logical_or(Labels[:]==0 , Labels[:]==1) ] ]
dummy, N1 = X01.shape
#Mean Creation
Xmean= X01.sum(axis=1)
Xmean = (1.0/(N1*1.0))*Xmean
# Thus we create data with zero mean
X01= X01-Xmean
#Covariance
C_X = (1.0/(N1*1.0-1.0))*(X01*np.transpose(X01))
D, E = np.linalg.eigh(C_X)
idx = D.argsort()[::-1]
D = D[idx]
E = E[:,idx]
P = np.transpose(E[:,0:100])
Y01 = P*X01
# Run the Training
WIH, WHO = Neural_Training(Y01, Labels01 , eta, Epochs)
# Create the results
Results = sigmoid(WHO*sigmoid(WIH*Y01))
# Find the decisions
d,samplenumb = Y01.shape
index = np.ones(samplenumb)
Results = np.asarray(Results).reshape(-1)
# Generate the Confusion Matrix using a hard threshold half of minimum and maximum
t1 = np.max(Results[Labels01[:]==0])
t2 = np.max(Results[Labels01[:]==1])
tr = (t2-t1)/2.0
# print threshold
print tr
R11 = np.sum(index[ np.logical_and(Results[:]<tr, Labels01[:]==0 )])
R22 = np.sum(index[ np.logical_and(Results[:]>tr, Labels01[:]==1 )])
R12 = np.sum(index[ np.logical_and(Results[:]>=tr, Labels01[:]==0 ) ])
R21 = np.sum(index[ np.logical_and(Results[:]<=tr, Labels01[:]==1 ) ])
ConfusionMatrix = np.matrix([[R11 ,R12] , [R21 , R22]])
# Print the results
print "Confusion Matrix n", ConfusionMatrix
File: /home/andres/Dropbox/Classes/…es/Data/SimpleNeuralNetwork.py Page 3 of 3
# Print some Labels
for i in xrange(0,15):
print("Gen Label {} = {} Real Label {}".format(i , round(Results[i],2), Labels01[i]))
Ad

More Related Content

Similar to Simple Neural Network Python Code (20)

When running the code below I am getting some errors (see image)- The.docx
When running the code below I am getting some errors (see image)- The.docxWhen running the code below I am getting some errors (see image)- The.docx
When running the code below I am getting some errors (see image)- The.docx
maximapikvu8
 
Please help fill in the missing code below in order for it run correct.docx
Please help fill in the missing code below in order for it run correct.docxPlease help fill in the missing code below in order for it run correct.docx
Please help fill in the missing code below in order for it run correct.docx
madalynbb3ja
 
About RNN
About RNNAbout RNN
About RNN
Young Oh Jeong
 
About RNN
About RNNAbout RNN
About RNN
Young Oh Jeong
 
Working with tf.data (TF 2)
Working with tf.data (TF 2)Working with tf.data (TF 2)
Working with tf.data (TF 2)
Oswald Campesato
 
Codecomparaison
CodecomparaisonCodecomparaison
Codecomparaison
SokhnaRokhayaDIOP
 
TensorFlow for IITians
TensorFlow for IITiansTensorFlow for IITians
TensorFlow for IITians
Ashish Bansal
 
Introduction to Neural Networks and Deep Learning from Scratch
Introduction to Neural Networks and Deep Learning from ScratchIntroduction to Neural Networks and Deep Learning from Scratch
Introduction to Neural Networks and Deep Learning from Scratch
Ahmed BESBES
 
Practicle 1.docx
Practicle 1.docxPracticle 1.docx
Practicle 1.docx
GaneshPawar819187
 
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
Implement the following sorting algorithms  Bubble Sort  Insertion S.pdfImplement the following sorting algorithms  Bubble Sort  Insertion S.pdf
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
kesav24
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
Please help this code is supposed to evaluate current node state and i.pdf
Please help this code is supposed to evaluate current node state and i.pdfPlease help this code is supposed to evaluate current node state and i.pdf
Please help this code is supposed to evaluate current node state and i.pdf
climatecontrolsv
 
Numerical Method Assignment
Numerical Method AssignmentNumerical Method Assignment
Numerical Method Assignment
ashikul akash
 
AI02_Python (cont.).pptx
AI02_Python (cont.).pptxAI02_Python (cont.).pptx
AI02_Python (cont.).pptx
Nguyễn Tiến
 
Tutorial on convolutional neural networks
Tutorial on convolutional neural networksTutorial on convolutional neural networks
Tutorial on convolutional neural networks
Hojin Yang
 
BASIC OF PYTHON MATPLOTLIB USED IN ARTIFICIAL INTELLIGENCE AND ML
BASIC OF PYTHON MATPLOTLIB USED IN ARTIFICIAL INTELLIGENCE AND MLBASIC OF PYTHON MATPLOTLIB USED IN ARTIFICIAL INTELLIGENCE AND ML
BASIC OF PYTHON MATPLOTLIB USED IN ARTIFICIAL INTELLIGENCE AND ML
AbhaysinhVansadia
 
Pythonbrasil - 2018 - Acelerando Soluções com GPU
Pythonbrasil - 2018 - Acelerando Soluções com GPUPythonbrasil - 2018 - Acelerando Soluções com GPU
Pythonbrasil - 2018 - Acelerando Soluções com GPU
Paulo Sergio Lemes Queiroz
 
multiple linear regression
multiple linear regressionmultiple linear regression
multiple linear regression
Akhilesh Joshi
 
assignment_7_sc report for soft comptuing
assignment_7_sc report for soft comptuingassignment_7_sc report for soft comptuing
assignment_7_sc report for soft comptuing
SainadhReddySyamalaA
 
Programming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAYProgramming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAY
vikram mahendra
 
When running the code below I am getting some errors (see image)- The.docx
When running the code below I am getting some errors (see image)- The.docxWhen running the code below I am getting some errors (see image)- The.docx
When running the code below I am getting some errors (see image)- The.docx
maximapikvu8
 
Please help fill in the missing code below in order for it run correct.docx
Please help fill in the missing code below in order for it run correct.docxPlease help fill in the missing code below in order for it run correct.docx
Please help fill in the missing code below in order for it run correct.docx
madalynbb3ja
 
Working with tf.data (TF 2)
Working with tf.data (TF 2)Working with tf.data (TF 2)
Working with tf.data (TF 2)
Oswald Campesato
 
TensorFlow for IITians
TensorFlow for IITiansTensorFlow for IITians
TensorFlow for IITians
Ashish Bansal
 
Introduction to Neural Networks and Deep Learning from Scratch
Introduction to Neural Networks and Deep Learning from ScratchIntroduction to Neural Networks and Deep Learning from Scratch
Introduction to Neural Networks and Deep Learning from Scratch
Ahmed BESBES
 
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
Implement the following sorting algorithms  Bubble Sort  Insertion S.pdfImplement the following sorting algorithms  Bubble Sort  Insertion S.pdf
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
kesav24
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
Please help this code is supposed to evaluate current node state and i.pdf
Please help this code is supposed to evaluate current node state and i.pdfPlease help this code is supposed to evaluate current node state and i.pdf
Please help this code is supposed to evaluate current node state and i.pdf
climatecontrolsv
 
Numerical Method Assignment
Numerical Method AssignmentNumerical Method Assignment
Numerical Method Assignment
ashikul akash
 
AI02_Python (cont.).pptx
AI02_Python (cont.).pptxAI02_Python (cont.).pptx
AI02_Python (cont.).pptx
Nguyễn Tiến
 
Tutorial on convolutional neural networks
Tutorial on convolutional neural networksTutorial on convolutional neural networks
Tutorial on convolutional neural networks
Hojin Yang
 
BASIC OF PYTHON MATPLOTLIB USED IN ARTIFICIAL INTELLIGENCE AND ML
BASIC OF PYTHON MATPLOTLIB USED IN ARTIFICIAL INTELLIGENCE AND MLBASIC OF PYTHON MATPLOTLIB USED IN ARTIFICIAL INTELLIGENCE AND ML
BASIC OF PYTHON MATPLOTLIB USED IN ARTIFICIAL INTELLIGENCE AND ML
AbhaysinhVansadia
 
Pythonbrasil - 2018 - Acelerando Soluções com GPU
Pythonbrasil - 2018 - Acelerando Soluções com GPUPythonbrasil - 2018 - Acelerando Soluções com GPU
Pythonbrasil - 2018 - Acelerando Soluções com GPU
Paulo Sergio Lemes Queiroz
 
multiple linear regression
multiple linear regressionmultiple linear regression
multiple linear regression
Akhilesh Joshi
 
assignment_7_sc report for soft comptuing
assignment_7_sc report for soft comptuingassignment_7_sc report for soft comptuing
assignment_7_sc report for soft comptuing
SainadhReddySyamalaA
 
Programming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAYProgramming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAY
vikram mahendra
 

More from Andres Mendez-Vazquez (20)

2.03 bayesian estimation
2.03 bayesian estimation2.03 bayesian estimation
2.03 bayesian estimation
Andres Mendez-Vazquez
 
05 linear transformations
05 linear transformations05 linear transformations
05 linear transformations
Andres Mendez-Vazquez
 
01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors
Andres Mendez-Vazquez
 
01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues
Andres Mendez-Vazquez
 
01.02 linear equations
01.02 linear equations01.02 linear equations
01.02 linear equations
Andres Mendez-Vazquez
 
01.01 vector spaces
01.01 vector spaces01.01 vector spaces
01.01 vector spaces
Andres Mendez-Vazquez
 
06 recurrent neural_networks
06 recurrent neural_networks06 recurrent neural_networks
06 recurrent neural_networks
Andres Mendez-Vazquez
 
05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation
Andres Mendez-Vazquez
 
Zetta global
Zetta globalZetta global
Zetta global
Andres Mendez-Vazquez
 
01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning
Andres Mendez-Vazquez
 
25 introduction reinforcement_learning
25 introduction reinforcement_learning25 introduction reinforcement_learning
25 introduction reinforcement_learning
Andres Mendez-Vazquez
 
Neural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning SyllabusNeural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning Syllabus
Andres Mendez-Vazquez
 
Introduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusIntroduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabus
Andres Mendez-Vazquez
 
Ideas 09 22_2018
Ideas 09 22_2018Ideas 09 22_2018
Ideas 09 22_2018
Andres Mendez-Vazquez
 
Ideas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data SciencesIdeas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data Sciences
Andres Mendez-Vazquez
 
Analysis of Algorithms Syllabus
Analysis of Algorithms  SyllabusAnalysis of Algorithms  Syllabus
Analysis of Algorithms Syllabus
Andres Mendez-Vazquez
 
20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations
Andres Mendez-Vazquez
 
18.1 combining models
18.1 combining models18.1 combining models
18.1 combining models
Andres Mendez-Vazquez
 
17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension
Andres Mendez-Vazquez
 
A basic introduction to learning
A basic introduction to learningA basic introduction to learning
A basic introduction to learning
Andres Mendez-Vazquez
 
01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors
Andres Mendez-Vazquez
 
01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues
Andres Mendez-Vazquez
 
05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation
Andres Mendez-Vazquez
 
01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning
Andres Mendez-Vazquez
 
25 introduction reinforcement_learning
25 introduction reinforcement_learning25 introduction reinforcement_learning
25 introduction reinforcement_learning
Andres Mendez-Vazquez
 
Neural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning SyllabusNeural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning Syllabus
Andres Mendez-Vazquez
 
Introduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusIntroduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabus
Andres Mendez-Vazquez
 
Ideas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data SciencesIdeas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data Sciences
Andres Mendez-Vazquez
 
20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations
Andres Mendez-Vazquez
 
Ad

Recently uploaded (20)

Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Artificial Intelligence introduction.pptx
Artificial Intelligence introduction.pptxArtificial Intelligence introduction.pptx
Artificial Intelligence introduction.pptx
DrMarwaElsherif
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
Data Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptxData Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptx
RushaliDeshmukh2
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
LECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's usesLECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's uses
CLokeshBehera123
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Artificial Intelligence introduction.pptx
Artificial Intelligence introduction.pptxArtificial Intelligence introduction.pptx
Artificial Intelligence introduction.pptx
DrMarwaElsherif
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
Data Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptxData Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptx
RushaliDeshmukh2
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
LECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's usesLECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's uses
CLokeshBehera123
 
Ad

Simple Neural Network Python Code

  • 1. File: /home/andres/Dropbox/Classes/…es/Data/SimpleNeuralNetwork.py Page 1 of 3 import matplotlib.pyplot as plt import numpy as np from scipy.special import expit def sigmoid(eval): return expit(eval) def Neural_Training(Y01, Labels01 , eta , Epochs): d,samplenumb = Y01.shape # Random [-1,1] init from Haykin WIH = 2*np.mat(np.random.rand(2*d,d)) -1.0 WHO = 2*np.mat(np.random.rand(1,2*d)) -1.0 difft = Labels01.astype(np.float64) for i in xrange(1,Epochs): #Get the input to the output layer y_j_temp = sigmoid(WIH*Y01) netk = WHO*y_j_temp zk = sigmoid(netk) # Creating Delta Wk diff1 = difft - zk tDeltaWk = eta*np.multiply(diff1,np.multiply(sigmoid(netk),1.0-sigmoid(netk))) tDeltaWk = np.tile(tDeltaWk,(2*d,1)) DeltaWk = np.multiply( y_j_temp,tDeltaWk) DeltaWk = np.transpose(np.sum(DeltaWk,1)) # New Weights WHO = WHO + DeltaWk #Creating Delta Wj dnetj = np.multiply(y_j_temp,1.0-y_j_temp) tprodsumk = np.multiply(np.transpose(DeltaWk),np.transpose(WHO)) tprodsumk = np.tile(tprodsumk, (1,samplenumb) ) tprodsumk = eta*np.multiply(tprodsumk,dnetj) DeltaWj = tprodsumk * np.transpose(Y01) # New Weights WIH = WIH + DeltaWj return WIH, WHO # Number of samples N= 60000 #Number of Epochs Epochs = 20 #Learning Rate eta = 0.001 # opening images for [r]eading as [b]inary in_file = open("train-images.idx3-ubyte", "rb") in_file.read(16) Data = in_file.read() in_file.close() # Transform the data stream X = np.fromstring(Data, dtype=np.uint8) X = X.astype(np.float64) X = np.mat(X)
  • 2. File: /home/andres/Dropbox/Classes/…es/Data/SimpleNeuralNetwork.py Page 2 of 3 X = X.reshape(N,784) X = np.transpose(X) # Now the labels: in_file = open("train-labels.idx1-ubyte", "rb") in_file.read(8) DLabel = in_file.read() in_file.close() # Transform the label Labels = np.fromstring(DLabel, dtype=np.uint8) Labels01 = Labels[ np.logical_or(Labels[:]==0 , Labels[:]==1) ] #Extract Data 01 X01 = X[:, Labels[ np.logical_or(Labels[:]==0 , Labels[:]==1) ] ] dummy, N1 = X01.shape #Mean Creation Xmean= X01.sum(axis=1) Xmean = (1.0/(N1*1.0))*Xmean # Thus we create data with zero mean X01= X01-Xmean #Covariance C_X = (1.0/(N1*1.0-1.0))*(X01*np.transpose(X01)) D, E = np.linalg.eigh(C_X) idx = D.argsort()[::-1] D = D[idx] E = E[:,idx] P = np.transpose(E[:,0:100]) Y01 = P*X01 # Run the Training WIH, WHO = Neural_Training(Y01, Labels01 , eta, Epochs) # Create the results Results = sigmoid(WHO*sigmoid(WIH*Y01)) # Find the decisions d,samplenumb = Y01.shape index = np.ones(samplenumb) Results = np.asarray(Results).reshape(-1) # Generate the Confusion Matrix using a hard threshold half of minimum and maximum t1 = np.max(Results[Labels01[:]==0]) t2 = np.max(Results[Labels01[:]==1]) tr = (t2-t1)/2.0 # print threshold print tr R11 = np.sum(index[ np.logical_and(Results[:]<tr, Labels01[:]==0 )]) R22 = np.sum(index[ np.logical_and(Results[:]>tr, Labels01[:]==1 )]) R12 = np.sum(index[ np.logical_and(Results[:]>=tr, Labels01[:]==0 ) ]) R21 = np.sum(index[ np.logical_and(Results[:]<=tr, Labels01[:]==1 ) ]) ConfusionMatrix = np.matrix([[R11 ,R12] , [R21 , R22]]) # Print the results print "Confusion Matrix n", ConfusionMatrix
  • 3. File: /home/andres/Dropbox/Classes/…es/Data/SimpleNeuralNetwork.py Page 3 of 3 # Print some Labels for i in xrange(0,15): print("Gen Label {} = {} Real Label {}".format(i , round(Results[i],2), Labels01[i]))