Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Science
  • Data Science Projects
  • Data Analysis
  • Data Visualization
  • Machine Learning
  • ML Projects
  • Deep Learning
  • NLP
  • Computer Vision
  • Artificial Intelligence
Open In App
Next Article:
A single neuron neural network in Python
Next article icon

A single neuron neural network in Python

Last Updated : 06 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Neural networks are the core of deep learning, a field that has practical applications in many different areas. Today neural networks are used for image classification, speech recognition, object detection, etc. Now, Let's try to understand the basic unit behind all these states of art techniques.
A single neuron transforms given input into some output. Depending on the given input and weights assigned to each input, decide whether the neuron fired or not. Let's assume the neuron has 3 input connections and one output.
 


We will be using tanh activation function in a given example.
The end goal is to find the optimal set of weights for this neuron that produces correct results. Do this by training the neuron with several different training examples. At each step calculate the error in the output of the neuron, and backpropagate the gradients. The step of calculating the output of a neuron is called forward propagation while the calculation of gradients is called back propagation.
Below is the implementation : 
 

Python3
# Python program to implement a  # single neuron neural network  # import all necessary libraries from numpy import exp, array, random, dot, tanh  # Class to create a neural  # network with single neuron class NeuralNetwork():          def __init__(self):                  # Using seed to make sure it'll           # generate same weights in every run         random.seed(1)                  # 3x1 Weight matrix         self.weight_matrix = 2 * random.random((3, 1)) - 1      # tanh as activation function     def tanh(self, x):         return tanh(x)      # derivative of tanh function.     # Needed to calculate the gradients.     def tanh_derivative(self, x):         return 1.0 - tanh(x) ** 2      # forward propagation     def forward_propagation(self, inputs):         return self.tanh(dot(inputs, self.weight_matrix))          # training the neural network.     def train(self, train_inputs, train_outputs,                             num_train_iterations):                                          # Number of iterations we want to         # perform for this set of input.         for iteration in range(num_train_iterations):             output = self.forward_propagation(train_inputs)              # Calculate the error in the output.             error = train_outputs - output              # multiply the error by input and then              # by gradient of tanh function to calculate             # the adjustment needs to be made in weights             adjustment = dot(train_inputs.T, error *                              self.tanh_derivative(output))                                           # Adjust the weight matrix             self.weight_matrix += adjustment  # Driver Code if __name__ == "__main__":          neural_network = NeuralNetwork()          print ('Random weights at the start of training')     print (neural_network.weight_matrix)      train_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])     train_outputs = array([[0, 1, 1, 0]]).T      neural_network.train(train_inputs, train_outputs, 10000)      print ('New weights after training')     print (neural_network.weight_matrix)      # Test the neural network with a new situation.     print ("Testing network on new examples ->")     print (neural_network.forward_propagation(array([1, 0, 0]))) 

Output : 
 

Random weights at the start of training [[-0.16595599]  [ 0.44064899]  [-0.99977125]]  New weights after training [[5.39428067]  [0.19482422]  [0.34317086]]  Testing network on new examples -> [0.99995873]


 


Next Article
A single neuron neural network in Python

R

Ravindra_P
Improve
Article Tags :
  • Deep Learning
  • AI-ML-DS
  • Neural Network

Similar Reads

    Single Layered Neural Networks in R Programming
    Neural networks also known as neural nets is a type of algorithm in machine learning and artificial intelligence that works the same as the human brain operates. The artificial neurons in the neural network depict the same behavior of neurons in the human brain. Neural networks are used in risk anal
    5 min read
    Handwritten Digit Recognition using Neural Network
    Handwritten digit recognition is a classic problem in machine learning and computer vision. It involves recognizing handwritten digits (0-9) from images or scanned documents. This task is widely used as a benchmark for evaluating machine learning models especially neural networks due to its simplici
    5 min read
    Training a Neural Network using Keras API in Tensorflow
    In the field of machine learning and deep learning has been significantly transformed by tools like TensorFlow and Keras. TensorFlow, developed by Google, is an open-source platform that provides a comprehensive ecosystem for machine learning. Keras, now fully integrated into TensorFlow, offers a us
    3 min read
    Neural Networks Using the R nnet Package
    A neural network is a computational model inspired by the structure and function of the human brain. It consists of interconnected nodes, called neurons, organized into layers. The network receives input data, processes it through multiple layers of neurons, and produces an output or prediction. The
    15+ min read
    Building a Simple Neural Network in R Programming
    The term Neural Networks refers to the system of neurons either organic or artificial in nature. In artificial intelligence reference, neural networks are a set of algorithms that are designed to recognize a pattern like a human brain. They interpret sensory data through a kind of machine perception
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences