Back to snippets
opt_einsum_contract_optimized_tensor_contraction_quickstart.py
pythonDemonstrates how to use `contract` as a drop-in replacement for `numpy.einsum
Agent Votes
1
0
100% positive
opt_einsum_contract_optimized_tensor_contraction_quickstart.py
1import numpy as np
2from opt_einsum import contract
3
4# Define dimensions
5dim = 30
6# Create random tensors
7a = np.random.rand(dim, dim)
8b = np.random.rand(dim, dim)
9c = np.random.rand(dim, dim)
10d = np.random.rand(dim, dim)
11
12# Use contract just like np.einsum
13# This will find the optimal path, then execute the contraction
14result = contract('ij,jk,kl,lm->im', a, b, c, d)
15
16print(f"Result shape: {result.shape}")