What is a Library?

Essentially a list of pre-written code that you can use to streamline and clean up your program.

Libraries can help simplify complex programs

APIS are specifications for how the procedures in a library behave, and how they can be used

Documentations for an API/library is necessary in understanding the behaviors provided by the API/library and how to use them

Libraries that we will go over: Requests, Pillow, Pandas, Numpy, Scikit-Learn, TensorFlow, matplotlib.

Required Installations

Please run the following commands in your vscode terminal in order to continue the lesson

  • pip install numpy
  • pip install matplotlib
  • pip install scikit-learn
  • pip install pillow
  • pip install pandas
  • pip install tensorflow
  • pip install requests

Images using requests and pillow libraries

‘Requests’ is focused on handling HTTP requests and web data while ‘Pillow’ is designed for data manipulation and analysis It’s common to see them used together in data-related assignments where data is fetched by HTTP requests using Requests and then processed and analyzed with Pandas.

Here’s an example:

import requests
from PIL import Image
from io import BytesIO

# Step 1: Download an image using Requests
image_url = "https://example.com/path/to/your/image.jpg"  # Replace with the actual URL of the image you want to download
response = requests.get(image_url)

if response.status_code == 200:
    # Step 2: Process the downloaded image using Pillow
    image_data = BytesIO(response.content)  # Create an in-memory binary stream from the response content
    img = Image.open(image_data)  # Open the image using Pillow

    # Perform image processing tasks here, like resizing or applying filters
    img = img.resize((x, y))  # Resize the image and replace x,y with desired amounts

    # Step 3: Save the processed image using Pillow
    img.save("processed_image.jpg")  # Save the processed image to a file

    print("Image downloaded, processed, and saved.")
else:
    print(f"Failed to download image. Status code: {response.status_code}")

Failed to download image. Status code: 404

In this code, we use the Requests library to download an image from a URL and then if the download is successful the HTTP status code 200 will pop up, and from there we create an in-memory binary stream (BytesIO) from the response content. We then use the Pillow library to open the image, make any necessary changes, and save the processed image to a file.

Here’s a step by step tutorial on how we wrote this code: 1)We started by importing the necessary libraries, which were Requests, Pillow, and io.

2)Download the Image

3)Use the Requests library to send an HTTP GET request to the URL to download the image. Check the response status code to make sure the download goes through(status code 200).

4)If the download is successful, create an in-memory binary stream (BytesIO) from the response content. Process the Image:

5)Utilize the Pillow library to open the image from the binary stream. Change photo to desired preference(ie: size) Save the Processed Image:

6)Save the processed image to a file using Pillow. Choose a filename and file format for the saved image.

Hack 1

Write a Python code that accomplishes the following tasks:

Downloads an image from a specified URL using the Requests library. Processes the downloaded image (like resizing) using the Pillow library. Save the processed image to a file.

import requests
from PIL import Image
from io import BytesIO

# Step 1: Download an image using Requests
image_url = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.bbc.co.uk%2Fbbcthree%2Farticle%2Fd3b2d5ce-8d59-4621-8161-2d368d018e29&psig=AOvVaw3fpUhF1RVMMrgOVb6D5Od5&ust=1698427299472000&source=images&cd=vfe&opi=89978449&ved=0CBAQjRxqFwoTCMD02PCclIIDFQAAAAAdAAAAABAE"  # Replace with the actual URL of the image you want to download
response = requests.get(image_url)

if response.status_code == 200:
    # Step 2: Process the downloaded image using Pillow
    image_data = BytesIO(response.content)  # Create an in-memory binary stream from the response content
    img = Image.open(image_data)  # Open the image using Pillow

    # Perform image processing tasks here, like resizing or applying filters
    img = img.resize((100, 100))  # Resize the image. Replace 100, 100 with desired width and height.

    # Step 3: Save the processed image using Pillow
    img.save("p0696xkv.jpg")  # Save the processed image to a file

    print("Image downloaded, processed, and saved.")
else:
    print(f"Failed to download image. Status code: {response.status_code}")

---------------------------------------------------------------------------

UnidentifiedImageError                    Traceback (most recent call last)

