Convert Figma logo to code with AI

trekhleb logohomemade-machine-learning

🤖 Python examples of popular machine learning algorithms with interactive Jupyter demos and math being explained

22,945
4,051
22,945
24

Top Related Projects

scikit-learn: machine learning in Python

185,446

An Open Source Machine Learning Framework for Everyone

82,049

Tensors and Dynamic neural networks in Python with strong GPU acceleration

61,580

Deep Learning for humans

12 weeks, 26 lessons, 52 quizzes, classic Machine Learning for all

A series of Jupyter notebooks that walk you through the fundamentals of Machine Learning and Deep Learning in Python using Scikit-Learn, Keras and TensorFlow 2.

Quick Overview

The trekhleb/homemade-machine-learning repository is an educational project that provides Python implementations of popular machine learning algorithms from scratch. It aims to help developers and data scientists understand the inner workings of various ML algorithms by presenting them in a clear, well-documented manner with practical examples.

Pros

  • Comprehensive coverage of fundamental machine learning algorithms
  • Well-structured code with detailed explanations and comments
  • Includes Jupyter notebooks with visualizations for better understanding
  • Suitable for both beginners and intermediate learners in machine learning

Cons

  • Not optimized for production use or large-scale datasets
  • May lack some advanced features found in established ML libraries
  • Limited to core algorithms, missing some newer or more specialized techniques
  • Requires a solid understanding of Python and basic math concepts

Code Examples

  1. Linear Regression:
import numpy as np
from homemade_machine_learning.linear_regression import LinearRegression

# Create and train the model
model = LinearRegression(learning_rate=0.01, iterations=1000)
model.fit(X_train, y_train)

# Make predictions
predictions = model.predict(X_test)
  1. K-Means Clustering:
from homemade_machine_learning.kmeans import KMeans

# Create and fit the model
kmeans = KMeans(n_clusters=3, max_iterations=100)
kmeans.fit(X)

# Get cluster assignments
labels = kmeans.predict(X)
  1. Decision Tree:
from homemade_machine_learning.decision_tree import DecisionTree

# Create and train the decision tree
tree = DecisionTree(max_depth=5)
tree.fit(X_train, y_train)

# Make predictions
predictions = tree.predict(X_test)

Getting Started

To get started with the homemade-machine-learning project:

  1. Clone the repository:

    git clone https://github.com/trekhleb/homemade-machine-learning.git
    
  2. Install the required dependencies:

    pip install -r requirements.txt
    
  3. Navigate to the desired algorithm's directory and run the Jupyter notebook or Python script:

    jupyter notebook linear_regression/linear_regression.ipynb
    
  4. Experiment with the code, modify parameters, and explore the implementations to deepen your understanding of machine learning algorithms.

Competitor Comparisons

scikit-learn: machine learning in Python

Pros of scikit-learn

  • Comprehensive and well-established library with a wide range of machine learning algorithms
  • Highly optimized and efficient implementations for production use
  • Extensive documentation and community support

Cons of scikit-learn

  • Less suitable for educational purposes or understanding algorithm internals
  • More complex API and steeper learning curve for beginners
  • Limited flexibility for customizing or modifying existing algorithms

Code Comparison

homemade-machine-learning:

class LogisticRegression:
    def __init__(self, learning_rate=0.01, num_iterations=1000):
        self.learning_rate = learning_rate
        self.num_iterations = num_iterations

    def fit(self, X, y):
        # Implementation of logistic regression training

scikit-learn:

from sklearn.linear_model import LogisticRegression

model = LogisticRegression()
model.fit(X, y)

The homemade-machine-learning repository provides a more detailed, educational implementation of algorithms, while scikit-learn offers a more concise, production-ready interface. The former is better for learning and understanding, while the latter is optimized for practical use in real-world applications.

185,446

An Open Source Machine Learning Framework for Everyone

Pros of TensorFlow

  • Comprehensive, production-ready framework with extensive ecosystem
  • Supports distributed computing and deployment across various platforms
  • Backed by Google, ensuring long-term support and frequent updates

Cons of TensorFlow

  • Steeper learning curve due to its complexity and extensive features
  • Can be overkill for simple projects or learning basic ML concepts
  • Requires more computational resources for setup and execution

Code Comparison

Homemade Machine Learning (Simple linear regression):

def predict(X):
    return X.dot(weights) + bias

def train(X, y, iterations, learning_rate):
    global weights, bias
    for i in range(iterations):
        predictions = predict(X)
        weights -= learning_rate * X.T.dot(predictions - y) / X.shape[0]
        bias -= learning_rate * (predictions - y).mean()

TensorFlow (Simple linear regression):

model = tf.keras.Sequential([
    tf.keras.layers.Dense(1, input_shape=(1,))
])
model.compile(optimizer='sgd', loss='mse')
model.fit(X, y, epochs=100)
predictions = model.predict(X_test)

