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}")
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.
#Code here
import requests
from PIL import Image
from io import BytesIO
# Step 1: Download an image using Requests
image_url = "https://d3544la1u8djza.cloudfront.net/APHI/Blog/2021/07-06/small+white+fluffy+dog+smiling+at+the+camera+in+close-up-min.jpg"
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((900, 600)) # 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}")
Image downloaded, processed, and saved.
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
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 poits
# Create and display a plot using Matplotlib
# your code here
# Create a simple line plot using Matplotlib
plt.plot(x, y1, label='Y Function', color='purple', linestyle='-') # Create the plot
plt.title('Y Function') # Set the title
plt.xlabel('x') # Label for the x-axis
plt.ylabel('y1') # Label for the y-axis
plt.grid(True) # Display a grid
plt.legend() # Show the legend
plt.show() # Display the plot
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}")
2023-10-26 10:25:56.300044: I tensorflow/core/util/port.cc:111] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
2023-10-26 10:25:56.302396: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.
2023-10-26 10:25:56.333635: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
2023-10-26 10:25:56.333662: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
2023-10-26 10:25:56.333687: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
2023-10-26 10:25:56.342531: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.
2023-10-26 10:25:56.343800: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
2023-10-26 10:25:57.287122: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT
/usr/lib/python3/dist-packages/scipy/__init__.py:146: UserWarning: A NumPy version >=1.17.3 and <1.25.0 is required for this version of SciPy (detected version 1.26.1
warnings.warn(f"A NumPy version >={np_minversion} and <{np_maxversion}"
Epoch 1/100
3/3 - 0s - loss: 4.2119 - 256ms/epoch - 85ms/step
Epoch 2/100
3/3 - 0s - loss: 4.1965 - 4ms/epoch - 1ms/step
Epoch 3/100
3/3 - 0s - loss: 4.1810 - 6ms/epoch - 2ms/step
Epoch 4/100
3/3 - 0s - loss: 4.1658 - 5ms/epoch - 2ms/step
Epoch 5/100
3/3 - 0s - loss: 4.1508 - 8ms/epoch - 3ms/step
Epoch 6/100
3/3 - 0s - loss: 4.1346 - 5ms/epoch - 2ms/step
Epoch 7/100
3/3 - 0s - loss: 4.1197 - 9ms/epoch - 3ms/step
Epoch 8/100
3/3 - 0s - loss: 4.1045 - 6ms/epoch - 2ms/step
Epoch 9/100
3/3 - 0s - loss: 4.0904 - 7ms/epoch - 2ms/step
Epoch 10/100
3/3 - 0s - loss: 4.0746 - 6ms/epoch - 2ms/step
Epoch 11/100
3/3 - 0s - loss: 4.0598 - 8ms/epoch - 3ms/step
Epoch 12/100
3/3 - 0s - loss: 4.0451 - 5ms/epoch - 2ms/step
Epoch 13/100
3/3 - 0s - loss: 4.0304 - 7ms/epoch - 2ms/step
Epoch 14/100
3/3 - 0s - loss: 4.0163 - 6ms/epoch - 2ms/step
Epoch 15/100
3/3 - 0s - loss: 4.0010 - 7ms/epoch - 2ms/step
Epoch 16/100
3/3 - 0s - loss: 3.9875 - 8ms/epoch - 3ms/step
Epoch 17/100
3/3 - 0s - loss: 3.9719 - 6ms/epoch - 2ms/step
Epoch 18/100
3/3 - 0s - loss: 3.9588 - 5ms/epoch - 2ms/step
Epoch 19/100
3/3 - 0s - loss: 3.9441 - 6ms/epoch - 2ms/step
Epoch 20/100
3/3 - 0s - loss: 3.9303 - 8ms/epoch - 3ms/step
Epoch 21/100
3/3 - 0s - loss: 3.9157 - 5ms/epoch - 2ms/step
Epoch 22/100
3/3 - 0s - loss: 3.9017 - 5ms/epoch - 2ms/step
Epoch 23/100
3/3 - 0s - loss: 3.8875 - 6ms/epoch - 2ms/step
Epoch 24/100
3/3 - 0s - loss: 3.8733 - 5ms/epoch - 2ms/step
Epoch 25/100
3/3 - 0s - loss: 3.8594 - 7ms/epoch - 2ms/step
Epoch 26/100
3/3 - 0s - loss: 3.8454 - 4ms/epoch - 1ms/step
Epoch 27/100
3/3 - 0s - loss: 3.8305 - 8ms/epoch - 3ms/step
Epoch 28/100
3/3 - 0s - loss: 3.8169 - 5ms/epoch - 2ms/step
Epoch 29/100
3/3 - 0s - loss: 3.8032 - 6ms/epoch - 2ms/step
Epoch 30/100
3/3 - 0s - loss: 3.7891 - 5ms/epoch - 2ms/step
Epoch 31/100
3/3 - 0s - loss: 3.7747 - 5ms/epoch - 2ms/step
Epoch 32/100
3/3 - 0s - loss: 3.7612 - 6ms/epoch - 2ms/step
Epoch 33/100
3/3 - 0s - loss: 3.7469 - 5ms/epoch - 2ms/step
Epoch 34/100
3/3 - 0s - loss: 3.7338 - 7ms/epoch - 2ms/step
Epoch 35/100
3/3 - 0s - loss: 3.7193 - 5ms/epoch - 2ms/step
Epoch 36/100
3/3 - 0s - loss: 3.7058 - 6ms/epoch - 2ms/step
Epoch 37/100
3/3 - 0s - loss: 3.6917 - 6ms/epoch - 2ms/step
Epoch 38/100
3/3 - 0s - loss: 3.6780 - 5ms/epoch - 2ms/step
Epoch 39/100
3/3 - 0s - loss: 3.6641 - 6ms/epoch - 2ms/step
Epoch 40/100
3/3 - 0s - loss: 3.6514 - 4ms/epoch - 1ms/step
Epoch 41/100
3/3 - 0s - loss: 3.6378 - 7ms/epoch - 2ms/step
Epoch 42/100
3/3 - 0s - loss: 3.6241 - 5ms/epoch - 2ms/step
Epoch 43/100
3/3 - 0s - loss: 3.6109 - 7ms/epoch - 2ms/step
Epoch 44/100
3/3 - 0s - loss: 3.5976 - 5ms/epoch - 2ms/step
Epoch 45/100
3/3 - 0s - loss: 3.5844 - 5ms/epoch - 2ms/step
Epoch 46/100
3/3 - 0s - loss: 3.5713 - 7ms/epoch - 2ms/step
Epoch 47/100
3/3 - 0s - loss: 3.5577 - 5ms/epoch - 2ms/step
Epoch 48/100
3/3 - 0s - loss: 3.5451 - 7ms/epoch - 2ms/step
Epoch 49/100
3/3 - 0s - loss: 3.5314 - 5ms/epoch - 2ms/step
Epoch 50/100
3/3 - 0s - loss: 3.5188 - 4ms/epoch - 1ms/step
Epoch 51/100
3/3 - 0s - loss: 3.5058 - 6ms/epoch - 2ms/step
Epoch 52/100
3/3 - 0s - loss: 3.4925 - 4ms/epoch - 1ms/step
Epoch 53/100
3/3 - 0s - loss: 3.4795 - 8ms/epoch - 3ms/step
Epoch 54/100
3/3 - 0s - loss: 3.4669 - 12ms/epoch - 4ms/step
Epoch 55/100
3/3 - 0s - loss: 3.4536 - 8ms/epoch - 3ms/step
Epoch 56/100
3/3 - 0s - loss: 3.4407 - 7ms/epoch - 2ms/step
Epoch 57/100
3/3 - 0s - loss: 3.4284 - 5ms/epoch - 2ms/step
Epoch 58/100
3/3 - 0s - loss: 3.4150 - 8ms/epoch - 3ms/step
Epoch 59/100
3/3 - 0s - loss: 3.4020 - 5ms/epoch - 2ms/step
Epoch 60/100
3/3 - 0s - loss: 3.3896 - 8ms/epoch - 3ms/step
Epoch 61/100
3/3 - 0s - loss: 3.3766 - 5ms/epoch - 2ms/step
Epoch 62/100
3/3 - 0s - loss: 3.3647 - 8ms/epoch - 3ms/step
Epoch 63/100
3/3 - 0s - loss: 3.3517 - 5ms/epoch - 2ms/step
Epoch 64/100
3/3 - 0s - loss: 3.3394 - 5ms/epoch - 2ms/step
Epoch 65/100
3/3 - 0s - loss: 3.3269 - 7ms/epoch - 2ms/step
Epoch 66/100
3/3 - 0s - loss: 3.3146 - 4ms/epoch - 1ms/step
Epoch 67/100
3/3 - 0s - loss: 3.3023 - 7ms/epoch - 2ms/step
Epoch 68/100
3/3 - 0s - loss: 3.2900 - 4ms/epoch - 1ms/step
Epoch 69/100
3/3 - 0s - loss: 3.2778 - 8ms/epoch - 3ms/step
Epoch 70/100
3/3 - 0s - loss: 3.2656 - 5ms/epoch - 2ms/step
Epoch 71/100
3/3 - 0s - loss: 3.2529 - 6ms/epoch - 2ms/step
Epoch 72/100
3/3 - 0s - loss: 3.2406 - 6ms/epoch - 2ms/step
Epoch 73/100
3/3 - 0s - loss: 3.2285 - 5ms/epoch - 2ms/step
Epoch 74/100
3/3 - 0s - loss: 3.2159 - 7ms/epoch - 2ms/step
Epoch 75/100
3/3 - 0s - loss: 3.2042 - 5ms/epoch - 2ms/step
Epoch 76/100
3/3 - 0s - loss: 3.1918 - 7ms/epoch - 2ms/step
Epoch 77/100
3/3 - 0s - loss: 3.1800 - 5ms/epoch - 2ms/step
Epoch 78/100
3/3 - 0s - loss: 3.1681 - 9ms/epoch - 3ms/step
Epoch 79/100
3/3 - 0s - loss: 3.1558 - 6ms/epoch - 2ms/step
Epoch 80/100
3/3 - 0s - loss: 3.1444 - 7ms/epoch - 2ms/step
Epoch 81/100
3/3 - 0s - loss: 3.1328 - 6ms/epoch - 2ms/step
Epoch 82/100
3/3 - 0s - loss: 3.1206 - 7ms/epoch - 2ms/step
Epoch 83/100
3/3 - 0s - loss: 3.1090 - 6ms/epoch - 2ms/step
Epoch 84/100
3/3 - 0s - loss: 3.0976 - 7ms/epoch - 2ms/step
Epoch 85/100
3/3 - 0s - loss: 3.0856 - 6ms/epoch - 2ms/step
Epoch 86/100
3/3 - 0s - loss: 3.0744 - 6ms/epoch - 2ms/step
Epoch 87/100
3/3 - 0s - loss: 3.0628 - 5ms/epoch - 2ms/step
Epoch 88/100
3/3 - 0s - loss: 3.0511 - 6ms/epoch - 2ms/step
Epoch 89/100
3/3 - 0s - loss: 3.0393 - 7ms/epoch - 2ms/step
Epoch 90/100
3/3 - 0s - loss: 3.0282 - 5ms/epoch - 2ms/step
Epoch 91/100
3/3 - 0s - loss: 3.0162 - 8ms/epoch - 3ms/step
Epoch 92/100
3/3 - 0s - loss: 3.0055 - 6ms/epoch - 2ms/step
Epoch 93/100
3/3 - 0s - loss: 2.9942 - 9ms/epoch - 3ms/step
Epoch 94/100
3/3 - 0s - loss: 2.9831 - 7ms/epoch - 2ms/step
Epoch 95/100
3/3 - 0s - loss: 2.9714 - 7ms/epoch - 2ms/step
Epoch 96/100
3/3 - 0s - loss: 2.9604 - 7ms/epoch - 2ms/step
Epoch 97/100
3/3 - 0s - loss: 2.9493 - 7ms/epoch - 2ms/step
Epoch 98/100
3/3 - 0s - loss: 2.9388 - 6ms/epoch - 2ms/step
Epoch 99/100
3/3 - 0s - loss: 2.9275 - 5ms/epoch - 2ms/step
Epoch 100/100
3/3 - 0s - loss: 2.9168 - 6ms/epoch - 2ms/step
1/1 [==============================] - 0s 50ms/step
Mean Squared Error: 2.4989
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
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 a custom dataset (replace this with your data loading code)
# Synthetic data: House prices based on number of bedrooms and square footage
np.random.seed(0)
num_samples = 100
bedrooms = np.random.randint(1, 5, num_samples)
square_footage = np.random.randint(1000, 2500, num_samples)
house_prices = 100000 + 50000 * bedrooms + 100 * square_footage + 10000 * np.random.randn(num_samples)
# Combine features (bedrooms and square footage) into one array
X = np.column_stack((bedrooms, square_footage))
y = house_prices.reshape(-1, 1)
# 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 regression model using TensorFlow and Keras
model = keras.Sequential([
layers.Input(shape=(1,)),
layers.Dense(1)
])
# Input shape adjusted to the number of features
# Output layer for regression
# 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
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/tmp/ipykernel_4331/2171878574.py in <module>
35
36 # Train the model
---> 37 model.fit(X_train, y_train, epochs=100, batch_size=32, verbose=2)
38
39 # Make predictions on the test set
~/.local/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py in error_handler(*args, **kwargs)
68 # To get the full stack trace, call:
69 # `tf.debugging.disable_traceback_filtering()`
---> 70 raise e.with_traceback(filtered_tb) from None
71 finally:
72 del filtered_tb
~/.local/lib/python3.10/site-packages/keras/src/engine/training.py in tf__train_function(iterator)
13 try:
14 do_return = True
---> 15 retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
16 except:
17 do_return = False
ValueError: in user code:
File "/home/isabelle/.local/lib/python3.10/site-packages/keras/src/engine/training.py", line 1377, in train_function *
return step_function(self, iterator)
File "/home/isabelle/.local/lib/python3.10/site-packages/keras/src/engine/training.py", line 1360, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/home/isabelle/.local/lib/python3.10/site-packages/keras/src/engine/training.py", line 1349, in run_step **
outputs = model.train_step(data)
File "/home/isabelle/.local/lib/python3.10/site-packages/keras/src/engine/training.py", line 1126, in train_step
y_pred = self(x, training=True)
File "/home/isabelle/.local/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/home/isabelle/.local/lib/python3.10/site-packages/keras/src/engine/input_spec.py", line 280, in assert_input_compatibility
raise ValueError(
ValueError: Exception encountered when calling layer 'sequential_1' (type Sequential).
Input 0 of layer "dense_1" is incompatible with the layer: expected axis -1 of input shape to have value 1, but received input with shape (None, 2)
Call arguments received by layer 'sequential_1' (type Sequential):
• inputs=tf.Tensor(shape=(None, 2), dtype=float32)
• training=True
• mask=None
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.
# your code here
import pandas as pd
import matplotlib.pyplot as plt
# data for gpa calculator (includes the classes i'm currently taking and my grades)
data = {
'class': ['Gov', 'CSP', 'Stats'],
'credits': [5, 5, 5],
'grade': ['A', 'A', 'A']
}
df = pd.DataFrame(data)
# dictionary for gpa grade points (AP weighted to match my classes)
grade_points = {
'A': 5.0,
'A-': 4.7,
'B+': 4.3,
'B': 4.0,
'B-': 3.7,
'C+': 3.3,
'C': 3.0,
'C-': 2.7
}
# calculate grade points for each class
df['grade points'] = df['grade'].map(grade_points)
df['total points'] = df['grade points'] * df['credits']
# calculate total credits and total grade points
total_credits = df['credits'].sum()
total_grade_points = df['total points'].sum()
# calculate the GPA
gpa = total_grade_points / total_credits
# print the GPA
def print_gpa():
print(f'isabelles current GPA for this trimester is {gpa:.2f}')
print_gpa()
# create bar graph
plt.figure(figsize=(8, 6))
plt.bar(df['class'], df['grade points'], color='lavender')
plt.xlabel('class')
plt.ylabel('grade points')
plt.title('grade points for isabelle classes')
plt.ylim(0, 5.0)
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.xticks(rotation=15)
plt.show()
isabelles current GPA for this trimester is 5.00
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.
# your code here
import random
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
# generate 50 random data points from range 0-100
random.seed(42)
data_points = [random.randint(0, 100) for _ in range(50)]
# customized colors for colorbar
colors = [('pink'), ('lavender'), ('lightblue')]
custom_cmap = LinearSegmentedColormap.from_list('custom_cmap', colors)
# create a scatter plot
plt.figure(figsize=(8, 6))
sc = plt.scatter(range(1, 51), data_points, c=data_points, cmap=custom_cmap, s=100, marker='o')
cbar = plt.colorbar(sc, label='Y', ticks=[0, 50, 100])
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Randomized Data')
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()
print("guys please give me a good grade, i even added cute colors 😻😻")
guys please give me a good grade, i even added cute colors 😻😻