Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Image Enhancement Techniques using OpenCV - Python
Next article icon

Implementing Rich getting Richer phenomenon using Barabasi Albert Model in Python

Last Updated : 01 Oct, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite- Introduction to Social Networks, Barabasi Albert Graph

In social networks, there is a phenomenon called Rich getting Richer also known as Preferential Attachment. In Preferential Attachment, a person who is already rich gets more and more and a person who is having less gets less. This is called the Rich getting Richer phenomena or Preferential Attachment.

For example, assume there are some students in a class and every student is friends with some students which is called its degree i.e a degree of a student Is the number of friends it has. Now the student with a higher degree is rich and the student with a low degree is poor. Now suppose there comes a new student in the class and he/she has to make m friends, so he/she will select students with a higher degree and become friends with them which increases the degree of rich. This is called Rich getting Richer or Preferential Attachment.

Barabasi Albert Model is the implementation of Preferential Attachment. 

Logic – Below are the logic behind the Barabasi Albert Model:

  1. Take a random graph with n0 nodes and connect them randomly with a condition that each has at least 1 link.
  2. At each time we add a new node n which is less or equal to n0 links that will connect the new node to n nodes already in the network.
  3. Now the probability that a node connects to a particular node will depend on its degree. (Preferential Attachment).

Approach – Below are the steps for implementing the Barabasi Albert Model:

  1. Take a graph with n nodes.
  2. Take m from the user i.e number of edges to be connected to the new node.
  3. Take m0 i.e initial number of nodes such that m<=m0.
  4. Now add the n-m0 nodes.
  5. Now add edges to these n-m0 nodes according to Preferential Attachment.

Below is the implementation of the Barabasi Albert model.

Python3




import networkx as nx
import random
import matplotlib.pyplot as plt
  
  
def display(g, i, ne):
    pos = nx.circular_layout(g)
      
    if i == '' and ne == '':
        new_node = []
        rest_nodes = g.nodes()
        new_edges = []
        rest_edges = g.edges()
    else:
        new_node = [i]
        rest_nodes = list(set(g.nodes()) - set(new_node))
        new_edges = ne
        rest_edges = list(set(g.edges()) - set(new_edges) - set([(b, a) for (a, b) in new_edges]))
    nx.draw_networkx_nodes(g, pos, nodelist=new_node, node_color='g')
    nx.draw_networkx_nodes(g, pos, nodelist=rest_nodes, node_color='r')
    nx.draw_networkx_edges(g, pos, edgelist=new_edges, style='dashdot')
    nx.draw_networkx_edges(g, pos, edgelist=rest_edges,)
    plt.show()
  
  
def barabasi_add_nodes(g, n, m0):
    m = m0 - 1
  
    for i in range(m0 + 1, n + 1):
        g.add_node(i)
        degrees = nx.degree(g)
        node_prob = {}
  
        s = 0
        for j in degrees:
            s += j[1]
        print(g.nodes())
          
        for each in g.nodes():
            node_prob[each] = (float)(degrees[each]) / s
  
        node_probabilities_cum = []
        prev = 0
          
        for n, p in node_prob.items():
            temp = [n, prev + p]
            node_probabilities_cum.append(temp)
            prev += p
  
        new_edges = []
        num_edges_added = 0
        target_nodes = []
  
        while (num_edges_added < m):
            prev_cum = 0
            r = random.random()
            k = 0
              
            while (not (r > prev_cum and r <= node_probabilities_cum[k][1])):
                prev_cum = node_probabilities_cum[k][1]
                k = k + 1
            target_node = node_probabilities_cum[k][0]
              
            if target_node in target_nodes:
                continue
              
            else:
                target_nodes.append(target_node)
            g.add_edge(i, target_node)
            num_edges_added += 1
            new_edges.append((i, target_node))
  
        print(num_edges_added, ' edges added')
  
    display(g, i, new_edges)
    return g
  
  
def plot_deg_dist(g):
    all_degrees = []
      
    for i in nx.degree(g):
        all_degrees.append(i[1])
    unique_degrees = list(set(all_degrees))
    unique_degrees.sort()
    count_of_degrees = []
  
    for i in unique_degrees:
        c = all_degrees.count(i)
        count_of_degrees.append(c)
  
    print(unique_degrees)
    print(count_of_degrees)
  
    plt.plot(unique_degrees, count_of_degrees, 'ro-')
    plt.xlabel('Degrees')
    plt.ylabel('Number of Nodes')
    plt.title('Degree Distribution')
    plt.show()
  
  
