Machine Learning for Materials (MATE70026)

repository·2026·Indexed 41 days ago

https://github.com/aronwalsh/mlformaterials

Course materials for MATE70026 at Imperial College London, focusing on representing composition-structure-property information for machine learning in materials science. Includes tutorials on using matminer, elementembeddings, pymatviz, and OPTIMADE, as well as practical implementations of linear regression, k-means clustering, and decision tree classifiers using scikit-learn, NumPy, and Pandas.

Tokens
15.4K
Snippets
56
Records
62
Agent score
51%

What's inside Machine Learning for Materials

  1. Build a Simple CNN with PyTorch

    2026

    A basic Convolutional Neural Network (CNN) architecture for image classification (e.g., FashionMNIST) typically involves:

    1. Convolutional Layers: nn.Conv2d to extract features.
    2. Activation Functions: nn.ReLU to introduce non-linearity.
    3. Pooling Layers: nn.MaxPool2d to reduce spatial dimensions.
    4. Flattening: nn.Flatten to transition from 2D feature maps to 1D vectors.
    5. Fully Connected Layers: nn.Linear for final classification.
    import torch
    import torch.nn as nn
    
    class SimpleCNN(nn.Module):
        def __init__(self):
            super(SimpleCNN, self).__init__()
            self.conv1 = nn.Conv2d(1, 32, kernel_size=3, padding=1)
            self.relu1 = nn.ReLU()
            self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
            self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
            self.relu2 = nn.ReLU()
            self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
            self.flatten = nn.Flatten()
            self.fc1 = nn.Linear(64 * 7 * 7, 128)
            self.relu3 = nn.ReLU()
            self.fc2 = nn.Linear(128, 10)
    
        def forward(self, x):
            x = self.pool1(self.relu1(self.conv1(x)))
            x = self.pool2(self.relu2(self.conv2(x)))
            x = self.flatten(x)
            x = self.relu3(self.fc1(x))
            x = self.fc2(x)
            return x
  2. Install deep learning libraries

    2026

    To follow the tutorials in this lecture, you need to install scikit-image for image processing and torchvision for computer vision datasets.

    !pip install scikit-image --quiet
    !pip install torchvision --quiet
  3. Find learning resources for Machine Learning in Materials Science

    2026

    A variety of educational resources are available for mastering machine learning applied to scientific domains:

    Courses and Guides

    • Foundational ML: AI For Everyone (Coursera), Microsoft ML for Beginners, Machine Learning for Everyone, Practical Deep Learning (fast.ai), Stanford ML Cheat Sheets.
    • Mathematics: Mathematics for Machine Learning Specialisation (Coursera), Numerics of ML.
    • Domain Specific (Chemistry/Materials): Agents for Science, Data Driven Chemistry, Introduction to Machine Learning in Chemistry, ML for Chemistry, Materials Informatics (various sources), Machine Learning for Materials (MSE Fall 2023/Spring 2024).
    • Specialized Topics: Gentle Introduction to Graph Neural Networks, LLM Visualisation, Homemade Machine Learning.

    Books

    • Core ML/DL: Dive into Deep Learning, Understanding Deep Learning, Deep Generative Modeling, Interpretable Machine Learning.
    • Scientific ML: Applications of Artificial Intelligence in Chemistry, Deep Learning for Molecules and Materials, Machine Learning in Materials Science, Bayesian Computation.

    Videos

    • Educational Channels: 3Blue1Brown (Neural Networks), Statquest with Josh Starmer, John Kitchin (Python for Science), Taylor Sparks (Materials Informatics).
    • Webinars: Materials Cloud, Materials Project.
  4. Access and load materials datasets with matminer

    2026

    You can explore available datasets in matminer using matminer.datasets.get_available_datasets(). To get detailed information about a specific dataset, use matminer.datasets.dataset_retrieval.get_all_dataset_info(). Once identified, load the dataset into a pandas DataFrame using load_dataset() from matminer.datasets.dataset_retrieval.

    import matminer
    from matminer.datasets.dataset_retrieval import load_dataset
    
    # List available datasets
    matminer.datasets.get_available_datasets(print_format='low')
    
    # Get detailed info for a specific dataset
    print(matminer.datasets.dataset_retrieval.get_all_dataset_info('matbench_log_kvrh'))
    
    # Load the dataset
    df = load_dataset('matbench_log_kvrh')
  5. Build a local copy of the course website

    2026

    To view the course website locally, you must use jupyter-book. First, install the jupyter-book package via pip, then navigate to the repository root and execute the build command.

    pip install -U jupyter-book
    
    # Navigate to the repository directory
    cd mlformaterials
    
    # Build the local site
    jupyter-book build .
  6. Access the Machine Learning for Materials course content

    2026

    The course materials are available as an online resource or can be downloaded for local use. You can browse individual files in the repository or download the entire course folder as a ZIP file to work offline.

    https://github.com/aronwalsh/MLforMaterials/archive/master.zip
  7. Install required libraries for crystal analysis

    2026

    To follow the workflows in this lecture, install the following libraries using pip. These include matminer for materials featurization, smact for charge-balanced composition screening, plotly for visualization, and multiprocess for parallel computing.

    !pip install matminer --quiet
    !pip install smact==3.2.0 --quiet
    !pip install plotly --quiet
    !pip install multiprocess --quiet
  8. Evaluate model performance using Cross-Validation

    2026

    To ensure a model generalizes to unseen data and is not overfitted, use $k$-fold cross-validation. Using sklearn.model_selection.KFold, you can split the data into $k$ subsets, training on $k-1$ and validating on the remaining one. Use cross_val_score to evaluate specific metrics like neg_mean_absolute_error or r2.

    from sklearn.model_selection import KFold, cross_val_score
    
    # Setup KFold
    cv = KFold(n_splits=5, shuffle=True, random_state=42)
    
    # Evaluate using MAE and R2
    mae_scores = cross_val_score(rf, X, y, cv=cv, scoring='neg_mean_absolute_error')
    r2_scores = cross_val_score(rf, X, y, cv=cv, scoring='r2')
    
    print(f'mean MAE = {np.mean(np.abs(mae_scores)):.3f}')
    print(f'mean r^2 = {np.mean(r2_scores):.3f}')
  9. Install required libraries for Machine Learning for Materials

    2026

    To follow the tutorials in this repository, you need to install matminer for materials informatics and seaborn for statistical visualization. You can check your numpy version using pip show numpy to ensure compatibility.

    !pip install matminer --quiet
    !pip install seaborn --quiet
    !pip show numpy
  10. What is Bayesian Optimisation (BO)?

    2026

    Bayesian Optimisation (BO) is a technique for optimising complex, expensive-to-evaluate functions (like physical experiments).

    Core Components:

    1. Surrogate Model: Typically a Gaussian Process (GP) that approximates the true objective function $O(x)$. It captures both the mean $\mu(x)$ and the uncertainty $\sigma(x)$ at any given point.
    2. Acquisition Function $\alpha(x)$: A mathematical function that decides where to sample next by balancing exploration (sampling in uncertain regions) and exploitation (sampling in regions known to be promising). Common functions include:
      • Probability of Improvement (PI)
      • Expected Improvement (EI)
      • Upper Confidence Bound (UCB)

    In materials research, BO is used to find optimal parameters like chemical composition or processing conditions without exhaustive trial-and-error.

  11. Perform PCA for dimensionality reduction

    2026

    Principal Component Analysis (PCA) can be used to reduce high-dimensional featurized data into 2D or 3D space for visualization.

    Workflow:

    1. Standardize features using sklearn.preprocessing.StandardScaler.
    2. Initialize sklearn.decomposition.PCA with n_components (e.g., 2 or 3).
    3. Use .fit_transform(X) to obtain the reduced coordinates.
    4. Plot using matplotlib or plotly.
    from sklearn.decomposition import PCA
    from sklearn.preprocessing import StandardScaler
    
    # 1. Standardize
    X_standardised = StandardScaler().fit_transform(X)
    
    # 2. & 3. Reduce to 2D
    pca = PCA(n_components=2)
    reduced_data = pca.fit_transform(X_standardised)
    
    # 4. Check variance
    print(f"Cumulative variance: {pca.explained_variance_ratio_.sum()}")