/workspaces/studentrep/studentrep/_notebooks/2023-10-26-Python-Libraries.ipynb Cell 9 line 1
      <a href='vscode-notebook-cell://codespaces%2Bturbo-space-tribble-6q44xwq4qjw3qrr/workspaces/studentrep/studentrep/_notebooks/2023-10-26-Python-Libraries.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=8'>9</a> if response.status_code == 200:
     <a href='vscode-notebook-cell://codespaces%2Bturbo-space-tribble-6q44xwq4qjw3qrr/workspaces/studentrep/studentrep/_notebooks/2023-10-26-Python-Libraries.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=9'>10</a>     # Step 2: Process the downloaded image using Pillow
     <a href='vscode-notebook-cell://codespaces%2Bturbo-space-tribble-6q44xwq4qjw3qrr/workspaces/studentrep/studentrep/_notebooks/2023-10-26-Python-Libraries.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=10'>11</a>     image_data = BytesIO(response.content)  # Create an in-memory binary stream from the response content
---> <a href='vscode-notebook-cell://codespaces%2Bturbo-space-tribble-6q44xwq4qjw3qrr/workspaces/studentrep/studentrep/_notebooks/2023-10-26-Python-Libraries.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=11'>12</a>     img = Image.open(image_data)  # Open the image using Pillow
     <a href='vscode-notebook-cell://codespaces%2Bturbo-space-tribble-6q44xwq4qjw3qrr/workspaces/studentrep/studentrep/_notebooks/2023-10-26-Python-Libraries.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=13'>14</a>     # Perform image processing tasks here, like resizing or applying filters
     <a href='vscode-notebook-cell://codespaces%2Bturbo-space-tribble-6q44xwq4qjw3qrr/workspaces/studentrep/studentrep/_notebooks/2023-10-26-Python-Libraries.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=14'>15</a>     img = img.resize((100, 100))  # Resize the image. Replace 100, 100 with desired width and height.


File ~/.local/lib/python3.10/site-packages/PIL/Image.py:3280, in open(fp, mode, formats)
   3278     warnings.warn(message)
   3279 msg = "cannot identify image file %r" % (filename if filename else fp)
-> 3280 raise UnidentifiedImageError(msg)


UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7fe7eefb7970>

Math Operations With Python Libraries

Numpy(Numerical Python) is used for numerical and scientific computing. It provides tools for handling large sets of numbers, such as data tables and arrays. Numpy makes it easier and more efficient to do mathematical tasks.

The Matplotlib library lets you create a visual representation of your data (graphs, charts, and etc.)

Example Sine Graph

Uses numpy and matplotlib libaries

import numpy as np
import matplotlib.pyplot as plt

# Generate sample data with NumPy
x = np.linspace(0, 2 * np.pi, 100) 
# Create an array of values from 0 to 2*pi
# 100 is included to have 100 points distributed between 0 and 2π to make graph smoother
y = np.sin(x)
# Compute the sine of each value

# Create a simple line plot using Matplotlib
plt.plot(x, y, label='Sine Function', color='blue', linestyle='-')  # Create the plot
plt.title('Sine Function')  # Set the title
plt.xlabel('x')  # Label for the x-axis
plt.ylabel('sin(x)')  # Label for the y-axis
plt.grid(True)  # Display a grid
plt.legend()  # Show the legend
plt.show()  # Display the plot

png

Hack 2

Using the data from the numpy library, create a visual graph using different matplotlib functions.

import numpy as np
import matplotlib.pyplot as plt

# Generate data for two lines
x = np.linspace(0, 10, 50)  # Create an array of values from 0 to 10
y1 = 2 * x + 1  # Set of data points

# Create a figure and axis object
fig, ax = plt.subplots()

# Plot the data
ax.plot(x, y1, label='2x + 1', color='purple')  # Plot y1 data with blue line

# Add labels and title
ax.set_xlabel('X-axis label')  # Set x-axis label
ax.set_ylabel('Y-axis label')  # Set y-axis label
ax.set_title('Sample Line Plot')  # Set title

# Add gridlines and legend
ax.grid(True)  # Show gridlines
ax.legend()  # Show legend

# Show the plot
plt.show()

png

