{"id":2480,"date":"2026-02-02T07:45:03","date_gmt":"2026-02-02T07:45:03","guid":{"rendered":"https:\/\/demo.materiamedica.net\/demo6\/?p=2480"},"modified":"2026-02-02T07:45:03","modified_gmt":"2026-02-02T07:45:03","slug":"chapter-11-numpy-array-reshaping","status":"publish","type":"post","link":"https:\/\/demo.materiamedica.net\/demo6\/chapter-11-numpy-array-reshaping\/","title":{"rendered":"Chapter 11: NumPy Array Reshaping"},"content":{"rendered":"<p dir=\"auto\"><strong>NumPy Array Reshaping<\/strong> \u2014 written exactly like a patient teacher sitting next to you, showing examples, drawing little mental pictures, explaining the rules, warning about common traps, and showing realistic patterns you will actually use in real projects.<\/p>\n<p dir=\"auto\">Let\u2019s go slowly and thoroughly.<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Python<\/div>\n<div>\n<pre tabindex=\"0\"><code>import numpy as np<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">1. What does reshaping actually mean?<\/h3>\n<p dir=\"auto\">Reshaping = <strong>changing how the data is organized<\/strong> in terms of dimensions, <strong>without changing the data itself<\/strong> or the total number of elements.<\/p>\n<p dir=\"auto\">You are just <strong>re-arranging the same numbers<\/strong> into a different grid \/ cube \/ structure.<\/p>\n<p dir=\"auto\"><strong>The golden rule you must memorize right now:<\/strong><\/p>\n<blockquote dir=\"auto\">\n<p dir=\"auto\">The <strong>total number of elements<\/strong> must stay exactly the same \u2192 product of old shape == product of new shape<\/p>\n<\/blockquote>\n<p dir=\"auto\">Examples:<\/p>\n<ul dir=\"auto\">\n<li>24 elements \u2192 can become (4,6), (3,8), (2,3,4), (6,4), (12,2), (24,), etc.<\/li>\n<li>24 elements \u2192 <strong>cannot<\/strong> become (5,5) or (3,7) \u2192 ValueError<\/li>\n<\/ul>\n<h3 dir=\"auto\">2. The most important method: .reshape()<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Python<\/div>\n<div>\n<pre tabindex=\"0\"><code>a = np.arange(24)\r\nprint(a)\r\n# [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]\r\nprint(a.shape)          # (24,)<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\">Now let\u2019s reshape:<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Python<\/div>\n<div>\n<pre tabindex=\"0\"><code># 2D matrix \u2013 most common case\r\nb = a.reshape(4, 6)\r\nprint(b.shape)          # (4, 6)\r\nprint(b)\r\n# [[ 0  1  2  3  4  5]\r\n#  [ 6  7  8  9 10 11]\r\n#  [12 13 14 15 16 17]\r\n#  [18 19 20 21 22 23]]\r\n\r\n# Different arrangement \u2013 same data\r\nc = a.reshape(3, 8)\r\nprint(c)\r\n# [[ 0  1  2  3  4  5  6  7]\r\n#  [ 8  9 10 11 12 13 14 15]\r\n#  [16 17 18 19 20 21 22 23]]<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Important observation:<\/strong><\/p>\n<p dir=\"auto\">NumPy fills the new array <strong>row by row<\/strong> (C-order, row-major order) by default.<\/p>\n<h3 dir=\"auto\">3. The magic number: -1 (very useful and very common)<\/h3>\n<p dir=\"auto\">You can use -1 in one dimension \u2192 NumPy automatically calculates it.<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Python<\/div>\n<div>\n<pre tabindex=\"0\"><code># I know I want 6 columns, don't care about rows\r\nd = a.reshape(-1, 6)\r\nprint(d.shape)          # (4, 6) \u2190 same as before\r\n\r\n# I want 4 rows, don't care about columns\r\ne = a.reshape(4, -1)\r\nprint(e.shape)          # (4, 6)\r\n\r\n# Make it 3D \u2013 very common in deep learning\r\nf = a.reshape(-1, 3, 4)     # -1 \u2192 automatically 2\r\nprint(f.shape)              # (2, 3, 4)<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>When students forget -1 and get error:<\/strong><\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Python<\/div>\n<div>\n<pre tabindex=\"0\"><code>a.reshape(5, 5)           # ValueError: cannot reshape array of size 24 into shape (5,5)\r\na.reshape(-1, 5)          # works \u2192 (4, 5) or (5, ?) depending on numbers<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">4. Very common real-world reshaping patterns (you will write these often)<\/h3>\n<p dir=\"auto\"><strong>Pattern 1: Flattening images for machine learning<\/strong><\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Python<\/div>\n<div>\n<pre tabindex=\"0\"><code># 100 RGB images of 28\u00d728 pixels\r\nimages = np.random.randint(0, 256, (100, 28, 28, 3), dtype=np.uint8)\r\nprint(images.shape)             # (100, 28, 28, 3)\r\n\r\nflat_images = images.reshape(100, -1)          # or images.reshape(100, 28*28*3)\r\nprint(flat_images.shape)                       # (100, 2352)<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Pattern 2: Turning flat vectors back into images<\/strong><\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Python<\/div>\n<div>\n<pre tabindex=\"0\"><code># Many ML models return flattened predictions\r\nflat = np.random.rand(64, 784)         # 64 samples \u00d7 784 pixels (28\u00d728)\r\nimages_reshaped = flat.reshape(64, 28, 28)      # or reshape(-1, 28, 28)\r\n# or with channels: reshape(-1, 28, 28, 1) for grayscale<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Pattern 3: Preparing time-series \/ sequence data<\/strong><\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Python<\/div>\n<div>\n<pre tabindex=\"0\"><code># 5000 time steps of 16 features\r\nts_data = np.random.randn(5000, 16)\r\n\r\n# Want windows of 30 timesteps \u2192 (samples, timesteps, features)\r\nwindowed = ts_data.reshape(-1, 30, 16)   # assuming divisible<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Pattern 4: Changing channel order (very common in deep learning)<\/strong><\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Python<\/div>\n<div>\n<pre tabindex=\"0\"><code>img_batch = np.random.rand(32, 224, 224, 3)      # (batch, H, W, C)  \u2190 TensorFlow\/Keras style\r\nimg_batch_pytorch = img_batch.transpose(0, 3, 1, 2)   # (batch, C, H, W)\r\n# or with reshape if you prefer:\r\n# img_batch_pytorch = img_batch.reshape(32, 3, 224, 224)<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">5. reshape() vs ravel() vs flatten() \u2014 important differences<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Python<\/div>\n<div>\n<pre tabindex=\"0\"><code>arr = np.arange(24).reshape(4, 6)\r\n\r\n# 1. ravel()  \u2192 usually returns a **view** (fast, memory efficient)\r\nr1 = arr.ravel()\r\nr1[0] = 999\r\nprint(arr[0,0])      # 999   \u2190 original changed \u2192 view!\r\n\r\n# 2. flatten() \u2192 always returns a **copy** (safer when you want independence)\r\nf1 = arr.flatten()\r\nf1[0] = 777\r\nprint(arr[0,0])      # still 999   \u2190 original unchanged\r\n\r\n# 3. reshape(-1) \u2192 same as ravel() in most cases (also usually view)<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Quick rule students should write down:<\/strong><\/p>\n<div>\n<div dir=\"auto\">\n<table dir=\"auto\">\n<thead>\n<tr>\n<th data-col-size=\"md\">Method<\/th>\n<th data-col-size=\"lg\">Usually returns<\/th>\n<th data-col-size=\"xl\">Use when&#8230;<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"md\">.ravel()<\/td>\n<td data-col-size=\"lg\"><strong>View<\/strong><\/td>\n<td data-col-size=\"xl\">You want fast flattening and don&#8217;t plan to modify<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">.flatten()<\/td>\n<td data-col-size=\"lg\"><strong>Copy<\/strong><\/td>\n<td data-col-size=\"xl\">You want a safe, independent 1D copy<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">.reshape(-1)<\/td>\n<td data-col-size=\"lg\"><strong>View<\/strong> (most cases)<\/td>\n<td data-col-size=\"xl\">You want to flatten or re-arrange safely<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">6. Common beginner mistakes with reshaping<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Python<\/div>\n<div>\n<pre tabindex=\"0\"><code># Mistake 1: Wrong number of elements\r\na = np.arange(10)\r\na.reshape(4, 4)                # ValueError\r\n\r\n# Mistake 2: Forgetting tuple\r\na.reshape(3, 4)                # correct\r\na.reshape(3 4)                 # SyntaxError\r\n\r\n# Mistake 3: Thinking reshape always copies\r\nb = a.reshape(2, 5)\r\nb[0,0] = 999\r\nprint(a)                       # a also changed!\r\n\r\n# Mistake 4: Using reshape on non-contiguous array (advanced trap)\r\nc = a[::2].reshape(3, -1)      # may fail or give unexpected result in some cases<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">Summary \u2013 Reshaping Cheat Sheet<\/h3>\n<div>\n<div dir=\"auto\">\n<table dir=\"auto\">\n<thead>\n<tr>\n<th data-col-size=\"lg\">What you want to do<\/th>\n<th data-col-size=\"md\">Best expression<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"lg\">Make 2D matrix with known columns<\/td>\n<td data-col-size=\"md\">arr.reshape(-1, num_cols)<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Make 2D matrix with known rows<\/td>\n<td data-col-size=\"md\">arr.reshape(num_rows, -1)<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Turn image batch into flat vectors<\/td>\n<td data-col-size=\"md\">images.reshape(num_images, -1)<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Turn flat vectors back to images<\/td>\n<td data-col-size=\"md\">flat.reshape(-1, height, width, channels)<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Flatten quickly (don\u2019t care about copy)<\/td>\n<td data-col-size=\"md\">arr.ravel() or arr.reshape(-1)<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Flatten safely (want copy)<\/td>\n<td data-col-size=\"md\">arr.flatten()<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Change order of axes (e.g. HWC \u2192 CHW)<\/td>\n<td data-col-size=\"md\">transpose() or reshape() with care<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Check if reshape is possible<\/td>\n<td data-col-size=\"md\">arr.size == new_rows * new_cols * \u2026<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\">Would you like to continue with any of these next?<\/p>\n<ul dir=\"auto\">\n<li>Reshape + copy vs view in depth<\/li>\n<li>Reshaping multi-dimensional arrays (3D, 4D)<\/li>\n<li>Common reshape patterns in computer vision \/ NLP<\/li>\n<li>Debugging \u201ccannot reshape\u201d errors<\/li>\n<li>Mini-exercise: reshape some image-like data together<\/li>\n<\/ul>\n<p dir=\"auto\">Just tell me what you want to focus on now! \ud83d\ude0a<\/p>\n","protected":false},"excerpt":{"rendered":"<p>NumPy Array Reshaping \u2014 written exactly like a patient teacher sitting next to you, showing examples, drawing little mental pictures, explaining the rules, warning about common traps, and showing realistic patterns you will actually&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[75],"tags":[],"class_list":["post-2480","post","type-post","status-publish","format-standard","hentry","category-numpy"],"_links":{"self":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2480","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/comments?post=2480"}],"version-history":[{"count":1,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2480\/revisions"}],"predecessor-version":[{"id":2481,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2480\/revisions\/2481"}],"wp:attachment":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/media?parent=2480"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/categories?post=2480"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/tags?post=2480"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}