Summary

Homemade Machine Learning is ideal for learning ML concepts from scratch, while TensorFlow is better suited for complex, production-ready projects. The former offers simplicity and transparency, while the latter provides scalability and extensive features at the cost of complexity.

82,049

Tensors and Dynamic neural networks in Python with strong GPU acceleration

Pros of PyTorch

  • Comprehensive, production-ready deep learning framework
  • Extensive community support and ecosystem
  • Optimized for performance and scalability

Cons of PyTorch

  • Steeper learning curve for beginners
  • Larger codebase and more complex architecture
  • Requires more computational resources

Code Comparison

Homemade Machine Learning:

class LogisticRegression:
    def __init__(self, learning_rate=0.01, num_iterations=1000):
        self.learning_rate = learning_rate
        self.num_iterations = num_iterations

PyTorch:

import torch.nn as nn

class LogisticRegression(nn.Module):
    def __init__(self, input_dim, output_dim):
        super(LogisticRegression, self).__init__()
        self.linear = nn.Linear(input_dim, output_dim)

Summary

Homemade Machine Learning is an educational project focused on implementing machine learning algorithms from scratch, making it ideal for learning fundamentals. PyTorch, on the other hand, is a powerful, industry-standard framework designed for building and deploying large-scale deep learning models. While Homemade Machine Learning offers simplicity and transparency, PyTorch provides advanced features, optimizations, and a vast ecosystem at the cost of increased complexity.

61,580

Deep Learning for humans

Pros of Keras

  • High-level API for easy and fast prototyping of neural networks
  • Supports multiple backend engines (TensorFlow, Theano, CNTK)
  • Extensive documentation and large community support

Cons of Keras

  • Less flexibility for low-level operations compared to pure implementations
  • Abstraction may hide some underlying complexities, potentially limiting deep understanding
  • Dependency on backend libraries may affect portability

Code Comparison

Keras:

from keras.models import Sequential
from keras.layers import Dense

model = Sequential([
    Dense(64, activation='relu', input_shape=(10,)),
    Dense(1, activation='sigmoid')
])

Homemade Machine Learning:

import numpy as np

class NeuralNetwork:
    def __init__(self, input_nodes, hidden_nodes, output_nodes):
        self.weights_input_hidden = np.random.randn(input_nodes, hidden_nodes)
        self.weights_hidden_output = np.random.randn(hidden_nodes, output_nodes)

Summary

Keras offers a user-friendly, high-level API for quick development of neural networks, while Homemade Machine Learning provides a more educational approach by implementing algorithms from scratch. Keras is better suited for production environments and rapid prototyping, whereas Homemade Machine Learning is ideal for learning the underlying concepts of machine learning algorithms.

12 weeks, 26 lessons, 52 quizzes, classic Machine Learning for all

Pros of ML-For-Beginners

  • Comprehensive curriculum covering a wide range of ML topics
  • Includes hands-on projects and quizzes for practical learning
  • Supports multiple programming languages (Python, R, JavaScript)

Cons of ML-For-Beginners

  • Less focus on mathematical foundations compared to Homemade-Machine-Learning
  • May be overwhelming for absolute beginners due to its breadth of content
  • Lacks in-depth explanations of some advanced ML concepts

Code Comparison

ML-For-Beginners (Python):

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=42)
model = RandomForestClassifier()
model.fit(X_train, y_train)

Homemade-Machine-Learning (Python):

class RandomForest:
    def __init__(self, n_trees=10, max_depth=None):
        self.n_trees = n_trees
        self.max_depth = max_depth
        self.trees = []

    def fit(self, X, y):
        for _ in range(self.n_trees):
            tree = DecisionTree(max_depth=self.max_depth)
            tree.fit(X, y)
            self.trees.append(tree)

The ML-For-Beginners example uses scikit-learn for implementation, while Homemade-Machine-Learning focuses on building algorithms from scratch, providing a deeper understanding of the underlying mechanics.

A series of Jupyter notebooks that walk you through the fundamentals of Machine Learning and Deep Learning in Python using Scikit-Learn, Keras and TensorFlow 2.

Pros of handson-ml2

  • More comprehensive coverage of machine learning topics
  • Includes practical exercises and real-world examples
  • Regularly updated with the latest TensorFlow and scikit-learn versions

Cons of handson-ml2

  • May be overwhelming for absolute beginners
  • Less focus on implementing algorithms from scratch
  • Requires more computational resources due to complex examples

Code Comparison

handson-ml2:

from sklearn.ensemble import RandomForestClassifier

forest_clf = RandomForestClassifier(n_estimators=100, random_state=42)
forest_clf.fit(X_train, y_train)
y_pred = forest_clf.predict(X_test)

