AI Wiki中文/EN

NumPy arrays: shape, broadcasting and ownership

NumPy 数组计算

Fit vectorized training statistics and check shape, axis, view/copy behavior and integer dtype boundaries with real NumPy.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The numbers can be right while the shape is wrong

Three observations have three features. We want to subtract each feature’s training mean and divide by its training standard deviation. A Python loop can do this one value at a time. NumPy expresses the same computation over an array, but we must still say which axis means “observations,” which means “features,” and which values are allowed to share memory.

An ndarray has a shape, a data type and a layout connecting indices to stored values. Vectorization moves many operations into compiled array routines; it does not choose the mathematical operation for us. Two compatible shapes may broadcast successfully and still represent the wrong problem. The broadcasting guide explains both the matching rule and cases where the resulting output becomes unexpectedly large.

The main example fits a standardization transform on training observations and reuses it on a new row. Alongside it, three short calculations expose a broadcasting mistake, a shared-buffer edit and an integer overflow.

Shape, axis and dtype are part of the contract

Reduce observations, retain features

Let X have n rows and p feature columns. For each column, compute the empirical mean and variance with denominator n:

μj=1n∑i=1nXij,σj2=1n∑i=1n(Xij−μj)2.\mu_j=\frac1n\sum_{i=1}^n X_{ij},\qquad \sigma_j^2=\frac1n\sum_{i=1}^n(X_{ij}-\mu_j)^2.

In a two-dimensional array, axis=0 reduces the row axis and produces one statistic per column. With keepdims=True, that axis remains with length one, so the result has shape (1,p). Reducing axis=1 instead would compute one statistic per observation. Omitting the axis flattens the reduction conceptually across all entries; that is not feature-wise standardization.

NumPy’s std reference defines the divisor as N-ddof. Here ddof=0 is an explicit preprocessing convention. Using ddof=1 changes the scale; neither setting automatically makes the square-root statistic an unbiased estimate of population standard deviation.

A constant training column has zero variance, so dividing by its standard deviation is undefined. We choose scale one for exactly constant columns in the converted training array:

