Code icon

The App is Under a Quick Maintenance

We apologize for the inconvenience. Please come back later

Menu iconMenu iconMachine Learning Hero
Machine Learning Hero

Chapter 1: Introduction to Machine Learning

Practical Exercises Chapter 1

Exercise 1: Understanding Types of Machine Learning

Task: Based on the explanation of supervised, unsupervised, and reinforcement learning, categorize the following real-world examples into the correct machine learning type:

  • A system that predicts house prices based on features like size, location, and number of rooms.
  • A program that groups customers into clusters based on purchasing behavior.
  • A robot learning to walk by receiving feedback from its environment.

Solution:

  • Supervised Learning: Predicting house prices based on features.
  • Unsupervised Learning: Grouping customers based on purchasing behavior.
  • Reinforcement Learning: A robot learning to walk by receiving feedback.

Exercise 2: Implementing Supervised Learning

Task: Use Scikit-learn to implement a basic supervised learning model. Load the Iris dataset, split it into training and testing sets, and train a Logistic Regression model to classify iris species. After training, evaluate the accuracy of the model on the test set.

Solution:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# Load the Iris dataset
iris = load_iris()
X = iris.data
y = iris.target

# 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)

# Initialize and train a Logistic Regression model
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)

# Make predictions and evaluate accuracy
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)

print(f"Model Accuracy: {accuracy:.2f}")

Exercise 3: Exploring Unsupervised Learning

Task: Implement a K-means clustering algorithm using Scikit-learn on the following dataset:

data = [[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]]

Use 2 clusters, and after fitting the model, print the cluster centers and the labels assigned to each data point.

Solution:

from sklearn.cluster import KMeans

# Define the dataset
data = [[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]]

# Fit the K-means model with 2 clusters
kmeans = KMeans(n_clusters=2, random_state=0).fit(data)

# Print cluster centers and labels
print(f"Cluster Centers: {kmeans.cluster_centers_}")
print(f"Data Labels: {kmeans.labels_}")

Exercise 4: Sentiment Analysis Using NLP

Task: Use TextBlob to perform sentiment analysis on the following text:

"The new phone model is amazing, I absolutely love the camera and the battery life!"

Write a Python script to compute and print the sentiment polarity.

Solution:

from textblob import TextBlob

# Define the text
text = "The new phone model is amazing, I absolutely love the camera and the battery life!"

# Perform sentiment analysis
blob = TextBlob(text)
sentiment = blob.sentiment

# Print the sentiment polarity
print(f"Sentiment Polarity: {sentiment.polarity}")

Exercise 5: Visualizing Data

Task: Use Matplotlib to plot a histogram of the following data:

data = [22, 25, 23, 20, 19, 22, 26, 30, 31, 22, 24, 25, 22, 27]

Create a histogram with 5 bins and label the axes appropriately.

Solution:

import matplotlib.pyplot as plt

# Define the data
data = [22, 25, 23, 20, 19, 22, 26, 30, 31, 22, 24, 25, 22, 27]

# Create a histogram
plt.hist(data, bins=5, edgecolor='black')

# Add labels and title
plt.title('Histogram of Data')
plt.xlabel('Values')
plt.ylabel('Frequency')

# Show the plot
plt.show()

Exercise 6: Building a Simple Neural Network with Keras

Task: Use Keras to build a simple feedforward neural network. Train the network on the Iris dataset to classify the species. The network should contain two hidden layers with 10 neurons each and use ReLU activation functions. Evaluate the accuracy on the test set.

Solution:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

# Load the Iris dataset
iris = load_iris()
X = iris.data
y = iris.target

# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Build the neural network
model = Sequential([
    Dense(10, input_dim=4, activation='relu'),
    Dense(10, activation='relu'),
    Dense(3, activation='softmax')
])

# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Train the model
model.fit(X_train, y_train, epochs=50, batch_size=10)

# Evaluate the model
loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test Accuracy: {accuracy:.2f}")

Exercise 7: Exploring Explainable AI (XAI)

Task: Use SHAP (SHapley Additive exPlanations) to explain the predictions of an XGBoost model on the Boston Housing Dataset. Print and plot the SHAP values for the first prediction.

Solution:

import shap
import xgboost
from shap.datasets import boston

# Load the Boston Housing dataset
X, y = boston()

# Train an XGBoost model
model = xgboost.XGBRegressor()
model.fit(X, y)

# Initialize SHAP explainer
explainer = shap.Explainer(model)
shap_values = explainer(X)

# Plot the SHAP values for the first prediction
shap.plots.waterfall(shap_values[0])

