Page 438 - AI_Ver_3.0_class_11
P. 438
Output:
0 23
1 25
2 30
3 35
4 50
dtype: int64
18. Do the following using the Iris Dataset:
a. Load the Iris dataset from Scikit Learn Library
b. Calculate and print the mean, median, and standard deviation for each feature.
c. Create a scatter plot of petal length vs. petal width, color-coded by species.
# Step 1: Import necessary libraries
import pandas as pd
import matplotlib.pyplot as plt
import statistics
from sklearn.datasets import load_iris
# Step 2: Load the Iris dataset from scikit-learn
iris = load_iris()
iris_data = pd.DataFrame(data=iris.data, columns=iris.feature_names)
iris_data['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)
# Step 3: Display the first 5 rows of the dataset
print("First 5 rows of the dataset:")
print(iris_data.head())
# Step 4: Calculate and display mean, median, and standard deviation
print("\nStatistics for each feature:")
for column in iris_data.columns[:-1]:
print("column being processed:", column)
mean_val = statistics.mean(iris_data[column])
median_val = statistics.median(iris_data[column])
std_dev_val = statistics.stdev(iris_data[column])
print(" Mean: ",mean_val)
print(" Median: ",median_val)
print(" Standard Deviation: ",std_dev_val)
'''Step 5: Create a scatter plot of petal length vs. petal width, color-coded by
species'''
plt.figure(figsize=(10, 6))
# Define colors for each species
colors = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'}
# Scatter plot for each species
for species in iris_data['species'].unique():
subset = iris_data[iris_data['species'] == species]
plt.scatter(subset['petal length (cm)'], subset['petal width (cm)'],
c=colors[species], label=species)
plt.title("Scatter plot of Petal Length vs. Petal Width")
plt.xlabel("Petal Length (cm)")
plt.ylabel("Petal Width (cm)")
plt.legend(title="Species")
plt.grid(True)
# Show the plot
plt.show()
436 Touchpad Artificial Intelligence (Ver. 3.0)-XI