Tensor Flow is used in deep learning and neural networks, while scikit-learn is used for typical machine learning tasks. When used together, they can tackle machine learning projects. In the code below, Tensor Flow is used for model creation and training. Scikit-learn is used for data-processing and model evaluation.

Pip install tensorflow scikit-learn

import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import StandardScaler
from tensorflow import keras
from tensorflow.keras import layers
# Generate synthetic data
np.random.seed(0)
X = np.random.rand(100, 1)  # Feature
y = 2 * X + 1 + 0.1 * np.random.randn(100, 1)  # Target variable with noise
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Standardize the features
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# Create a simple linear regression model using TensorFlow and Keras
model = keras.Sequential([
    layers.Input(shape=(1,)),
    layers.Dense(1)
])
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
# Train the model
model.fit(X_train, y_train, epochs=100, batch_size=32, verbose=2)
# Make predictions on the test set
y_pred = model.predict(X_test)
# Calculate the Mean Squared Error on the test set
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse:.4f}")
Epoch 1/100
3/3 - 0s - loss: 3.8210 - 252ms/epoch - 84ms/step
Epoch 2/100
3/3 - 0s - loss: 3.8088 - 5ms/epoch - 2ms/step
Epoch 3/100
3/3 - 0s - loss: 3.7959 - 4ms/epoch - 1ms/step
Epoch 4/100
3/3 - 0s - loss: 3.7835 - 4ms/epoch - 1ms/step
Epoch 5/100
3/3 - 0s - loss: 3.7717 - 4ms/epoch - 1ms/step
Epoch 6/100
3/3 - 0s - loss: 3.7590 - 4ms/epoch - 1ms/step
Epoch 7/100
3/3 - 0s - loss: 3.7464 - 4ms/epoch - 1ms/step
Epoch 8/100
3/3 - 0s - loss: 3.7346 - 4ms/epoch - 1ms/step
Epoch 9/100
3/3 - 0s - loss: 3.7222 - 4ms/epoch - 1ms/step
Epoch 10/100
3/3 - 0s - loss: 3.7104 - 4ms/epoch - 1ms/step
Epoch 11/100
3/3 - 0s - loss: 3.6979 - 4ms/epoch - 1ms/step
Epoch 12/100
3/3 - 0s - loss: 3.6859 - 6ms/epoch - 2ms/step
Epoch 13/100
3/3 - 0s - loss: 3.6739 - 4ms/epoch - 1ms/step
Epoch 14/100
3/3 - 0s - loss: 3.6619 - 4ms/epoch - 1ms/step
Epoch 15/100
3/3 - 0s - loss: 3.6499 - 4ms/epoch - 1ms/step
Epoch 16/100
3/3 - 0s - loss: 3.6381 - 4ms/epoch - 1ms/step
Epoch 17/100
3/3 - 0s - loss: 3.6260 - 4ms/epoch - 1ms/step
Epoch 18/100
3/3 - 0s - loss: 3.6138 - 4ms/epoch - 1ms/step
Epoch 19/100
3/3 - 0s - loss: 3.6021 - 5ms/epoch - 2ms/step
Epoch 20/100
3/3 - 0s - loss: 3.5901 - 4ms/epoch - 1ms/step
Epoch 21/100
3/3 - 0s - loss: 3.5784 - 5ms/epoch - 2ms/step
Epoch 22/100
3/3 - 0s - loss: 3.5662 - 5ms/epoch - 2ms/step
Epoch 23/100
3/3 - 0s - loss: 3.5549 - 4ms/epoch - 1ms/step
Epoch 24/100
3/3 - 0s - loss: 3.5427 - 4ms/epoch - 1ms/step
Epoch 25/100
3/3 - 0s - loss: 3.5310 - 4ms/epoch - 1ms/step
Epoch 26/100
3/3 - 0s - loss: 3.5191 - 4ms/epoch - 1ms/step
Epoch 27/100
3/3 - 0s - loss: 3.5078 - 4ms/epoch - 1ms/step
Epoch 28/100
3/3 - 0s - loss: 3.4962 - 4ms/epoch - 1ms/step
Epoch 29/100
3/3 - 0s - loss: 3.4845 - 4ms/epoch - 1ms/step
Epoch 30/100
3/3 - 0s - loss: 3.4731 - 5ms/epoch - 2ms/step
Epoch 31/100
3/3 - 0s - loss: 3.4613 - 5ms/epoch - 2ms/step
Epoch 32/100
3/3 - 0s - loss: 3.4499 - 4ms/epoch - 1ms/step
Epoch 33/100
3/3 - 0s - loss: 3.4382 - 4ms/epoch - 1ms/step
Epoch 34/100
3/3 - 0s - loss: 3.4268 - 4ms/epoch - 1ms/step
Epoch 35/100
3/3 - 0s - loss: 3.4154 - 4ms/epoch - 1ms/step
Epoch 36/100
3/3 - 0s - loss: 3.4044 - 6ms/epoch - 2ms/step
Epoch 37/100
3/3 - 0s - loss: 3.3927 - 5ms/epoch - 2ms/step
Epoch 38/100
3/3 - 0s - loss: 3.3816 - 4ms/epoch - 1ms/step
Epoch 39/100
3/3 - 0s - loss: 3.3702 - 4ms/epoch - 1ms/step
Epoch 40/100
3/3 - 0s - loss: 3.3590 - 4ms/epoch - 1ms/step
Epoch 41/100
3/3 - 0s - loss: 3.3477 - 4ms/epoch - 1ms/step
Epoch 42/100
3/3 - 0s - loss: 3.3371 - 4ms/epoch - 1ms/step
Epoch 43/100
3/3 - 0s - loss: 3.3259 - 4ms/epoch - 1ms/step
Epoch 44/100
3/3 - 0s - loss: 3.3145 - 4ms/epoch - 1ms/step
Epoch 45/100
3/3 - 0s - loss: 3.3036 - 8ms/epoch - 3ms/step
Epoch 46/100
3/3 - 0s - loss: 3.2924 - 6ms/epoch - 2ms/step
Epoch 47/100
3/3 - 0s - loss: 3.2816 - 4ms/epoch - 1ms/step
Epoch 48/100
3/3 - 0s - loss: 3.2705 - 4ms/epoch - 1ms/step
Epoch 49/100
3/3 - 0s - loss: 3.2595 - 6ms/epoch - 2ms/step
Epoch 50/100
3/3 - 0s - loss: 3.2486 - 4ms/epoch - 1ms/step
Epoch 51/100
3/3 - 0s - loss: 3.2380 - 5ms/epoch - 2ms/step
Epoch 52/100
3/3 - 0s - loss: 3.2267 - 4ms/epoch - 1ms/step
Epoch 53/100
3/3 - 0s - loss: 3.2162 - 5ms/epoch - 2ms/step
Epoch 54/100
3/3 - 0s - loss: 3.2052 - 4ms/epoch - 1ms/step
Epoch 55/100
3/3 - 0s - loss: 3.1944 - 4ms/epoch - 1ms/step
Epoch 56/100
3/3 - 0s - loss: 3.1838 - 4ms/epoch - 1ms/step
Epoch 57/100
3/3 - 0s - loss: 3.1729 - 4ms/epoch - 1ms/step
Epoch 58/100
3/3 - 0s - loss: 3.1623 - 4ms/epoch - 1ms/step
Epoch 59/100
3/3 - 0s - loss: 3.1519 - 4ms/epoch - 1ms/step
Epoch 60/100
3/3 - 0s - loss: 3.1414 - 4ms/epoch - 1ms/step
Epoch 61/100
3/3 - 0s - loss: 3.1308 - 4ms/epoch - 1ms/step
Epoch 62/100
3/3 - 0s - loss: 3.1200 - 5ms/epoch - 2ms/step
Epoch 63/100
3/3 - 0s - loss: 3.1096 - 4ms/epoch - 1ms/step
Epoch 64/100
3/3 - 0s - loss: 3.0994 - 4ms/epoch - 1ms/step
Epoch 65/100
3/3 - 0s - loss: 3.0884 - 4ms/epoch - 1ms/step
Epoch 66/100
3/3 - 0s - loss: 3.0785 - 4ms/epoch - 1ms/step
Epoch 67/100
3/3 - 0s - loss: 3.0677 - 4ms/epoch - 1ms/step
Epoch 68/100
3/3 - 0s - loss: 3.0575 - 5ms/epoch - 2ms/step
Epoch 69/100
3/3 - 0s - loss: 3.0467 - 4ms/epoch - 1ms/step
Epoch 70/100
3/3 - 0s - loss: 3.0366 - 4ms/epoch - 1ms/step
Epoch 71/100
3/3 - 0s - loss: 3.0263 - 4ms/epoch - 1ms/step
Epoch 72/100
3/3 - 0s - loss: 3.0158 - 4ms/epoch - 1ms/step
Epoch 73/100
3/3 - 0s - loss: 3.0057 - 4ms/epoch - 1ms/step
Epoch 74/100
3/3 - 0s - loss: 2.9953 - 4ms/epoch - 1ms/step
Epoch 75/100
3/3 - 0s - loss: 2.9851 - 7ms/epoch - 2ms/step
Epoch 76/100
3/3 - 0s - loss: 2.9748 - 6ms/epoch - 2ms/step
Epoch 77/100
3/3 - 0s - loss: 2.9645 - 4ms/epoch - 1ms/step
Epoch 78/100
3/3 - 0s - loss: 2.9549 - 4ms/epoch - 1ms/step
Epoch 79/100
3/3 - 0s - loss: 2.9444 - 4ms/epoch - 1ms/step
Epoch 80/100
3/3 - 0s - loss: 2.9346 - 4ms/epoch - 1ms/step
Epoch 81/100
3/3 - 0s - loss: 2.9246 - 4ms/epoch - 1ms/step
Epoch 82/100
3/3 - 0s - loss: 2.9147 - 4ms/epoch - 1ms/step
Epoch 83/100
3/3 - 0s - loss: 2.9046 - 5ms/epoch - 2ms/step
Epoch 84/100
3/3 - 0s - loss: 2.8948 - 5ms/epoch - 2ms/step
Epoch 85/100
3/3 - 0s - loss: 2.8851 - 7ms/epoch - 2ms/step
Epoch 86/100
3/3 - 0s - loss: 2.8752 - 6ms/epoch - 2ms/step
Epoch 87/100
3/3 - 0s - loss: 2.8655 - 4ms/epoch - 1ms/step
Epoch 88/100
3/3 - 0s - loss: 2.8560 - 5ms/epoch - 2ms/step
Epoch 89/100
3/3 - 0s - loss: 2.8462 - 4ms/epoch - 1ms/step
Epoch 90/100
3/3 - 0s - loss: 2.8364 - 4ms/epoch - 1ms/step
Epoch 91/100
3/3 - 0s - loss: 2.8269 - 4ms/epoch - 1ms/step
Epoch 92/100
3/3 - 0s - loss: 2.8172 - 5ms/epoch - 2ms/step
Epoch 93/100
3/3 - 0s - loss: 2.8077 - 4ms/epoch - 1ms/step
Epoch 94/100
3/3 - 0s - loss: 2.7982 - 5ms/epoch - 2ms/step
Epoch 95/100
3/3 - 0s - loss: 2.7885 - 5ms/epoch - 2ms/step
Epoch 96/100
3/3 - 0s - loss: 2.7791 - 4ms/epoch - 1ms/step
Epoch 97/100
3/3 - 0s - loss: 2.7695 - 5ms/epoch - 2ms/step
Epoch 98/100
3/3 - 0s - loss: 2.7602 - 4ms/epoch - 1ms/step
Epoch 99/100
3/3 - 0s - loss: 2.7507 - 4ms/epoch - 1ms/step
Epoch 100/100
3/3 - 0s - loss: 2.7414 - 4ms/epoch - 1ms/step
1/1 [==============================] - 0s 49ms/step
Mean Squared Error: 2.6322

