liveBook · Manning

Tensor reshaping

As explained in Grokking Statistics

A NumPy array operation that changes an array’s dimensions without changing its element values.

Tensor reshaping changes an array’s dimensions without changing its element values. In a scikit-learn logistic-regression example, reshape(-1, 1) turns one-dimensional input data into a single column of observations. section 8.3

Giving x the shape the model expects

A toddler-meltdown dataset stores hours without a nap in a NumPy array. Applying .reshape(-1, 1) makes x a column, preventing the input-format error that would otherwise occur. The output y remains one-dimensional because scikit-learn treats it as one response variable. section 8.3

import numpy as np
from sklearn.linear_model import LogisticRegression

x = np.array([0.1, 0.5, 0.7, 1.2, 1.2, 1.5, 1.6, 1.9, 2.5, 2.5,
              2.7, 3.2, 3.3, 3.7, 3.8, 4.1, 4.5, 4.5, 4.5, 5.0,
              5.1, 5.6, 5.7, 6.2, 6.3]) \
    .reshape(-1, 1)  #1

y = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0,
              0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0,
              1.0, 1.0, 1.0, 1.0, 1.0])  #2

model = LogisticRegression(penalty=None)  #3
model.fit(x, y)   #3

b1 = model.coef_.flatten()[0]  #4
b0 = model.intercept_[0]  #4
print(f"β₀={b0:.4f}, β₁={b1:.4f}")  #5

The listing shows reshaping applied directly to NumPy input before fitting LogisticRegression. section 8.3

How Grokking Statistics covers it

How deep it goes
Explains the required column shape and resulting error avoidance, but does not examine reshaping internals.
Examples
Uses hours-without-a-nap observations reshaped into a single input column.
What it assumes
Assumes NumPy arrays and model inputs, while clarifying the differing shapes expected for x and y.
What you can do after
Apply it via NumPy to format single-variable input for LogisticRegression.
How it connects
Connects tensor reshaping with NumPy arrays, logistic regression, and scikit-learn.

Also explained in

Compare how 3 books explain tensor reshaping →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Statistics. The section links point to the parts of the book it draws on.