These practical exercises help reinforce the core concepts introduced in Chapter 1. By working through these tasks, you'll gain hands-on experience in understanding the types of machine learning, building simple models, performing data manipulation and visualization, and even diving into cutting-edge topics like explainable AI. Make sure to take your time with each exercise, and feel free to tweak the code to explore further!

Practical Exercises Chapter 1

Exercise 1: Understanding Types of Machine Learning

Task: Based on the explanation of supervised, unsupervised, and reinforcement learning, categorize the following real-world examples into the correct machine learning type:

  • A system that predicts house prices based on features like size, location, and number of rooms.
  • A program that groups customers into clusters based on purchasing behavior.
  • A robot learning to walk by receiving feedback from its environment.

Solution:

  • Supervised Learning: Predicting house prices based on features.
  • Unsupervised Learning: Grouping customers based on purchasing behavior.
  • Reinforcement Learning: A robot learning to walk by receiving feedback.

Exercise 2: Implementing Supervised Learning

Task: Use Scikit-learn to implement a basic supervised learning model. Load the Iris dataset, split it into training and testing sets, and train a Logistic Regression model to classify iris species. After training, evaluate the accuracy of the model on the test set.

Solution:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# Load the Iris dataset
iris = load_iris()
X = iris.data
y = iris.target

# 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)

# Initialize and train a Logistic Regression model
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)

# Make predictions and evaluate accuracy
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)

print(f"Model Accuracy: {accuracy:.2f}")

Exercise 3: Exploring Unsupervised Learning

Task: Implement a K-means clustering algorithm using Scikit-learn on the following dataset:

data = [[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]]

Use 2 clusters, and after fitting the model, print the cluster centers and the labels assigned to each data point.

Solution:

from sklearn.cluster import KMeans

# Define the dataset
data = [[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]]

# Fit the K-means model with 2 clusters
kmeans = KMeans(n_clusters=2, random_state=0).fit(data)

# Print cluster centers and labels
print(f"Cluster Centers: {kmeans.cluster_centers_}")
print(f"Data Labels: {kmeans.labels_}")

Exercise 4: Sentiment Analysis Using NLP

Task: Use TextBlob to perform sentiment analysis on the following text:

"The new phone model is amazing, I absolutely love the camera and the battery life!"

Write a Python script to compute and print the sentiment polarity.

Solution:

from textblob import TextBlob

# Define the text
text = "The new phone model is amazing, I absolutely love the camera and the battery life!"

# Perform sentiment analysis
blob = TextBlob(text)
sentiment = blob.sentiment

# Print the sentiment polarity
print(f"Sentiment Polarity: {sentiment.polarity}")

Exercise 5: Visualizing Data

Task: Use Matplotlib to plot a histogram of the following data:

data = [22, 25, 23, 20, 19, 22, 26, 30, 31, 22, 24, 25, 22, 27]

Create a histogram with 5 bins and label the axes appropriately.

Solution:

import matplotlib.pyplot as plt

# Define the data
data = [22, 25, 23, 20, 19, 22, 26, 30, 31, 22, 24, 25, 22, 27]

# Create a histogram
plt.hist(data, bins=5, edgecolor='black')

# Add labels and title
plt.title('Histogram of Data')
plt.xlabel('Values')
plt.ylabel('Frequency')

# Show the plot
plt.show()

Exercise 6: Building a Simple Neural Network with Keras

Task: Use Keras to build a simple feedforward neural network. Train the network on the Iris dataset to classify the species. The network should contain two hidden layers with 10 neurons each and use ReLU activation functions. Evaluate the accuracy on the test set.

Solution:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

# Load the Iris dataset
iris = load_iris()
X = iris.data
y = iris.target

# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Build the neural network
model = Sequential([
    Dense(10, input_dim=4, activation='relu'),
    Dense(10, activation='relu'),
    Dense(3, activation='softmax')
])

# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Train the model
model.fit(X_train, y_train, epochs=50, batch_size=10)

# Evaluate the model
loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test Accuracy: {accuracy:.2f}")

Exercise 7: Exploring Explainable AI (XAI)

Task: Use SHAP (SHapley Additive exPlanations) to explain the predictions of an XGBoost model on the Boston Housing Dataset. Print and plot the SHAP values for the first prediction.

Solution:

import shap
import xgboost
from shap.datasets import boston

# Load the Boston Housing dataset
X, y = boston()

# Train an XGBoost model
model = xgboost.XGBRegressor()
model.fit(X, y)

# Initialize SHAP explainer
explainer = shap.Explainer(model)
shap_values = explainer(X)

# Plot the SHAP values for the first prediction
shap.plots.waterfall(shap_values[0])

These practical exercises help reinforce the core concepts introduced in Chapter 1. By working through these tasks, you'll gain hands-on experience in understanding the types of machine learning, building simple models, performing data manipulation and visualization, and even diving into cutting-edge topics like explainable AI. Make sure to take your time with each exercise, and feel free to tweak the code to explore further!