sj={1∀i, Xij=X1j,σj∃i, Xij≠X1j,Zij=Xij−μjsj.s_j=\begin{cases}1&\forall i,\ X_{ij}=X_{1j},\\\sigma_j&\exists i,\ X_{ij}\ne X_{1j},\end{cases}\qquad Z_{ij}=\frac{X_{ij}-\mu_j}{s_j}.

A constant training column becomes zero. A future value different from that training constant becomes its raw deviation under this scale-one policy; it is not forced to zero. Nonconstant training columns have approximately zero mean and unit variance after transformation, subject to floating-point error. New observations need not have either property. Standardization also does not make a distribution Gaussian.

Broadcasting matches trailing axes

NumPy compares shapes from the right. Each pair of dimensions must be equal or one must be one; a missing leading dimension acts like one. The (1,p) mean and scale therefore broadcast across (n,p) observations without constructing n separate copies of the statistics. Broadcasting rules

The rule does not know our labels. A column of shape (n,1) plus a vector of shape (n,) creates (n,n) for n greater than one: the vector acts like (1,n). If we intended to add one value per row, explicitly reshape the second operand to (n,1). An unexpected output shape is often a correctness failure before it becomes a memory problem.

Also distinguish *, which multiplies corresponding broadcast elements, from @, which performs matrix multiplication for two-dimensional operands. A dot product, a column-wise reduction and an elementwise product are different operations even when their inputs contain the same numbers.

Views share storage; dtype limits arithmetic

Basic slicing normally returns a view onto the same data buffer. Editing that view can edit its source. Reading through advanced indexing, such as a list of column indices, creates a copy. But assigning directly to a[:, [0,2]] writes into a, so “advanced indexing makes a copy” is not a reason to treat indexed assignment as harmless. reshape may return a view or require a copy depending on layout. Use an explicit .copy() when independent storage is required, and inspect sharing when it matters. Copies and views

A numeric dtype has finite precision and range. The signed eight-bit range is −128 to 127. Adding two int8 arrays can overflow that range; converting the already-overflowed result afterward does not restore the lost value. Promote before the arithmetic. Python’s arbitrary-precision int and a NumPy fixed-width integer are different types with different behavior. NumPy data types

Fit once, transform with the same statistics

This complete program uses NumPy 1.26.4 with Python 3.12. It accepts plain two-dimensional numeric arrays, copies them to float64, and never edits the input. Training requires at least one row and one feature. Queries may have zero rows but must retain the training feature count. Boolean, object, string and complex arrays are rejected, as are nonfinite values and converted magnitudes above one million. These restrictions keep the numerical example small in scope.

Constant columns are detected by exact equality after conversion. Their mean is set to the observed constant, avoiding a tiny spurious residual from repeated-sum rounding. For nonconstant columns, a standard deviation below 1e-12 is rejected rather than silently replaced by an epsilon. That guard has units and excludes some mathematically valid data; it is not a universal near-constant test. Pass an unmodified fitted model to transform.

import numpy as np


def matrix(array, features=None, allow_empty=False):
    if type(array) is not np.ndarray or array.ndim != 2 or array.shape[1] == 0:
        raise ValueError('expected a plain two-dimensional ndarray with features')
    if not allow_empty and array.shape[0] == 0:
        raise ValueError('training requires at least one row')
    if features is not None and array.shape[1] != features:
        raise ValueError('feature count differs from training')
    if array.dtype.kind not in 'iuf':
        raise ValueError('use real integer or floating arrays, not bool/object/complex')
    try:
        with np.errstate(over='raise', invalid='raise'):
            x = np.array(array, dtype=np.float64, copy=True)
    except FloatingPointError as exc:
        raise ValueError('conversion to float64 failed') from exc
    if not np.isfinite(x).all() or np.any(np.abs(x) > 1e6):
        raise ValueError('finite coordinates with magnitude at most 1e6 required')
    return x


def fit_standardizer(train):
    x = matrix(train)
    mean = x.mean(axis=0, keepdims=True)
    constant = np.all(x == x[:1], axis=0, keepdims=True)
    # Preserve the observed constant exactly despite mean-summation rounding.
    mean = np.where(constant, x[:1], mean)
    std = x.std(axis=0, ddof=0, keepdims=True)
    if np.any((~constant) & (std < 1e-12)):
        raise ValueError('nonconstant column has unresolved teaching-scale variance')
    scale = np.where(constant, 1.0, std)
    return {'mean': mean, 'scale': scale, 'constant': constant,
            'features': x.shape[1]}


def transform(model, data):
    # model must be an unmodified fit_standardizer result.
    x = matrix(data, model['features'], allow_empty=True)
    return (x - model['mean']) / model['scale']


def main():
    train = np.array([[2, 10, 5], [4, 14, 5], [6, 18, 5]], dtype=np.int16)
    model = fit_standardizer(train)
    print('mean shape / values:', model['mean'].shape, model['mean'].tolist())
    print('scale:', model['scale'].round(6).tolist())
    print('constant:', model['constant'].tolist())
    print('training:', transform(model, train).round(6).tolist())
    print('new row:', transform(model, np.array([[8, 22, 7]])).round(6).tolist())
    column = np.array([[1], [2], [3]])
    vector = np.array([10, 20, 30])
    print('broadcast shapes:', (column + vector).shape, (column + vector[:, None]).shape)
    base = np.arange(6).reshape(2, 3)
    view = base[:, 1:]
    gathered = base[:, [0, 2]]
    view[0, 0] = 99
    gathered[0, 0] = -7
    print('base after edits:', base.tolist())
    print('shared buffers:', np.shares_memory(base, view), np.shares_memory(base, gathered))
    small = np.array([100, 110], dtype=np.int8)
    print('int8 sum:', (small + small).tolist())
    promoted = small.astype(np.int64)
    print('promoted sum:', (promoted + promoted).tolist())


if __name__ == '__main__':
    main()

Output:

mean shape / values: (1, 3) [[4.0, 14.0, 5.0]]
scale: [[1.632993, 3.265986, 1.0]]
constant: [[False, False, True]]
training: [[-1.224745, -1.224745, 0.0], [0.0, 0.0, 0.0], [1.224745, 1.224745, 0.0]]
new row: [[2.44949, 2.44949, 2.0]]
broadcast shapes: (3, 3) (3, 1)
base after edits: [[0, 99, 2], [3, 4, 5]]
shared buffers: True False
int8 sum: [-56, -36]
promoted sum: [200, 220]

The first two scales are sqrt(8/3) and sqrt(32/3). The third is one by policy. In the new row, the first two values become sqrt(6), while the third becomes 2. Refitting on that one query would instead treat every column as constant and change the meaning of the transform.

The (3,3) broadcasting result is valid array arithmetic but wrong for a requested column-wise row offset. In the editing example, only the basic-slice assignment reaches the original array. In the overflow example, the correct sums 200 and 220 require a wider dtype before addition; the negative int8 values are not unusually small observations.

For n training rows and p features, fitting performs O(n*p) numerical operations and uses O(n*p) temporary storage plus O(p) fitted statistics. Transforming m rows takes O(m*p) operations and output storage, with temporary copies of the same order. Broadcasting the statistics does not replicate their buffer, but the output and arithmetic intermediates are still dense arrays. A mistaken outer operation can turn a linear-sized pair of inputs into a quadratic-sized output. These bounds explain work and storage, not a measured speedup over every possible Python loop.

Array arithmetic does not validate the dataset

The fitted state records positions, not feature names. Swapping two columns in new data can satisfy the shape check while producing a meaningless result. Keep the feature order in an external schema or use labeled data before crossing into an array. A view can also outlive assumptions about its source; later edits to the shared buffer change what a consumer sees.

float64 is a deliberate computation type, not exact real arithmetic. Converting higher-precision input can round values, and low-precision input may have already lost information. The implementation rejects nonfinite and very small nonconstant scales, but it is not a robust estimator or a general remedy for ill conditioning. Outliers can strongly affect means and standard deviations.

This example has no missing-value imputation. Replacing missing values with zero without an explicit rule changes the data. Fit preprocessing only on the training partition and reuse it for validation or test rows; including those rows in the estimated mean and scale changes the evaluation procedure.

Vectorization is useful when the operation matches array semantics. It can also allocate too much memory or make a wrong axis harder to notice. Check shape, dtype, a few scalar calculations and mutation behavior before optimizing throughput.

Predict shape, value and aliasing

  1. Read an axis. A training array has shape (8,4). What is the shape of mean(axis=0, keepdims=True)? What would axis=1 mean?
Keep the reduced axis

Answer: The first result has shape (1,4), one mean per feature. Reducing axis one with keepdims=True gives (8,1), one mean per observation. Both shapes may broadcast, but they describe different preprocessing operations.

  1. Avoid an outer sum. Why does (3,1)+(3,) produce (3,3)? How do we express one offset per row?
Align trailing dimensions

Answer: NumPy treats the one-dimensional shape as (1,3) for broadcasting. The first dimension expands to three and the second also expands to three. Use offset[:,None] to give the offset shape (3,1) before adding it to the column.

  1. Interpret a constant feature. Training values in a column are all 5, and a new value is 7. Under this program’s policy, what is its transformed value?
Reuse the fitted scale

Answer: The training mean is 5 and the scale is one, so the value becomes 2. Constant training entries became zero, but future values are not forced to match them. Recomputing the mean on the query would use different fitted statistics.

  1. Separate copying from promotion. Why do .copy() and .astype(np.int64) solve different problems? Can casting after int8 addition fix overflow?
Track storage and arithmetic separately

Answer: An explicit copy separates the data buffer, while conversion to int64 selects a wider integer representation. A copy with the same int8 dtype can still overflow. Casting the already-overflowed result preserves its wrong values; promote the operands before adding them.

Array semantics are the foundation of numerical code

The NumPy guides on broadcasting, copies and types describe separate contracts that interact in a numerical program. Broadcasting controls index compatibility, views control ownership, and dtype controls representation. The standard-deviation reference adds reduction and precision conventions. Understanding those contracts makes array code easier to review than memorizing a long API list.

The same discipline applies to linear regression and backpropagation: an axis mismatch or preprocessing leak changes the model before optimization starts. Dataframes add labels and relational operations; they solve some alignment problems while introducing their own rules about missing values and joins.

Make a prediction, then check

Why does adding shapes (3,1) and (3,) create (3,3)?

Choose one answer

Learning objectives

  • Read array shape and reduction axes before relying on broadcasting.
  • Fit and reuse feature statistics with an explicit constant-column policy.
  • Distinguish shared storage, indexed assignment and dtype overflow.

Prerequisites & connections

Explore related knowledge →

References

  1. Broadcasting — NumPy v1.26 Manual
    NumPy Developers
  2. Copies and views — NumPy v1.26 Manual
    NumPy Developers
  3. Data types — NumPy v1.26 Manual
    NumPy Developers
  4. numpy.std — NumPy v1.26 Manual
    NumPy Developers

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Eight tests pass in <repo>/.venv/bin/python: actual CPython 3.12.4 and NumPy 1.26.4. Exact Fraction raw-moment scalar references verify nine fitted mean/scale/constant arrays and 63 new-row output values across integer, float32 and float64 inputs.
  • Verified ddof=0 convention, constant 0.1 mean preservation, noncontiguous/reversed inputs, no input/model aliasing, query-batch independence and empty query shape. Actual library tests cover outer broadcasting, reduction axes, matrix versus elementwise products, basic-slice aliasing, advanced-indexed reads and writes, int8 wraparound with an independent modular oracle, promotion timing and invalid/numerically unresolved input. Ten stdout lines match both articles.
  • Complete original bilingual text, identical code, two matching displays, six anchors and four answered exercises pass strict MDX/KaTeX and actual React HTML/MathML. Only article_text controls paths. Written denotes AI author checking, not human review. No timing claim, global installation, whole-site build or copied library distribution; repository dependency integration remains the parent task.
  • All eight author tests passed under the repository isolated CPython 3.12.4 with NumPy 1.26.4. An independent 90-digit Decimal reference combines streaming incremental means with the pairwise-dispersion identity sum over i<j of (xi-xj)^2 divided by n^2, avoiding the author raw-moment formula and NumPy centered reduction. Five targeted fits and 22 query coordinates agree, including large offsets, small accepted variance and positive/negative minimum-subnormal constant columns.
  • Independently reconstructed four byte addresses of a negative-stride noncontiguous view and checked the corresponding source mutations while an advanced-indexed copy retained its values. Also checked the exact 1e-12 accepted scale versus a below-threshold rejection, and ownership for read-only caller input. This supplements the author tests instead of repeating their full combinations.
  • Read full EN/ZH text, program, exercises and metadata. Verified training-only fit dependence, feature-position limitation, converted-array constant policy, query-batch independence, explicit unmodified-model precondition, ddof and dtype semantics, temporary/output storage and floating-point scope. No substantive defect or required revision was identified.
  • Strict MDX/KaTeX and actual React HTML passed with two matching displays, six stable anchors and four answers per language. Author tests confirm identical code and ten actual stdout lines. All five hashes match the frozen manifest; source IDs and URLs below are copied exactly from metadata. The reviewer edited no author or repository files.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • Broadcasting — NumPy v1.26 Manual · Actually read general trailing-axis/equal-or-one rules at lines 64–85, conceptual rather than materialized stretching at 41–56, and outer-operation/output-memory discussion at 154–169. The article’s three-by-three counterexample and training-standardization model are original.
  • Copies and views — NumPy v1.26 Manual · Actually read basic indexing views, advanced-indexing copies, distinction for direct indexed assignment at lines 68–95, and reshape layout-dependent copy/view behavior. The chapter uses shares_memory for actual examples, not a simplistic base-is-None test.
  • Data types — NumPy v1.26 Manual · Actually read fixed numeric dtypes and Overflow Errors section at lines 122–138, including contrast with Python arbitrary-precision int and iinfo/finfo. Independently ran int8 array addition and promotion before/after overflow in the pinned library.
  • numpy.std — NumPy v1.26 Manual · Actually read dtype accumulator, axis, ddof and keepdims parameters at lines 82–105 and variance/standard-deviation/precision notes 128–135. The chapter states denominator n and does not call ddof=1 an unbiased standard-deviation estimator.
  • Broadcasting — NumPy v1.26 Manual · Actually read the official versioned 1.26 broadcasting guide: lines 42–56 conceptual scalar stretching without materialized copies, 64–85 trailing-dimension/equal-or-one matching, and 154–169 outer operation and output-size consequences. No universal performance speedup claim is inferred.
  • Copies and views — NumPy v1.26 Manual · Actually read the official 1.26 copies/views guide, lines 39–46 buffer/metadata distinction, 53–93 basic versus advanced reads and direct indexed assignment, 95–109 reshape layout limits. Reviewed actual shares_memory use rather than relying solely on the simplified base-property discussion.
  • Data types — NumPy v1.26 Manual · Actually read official 1.26 types, lines 44–74 finite-width/platform-dependent types and 122–152 integer overflow, Python integer contrast and extended precision limitations. Executed NumPy 1.26.4 through the repository isolated interpreter; no NumPy 2 promotion rules imported into this chapter.
  • numpy.std — NumPy v1.26 Manual · Actually read official 1.26 std API, lines 82–105 axis/dtype/ddof/keepdims and 128–135 variance divisor, standard-deviation bias and accumulation precision. The chapter correctly uses ddof=0 for preprocessing, not an unbiased-estimator assertion.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.