A decrease in loss and time metrics (ms/epoch and ms/step) shows the efficiency increases as the training epochs increases

Hack

fill in the missing code to match the custom data set

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

# Standardize the features
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# Create a regression model using TensorFlow and Keras
model = keras.Sequential([
    layers.Dense(64, activation='relu', input_shape=[X_train.shape[1]]),  # Input shape adjusted to the number of features
    layers.Dense(64, activation='relu'),
    layers.Dense(1)  # Output layer for regression
])

# Compile the model for regression
model.compile(
    optimizer='adam',
    loss='mean_squared_error'  # Using MSE as the loss function
)

# Train the model
history = model.fit(
    X_train, y_train,
    epochs=10,
    validation_split=0.2
)

# Make predictions on the test set
y_pred = model.predict(X_test)

# Calculate the Mean Squared Error on the test set
mse = mean_squared_error(y_test, y_pred)
print(f'Mean Squared Error on the test set: {mse}')

Epoch 1/10
2/2 [==============================] - 1s 110ms/step - loss: 4.2684 - val_loss: 4.0760
Epoch 2/10
2/2 [==============================] - 0s 17ms/step - loss: 4.0404 - val_loss: 3.8778
Epoch 3/10
2/2 [==============================] - 0s 16ms/step - loss: 3.8253 - val_loss: 3.6974
Epoch 4/10
2/2 [==============================] - 0s 16ms/step - loss: 3.6399 - val_loss: 3.5315
Epoch 5/10
2/2 [==============================] - 0s 16ms/step - loss: 3.4615 - val_loss: 3.3764
Epoch 6/10
2/2 [==============================] - 0s 17ms/step - loss: 3.3008 - val_loss: 3.2325
Epoch 7/10
2/2 [==============================] - 0s 16ms/step - loss: 3.1515 - val_loss: 3.0980
Epoch 8/10
2/2 [==============================] - 0s 17ms/step - loss: 3.0054 - val_loss: 2.9698
Epoch 9/10
2/2 [==============================] - 0s 16ms/step - loss: 2.8696 - val_loss: 2.8459
Epoch 10/10
2/2 [==============================] - 0s 17ms/step - loss: 2.7426 - val_loss: 2.7241
1/1 [==============================] - 0s 34ms/step
Mean Squared Error on the test set: 1.9092429733076144

