This is a self-correcting activity generated by nbgrader. Fill in any place that says YOUR CODE HERE or YOUR ANSWER HERE. Run subsequent cells to check your code.


NumPy

Environment setup

import platform

print(f"Python version: {platform.python_version()}")
assert platform.python_version_tuple() >= ("3", "6")

import numpy as np
import matplotlib.pyplot as plt

print(f"NumPy version: {np.__version__}")
# Setup plots
%matplotlib inline
plt.rcParams["figure.figsize"] = 10, 8
%config InlineBackend.figure_format = "retina"
# Import ML packages
import sklearn

print(f"scikit-learn version: {sklearn.__version__}")

from sklearn.datasets import load_sample_images

Part 1: Tensor Basics

Question

Create a 2D tensor (a matrix) with dimensions (3,4) containing integer values of your choice. Store this tensor in a variable named x.

# YOUR CODE HERE
print(x)

# Assert dimensions
assert x.ndim == 2
assert x.shape == (3, 4)

# Assert data type 
assert issubclass(x.dtype.type, np.integer)

Question

Update the shape of the previous tensor so that it has dimensions (6,2).

# YOUR CODE HERE
print(x)

# Assert tensor dimensions
assert x.ndim == 2
assert x.shape == (6, 2)

Question

Change the type of the previous tensor values to float32.

# YOUR CODE HERE
print(x)

# Assert data type
assert issubclass(x.dtype.type, np.floating)

Part 2: Image Management

# Load samples images
images = np.asarray(load_sample_images().images)
print(f"Number of images: {len(images)}. Images tensor: {images.shape}")

first_image = images[0]
# Display first image
plt.imshow(first_image)

# Print details about first image
print(f"First image: {first_image.shape}")

Question

Store in variables respectively named rgb_values_topleft and rgb_values_bottomright the RGB values of the top-left and bottom-right pixels of the first image.

# YOUR CODE HERE
print(f"Top-left pixel: {rgb_values_topleft}")
assert rgb_values_topleft.shape == (3,)

print(f"Bottom-right pixel: {rgb_values_bottomright}")
assert rgb_values_bottomright.shape == (3,)

Question

Reshape the previous images tensor into a 2D tensor.

# YOUR CODE HERE
# Assert new tensor dimensions
assert images.shape == (2, 819840)

# Assert RGB values of top-left in first image
assert np.array_equal(rgb_values_topleft, images[0,:3])

# Assert RGB values of bottom-right pixel in first image
assert np.array_equal(rgb_values_bottomright, images[0,819837:])