Practical Exercises Chapter 1

Exercise 1: Understanding Types of Machine Learning

Task: Based on the explanation of supervised, unsupervised, and reinforcement learning, categorize the following real-world examples into the correct machine learning type:

  • A system that predicts house prices based on features like size, location, and number of rooms.
  • A program that groups customers into clusters based on purchasing behavior.
  • A robot learning to walk by receiving feedback from its environment.

Solution:

  • Supervised Learning: Predicting house prices based on features.
  • Unsupervised Learning: Grouping customers based on purchasing behavior.
  • Reinforcement Learning: A robot learning to walk by receiving feedback.

Exercise 2: Implementing Supervised Learning

Task: Use Scikit-learn to implement a basic supervised learning model. Load the Iris dataset, split it into training and testing sets, and train a Logistic Regression model to classify iris species. After training, evaluate the accuracy of the model on the test set.

Solution:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# Load the Iris dataset
iris = load_iris()
X = iris.data
y = iris.target

# 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)

# Initialize and train a Logistic Regression model
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)

# Make predictions and evaluate accuracy
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)

print(f"Model Accuracy: {accuracy:.2f}")

Exercise 3: Exploring Unsupervised Learning

Task: Implement a K-means clustering algorithm using Scikit-learn on the following dataset:

data = [[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]]

Use 2 clusters, and after fitting the model, print the cluster centers and the labels assigned to each data point.

Solution:

from sklearn.cluster import KMeans

# Define the dataset
data = [[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]]

# Fit the K-means model with 2 clusters
kmeans = KMeans(n_clusters=2, random_state=0).fit(data)

# Print cluster centers and labels
print(f"Cluster Centers: {kmeans.cluster_centers_}")
print(f"Data Labels: {kmeans.labels_}")

Exercise 4: Sentiment Analysis Using NLP

Task: Use TextBlob to perform sentiment analysis on the following text:

"The new phone model is amazing, I absolutely love the camera and the battery life!"

Write a Python script to compute and print the sentiment polarity.

Solution:

from textblob import TextBlob

# Define the text
text = "The new phone model is amazing, I absolutely love the camera and the battery life!"

# Perform sentiment analysis
blob = TextBlob(text)
sentiment = blob.sentiment

# Print the sentiment polarity
print(f"Sentiment Polarity: {sentiment.polarity}")

Exercise 5: Visualizing Data

Task: Use Matplotlib to plot a histogram of the following data:

data = [22, 25, 23, 20, 19, 22, 26, 30, 31, 22, 24, 25, 22, 27]

Create a histogram with 5 bins and label the axes appropriately.

Solution:

import matplotlib.pyplot as plt

# Define the data
data = [22, 25, 23, 20, 19, 22, 26, 30, 31, 22, 24, 25, 22, 27]

# Create a histogram
plt.hist(data, bins=5, edgecolor='black')

# Add labels and title
plt.title('Histogram of Data')
plt.xlabel('Values')
plt.ylabel('Frequency')

# Show the plot
plt.show()

Exercise 6: Building a Simple Neural Network with Keras

Task: Use Keras to build a simple feedforward neural network. Train the network on the Iris dataset to classify the species. The network should contain two hidden layers with 10 neurons each and use ReLU activation functions. Evaluate the accuracy on the test set.

Solution:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

# Load the Iris dataset
iris = load_iris()
X = iris.data
y = iris.target

# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Build the neural network
model = Sequential([
    Dense(10, input_dim=4, activation='relu'),
    Dense(10, activation='relu'),
    Dense(3, activation='softmax')
])

# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Train the model
model.fit(X_train, y_train, epochs=50, batch_size=10)

# Evaluate the model
loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test Accuracy: {accuracy:.2f}")

Exercise 7: Exploring Explainable AI (XAI)

Task: Use SHAP (SHapley Additive exPlanations) to explain the predictions of an XGBoost model on the Boston Housing Dataset. Print and plot the SHAP values for the first prediction.

Solution:

import shap
import xgboost
from shap.datasets import boston

# Load the Boston Housing dataset
X, y = boston()

# Train an XGBoost model
model = xgboost.XGBRegressor()
model.fit(X, y)

# Initialize SHAP explainer
explainer = shap.Explainer(model)
shap_values = explainer(X)

# Plot the SHAP values for the first prediction
shap.plots.waterfall(shap_values[0])

These practical exercises help reinforce the core concepts introduced in Chapter 1. By working through these tasks, you'll gain hands-on experience in understanding the types of machine learning, building simple models, performing data manipulation and visualization, and even diving into cutting-edge topics like explainable AI. Make sure to take your time with each exercise, and feel free to tweak the code to explore further!

