Nx vs NumPy comparison
This document compares the Nx library (OCaml) with NumPy (Python), highlighting similarities, differences, and providing equivalent code examples.
- Nx vs NumPy Comparison
1. Overview
Nx is a numerical computing library for OCaml, close to NumPy in its names and its broadcasting rules. The two differ in these ways:
- Arrays are values: an Nx operation returns a new array and never changes its operands. Where NumPy assigns into an array, Nx's
setandscatterreturn the updated array. Giving an array up withdonatelets the operation that reads it write its result into the array's memory. - Arrays lie on device sets: an array made from numbers is a host array, computed by Nx's C kernels. An array may also lie on the devices of a set, and an operation computes where its operands lie.
- Types fix dtypes: the operands of an operation share a dtype by their types, and Nx never promotes or casts one implicitly.
castconverts explicitly. Nx has boolean and bit arrays, and no string arrays. - Randomness comes from keys: every draw is a function of a key, given as
~keyor taken from the enclosingRng.with_keyscope. Outside every scope a draw takes the next key of the domain's own, seeded from the system's entropy. - Operators live in
Nx.Infix: a local open,Nx.Infix.(a * b + c), applies them to arrays inside the parentheses, where integer arithmetic isStdlib.( + ), and*$,+$take a scalar operand (nx.mli, Operators).
If you notice an undocumented difference, please open an issue; it's probably a bug.
2. Array creation
Basic array creation
Nx:
(* Creating a zeros array *) let zeros = Nx.zeros Nx.float64 [|3; 3|] (* Creating a ones array *) let ones = Nx.ones Nx.float64 [|3; 3|] (* Creating an array with a specific value *) let full = Nx.full Nx.float64 [|3; 3|] 5.0 (* Creating a range *) let range = Nx.arange Nx.int32 0 10 1 (* Creating an identity matrix *) let identity = Nx.eye Nx.float64 3
NumPy:
# Creating a zeros array zeros = np.zeros((3, 3)) # Creating a ones array ones = np.ones((3, 3)) # Creating an array with a specific value full = np.full((3, 3), 5.0) # Creating a range range_array = np.arange(0, 10, 1) # Creating an identity matrix identity = np.identity(3)
Advanced array creation
Nx:
(* Creating from existing data *) let data = [|1.0; 2.0; 3.0; 4.0|] let arr = Nx.create Nx.float64 [|2; 2|] data (* Creating using a function *) let init_arr = Nx.init Nx.float64 [|3; 3|] (fun idx -> float_of_int (idx.(0) + idx.(1)))
NumPy:
# Creating from existing data data = [1.0, 2.0, 3.0, 4.0] arr = np.array(data).reshape(2, 2) # Creating using a function init_arr = np.fromfunction(lambda i, j: i + j, (3, 3))
3. Array operations
Basic operations
Nx:
(* Element-wise addition *) let result = Nx.add arr1 arr2 (* Scalar multiplication *) let scaled = Nx.mul_s arr 2.0 (* Matrix multiplication *) let matmul_result = Nx.matmul arr1 arr2
NumPy:
# Element-wise addition result = arr1 + arr2 # In-place addition arr1 += arr2 # Scalar multiplication scaled = arr * 2.0 # Matrix multiplication matmul_result = arr1 @ arr2 # or np.matmul(arr1, arr2)
Array manipulation
Nx:
(* Reshape array *) let reshaped = Nx.reshape [|1; 6|] arr (* Transpose array *) let transposed = Nx.transpose arr (* Flatten array *) let flattened = Nx.flatten arr (* Concatenate arrays *) let concat = Nx.concatenate ~axis:0 [arr1; arr2]
NumPy:
# Reshape array reshaped = arr.reshape(1, 6) # Transpose array transposed = arr.transpose() # Flatten array flattened = arr.flatten() # Concatenate arrays concat = np.concatenate([arr1, arr2], axis=0)
4. Element access and slicing
Nx:
(* Get a single element *) let element = Nx.item [0; 1] arr (* An array with one element replaced (arrays are values) *) let arr' = Nx.(set [ I 0; I 1 ] (scalar float64 5.0) arr) (* Get a slice/subarray *) let row = Nx.get [0] arr
NumPy:
# Get a single element element = arr[0, 1] # Set a single element arr[0, 1] = 5.0 # Get a slice/subarray slice = arr[0]
5. Statistical functions
Nx.quantile sorts NaN last, so a NaN reaches only the upper quantiles, where
np.quantile gives NaN for every quantile of a lane that holds one.
Nx:
(* Sum of all elements *) let total = Nx.sum arr (* Mean of all elements *) let avg = Nx.mean arr (* Min and max values *) let min_val = Nx.min arr let max_val = Nx.max arr (* Sum along an axis *) let axis_sum = Nx.sum ~axes:[ 0 ] arr (* Quartiles along an axis, one row per probability *) let quartiles = Nx.quantile ~axis:0 [| 0.25; 0.5; 0.75 |] arr
NumPy:
# Sum of all elements total = np.sum(arr) # Mean of all elements avg = np.mean(arr) # Min and max values min_val = np.min(arr) max_val = np.max(arr) # Sum along an axis axis_sum = np.sum(arr, axis=0) # Quartiles along an axis, one row per probability quartiles = np.quantile(arr, [0.25, 0.5, 0.75], axis=0)
6. Linear algebra
Nx:
(* Matrix inverse *) let inv_a = Nx.inv a (* Solve linear system Ax = b *) let x = Nx.solve a b (* SVD decomposition, singular values in float64 *) let u, s, vt = Nx.svd Nx.float64 a (* Eigenvalue decomposition, in complex128 *) let eigenvalues, eigenvectors = Nx.eig Nx.complex128 a
NumPy:
# Matrix inverse inv_a = np.linalg.inv(a) # Solve linear system Ax = b x = np.linalg.solve(a, b) # SVD decomposition u, s, vt = np.linalg.svd(a) # Eigenvalue decomposition eigenvalues, eigenvectors = np.linalg.eig(a)
7. Broadcasting
Nx:
(* Broadcast a smaller array to match dimensions *) let broadcasted = Nx.broadcast_to [|3; 3|] smaller_arr (* Broadcasting happens automatically in operations *) let result = Nx.add matrix vector
NumPy:
# Broadcast a smaller array to match dimensions broadcasted = np.broadcast_to(smaller_arr, (3, 3)) # Broadcasting happens automatically in operations result = matrix + vector
8. Conditional operations
Nx:
(* Create a boolean mask *) let mask = Nx.greater_s arr 0.5 (* Apply condition with where *) let result = Nx.where mask arr1 arr2
NumPy:
# Create a boolean mask mask = arr > 0.5 # Apply condition with where result = np.where(mask, arr1, arr2)
Masks, sorting and grouping
Rows of keys sort column 0 first, where np.lexsort sorts by its last key
first. Nx.unique numbers groups in order of first appearance, where
np.unique numbers them in sorted order.
Nx:
(* Positions where a mask holds, and the elements there *) let hits = Nx.positions mask let kept = Nx.(slice [ M mask ] x) (* Sort by a, then by b descending *) let perm = Nx.lexsort (Nx.stack ~axis:1 [ Nx.order_key Nx.uint64 a; Nx.bitwise_not (Nx.order_key Nx.uint64 b) ]) (* Where queries fall among sorted knots *) let bins = Nx.searchsorted ~side:`Right knots q (* Group ids, each group's first position and size *) let g = Nx.unique keys (* Maxima at indices, and counts per id *) let m = Nx.scatter ~combine:Nx.Max ~axis:0 indices values base let counts = Nx.reduce_segments Nx.Add ~segments:k ids (Nx.ones Nx.int64 [| Nx.dim 0 ids |])
NumPy:
# Positions where a mask holds, and the elements there
hits = np.flatnonzero(mask)
kept = x[mask]
# Sort by a, then by b descending
perm = np.lexsort((-b, a))
# Where queries fall among sorted knots
bins = np.searchsorted(knots, q, side="right")
# Group ids, each group's first position and size
uniq, first, ids, counts = np.unique(keys, return_index=True,
return_inverse=True, return_counts=True)
# Maxima at indices, and counts per id
m = base.copy(); np.maximum.at(m, indices, values)
counts = np.bincount(ids, minlength=k)9. Random number generation
Nx:
(* Generate uniform random numbers *) let random = Nx.Rng.uniform Nx.float64 [| 3; 3 |] (* Generate normal distributed random numbers *) let normal = Nx.Rng.normal Nx.float64 [| 3; 3 |] (* For reproducibility, draw inside a scope rooted at a key *) let reproducible = Nx.Rng.with_key (Nx.Rng.key 42) (fun () -> Nx.Rng.uniform Nx.float64 [| 3; 3 |]) (* Or give each draw its own key; a key is used one way only *) let keys = Nx.Rng.split ~n:2 (Nx.Rng.key 7) let a = Nx.Rng.normal ~key:keys.(0) Nx.float64 [| 3 |] let b = Nx.Rng.normal ~key:keys.(1) Nx.float64 [| 3 |] (* A shuffle gathers at a random permutation *) let shuffled = Nx.take (Nx.Rng.permutation 3) a
NumPy:
# Generate uniform random numbers random = np.random.rand(3, 3) # Generate normal distributed random numbers normal = np.random.randn(3, 3) # For reproducibility, seed a generator rng = np.random.default_rng(42) reproducible = rng.random((3, 3)) # Each generator holds its own state a = rng.standard_normal(3) b = rng.standard_normal(3) # Shuffle shuffled = rng.permutation(a)
10. Real-world example: Linear regression
Nx:
(* Generate sample data *) let x = Nx.linspace Nx.float64 0.0 10.0 100 let y = Nx.(Infix.((x *$ 2.0) + Rng.normal float64 [| 100 |])) (* Reshape x for design matrix *) let x_design = Nx.(concatenate ~axis:1 [ ones float64 [| 100; 1 |]; reshape [| 100; 1 |] x ]) (* Compute coefficients using normal equation *) let xtx = Nx.matmul (Nx.transpose x_design) x_design let xty = Nx.matmul (Nx.transpose x_design) (Nx.reshape [| 100; 1 |] y) let coeffs = Nx.solve xtx xty (* Make predictions *) let y_pred = Nx.matmul x_design coeffs
NumPy:
# Generate sample data x = np.linspace(0, 10, 100) y = 2 * x + np.random.randn(100) # Reshape x for design matrix x_design = np.column_stack((np.ones(100), x)) # Compute coefficients using normal equation xtx = x_design.T @ x_design xty = x_design.T @ y.reshape(100, 1) coeffs = np.linalg.solve(xtx, xty) # Make predictions y_pred = x_design @ coeffs
this page is tested with mdxedit this page ↗