Thinc

9.1.1 · active · verified Sun Mar 29

Thinc is a lightweight deep learning library from the makers of spaCy and Prodigy, offering a type-checked, functional-programming API for composing models. It emphasizes composition over inheritance and supports wrapping layers from other frameworks like PyTorch, TensorFlow, and MXNet, allowing for flexible model development. Thinc is actively maintained with frequent releases to support new Python versions and address bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a basic feed-forward neural network using Thinc's functional API and combinators (`chain`, `Relu`, `Softmax`). It shows how to define operators, initialize a model, and perform a simulated forward pass.

import thinc.api as api

# Define a simple feed-forward model using combinators
n_hidden = 128

with api.Model.define_operators({ ">>" : api.chain }):
    model = api.Relu(nO=n_hidden) >> api.Relu(nO=n_hidden) >> api.Softmax()

# Initialize the model (e.g., with dummy data for shape inference)
# In a real scenario, this would be done with actual data or explicit nI/nO.
# For demonstration, we'll manually set nI if it's not inferred.
if model.init_no_grad is None:
    model.init_no_grad = lambda X, Y: (X, Y)

# Example: If your model requires an input dimension, set it manually or via dummy data
# For this simple model, `nI` must be set if not inferred from `X` during init.
# Let's assume an input dimension of 784 (e.g., for MNIST flattened images)
model.set_dim("nI", 784)
model.initialize() # Initialize parameters

print(f"Model: {model.name}")
print(f"Input dimension (nI): {model.get_dim('nI')}")
print(f"Output dimension (nO): {model.get_dim('nO')}")
print(f"Number of parameters: {model.to_bytes().nbytes} bytes")

# Simulate a forward pass (requires numpy for dummy data)
import numpy
X_dummy = numpy.random.rand(10, model.get_dim('nI')).astype('f')
Y_dummy, callback = model(X_dummy, is_train=False)
print(f"Output shape: {Y_dummy.shape}")

view raw JSON →