HOMEWORK 1

Create a GPA calculator using Pandas and Matplot libraries and make: 1) A dataframe 2) A specified dictionary 3) and a print function that outputs the final GPA

Extra points can be earned with creativity.

import pandas as pd
import matplotlib.pyplot as plt

# Step 1: Create a dataframe
data = {
    'Course': ['AP Calculus BC', 'Regular English', 'Regular History', 'AP Bio', 'Honors Engineering'],
    'Credits': [5, 3, 3, 3, 2],
    'Grade': ['A', 'B', 'A', 'A', 'A']
}
df = pd.DataFrame(data)

# Step 2: Create a specified dictionary for grade conversion
grade_dict = {'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F': 0.0}

# Step 3: Create a function to calculate GPA
def calculate_gpa(df, grade_dict):
    df['Grade Points'] = df['Grade'].map(grade_dict)
    df['Weighted Points'] = df['Grade Points'] * df['Credits']
    total_points = df['Weighted Points'].sum()
    total_credits = df['Credits'].sum()
    gpa = total_points / total_credits
    return round(gpa, 2)

# Calculate GPA
final_gpa = calculate_gpa(df, grade_dict)
print(f'Final GPA: {final_gpa}')

# Extra: Visualize the data
fig, ax = plt.subplots(figsize=(10, 6))
bars = plt.bar(df['Course'], df['Grade Points'], color=['blue', 'orange', 'green', 'red', 'purple'])
plt.xlabel('Course')
plt.ylabel('Grade Points')
plt.title('Grade Points per Course')
plt.ylim(0, 4.0)

# Add the GPA on the plot
plt.axhline(y=final_gpa, color='r', linestyle='-', label=f'GPA: {final_gpa}')
plt.legend()

# Show plot
plt.show()
Final GPA: 3.81

png

HOMEWORK 2

Import and use the “random” library to generate 50 different points from the range 0-100, then display the randomized data using a scatter plot.

Extra points can be earned with creativity.

import random
import matplotlib.pyplot as plt

# Generate 50 random points
x = [random.randint(0, 100) for _ in range(50)]
y = [random.randint(0, 100) for _ in range(50)]

# Create a scatter plot
plt.figure(figsize=(10, 6))
scatter = plt.scatter(x, y, c=y, cmap='viridis', s=100, alpha=0.5)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Random Scatter Plot')
plt.colorbar(scatter, label='Value')
plt.grid(True)

# Show plot
plt.show()

png