SlideShare a Scribd company logo
1 of 3
Download to read offline
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]))

More Related Content

What's hot

Eigen values and eigenvectors
Eigen values and eigenvectorsEigen values and eigenvectors
Eigen values and eigenvectorsAmit Singh
 
Sequences and Series
Sequences and SeriesSequences and Series
Sequences and Seriessujathavvv
 
Fuzzy Logic.pptx
Fuzzy Logic.pptxFuzzy Logic.pptx
Fuzzy Logic.pptxImXaib
 
Partial derivative1
Partial derivative1Partial derivative1
Partial derivative1Nidhu Sharma
 
Comparing EDA with classical and Bayesian analysis.pptx
Comparing EDA with classical and Bayesian analysis.pptxComparing EDA with classical and Bayesian analysis.pptx
Comparing EDA with classical and Bayesian analysis.pptxPremaGanesh1
 
Pigeonhole Principle,Cardinality,Countability
Pigeonhole Principle,Cardinality,CountabilityPigeonhole Principle,Cardinality,Countability
Pigeonhole Principle,Cardinality,CountabilityKiran Munir
 
One Dimensional Array
One Dimensional Array One Dimensional Array
One Dimensional Array dincyjain
 
Mealy state machine
Mealy state machineMealy state machine
Mealy state machineArif Siyal
 
Linear Algebra PowerPoint
Linear Algebra PowerPointLinear Algebra PowerPoint
Linear Algebra PowerPointAshley Carter
 
Different types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with AnimationDifferent types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with AnimationZakaria Hossain
 
Moment generating function
Moment generating functionMoment generating function
Moment generating functioneddyboadu
 
Exclusive OR GAte
Exclusive OR GAteExclusive OR GAte
Exclusive OR GAteawais ahmad
 
Chance detection in football broadcasts
Chance detection in football broadcastsChance detection in football broadcasts
Chance detection in football broadcastsAuke vanderSchaar
 
5 cramer-rao lower bound
5 cramer-rao lower bound5 cramer-rao lower bound
5 cramer-rao lower boundSolo Hermelin
 
Maximal and minimal elements of poset.pptx
Maximal and minimal elements of poset.pptxMaximal and minimal elements of poset.pptx
Maximal and minimal elements of poset.pptxKiran Kumar Malik
 
Lecture 6 disjoint set
Lecture 6 disjoint setLecture 6 disjoint set
Lecture 6 disjoint setAbirami A
 
formulation of first order linear and nonlinear 2nd order differential equation
formulation of first order linear and nonlinear 2nd order differential equationformulation of first order linear and nonlinear 2nd order differential equation
formulation of first order linear and nonlinear 2nd order differential equationMahaswari Jogia
 

What's hot (20)

Eigen values and eigenvectors
Eigen values and eigenvectorsEigen values and eigenvectors
Eigen values and eigenvectors
 
fuzzy set
fuzzy setfuzzy set
fuzzy set
 
Sequences and Series
Sequences and SeriesSequences and Series
Sequences and Series
 
Fuzzy Logic.pptx
Fuzzy Logic.pptxFuzzy Logic.pptx
Fuzzy Logic.pptx
 
Partial derivative1
Partial derivative1Partial derivative1
Partial derivative1
 
lattice
 lattice lattice
lattice
 
Comparing EDA with classical and Bayesian analysis.pptx
Comparing EDA with classical and Bayesian analysis.pptxComparing EDA with classical and Bayesian analysis.pptx
Comparing EDA with classical and Bayesian analysis.pptx
 
Pigeonhole Principle,Cardinality,Countability
Pigeonhole Principle,Cardinality,CountabilityPigeonhole Principle,Cardinality,Countability
Pigeonhole Principle,Cardinality,Countability
 
One Dimensional Array
One Dimensional Array One Dimensional Array
One Dimensional Array
 
Mealy state machine
Mealy state machineMealy state machine
Mealy state machine
 
Matrices & Determinants
Matrices & DeterminantsMatrices & Determinants
Matrices & Determinants
 
Linear Algebra PowerPoint
Linear Algebra PowerPointLinear Algebra PowerPoint
Linear Algebra PowerPoint
 
Different types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with AnimationDifferent types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with Animation
 
Moment generating function
Moment generating functionMoment generating function
Moment generating function
 
Exclusive OR GAte
Exclusive OR GAteExclusive OR GAte
Exclusive OR GAte
 
Chance detection in football broadcasts
Chance detection in football broadcastsChance detection in football broadcasts
Chance detection in football broadcasts
 
5 cramer-rao lower bound
5 cramer-rao lower bound5 cramer-rao lower bound
5 cramer-rao lower bound
 
Maximal and minimal elements of poset.pptx
Maximal and minimal elements of poset.pptxMaximal and minimal elements of poset.pptx
Maximal and minimal elements of poset.pptx
 
Lecture 6 disjoint set
Lecture 6 disjoint setLecture 6 disjoint set
Lecture 6 disjoint set
 
formulation of first order linear and nonlinear 2nd order differential equation
formulation of first order linear and nonlinear 2nd order differential equationformulation of first order linear and nonlinear 2nd order differential equation
formulation of first order linear and nonlinear 2nd order differential equation
 