homemade-machine-learning:

class RandomForest:
    def __init__(self, n_trees=10, max_depth=None):
        self.n_trees = n_trees
        self.max_depth = max_depth
        self.trees = []

    def fit(self, X, y):
        for _ in range(self.n_trees):
            tree = DecisionTree(max_depth=self.max_depth)
            tree.fit(X, y)
            self.trees.append(tree)

The homemade-machine-learning repository focuses on implementing algorithms from scratch, providing a deeper understanding of the underlying concepts. In contrast, handson-ml2 utilizes existing libraries like scikit-learn, emphasizing practical application and industry-standard tools.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Homemade Machine Learning

🇺🇦 UKRAINE IS BEING ATTACKED BY RUSSIAN ARMY. CIVILIANS ARE GETTING KILLED. RESIDENTIAL AREAS ARE GETTING BOMBED.


Binder

Read this in other languages: Español

You might be interested in 🤖 Interactive Machine Learning Experiments

For Octave/MatLab version of this repository please check machine-learning-octave project.

This repository contains examples of popular machine learning algorithms implemented in Python with mathematics behind them being explained. Each algorithm has interactive Jupyter Notebook demo that allows you to play with training data, algorithms configurations and immediately see the results, charts and predictions right in your browser. In most cases the explanations are based on this great machine learning course by Andrew Ng.

The purpose of this repository is not to implement machine learning algorithms by using 3rd party library one-liners but rather to practice implementing these algorithms from scratch and get better understanding of the mathematics behind each algorithm. That's why all algorithms implementations are called "homemade" and not intended to be used for production.

Supervised Learning

In supervised learning we have a set of training data as an input and a set of labels or "correct answers" for each training set as an output. Then we're training our model (machine learning algorithm parameters) to map the input to the output correctly (to do correct prediction). The ultimate purpose is to find such model parameters that will successfully continue correct input→output mapping (predictions) even for new input examples.

Regression

In regression problems we do real value predictions. Basically we try to draw a line/plane/n-dimensional plane along the training examples.

Usage examples: stock price forecast, sales analysis, dependency of any number, etc.

🤖 Linear Regression

Classification

In classification problems we split input examples by certain characteristic.

Usage examples: spam-filters, language detection, finding similar documents, handwritten letters recognition, etc.

🤖 Logistic Regression

Unsupervised Learning

Unsupervised learning is a branch of machine learning that learns from test data that has not been labeled, classified or categorized. Instead of responding to feedback, unsupervised learning identifies commonalities in the data and reacts based on the presence or absence of such commonalities in each new piece of data.

Clustering

In clustering problems we split the training examples by unknown characteristics. The algorithm itself decides what characteristic to use for splitting.

Usage examples: market segmentation, social networks analysis, organize computing clusters, astronomical data analysis, image compression, etc.

🤖 K-means Algorithm

Anomaly Detection

Anomaly detection (also outlier detection) is the identification of rare items, events or observations which raise suspicions by differing significantly from the majority of the data.

Usage examples: intrusion detection, fraud detection, system health monitoring, removing anomalous data from the dataset etc.

🤖 Anomaly Detection using Gaussian Distribution

Neural Network (NN)

The neural network itself isn't an algorithm, but rather a framework for many different machine learning algorithms to work together and process complex data inputs.

Usage examples: as a substitute of all other algorithms in general, image recognition, voice recognition, image processing (applying specific style), language translation, etc.

🤖 Multilayer Perceptron (MLP)

Machine Learning Map

Machine Learning Map

The source of the following machine learning topics map is this wonderful blog post

Prerequisites

Installing Python

Make sure that you have Python installed on your machine.

You might want to use venv standard Python library to create virtual environments and have Python, pip and all dependent packages to be installed and served from the local project directory to avoid messing with system wide packages and their versions.

Installing Dependencies

Install all dependencies that are required for the project by running:

pip install -r requirements.txt

Launching Jupyter Locally

All demos in the project may be run directly in your browser without installing Jupyter locally. But if you want to launch Jupyter Notebook locally you may do it by running the following command from the root folder of the project:

jupyter notebook

After this Jupyter Notebook will be accessible by http://localhost:8888.

Launching Jupyter Remotely

Each algorithm section contains demo links to Jupyter NBViewer. This is fast online previewer for Jupyter notebooks where you may see demo code, charts and data right in your browser without installing anything locally. In case if you want to change the code and experiment with demo notebook you need to launch the notebook in Binder. You may do it by simply clicking the "Execute on Binder" link in top right corner of the NBViewer.

Datasets

The list of datasets that is being used for Jupyter Notebook demos may be found in data folder.

Supporting the project

You may support this project via ❤️️ GitHub or ❤️️ Patreon.

Author