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://th-thumbnailer.cdn-si-edu.com/wDCKX3gxut2u6NOg4zAx43fjZkk=/800x600/https://tf-cmsv2-smithsonianmag-media.s3.amazonaws.com/filer/Design-Decoded-Smiley-Face-631%20copy.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((200, 200)) # 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
plt.plot(x, y1, label='Linear Graph', color='green', linestyle='-') # Create the plot
plt.title('Linear Graph') # Set the title
plt.xlabel('x') # Label for the x-axis
plt.ylabel('y') # 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:24:17.527002: 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:24:17.629267: 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:24:18.134236: 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:24:18.135055: 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:24:18.135935: 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:24:18.456921: 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:24:18.459551: 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:24:20.795753: 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 - 1s - loss: 3.7639 - 873ms/epoch - 291ms/step
Epoch 2/100
3/3 - 0s - loss: 3.7522 - 22ms/epoch - 7ms/step
Epoch 3/100
3/3 - 0s - loss: 3.7402 - 22ms/epoch - 7ms/step
Epoch 4/100
3/3 - 0s - loss: 3.7286 - 17ms/epoch - 6ms/step
Epoch 5/100
3/3 - 0s - loss: 3.7169 - 24ms/epoch - 8ms/step
Epoch 6/100
3/3 - 0s - loss: 3.7052 - 22ms/epoch - 7ms/step
Epoch 7/100
3/3 - 0s - loss: 3.6936 - 20ms/epoch - 7ms/step
Epoch 8/100
3/3 - 0s - loss: 3.6819 - 24ms/epoch - 8ms/step
Epoch 9/100
3/3 - 0s - loss: 3.6705 - 17ms/epoch - 6ms/step
Epoch 10/100
3/3 - 0s - loss: 3.6589 - 22ms/epoch - 7ms/step
Epoch 11/100
3/3 - 0s - loss: 3.6475 - 18ms/epoch - 6ms/step
Epoch 12/100
3/3 - 0s - loss: 3.6360 - 18ms/epoch - 6ms/step
Epoch 13/100
3/3 - 0s - loss: 3.6246 - 15ms/epoch - 5ms/step
Epoch 14/100
3/3 - 0s - loss: 3.6131 - 20ms/epoch - 7ms/step
Epoch 15/100
3/3 - 0s - loss: 3.6016 - 23ms/epoch - 8ms/step
Epoch 16/100
3/3 - 0s - loss: 3.5905 - 13ms/epoch - 4ms/step
Epoch 17/100
3/3 - 0s - loss: 3.5789 - 18ms/epoch - 6ms/step
Epoch 18/100
3/3 - 0s - loss: 3.5674 - 17ms/epoch - 6ms/step
Epoch 19/100
3/3 - 0s - loss: 3.5562 - 18ms/epoch - 6ms/step
Epoch 20/100
3/3 - 0s - loss: 3.5448 - 13ms/epoch - 4ms/step
Epoch 21/100
3/3 - 0s - loss: 3.5334 - 13ms/epoch - 4ms/step
Epoch 22/100
3/3 - 0s - loss: 3.5222 - 16ms/epoch - 5ms/step
Epoch 23/100
3/3 - 0s - loss: 3.5110 - 17ms/epoch - 6ms/step
Epoch 24/100
3/3 - 0s - loss: 3.4999 - 17ms/epoch - 6ms/step
Epoch 25/100
3/3 - 0s - loss: 3.4885 - 18ms/epoch - 6ms/step
Epoch 26/100
3/3 - 0s - loss: 3.4774 - 15ms/epoch - 5ms/step
Epoch 27/100
3/3 - 0s - loss: 3.4663 - 15ms/epoch - 5ms/step
Epoch 28/100
3/3 - 0s - loss: 3.4555 - 12ms/epoch - 4ms/step
Epoch 29/100
3/3 - 0s - loss: 3.4443 - 11ms/epoch - 4ms/step
Epoch 30/100
3/3 - 0s - loss: 3.4333 - 11ms/epoch - 4ms/step
Epoch 31/100
3/3 - 0s - loss: 3.4222 - 21ms/epoch - 7ms/step
Epoch 32/100
3/3 - 0s - loss: 3.4112 - 12ms/epoch - 4ms/step
Epoch 33/100
3/3 - 0s - loss: 3.4004 - 13ms/epoch - 4ms/step
Epoch 34/100
3/3 - 0s - loss: 3.3895 - 13ms/epoch - 4ms/step
Epoch 35/100
3/3 - 0s - loss: 3.3787 - 13ms/epoch - 4ms/step
Epoch 36/100
3/3 - 0s - loss: 3.3680 - 18ms/epoch - 6ms/step
Epoch 37/100
3/3 - 0s - loss: 3.3572 - 19ms/epoch - 6ms/step
Epoch 38/100
3/3 - 0s - loss: 3.3464 - 28ms/epoch - 9ms/step
Epoch 39/100
3/3 - 0s - loss: 3.3357 - 22ms/epoch - 7ms/step
Epoch 40/100
3/3 - 0s - loss: 3.3253 - 26ms/epoch - 9ms/step
Epoch 41/100
3/3 - 0s - loss: 3.3144 - 22ms/epoch - 7ms/step
Epoch 42/100
3/3 - 0s - loss: 3.3039 - 17ms/epoch - 6ms/step
Epoch 43/100
3/3 - 0s - loss: 3.2931 - 24ms/epoch - 8ms/step
Epoch 44/100
3/3 - 0s - loss: 3.2826 - 20ms/epoch - 7ms/step
Epoch 45/100
3/3 - 0s - loss: 3.2720 - 11ms/epoch - 4ms/step
Epoch 46/100
3/3 - 0s - loss: 3.2615 - 17ms/epoch - 6ms/step
Epoch 47/100
3/3 - 0s - loss: 3.2510 - 19ms/epoch - 6ms/step
Epoch 48/100
3/3 - 0s - loss: 3.2406 - 15ms/epoch - 5ms/step
Epoch 49/100
3/3 - 0s - loss: 3.2301 - 18ms/epoch - 6ms/step
Epoch 50/100
3/3 - 0s - loss: 3.2197 - 27ms/epoch - 9ms/step
Epoch 51/100
3/3 - 0s - loss: 3.2094 - 17ms/epoch - 6ms/step
Epoch 52/100
3/3 - 0s - loss: 3.1989 - 19ms/epoch - 6ms/step
Epoch 53/100
3/3 - 0s - loss: 3.1886 - 21ms/epoch - 7ms/step
Epoch 54/100
3/3 - 0s - loss: 3.1782 - 18ms/epoch - 6ms/step
Epoch 55/100
3/3 - 0s - loss: 3.1680 - 18ms/epoch - 6ms/step
Epoch 56/100
3/3 - 0s - loss: 3.1576 - 19ms/epoch - 6ms/step
Epoch 57/100
3/3 - 0s - loss: 3.1474 - 19ms/epoch - 6ms/step
Epoch 58/100
3/3 - 0s - loss: 3.1372 - 18ms/epoch - 6ms/step
Epoch 59/100
3/3 - 0s - loss: 3.1269 - 13ms/epoch - 4ms/step
Epoch 60/100
3/3 - 0s - loss: 3.1167 - 15ms/epoch - 5ms/step
Epoch 61/100
3/3 - 0s - loss: 3.1066 - 21ms/epoch - 7ms/step
Epoch 62/100
3/3 - 0s - loss: 3.0964 - 24ms/epoch - 8ms/step
Epoch 63/100
3/3 - 0s - loss: 3.0865 - 15ms/epoch - 5ms/step
Epoch 64/100
3/3 - 0s - loss: 3.0763 - 21ms/epoch - 7ms/step
Epoch 65/100
3/3 - 0s - loss: 3.0662 - 15ms/epoch - 5ms/step
Epoch 66/100
3/3 - 0s - loss: 3.0561 - 16ms/epoch - 5ms/step
Epoch 67/100
3/3 - 0s - loss: 3.0462 - 16ms/epoch - 5ms/step
Epoch 68/100
3/3 - 0s - loss: 3.0363 - 19ms/epoch - 6ms/step
Epoch 69/100
3/3 - 0s - loss: 3.0262 - 12ms/epoch - 4ms/step
Epoch 70/100
3/3 - 0s - loss: 3.0163 - 19ms/epoch - 6ms/step
Epoch 71/100
3/3 - 0s - loss: 3.0063 - 15ms/epoch - 5ms/step
Epoch 72/100
3/3 - 0s - loss: 2.9964 - 16ms/epoch - 5ms/step
Epoch 73/100
3/3 - 0s - loss: 2.9865 - 19ms/epoch - 6ms/step
Epoch 74/100
3/3 - 0s - loss: 2.9767 - 24ms/epoch - 8ms/step
Epoch 75/100
3/3 - 0s - loss: 2.9669 - 20ms/epoch - 7ms/step
Epoch 76/100
3/3 - 0s - loss: 2.9570 - 19ms/epoch - 6ms/step
Epoch 77/100
3/3 - 0s - loss: 2.9473 - 16ms/epoch - 5ms/step
Epoch 78/100
3/3 - 0s - loss: 2.9375 - 16ms/epoch - 5ms/step
Epoch 79/100
3/3 - 0s - loss: 2.9278 - 13ms/epoch - 4ms/step
Epoch 80/100
3/3 - 0s - loss: 2.9182 - 12ms/epoch - 4ms/step
Epoch 81/100
3/3 - 0s - loss: 2.9085 - 15ms/epoch - 5ms/step
Epoch 82/100
3/3 - 0s - loss: 2.8989 - 20ms/epoch - 7ms/step
Epoch 83/100
3/3 - 0s - loss: 2.8892 - 17ms/epoch - 6ms/step
Epoch 84/100
3/3 - 0s - loss: 2.8796 - 17ms/epoch - 6ms/step
Epoch 85/100
3/3 - 0s - loss: 2.8701 - 26ms/epoch - 9ms/step
Epoch 86/100
3/3 - 0s - loss: 2.8605 - 17ms/epoch - 6ms/step
Epoch 87/100
3/3 - 0s - loss: 2.8510 - 18ms/epoch - 6ms/step
Epoch 88/100
3/3 - 0s - loss: 2.8417 - 19ms/epoch - 6ms/step
Epoch 89/100
3/3 - 0s - loss: 2.8320 - 14ms/epoch - 5ms/step
Epoch 90/100
3/3 - 0s - loss: 2.8227 - 23ms/epoch - 8ms/step
Epoch 91/100
3/3 - 0s - loss: 2.8132 - 17ms/epoch - 6ms/step
Epoch 92/100
3/3 - 0s - loss: 2.8038 - 21ms/epoch - 7ms/step
Epoch 93/100
3/3 - 0s - loss: 2.7945 - 17ms/epoch - 6ms/step
Epoch 94/100
3/3 - 0s - loss: 2.7851 - 18ms/epoch - 6ms/step
Epoch 95/100
3/3 - 0s - loss: 2.7758 - 24ms/epoch - 8ms/step
Epoch 96/100
3/3 - 0s - loss: 2.7664 - 12ms/epoch - 4ms/step
Epoch 97/100
3/3 - 0s - loss: 2.7572 - 19ms/epoch - 6ms/step
Epoch 98/100
3/3 - 0s - loss: 2.7479 - 11ms/epoch - 4ms/step
Epoch 99/100
3/3 - 0s - loss: 2.7386 - 9ms/epoch - 3ms/step
Epoch 100/100
3/3 - 0s - loss: 2.7294 - 10ms/epoch - 3ms/step
1/1 [==============================] - 0s 144ms/step
Mean Squared Error: 2.6875
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 for regression
# Using MSE as the loss function
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_2888/2855242047.py in <module>
36
37 # Train the model
---> 38 model.fit(X_train, y_train, epochs=100, batch_size=32, verbose=2)
39
40 # 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/ryanliu/.local/lib/python3.10/site-packages/keras/src/engine/training.py", line 1377, in train_function *
return step_function(self, iterator)
File "/home/ryanliu/.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/ryanliu/.local/lib/python3.10/site-packages/keras/src/engine/training.py", line 1349, in run_step **
outputs = model.train_step(data)
File "/home/ryanliu/.local/lib/python3.10/site-packages/keras/src/engine/training.py", line 1126, in train_step
y_pred = self(x, training=True)
File "/home/ryanliu/.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/ryanliu/.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_4' (type Sequential).
Input 0 of layer "dense_4" 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_4' (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.
import pandas as pd
import matplotlib.pyplot as plt
data = {'Course': ['Physics', 'CSP', 'History', 'English', 'Math'],
'Grade': ['A', 'B', 'C', 'D', 'F']}
df = pd.DataFrame(data)
gpas = {'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F': 0.0}
def calculate_gpa(dataframe):
total_weighted_points = 0
total_classes = 0
for index, row in dataframe.iterrows():
grade = row['Grade']
if grade in gpas:
gpa = gpas[grade]
total_weighted_points += gpa
total_classes += 1
if total_classes == 0:
print("No valid grades to calculate GPA.")
return
final_gpa = total_weighted_points / total_classes
print("Average GPA: {:.2f}".format(final_gpa))
plt.bar(dataframe['Course'], [gpas[grade] for grade in dataframe['Grade']], color='blue')
plt.title('GPA Chart')
plt.xlabel('Courses')
plt.ylabel('GPA')
plt.ylim(0, 4.0)
plt.show()
calculate_gpa(df)
Average GPA: 2.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.
import pandas as pd
import matplotlib.pyplot as plt
import random
random_data = {'X': [random.randint(0, 100) for _ in range(50)],
'Y': [random.randint(0, 100) for _ in range(50)]}
random_df = pd.DataFrame(random_data)
print("Random Data:")
print(random_df)
plt.scatter(random_df['X'], random_df['Y'], color='red', marker='o')
plt.title('Random Data Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
Random Data:
X Y
0 11 42
1 1 89
2 96 74
3 31 95
4 6 58
5 9 39
6 88 33
7 89 98
8 27 49
9 51 70
10 50 84
11 97 16
12 55 100
13 63 27
14 56 51
15 26 55
16 42 29
17 34 58
18 24 97
19 15 93
20 49 49
21 63 54
22 67 60
23 82 88
24 59 35
25 42 33
26 92 100
27 84 76
28 22 29
29 68 18
30 51 68
31 48 77
32 38 87
33 94 97
34 84 61
35 22 36
36 9 77
37 44 79
38 89 47
39 72 29
40 19 41
41 60 84
42 25 85
43 55 4
44 96 67
45 35 13
46 7 45
47 26 64
48 57 40
49 59 61