Overview
This class introduced the essential Python libraries for machine learning: NumPy, pandas, matplotlib, scikit-learn, and seaborn. It focused on data visualization using matplotlib, covering basic plots, subplots, and various chart types. The session then transitioned to scikit-learn, demonstrating the complete workflow of loading a dataset (Iris), splitting data, training a k-nearest neighbors (KNN) classifier, evaluating accuracy, and making predictions. The class concluded with a brief mention of saving models. This practical session lays the foundational toolkit for implementing and visualizing machine learning models, preceding deeper dives into specific algorithms like linear regression and KNN.
Learning outcomes
- Install and utilize core Python ML libraries (NumPy, pandas, matplotlib, scikit-learn).
- Create and customize various plots (line, scatter, bar, histogram, pie) using matplotlib.
- Load a built-in dataset using scikit-learn and split it into training and testing sets.
- Train a simple classifier (KNN), evaluate its accuracy, and use it to predict new samples.
- Understand the purpose of saving and loading trained models.
Core concepts
Data Visualization with Matplotlib
Definition: Matplotlib is a low-level, open-source library for creating static, animated, and interactive visualizations in Python. Why it matters: Visualizing data is crucial for understanding distributions, spotting patterns, and communicating results before and after model training. Connection: It is used alongside pandas for data exploration and alongside scikit-learn for visualizing model performance (e.g., decision boundaries, error plots).
Scikit-learn Workflow
Definition: Scikit-learn is a comprehensive library providing consistent APIs for data preprocessing, model training, validation, and evaluation. Why it matters: It standardizes the ML process, making it easier to implement, compare, and productionize algorithms. Connection: It builds on NumPy and pandas for data handling and is the primary library used for implementing algorithms taught in the course, from linear regression to advanced models.
Train-Test Split
Definition: The practice of randomly partitioning a dataset into a subset for training the model and a separate subset for evaluating its performance. Why it matters: It provides an unbiased estimate of model performance on unseen data, preventing overfitting. Connection: It is a mandatory step after data loading and before model training in the scikit-learn workflow.
Model Persistence
Definition: Saving a trained model to disk (using joblib or pickle) so it can be reloaded and used for predictions without retraining. Why it matters: It enables deployment and reuse of models, saving computational resources. Connection: It is the final step after model training and evaluation, allowing the model to be applied to new data in the future.
Formulas and maths
(No explicit formulas or equations were presented in this class.)
Worked examples
Matplotlib Examples
- Line Plot:
x = np.arange(0, 7)generates points [0,1,2,3,4,5,6].y = [0, 250]plots a line from (0,0) to (6,250). - Markers: Adding
marker='o'toplt.plot(x, y)displays points on the line. - Labels & Title:
plt.xlabel("average pulse"),plt.ylabel("calorie voltage"),plt.title("sport watch data"). - Subplots:
plt.subplot(1, 2, 1)andplt.subplot(1, 2, 2)create two plots side-by-side in a 1-row, 2-column figure. - Scatter Plot:
plt.scatter(x, y)creates a scatter plot instead of a line plot. - Bar Chart:
plt.bar(x, y, color='red', width=0.1)creates a red bar chart with specified bar width. - Histogram:
x = np.random.uniform(170, 10, 100)generates 100 random values around 170.plt.hist(x)plots their frequency distribution. - Pie Chart:
y = np.array([35, 25, 25, 15]).plt.pie(y, labels=['apple', 'banana', 'cherry', 'dates'], startangle=90, explode=(0.2, 0, 0, 0))creates a labeled pie chart starting at 90 degrees, with the first slice ('apple') exploded out by 0.2.
Scikit-learn Workflow with Iris Dataset
- Load Data: Iris dataset features:
['sepal length', 'sepal width', 'petal length', 'petal width']. Target names:['setosa', 'versicolor', 'virginica']. - Split Data:
train_test_split(X, y, test_size=0.3, random_state=42).- Result:
X_trainshape(105, 4),X_testshape(45, 4);y_trainshape(105,),y_testshape(45,).
- Result:
- Train KNN:
knn = KNeighborsClassifier(n_neighbors=3).knn.fit(X_train, y_train). - Evaluate:
y_pred = knn.predict(X_test).accuracy_score(y_test, y_pred)returned98.33%. - Predict New Samples:
- Sample
[[5.1, 3.5, 1.4, 0.2]]→ Predicted species:'versicolor'. - Sample
[[100, 20, 30, 40]]→ Predicted species:'virginica'.
- Sample
Questions asked in class
- Q: "In the advanced model we will start the deep learning yes for the deep learning vital tensor flow library that is used is there any plan?"
- A: "Yes 100% we'll cover the tensor flow and we will see the neural network convolution neural network transformer all the things we will see okay in this particular subject we will see all the things just like a transformer the cnn nlp everything we will cover."
- Q: "Can you so plotting of whole data set whole data set we cannot plot okay there is a two kind of axis is there two axis only so two axis but though feature xr we can plot if you need to plot the so many things in the one graph then we cannot but we can draw the many kind of the subplot that can showcase the different different uh thing."
- A: The instructor confirmed that for datasets with many features, subplots can be used instead of plotting everything on one graph.
- Q: Regarding error: "import matplotlib.py plot is a pld uh import in the line add in it is the line one import matplotlib.py plot invalid non-printable character."
- A: The code is correct, but the student should check their specific error, possibly a hidden character issue.
- Q: "Plotting an array in the histogram is not possible sir uh just like okay array no no not possible because we need to give the median okay and we need to give the that center value."
- A: A histogram requires multiple values/bins to calculate frequencies; a single array value like 170 cannot be plotted directly.
- Q: “Is the proportion of each element the same even if the angle changes?” (Referring to pie chart start angle)
- A: Yes, 100%, the proportion is the same, only the starting point changes.
- Q: “Where did we get this Iris dataset?”
- A: It is an in‑built dataset in scikit‑learn; also available on Kaggle.
- Q: “Target column will be only one?”
- A: Yes, 100%, the target column is always one because we need to classify.
- Q: “What is the meaning of saving the model?”
- A: Saving the model means after training on a dataset, the model is saved so that when new data arrives, you can directly test on that trained model without retraining.
Key takeaways
- NumPy is for numerical arrays, pandas for data handling, matplotlib for basic visualization, scikit-learn for ML algorithms, and seaborn for advanced statistical plots.
- In matplotlib, the
markerparameter adds points to a line plot; without it, only a line is drawn. - The
plt.subplot()function allows multiple plots to be arranged within a single figure. - A histogram visualizes the frequency distribution of data and requires multiple data points to create meaningful bins.
- In a pie chart, the
startangleparameter rotates the chart, and theexplodeparameter offsets a slice for emphasis. - Scikit-learn's
load_*functions provide easy access to standard datasets like Iris for practice. - The standard ML workflow involves: 1) Load Data, 2) Split Data (
train_test_split), 3) Train Model (model.fit), 4) Evaluate Model (model.predict,accuracy_score). - The
random_stateparameter intrain_test_splitensures the data split is reproducible. - A trained model can be saved to a file using
joblib.dumpand later reloaded withjoblib.loadfor predictions on new data. - The
fitmethod is used for training, and thepredictmethod is used for generating predictions on new data. - The accuracy score compares predicted labels to true labels and is a fundamental metric for classification tasks.
- Deep learning libraries (TensorFlow) and models (CNN, NLP, transformers) will be covered later in the course.
Exam-style questions
- Describe the purpose of the
train_test_splitfunction in scikit-learn and explain the role of therandom_stateparameter.- Outline:
train_test_splitpartitions data into training and testing sets to evaluate model performance on unseen data. Therandom_stateparameter seeds the random number generator, ensuring the same split is produced every time the code is run, which is crucial for reproducibility.
- Outline:
- Given a dataset with 150 samples, you perform
train_test_splitwithtest_size=0.3. What will be the dimensions of yourX_trainandX_testarrays?- Outline:
test_size=0.3means 30% of 150 samples (45 samples) are used for testing. Therefore,X_testwill have 45 rows. The remaining 70% (105 samples) will be for training, soX_trainwill have 105 rows. The number of columns depends on the features.
- Outline:
- You have trained a KNN classifier and achieved 95% accuracy on the test set. You then use the model to predict a brand new, single sample. Does this prediction affect the model's previously calculated accuracy score? Why or why not?
- Outline: No, it does not. The accuracy score is calculated solely on the test set used during evaluation. Predicting a new sample is a separate operation using the already-trained model parameters and does not alter the model or the historical test set results.
- When creating a histogram, why is it incorrect to pass a single value (e.g.,
plt.hist(170))? What does a histogram actually represent?- Outline: A histogram represents the frequency distribution of a dataset by grouping values into bins. A single value provides no distribution to visualize; it has a frequency of 1. The function expects an array of values to compute and plot the frequency across multiple bins.
Glossary
- NumPy - A Python library for efficient numerical computations and array operations.
- pandas - A Python library for data manipulation and analysis, using DataFrames.
- matplotlib - A foundational Python library for creating static, animated, and interactive visualizations.
- scikit-learn - A comprehensive Python library for machine learning, offering tools for classification, regression, clustering, and more.
- seaborn - A Python visualization library based on matplotlib for drawing attractive statistical graphics.
- Marker - In matplotlib, a symbol used to mark data points on a plot (e.g., 'o' for circle).
- Subplot - A method in matplotlib to arrange multiple plots within a single figure.
- Histogram - A graph showing the frequency distribution of numerical data using adjacent bars.
- Train-Test Split - The process of dividing a dataset into separate sets for training a model and testing its performance.
- Fit Method - The scikit-learn method used to train a model on training data.
- Predict Method - The scikit-learn method used to generate predictions using a trained model.
- Accuracy Score - A metric for classification models, defined as the proportion of correct predictions.
- joblib - A library (often from
sklearn) used for efficiently saving and loading Python objects, especially trained ML models.
Follow-ups
- The complete code file from the class is available on Moodle for practice.
- Detailed explanation of the k-nearest neighbors (KNN) algorithm and how to choose the optimal
n_neighborsvalue will be covered in an upcoming class. - Explanation of other evaluation metrics (precision, recall, F1-score) available in
sklearn.metrics. - How to handle custom datasets (not in‑built) using pandas with scikit‑learn will be demonstrated.
- The first assignment will be given after one week.
- The next class will begin implementation of the first model: linear regression, followed by multiple linear regression.
- Deep learning topics (TensorFlow, Convolutional Neural Networks, Natural Language Processing, transformers) are confirmed for later coverage in the course.