Practical Exercises Chapter 1

Exercise 1: Understanding Types of Machine Learning

Task: Based on the explanation of supervised, unsupervised, and reinforcement learning, categorize the following real-world examples into the correct machine learning type:

  • A system that predicts house prices based on features like size, location, and number of rooms.
  • A program that groups customers into clusters based on purchasing behavior.
  • A robot learning to walk by receiving feedback from its environment.

Solution:

  • Supervised Learning: Predicting house prices based on features.
  • Unsupervised Learning: Grouping customers based on purchasing behavior.
  • Reinforcement Learning: A robot learning to walk by receiving feedback.

Exercise 2: Implementing Supervised Learning

Task: Use Scikit-learn to implement a basic supervised learning model. Load the Iris dataset, split it into training and testing sets, and train a Logistic Regression model to classify iris species. After training, evaluate the accuracy of the model on the test set.

Solution:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# Load the Iris dataset
iris = load_iris()
X = iris.data
y = iris.target

# 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)

# Initialize and train a Logistic Regression model
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)

# Make predictions and evaluate accuracy
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)

print(f"Model Accuracy: {accuracy:.2f}")

Exercise 3: Exploring Unsupervised Learning

Task: Implement a K-means clustering algorithm using Scikit-learn on the following dataset:

data = [[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]]

Use 2 clusters, and after fitting the model, print the cluster centers and the labels assigned to each data point.

Solution:

from sklearn.cluster import KMeans

# Define the dataset
data = [[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]]

# Fit the K-means model with 2 clusters
kmeans = KMeans(n_clusters=2, random_state=0).fit(data)

# Print cluster centers and labels
print(f"Cluster Centers: {kmeans.cluster_centers_}")
print(f"Data Labels: {kmeans.labels_}")

Exercise 4: Sentiment Analysis Using NLP

Task: Use TextBlob to perform sentiment analysis on the following text:

"The new phone model is amazing, I absolutely love the camera and the battery life!"

Write a Python script to compute and print the sentiment polarity.

Solution:

from textblob import TextBlob

# Define the text
text = "The new phone model is amazing, I absolutely love the camera and the battery life!"

# Perform sentiment analysis
blob = TextBlob(text)
sentiment = blob.sentiment

# Print the sentiment polarity
print(f"Sentiment Polarity: {sentiment.polarity}")

Exercise 5: Visualizing Data

Task: Use Matplotlib to plot a histogram of the following data:

data = [22, 25, 23, 20, 19, 22, 26, 30, 31, 22, 24, 25, 22, 27]

Create a histogram with 5 bins and label the axes appropriately.

Solution:

import matplotlib.pyplot as plt

# Define the data
data = [22, 25, 23, 20, 19, 22, 26, 30, 31, 22, 24, 25, 22, 27]

# Create a histogram
plt.hist(data, bins=5, edgecolor='black')

# Add labels and title
plt.title('Histogram of Data')
plt.xlabel('Values')
plt.ylabel('Frequency')

# Show the plot
plt.show()

Exercise 6: Building a Simple Neural Network with Keras

Task: Use Keras to build a simple feedforward neural network. Train the network on the Iris dataset to classify the species. The network should contain two hidden layers with 10 neurons each and use ReLU activation functions. Evaluate the accuracy on the test set.

Solution:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

# Load the Iris dataset
iris = load_iris()
X = iris.data
y = iris.target

# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Build the neural network
model = Sequential([
    Dense(10, input_dim=4, activation='relu'),
    Dense(10, activation='relu'),
    Dense(3, activation='softmax')
])

# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Train the model
model.fit(X_train, y_train, epochs=50, batch_size=10)

# Evaluate the model
loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test Accuracy: {accuracy:.2f}")

Exercise 7: Exploring Explainable AI (XAI)

Task: Use SHAP (SHapley Additive exPlanations) to explain the predictions of an XGBoost model on the Boston Housing Dataset. Print and plot the SHAP values for the first prediction.

Solution:

import shap
import xgboost
from shap.datasets import boston

# Load the Boston Housing dataset
X, y = boston()

# Train an XGBoost model
model = xgboost.XGBRegressor()
model.fit(X, y)

# Initialize SHAP explainer
explainer = shap.Explainer(model)
shap_values = explainer(X)

# Plot the SHAP values for the first prediction
shap.plots.waterfall(shap_values[0])

These practical exercises help reinforce the core concepts introduced in Chapter 1. By working through these tasks, you'll gain hands-on experience in understanding the types of machine learning, building simple models, performing data manipulation and visualization, and even diving into cutting-edge topics like explainable AI. Make sure to take your time with each exercise, and feel free to tweak the code to explore further!