N = 10
m0 = random.randint(2, N / 5)
g = nx.path_graph(m0)
display(g, '', '')
  
g = barabasi_add_nodes(g, N, m0)
plot_deg_dist(g)
 
 

Output:

Enter the value of n: 10  3  [0, 1, 3]  1  edges added  [0, 1, 3, 4]  1  edges added  [0, 1, 3, 4, 5]  1  edges added  [0, 1, 3, 4, 5, 6]  1  edges added  [0, 1, 3, 4, 5, 6, 7]  1  edges added  [0, 1, 3, 4, 5, 6, 7, 8]  1  edges added  [0, 1, 3, 4, 5, 6, 7, 8, 9]  1  edges added  [0, 1, 3, 4, 5, 6, 7, 8, 9, 10]  1  edges added  [1, 2, 3, 6]  [7, 1, 1, 1]  

Initial Graph with m0 nodes

Final Node with new node added

Distribution Graph



Next Article
Image Enhancement Techniques using OpenCV - Python

S

sankalpsharma424
Improve
Article Tags :
  • Advanced Data Structure
  • AI-ML-DS
  • DSA
  • Graph
  • Machine Learning
  • python
Practice Tags :
  • Advanced Data Structure
  • Graph
  • Machine Learning
  • python

Similar Reads

  • Implementing Artificial Neural Network training process in Python
    An Artificial Neural Network (ANN) is an information processing paradigm that is inspired by the brain. ANNs, like people, learn by example. An ANN is configured for a specific application, such as pattern recognition or data classification, through a learning process. Learning largely involves adju
    4 min read
  • Image Enhancement Techniques using OpenCV - Python
    Image enhancement is the process of improving the quality and appearance of an image. It can be used to correct flaws or defects in an image, or to simply make an image more visually appealing. Image enhancement techniques can be applied to a wide range of images, including photographs, scans, and d
    15+ min read
  • Performing Batch Multiplication in PyTorch Without Using torch.bmm
    Batch multiplication is a fundamental operation in deep learning and scientific computing, especially when working with large datasets and models. PyTorch, a popular deep learning framework, provides several methods for matrix multiplication, including torch.bmm for batch matrix multiplication. Howe
    5 min read
  • How to Implement Adam Gradient Descent from Scratch using Python?
    Grade descent is an extensively used optimization algorithm in machine literacy and deep literacy. It's used to minimize the cost or loss function of a model by iteratively confirming the model's parameters grounded on the slants of the cost function with respect to those parameters. One variant of
    14 min read
  • Analysis of test data using K-Means Clustering in Python
    In data science K-Means clustering is one of the most popular unsupervised machine learning algorithms. It is primarily used for grouping similar data points together based on their features which helps in discovering inherent patterns in the dataset. In this article we will demonstrates how to appl
    4 min read
  • Implementing Recurrent Neural Networks in PyTorch
    Recurrent Neural Networks (RNNs) are a class of neural networks that are particularly effective for sequential data. Unlike traditional feedforward neural networks RNNs have connections that form loops allowing them to maintain a hidden state that can capture information from previous inputs. This m
    6 min read
  • Python for Data Science - Learn the Uses of Python in Data Science
    In this Python for Data Science guide, we'll explore the exciting world of Python and its wide-ranging applications in data science. We will also explore a variety of data science techniques used in data science using the Python programming language. We all know that data Science is applied to gathe
    6 min read
  • Implementation of Erdos-Renyi Model on Social Networks
    Prerequisite: Introduction to Social Networks, Erdos-Renyi Model Erdos Renyi model is used to create random networks or graphs on social networking. In the Erdos Reny model, each edge has a fixed probability of being present and being absent independent of the edges in a network. Implementing a Soci
    3 min read
  • Implement Deep Autoencoder in PyTorch for Image Reconstruction
    Since the availability of staggering amounts of data on the internet, researchers and scientists from industry and academia keep trying to develop more efficient and reliable data transfer modes than the current state-of-the-art methods. Autoencoders are one of the key elements found in recent times
    8 min read
  • How to Make Better Models in Python using SVM Classifier and RBF Kernel
    As machine learning models continue to become more popular and widespread, it is important for data scientists and developers to understand how to build the best models possible. One powerful tool that can be used to improve the accuracy and performance of machine learning models is the support vect
    5 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