Similar to Simple Neural Network Python Code

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.docxmaximapikvu8
 
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.docxmadalynbb3ja
 
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 IITiansAshish 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 ScratchAhmed 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.pdfkesav24
 
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.docSrikrishnaVundavalli
 
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.pdfclimatecontrolsv
 
Numerical Method Assignment
Numerical Method AssignmentNumerical Method Assignment
Numerical Method Assignmentashikul akash
 
AI02_Python (cont.).pptx
AI02_Python (cont.).pptxAI02_Python (cont.).pptx
AI02_Python (cont.).pptxNguyễn Tiến
 
Tutorial on convolutional neural networks
Tutorial on convolutional neural networksTutorial on convolutional neural networks
Tutorial on convolutional neural networksHojin Yang
 
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 GPUPaulo Sergio Lemes Queiroz
 
multiple linear regression
multiple linear regressionmultiple linear regression
multiple linear regressionAkhilesh Joshi
 
Programming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAYProgramming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAYvikram mahendra
 
Ch01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonCh01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonshin
 
Matlab assignment
Matlab assignmentMatlab assignment
Matlab assignmentRutvik
 

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
 
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
 
About RNN
About RNNAbout RNN
About RNN
 
About RNN
About RNNAbout RNN
About RNN
 
Working with tf.data (TF 2)
Working with tf.data (TF 2)Working with tf.data (TF 2)
Working with tf.data (TF 2)
 
Codecomparaison
CodecomparaisonCodecomparaison
Codecomparaison
 
TensorFlow for IITians
TensorFlow for IITiansTensorFlow for IITians
TensorFlow for IITians
 
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
 
Practicle 1.docx
Practicle 1.docxPracticle 1.docx
Practicle 1.docx
 
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
 
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
 
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
 
Numerical Method Assignment
Numerical Method AssignmentNumerical Method Assignment
Numerical Method Assignment
 
AI02_Python (cont.).pptx
AI02_Python (cont.).pptxAI02_Python (cont.).pptx
AI02_Python (cont.).pptx
 
Tutorial on convolutional neural networks
Tutorial on convolutional neural networksTutorial on convolutional neural networks
Tutorial on convolutional neural networks
 
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
 
multiple linear regression
multiple linear regressionmultiple linear regression
multiple linear regression
 
Programming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAYProgramming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAY
 
Ch01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonCh01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluiton
 
Matlab assignment
Matlab assignmentMatlab assignment
Matlab assignment
 

More from 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_vectorsAndres 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_issuesAndres Mendez-Vazquez
 
05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiationAndres 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 LearningAndres Mendez-Vazquez
 
25 introduction reinforcement_learning
25 introduction reinforcement_learning25 introduction reinforcement_learning
25 introduction reinforcement_learningAndres Mendez-Vazquez
 
Neural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning SyllabusNeural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning SyllabusAndres Mendez-Vazquez
 
Introduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusIntroduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusAndres 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 SciencesAndres 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 variationsAndres Mendez-Vazquez
 

More from Andres Mendez-Vazquez (20)

2.03 bayesian estimation
2.03 bayesian estimation2.03 bayesian estimation
2.03 bayesian estimation
 
05 linear transformations
05 linear transformations05 linear transformations
05 linear transformations
 
01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors
 
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
 
01.02 linear equations
01.02 linear equations01.02 linear equations
01.02 linear equations
 
01.01 vector spaces
01.01 vector spaces01.01 vector spaces
01.01 vector spaces
 
06 recurrent neural_networks
06 recurrent neural_networks06 recurrent neural_networks
06 recurrent neural_networks
 
05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation
 
Zetta global
Zetta globalZetta global
Zetta global
 
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
 
25 introduction reinforcement_learning
25 introduction reinforcement_learning25 introduction reinforcement_learning
25 introduction reinforcement_learning
 
Neural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning SyllabusNeural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning Syllabus
 
Introduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusIntroduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabus
 
Ideas 09 22_2018
Ideas 09 22_2018Ideas 09 22_2018
Ideas 09 22_2018
 
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
 
Analysis of Algorithms Syllabus
Analysis of Algorithms  SyllabusAnalysis of Algorithms  Syllabus
Analysis of Algorithms Syllabus
 
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
 
18.1 combining models
18.1 combining models18.1 combining models
18.1 combining models
 
17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension
 
A basic introduction to learning
A basic introduction to learningA basic introduction to learning
A basic introduction to learning
 

Recently uploaded

457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptxrouholahahmadi9876
 
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using PipesLinux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using PipesRashidFaridChishti
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementDr. Deepak Mudgal
 
fitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptfitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptAfnanAhmad53
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Servicemeghakumariji156
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxMuhammadAsimMuhammad6
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxNANDHAKUMARA10
 
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...jabtakhaidam7
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdfKamal Acharya
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...Amil baba
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 

Recently uploaded (20)

457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
 
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using PipesLinux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth Reinforcement
 
fitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptfitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .ppt
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptx
 
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 

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]))