Random Integer Histogram with NumPy
Random Integer Histogram with NumPy
Source Code:
1. Print the installed version of the NumPy library.
Theory: It's often useful to know which version of a library you are using, especially since
functionality or APIs can change between versions. NumPy provides a built-in attribute __version__
to get the installed version.
print("1. NumPy version:", np.__version__)
2. Convert a list of numeric values into a one-dimensional NumPy array.
Theory: NumPy arrays are more efficient than Python lists for numerical operations. You can
convert a Python list to a NumPy array using [Link](). The resulting array is homogeneous and
supports vectorized operations.
num_list = [1, 2, 3, 4, 5]
array_1d = [Link](num_list)
print("2. One-dimensional NumPy array:", array_1d)
3. Create a 3x3 matrix with values ranging from 2 to 10 (inclusive).
Theory: [Link](start, stop) generates values from start up to but not including stop. To include 10,
we set stop to 11. Then, .reshape() changes the 1D array into a 2D matrix.
matrix_3x3 = [Link](2, 11).reshape(3, 3)
print("3. 3x3 matrix from 2 to 10:\n", matrix_3x3)
4. Create an array containing values from 12 to 38 (inclusive).
Theory: [Link]() creates a range of values. The stop argument is exclusive, so to include 38, we
use 39 as stop.
array_12_38 = [Link](12, 39)
print("4. Array from 12 to 38:", array_12_38)
5. Convert a given array to a floating-point datatype.
Theory: NumPy arrays have a dtype attribute that specifies the data type of elements. You can
convert to another type (e.g., float) using the .astype() method.
arr = [Link]([1, 2, 3, 4])
arr_float = [Link](float)
print("5. Array converted to float:", arr_float)
6. Generate 10 evenly spaced numbers between 0 and 1 using linspace().
Theory: [Link](start, stop, num) generates num equally spaced values between start and stop
(inclusive), useful for sampling continuous intervals.
linspace_array = [Link](0, 1, 10)
print("6. 10 evenly spaced numbers between 0 and 1:\n", linspace_array)
7. Generate an array containing numbers in reverse order from 10 to 1 using arange().
Theory: You can specify a negative step in [Link](start, stop, step) to generate a decreasing
sequence.
reverse_array = [Link](10, 0, -1)
print("7. Numbers from 10 to 1 in reverse order:", reverse_array)
8. Create a 5x4 matrix using values from 1 to 20 (inclusive).
Theory: Reshaping allows you to change the shape of an array without changing its data. Make sure
the total elements match.
matrix_5x4 = [Link](1, 21).reshape(5, 4)
print("8. 5x4 matrix from 1 to 20:\n", matrix_5x4)
9. Create a 3x2 matrix filled with zeros.
Theory: [Link](shape) creates an array filled with zeros. The shape is given as a tuple (rows,
columns).
zeros_matrix = [Link]((3, 2))
print("9. 3x2 matrix of zeros:\n", zeros_matrix)
10. Create a 3x2 matrix filled with ones.
Theory: Similarly, [Link](shape) creates an array filled with ones.
ones_matrix = [Link]((3, 2))
print("10. 3x2 matrix of ones:\n", ones_matrix
11. Convert a 2x2 matrix into a one-dimensional flattened array.
Theory: Flattening converts a multi-dimensional array into a 1D array. Use .flatten() or .ravel()
for this.
matrix_2x2 = [Link]([[1, 2], [3, 4]])
flattened_array = matrix_2x2.flatten()
print("11. Flattened array from 2x2 matrix:", flattened_array)
Output-
Assigement No: 2
Source Code:
1. Write a NumPy program to perform element-wise addition, subtraction, multiplication,
and division on two arrays.
Theory: NumPy arrays support element-wise arithmetic operations. When you add, subtract, multiply,
or divide two arrays of the same shape, the operations are applied element by element.
import numpy as np
arr1 = [Link]([10, 20, 30, 40])
arr2 = [Link]([1, 2, 3, 4])
add = arr1 + arr2
sub = arr1 - arr2
mul = arr1 * arr2
div = arr1 / arr2 # Division results in float values
print("1. Addition:", add)
print(" Subtraction:", sub)
print(" Multiplication:", mul)
print(" Division:", div)
2. Write a NumPy program to compute the logarithm of the sum of exponentials of input
values. Also compute the sum of exponentials using base-2.
Theory: The "log-sum-exp" trick is a numerical technique used in statistics and machine learning to
avoid underflow or overflow when working with exponentials and logarithms. NumPy provides
[Link]() and np.logaddexp2() for base-e and base-2 respectively.
values = [Link]([1.0, 2.0, 3.0])
log_sum_exp = [Link]([Link]([Link](values)))
log_sum_exp_base2 = np.log2([Link](2 ** values))
print("2. Log of sum of exponentials (base e):", log_sum_exp)
print(" Log of sum of exponentials (base 2):", log_sum_exp_base2)
3. Write a NumPy program to compute the largest integer less than or equal to the result of
element-wise division between two arrays.
Theory: This is equivalent to the floor division or the floor of the division. Use [Link]() on the
division result or use integer division //.
arr1 = [Link]([10, 20, 30, 40])
arr2 = [Link]([3, 7, 4, 6])
floor_division = [Link](arr1 / arr2)
floor_division_alt = arr1 // arr2
print("3. Floor of element-wise division:", floor_division)
print(" Using integer division operator:", floor_division_alt)
4. Write a NumPy program to compute the element-wise power of array values.
Theory: You can raise each element of an array to a specified power using [Link]() or the **
operator.
base_array = [Link]([2, 3, 4, 5])
exponent = 3
power_result = [Link](base_array, exponent)
# or base_array ** exponent
print("4. Element-wise power:", power_result)
5. Write a NumPy program to compute the floor, ceiling, and truncated values of the
elements of a NumPy array.
Theory:
[Link]() returns the largest integer less than or equal to each element.
[Link]() returns the smallest integer greater than or equal to each element.
[Link]() truncates towards zero (drops the decimal part).
arr = [Link]([1.7, 2.3, -3.5, -4.8])
floor_vals = [Link](arr)
ceil_vals = [Link](arr)
trunc_vals = [Link](arr)
print("5. Floor values:", floor_vals)
print(" Ceiling values:", ceil_vals)
print(" Truncated values:", trunc_vals)
6. Write a NumPy program to multiply a 5x3 matrix with a 3x2 matrix and compute the
resulting matrix product,
Theory: Matrix multiplication is done with [Link]() or the @ operator. The number of columns in the
first matrix must match the number of rows in the second.
mat1 = [Link](1, 16).reshape(5, 3) # 5x3 matrix
mat2 = [Link](1, 7).reshape(3, 2) # 3x2 matrix
product = [Link](mat1, mat2)
# or product = mat1 @ mat2
print("6. Matrix product (5x3 * 3x2):\n", product)
Output-
Assignment No-3
Source Code:
NumPy–RandomNumberGeneration
1. Write a NumPy program to generate an array of six random integers between 10 and 30
(inclusive)
Theory: NumPy provides the [Link] module to generate random numbers. To generate random
integers within a specified range, you can use [Link](low, high, size).
low is the inclusive lower bound.
high is the exclusive upper bound (i.e., the generated integers are less than high).
size specifies the shape or number of random numbers to generate.
Since high is exclusive, to include 30 in the range, we set high=31.
import numpy as np
# Generate 6 random integers between 10 and 30 (inclusive)
random_integers = [Link](10, 31, size=6)
print("Random integers between 10 and 30 (inclusive):", random_integers)
2. Write a NumPy program to create a 3×3×3 array filled with random values
Theory: NumPy's [Link] module can generate arrays filled with random values from various
distributions. The function [Link](size) generates random floats in the half-open interval
[0.0, 1.0).
The size parameter specifies the shape of the output array.
Here, we want a 3-dimensional array with dimensions 3×3×3, so we pass size=(3, 3, 3).
import numpy as np
# Create a 3x3x3 array with random float values between 0 and 1
random_array = [Link](size=(3, 3, 3))
print("3x3x3 array filled with random values:\n", random_array)
3. Write a NumPy program to create a 5×5 array with random values and determine the
minimum and maximum values within the array.
Theory: To generate random values in NumPy, you can use [Link](size) which produces
floats between 0 and 1.
To create a 2D array (matrix), specify the shape as a tuple, e.g., (5, 5).
To find the minimum and maximum values in an array, use [Link](array) and [Link](array)
respectively. These functions work on the entire array or along specific axes.
import numpy as np
# Create a 5x5 array with random values between 0 and 1
random_matrix = [Link]((5, 5))
print("5x5 array with random values:\n", random_matrix)
# Find the minimum value in the array
min_value = [Link](random_matrix)
print("Minimum value in the array:", min_value)
# Find the maximum value in the array
max_value = [Link](random_matrix)
print("Maximum value in the array:", max_value)
Output-
Assignment No-4
Source Code:
1) Write a NumPy program to create NumPy random array contain 10
elements from 10 to 90
import numpy as np
# Create a NumPy random array containing 10 elements from 10 to 90 (inclusive)
random_array = [Link](10, 91, size=10)
print("Random array with 10 elements between 10 and 90:", random_array)
Output-
Assignment No-5
Source Code:
import numpy as np
# Given NumPy array
arr = [Link]([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
# 1. Sum of all elements
total_sum = [Link](arr)
print("1. Sum of all elements:", total_sum)
# 2. Mean of all elements
mean_val = [Link](arr)
print("2. Mean of all elements:", mean_val)
# 3. Maximum value among all elements
max_val = [Link](arr)
print("3. Maximum value:", max_val)
# 4. Minimum value among all elements
min_val = [Link](arr)
print("4. Minimum value:", min_val)
# 5. Standard deviation of all elements
std_dev = [Link](arr)
print("5. Standard deviation:", std_dev)
# 6. Sum of elements along each column (axis=0)
sum_columns = [Link](arr, axis=0)
print("6. Sum along each column:", sum_columns)
# 7. Sum of elements along each row (axis=1)
sum_rows = [Link](arr, axis=1)
print("7. Sum along each row:", sum_rows)
# 8. Maximum value along each column and each row
max_columns = [Link](arr, axis=0)
max_rows = [Link](arr, axis=1)
print("8. Max along each column:", max_columns)
print(" Max along each row:", max_rows)
# 9. Minimum value along each column and each row
min_columns = [Link](arr, axis=0)
min_rows = [Link](arr, axis=1)
print("9. Min along each column:", min_columns)
print(" Min along each row:", min_rows)
Output-
Assignment No-6
Source Code:
import pandas as pd
# Create the Employee DataFrame
data = {
'Emp_ID': [100, 110, 120, 130, 140],
'Name': ['Kabir', 'Rishav', 'Seema', 'David', 'Ruchi'],
'Dept': ['IT', 'Finance', 'IT', 'IT', 'HRD'],
'Salary': [34000, 28500, 13500, 41000, 17000],
'Status': ['Regular', 'Regular', 'Regular', 'Contract', 'Regular']
}
df = [Link](data)
# 1. Display the DataFrame in descending order of salary.
print("1. DataFrame sorted by descending Salary:")
print(df.sort_values(by='Salary', ascending=False))
# 2. Update the salary of all employees with 'Contract' status to ₹19,000.
[Link][df['Status'] == 'Contract', 'Salary'] = 19000
print("\n2. Salary updated for 'Contract' employees:")
print(df)
# 3. Count the total number of employees in each department.
dept_counts = df['Dept'].value_counts()
print("\n3. Number of employees in each department:")
print(dept_counts)
# 4. Display the maximum salary among employees with 'Contract' status.
max_contract_salary = [Link][df['Status'] == 'Contract', 'Salary'].max()
print("\n4. Maximum salary among 'Contract' employees:", max_contract_salary)
# 5. Display the 4th record of the DataFrame (index 3)
print("\n5. Fourth record of the DataFrame:")
print([Link][3])
# 6. Delete the column named 'Status' from the DataFrame.
df = [Link](columns=['Status'])
print("\n6. DataFrame after deleting 'Status' column:")
print(df)
# 7. Display the maximum salary among employees in the 'IT' department.
max_it_salary = [Link][df['Dept'] == 'IT', 'Salary'].max()
print("\n7. Maximum salary in 'IT' department:", max_it_salary)
Output-
Assignment No-7
Source Code:
import pandas as pd
# 1. Create a DataFrame using the given dataset
data = {
'Player_ID': [101, 102, 103, 104, 105, 106, 107],
'Name': ['Virat', 'Rohit', 'Dhoni', 'Warner', 'Rahul', 'Hardik', 'Jadeja'],
'Team': ['RCB', 'MI', 'CSK', 'SRH', 'RCB', 'MI', 'CSK'],
'Runs': [9800, 8700, 8900, 9200, 8300, 7900, 8200],
'Bid_Price': [3.2, 3.6, 2.9, 4.0, 3.1, 3.7, 2.8] }
df = [Link](data)
# 2. Retrieve the first 2 and last 3 rows of the DataFrame
print("2. First 2 rows:\n", [Link](2))
print("\nLast 3 rows:\n", [Link](3))
# 3. Identify the player with the highest bid price (most expensive player)
most_expensive_player = [Link][df['Bid_Price'].idxmax()]
print("\n3. Player with highest bid price:\n", most_expensive_player)
# 4. Display the total number of players in each team
players_per_team = df['Team'].value_counts()
print("\n4. Total number of players in each team:\n", players_per_team)
# 5. Find the player with the highest bid price from each team
max_bid_per_team = [Link][[Link]('Team')['Bid_Price'].idxmax()]
print("\n5. Player with highest bid price from each team:\n", max_bid_per_team)
# 6. Calculate the average number of runs scored by players of each team
avg_runs_per_team = [Link]('Team')['Runs'].mean()
print("\n6. Average runs scored by players of each team:\n", avg_runs_per_team)
# 7. Sort all players in descending order according to their bid price
sorted_players = df.sort_values(by='Bid_Price', ascending=False)
print("\n7. Players sorted by descending bid price:\n", sorted_players)
Output-
Assignment No-8
Source Code:
import pandas as pd
import numpy as np
# Given data and labels
data = {
'birds': ['Cranes', 'Cranes', 'plovers', 'spoonbills', 'spoonbills',
'Cranes', 'plovers', 'Cranes', 'spoonbills', 'spoonbills'],
'age': [3.5, 4, 1.5, [Link], 6, 3, 5.5, [Link], 8, 4],
'visits': [2, 4, 3, 4, 3, 4, 2, 2, 3, 2],
'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']
}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
# 1. Create DataFrame
birds = [Link](data, index=labels)
# 2. Display basic info about the DataFrame
print("2. DataFrame info:")
print([Link]())
# 3. Print first two rows
print("\n3. First two rows:")
print([Link](2))
# 4. Display all rows showing only 'birds' and 'age' columns
print("\n4. 'birds' and 'age' columns:")
print(birds[['birds', 'age']])
# 5. Select rows at index positions [2,3,7] and columns ['birds','age','visits']
print("\n5. Selected rows and columns:")
print([Link][['c', 'd', 'h'], ['birds', 'age', 'visits']])
# 6. Rows where visits < 4
print("\n6. Rows where visits < 4:")
print(birds[birds['visits'] < 4])
# 7. Rows where 'age' is missing, display 'birds' and 'visits'
print("\n7. Rows with missing age:")
print(birds[birds['age'].isna()][['birds', 'visits']])
# 8. Rows where bird is 'Cranes' and age < 4
print("\n8. 'Cranes' with age < 4:")
print(birds[(birds['birds'] == 'Cranes') & (birds['age'] < 4)])
# 9. Rows where age is between 2 and 4 inclusive
print("\n9. Age between 2 and 4 inclusive:")
print(birds[birds['age'].between(2, 4)])
# 10. Total visits for bird type 'Cranes'
total_visits_cranes = [Link][birds['birds'] == 'Cranes', 'visits'].sum()
print("\n10. Total visits for 'Cranes':", total_visits_cranes)
# 11. Mean age for each unique bird type
mean_age_per_bird = [Link]('birds')['age'].mean()
print("\n11. Mean age per bird type:")
print(mean_age_per_bird)
# 12. Append a new row 'k', then delete it to restore original DataFrame
new_row = [Link]({'birds': ['eagle'], 'age': [5], 'visits': [1], 'priority': ['yes']}, index=['k'])
birds = [Link]([birds, new_row])
print("\n12. After appending new row 'k':")
print([Link]['k'])
birds = [Link]('k') # Remove appended row to restore
print("After deleting row 'k':")
print([Link]())
# 13. Count occurrences of each bird type
bird_counts = birds['birds'].value_counts()
print("\n13. Count of each bird type:")
print(bird_counts)
# 14. Sort DataFrame by 'age' descending, then 'visits' ascending
sorted_birds = birds.sort_values(by=['age', 'visits'], ascending=[False, True])
print("\n14. Sorted by age desc and visits asc:")
print(sorted_birds)
# 15. Replace 'priority' column values: 'yes'->1, 'no'->0
birds['priority'] = birds['priority'].map({'yes': 1, 'no': 0})
print("\n15. 'priority' replaced with 1 and 0:")
print(birds)
# 16. Replace all 'Cranes' in 'birds' column with 'trumpeters'
birds['birds'] = birds['birds'].replace('Cranes', 'trumpeters')
print("\n16. 'birds' column after replacing 'Cranes' with 'trumpeters':")
print(birds)
Output-
Assignment No:– 9
Source Code:
1. To create the above dataframe
import pandas as pd
# Creating the DataFrame
data = {
'employee': ['Sahay', 'George', 'Priya', 'Manila', 'Raina', 'Manila', 'Priya'],
'sales': [125600, 235600, 213400, 189000, 456000, 172000, 201400],
'Quarter': [1, 1, 1, 1, 1, 2, 2],
'State': ['Delhi', 'Tamil Nadu', 'Kerala', 'Haryana', 'West Bengal', 'Haryana', 'Kerala']
}
df = [Link](data)
print(df)
2. To find total sales per state.
state_sales = [Link]('State')['sales'].sum()
print(state_sales)
3. To find total sales per employee
employee_sales = [Link]('employee')['sales'].sum()
print(employee_sales)
4. To find average sales on both employee and state wise
avg_employee_sales = [Link]('employee')['sales'].mean()
print(avg_employee_sales)
5. To find mean,median and minimum sale statewise
state_stats = [Link]('State')['sales'].agg(['mean', 'median', 'min'])
print(state_stats)
6. To find maximum sales quarter-wise
max_sales_quarter = [Link]('Quarter')['sales'].max()
print(max_sales_quarter)
Output-
Assignment No:– 10
Source Code:
1. Import the necessary libraries
import pandas as pd
import numpy as np
2. Import the dataset and assign it to drinks
url = '[Link]
drinks = pd.read_csv(url)
# View the first few rows
print([Link]())
3. Which continent drinks more beer on average?
beer_avg = [Link]('continent')['beer_servings'].mean()
print("Average beer consumption per continent:")
print(beer_avg)
# Continent with max average beer consumption
most_beer = beer_avg.idxmax()
print(f"\nContinent that drinks most beer on average: {most_beer}")
4. For each continent, print statistics for wine consumption
wine_stats = [Link]('continent')['wine_servings'].describe()
print("\nWine Consumption Statistics per Continent:")
print(wine_stats)
5. Mean alcohol consumption per continent for every column
mean_alcohol = [Link]('continent').mean(numeric_only=True)
print("\nMean Alcohol Consumption per Continent:")
print(mean_alcohol)
6. Median alcohol consumption per continent for every column
median_alcohol = [Link]('continent').median(numeric_only=True)
print("\nMedian Alcohol Consumption per Continent:")
print(median_alcohol)
7. Mean, Min, and Max for Spirit Consumption
spirit_stats = drinks['spirit_servings'].agg(['mean', 'min', 'max'])
print("\nStatistics for Spirit Consumption:")
print(spirit_stats)
Output-
Assignment No:– 11
Source Code:
1. Generate a random array of 50 integers and display them using a line chart, scatter
plot, histogram and box plot. Apply appropriate color, labels and styling options.
import numpy as np
import [Link] as plt
# Set random seed for reproducibility
[Link](42)
# Generate 50 random integers between 10 and 100
data = [Link](10, 100, 50)
# ========== Line Chart ==========
[Link](figsize=(8, 4))
[Link](data, color='blue', marker='o', linestyle='-', linewidth=2)
[Link]("Line Chart of Random Integers", fontsize=14)
[Link]("Index", fontsize=12)
[Link]("Value", fontsize=12)
[Link](True)
plt.tight_layout()
[Link]()
# ========== Scatter Plot ==========
[Link](figsize=(8, 4))
[Link](range(len(data)), data, color='green', edgecolors='black', s=70)
[Link]("Scatter Plot of Random Integers", fontsize=14)
[Link]("Index", fontsize=12)
[Link]("Value", fontsize=12)
[Link](True)
plt.tight_layout()
[Link]()
# ========== Histogram ==========
[Link](figsize=(8, 4))
[Link](data, bins=10, color='orange', edgecolor='black')
[Link]("Histogram of Random Integers", fontsize=14)
[Link]("Value", fontsize=12)
[Link]("Frequency", fontsize=12)
[Link](axis='y')
plt.tight_layout()
[Link]()
# ========== Box Plot ==========
[Link](figsize=(6, 4))
[Link](data, patch_artist=True,
boxprops=dict(facecolor='purple', color='black'),
medianprops=dict(color='yellow'))
[Link]("Box Plot of Random Integers", fontsize=14)
[Link]("Value", fontsize=12)
plt.tight_layout()
[Link]()
2. Add two outliers to the above data and display the box plot
import numpy as np
import [Link] as plt
# Original data (same seed for consistency)
[Link](42)
data = [Link](10, 100, 50)
# Add two outliers
data_with_outliers = [Link](data, [200, 250])
# ========== Box Plot with Outliers ==========
[Link](figsize=(6, 4))
[Link](data_with_outliers, patch_artist=True,
boxprops=dict(facecolor='red', color='black'),
medianprops=dict(color='yellow'),
flierprops=dict(marker='o', markerfacecolor='blue', markersize=10, linestyle='none'))
[Link]("Box Plot with Outliers", fontsize=14)
[Link]("Value", fontsize=12)
plt.tight_layout()
[Link]()
3. Create two lists, one representing subject names and the other representing marks
obtained in those subjects. Display the data in a pie chart and bar chart
import [Link] as plt
# Subject names and corresponding marks
subjects = ['Math', 'Science', 'English', 'History', 'Geography']
marks = [88, 92, 75, 85, 80]
# ===== Bar Chart =====
[Link](figsize=(8, 5))
[Link](subjects, marks, color='skyblue', edgecolor='black')
[Link]("Marks Obtained in Subjects", fontsize=14)
[Link]("Subjects", fontsize=12)
[Link]("Marks", fontsize=12)
[Link](0, 100)
[Link](axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
[Link]()
# ===== Pie Chart =====
[Link](figsize=(6, 6))
colors = ['gold', 'lightgreen', 'lightcoral', 'lightskyblue', 'violet']
[Link](marks, labels=subjects, autopct='%1.1f%%', startangle=140, colors=colors)
[Link]("Marks Distribution by Subject", fontsize=14)
[Link]('equal') # Equal aspect ratio ensures a perfect circle.
plt.tight_layout()
[Link]()
4. Write a Python program to create a Bar plot to get the frequency of the three
species of the Iris data.
import pandas as pd
import [Link] as plt
# Load the Iris dataset from URL
url = "[Link]
iris = pd.read_csv(url)
# Count frequency of each species
species_counts = iris['species'].value_counts()
# Bar plot using matplotlib
[Link](figsize=(7, 5))
[Link](species_counts.index, species_counts.values, color='orchid', edgecolor='black')
[Link]("Frequency of Iris Species", fontsize=14)
[Link]("Species", fontsize=12)
[Link]("Count", fontsize=12)
[Link](axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
[Link]()
5. Write a Python program to create a Pie plot to get the frequency of the three species
of the Iris data.
import pandas as pd
import [Link] as plt
# Load the Iris dataset from URL
url = "[Link]
iris = pd.read_csv(url)
# Count frequency of each species
species_counts = iris['species'].value_counts()
# Pie chart using matplotlib
[Link](figsize=(6, 6))
colors = ['lightcoral', 'gold', 'lightblue']
[Link](species_counts.values,
labels=species_counts.index,
autopct='%1.1f%%',
startangle=140,
colors=colors)
[Link]("Iris Species Distrib
6. Write a Python program to create a histogram of the three species of the Iris data.
Iris dataset: [Link]
import pandas as pd
import [Link] as plt
# Load the Iris dataset
url = "[Link]
iris = pd.read_csv(url)
# Set figure size
[Link](figsize=(10, 6))
# Plot histogram for each species using different colors
species_list = iris['species'].unique()
colors = ['red', 'green', 'blue']
# Plot sepal_length histogram for each species
for species, color in zip(species_list, colors):
subset = iris[iris['species'] == species]
[Link](subset['sepal_length'],
bins=10,
alpha=0.6,
label=species,
color=color,
edgecolor='black')
# Add titles and labels
[Link]("Histogram of Sepal Length for Each Iris Species", fontsize=14)
[Link]("Sepal Length (cm)", fontsize=12)
[Link]("Frequency", fontsize=12)
[Link]()
[Link](axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
[Link]()
Output-
Assignment No:– 12
Source Code:
1) To create model using simple linear regression (Single variable)
Dataset : [Link]
import pandas as pd
import numpy as np
import [Link] as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from [Link] import mean_squared_error, r2_score
# Step 1: Load the dataset url =
"[Link]
%20student_scores.csv"
# Note: Kaggle files require login, so we use a sample Salary dataset from GitHub for demonstration
# Replace above line with local CSV path if you downloaded from Kaggle
df = pd.read_csv("Salary_Data.csv") # If using local file from Kaggle
# Step 2: Explore the dataset
print([Link]())
print([Link]())
# Step 3: Separate variables
X = df[['YearsExperience']] # independent variable
y = df['Salary'] # dependent variable
# Step 4: Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# Step 5: Train the model
model = LinearRegression()
[Link](X_train, y_train)
# Step 6: Predict on test data
y_pred = [Link](X_test)
# Step 7: Model evaluation
print(f"Intercept: {model.intercept_}")
print(f"Slope: {model.coef_[0]}")
print(f"Mean Squared Error: {mean_squared_error(y_test, y_pred):.2f}")
print(f"R-squared: {r2_score(y_test, y_pred):.2f}")
# Step 8: Plot regression line
[Link](figsize=(8, 5))
[Link](X, y, color='blue', label="Actual data")
[Link](X, [Link](X), color='red', linewidth=2, label="Regression line")
[Link]("Salary vs Years of Experience", fontsize=14)
[Link]("Years of Experience")
[Link]("Salary")
[Link]()
[Link](True)
plt.tight_layout()
[Link]()
Output-
Assignment No:– 13
Source Code:
1. To create model using Multivariate Regression
Dataset: [Link]
import pandas as pd
import numpy as np
import [Link] as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from [Link] import mean_squared_error, r2_score
# Step 1: Load the dataset
df = pd.read_csv("[Link]") # Use the uploaded file
print([Link]())
print([Link]())
# Step 2: Independent & dependent variables
X = df[['Total Experience', 'Team Lead Experience', 'Project Manager Experience', 'Certifications']]
y = df['Salary']
# Step 3: Split into training and testing
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# Step 4: Train the Linear Regression model
model = LinearRegression()
[Link](X_train, y_train)
# Step 5: Make predictions
y_pred = [Link](X_test)
# Step 6: Evaluate the model
print("\nModel Coefficients:")
print("Intercept:", model.intercept_)
print("Coefficients:", model.coef_)
print("\nEvaluation Metrics:")
print("Mean Squared Error:", mean_squared_error(y_test, y_pred))
print("R-squared Score:", r2_score(y_test, y_pred))
# Step 7: Compare actual vs predicted
comparison = [Link]({'Actual Salary': y_test, 'Predicted Salary': y_pred})
print("\nComparison:\n", [Link]())
# Step 8: Plot Actual vs Predicted
[Link](figsize=(8, 5))
[Link](y_test, y_pred, color='green')
[Link]([[Link](), [Link]()], [[Link](), [Link]()], 'r--', lw=2)
[Link]('Actual Salary')
[Link]('Predicted Salary')
[Link]('Actual vs Predicted Salary (Multivariate Regression)')
[Link](True)
plt.tight_layout()
[Link]()
Output-
Assignment No:– 14
Source Code:
1. To create model using Logistic Regression(Dataset:
# [Link]
import pandas as pd
import numpy as np
import [Link] as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from [Link] import StandardScaler
from [Link] import classification_report, confusion_matrix, accuracy_score
df = pd.read_csv('Social_Network_Ads.csv')
print([Link]())
# Drop User ID and Gender (optional, depending on use)
df = [Link](['User ID'], axis=1)
# Encode Gender (optional)
df['Gender'] = df['Gender'].map({'Male': 0, 'Female': 1})
# Features and target
X = df[['Age', 'EstimatedSalary']]
y = df['Purchased']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = [Link](X_test)
model = LogisticRegression()
[Link](X_train, y_train)
y_pred = [Link](X_test)
print("Accuracy Score:", accuracy_score(y_test, y_pred))
print("Classification Report:\n", classification_report(y_test, y_pred))
# Confusion Matrix
[Link](confusion_matrix(y_test, y_pred), annot=True, fmt='d', cmap='Blues')
[Link]('Confusion Matrix')
[Link]('Predicted')
[Link]('Actual')
[Link]()
2. To create model using KNN(Dataset: [Link]
network-ads)
import pandas as pd
import numpy as np
import [Link] as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from [Link] import KNeighborsClassifier
from [Link] import accuracy_score, confusion_matrix, classification_report
df = pd.read_csv("Social_Network_Ads.csv")
print([Link]())
# Drop User ID column
df = [Link](['User ID'], axis=1)
# Encode Gender (optional step, since we're using only numerical features)
df['Gender'] = df['Gender'].map({'Male': 0, 'Female': 1})
# Features and Target
X = df[['Age', 'EstimatedSalary']]
y = df['Purchased']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = [Link](X_test)
knn = KNeighborsClassifier(n_neighbors=5) # you can tune 'k'
[Link](X_train, y_train)
y_pred = [Link](X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Classification Report:\n", classification_report(y_test, y_pred))
# Confusion Matrix
[Link](confusion_matrix(y_test, y_pred), annot=True, fmt='d', cmap='Blues')
[Link]('KNN Confusion Matrix')
[Link]('Predicted')
[Link]('Actual')
[Link]()
3. To create model using SVM (Dataset: [Link]
network-ads)
import pandas as pd
import numpy as np
import [Link] as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from [Link] import SVC
from [Link] import accuracy_score, confusion_matrix, classification_report
df = pd.read_csv('Social_Network_Ads.csv')
print([Link]())
# Drop unnecessary columns
df = [Link](['User ID'], axis=1)
# Optionally encode Gender
df['Gender'] = df['Gender'].map({'Male': 0, 'Female': 1})
# Select features and target
X = df[['Age', 'EstimatedSalary']]
y = df['Purchased']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = [Link](X_test)
# Create SVM classifier (linear, rbf, poly kernels available)
model = SVC(kernel='rbf', random_state=42)
[Link](X_train, y_train)
y_pred = [Link](X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Classification Report:\n", classification_report(y_test, y_pred))
# Confusion Matrix
[Link](confusion_matrix(y_test, y_pred), annot=True, fmt='d', cmap='Blues')
[Link]('SVM Confusion Matrix')
[Link]('Predicted')
[Link]('Actual')
[Link]()
4. To create model using Disease Tree (Dataset:
[Link]
# Step 1: Import Libraries
import pandas as pd
import numpy as np
import [Link] as plt
from sklearn.model_selection import train_test_split
from [Link] import DecisionTreeClassifier, plot_tree
from [Link] import accuracy_score, classification_report, confusion_matrix
# Step 2: Load Dataset
data = pd.read_csv('Social_Network_Ads2.csv')
print("First 5 rows of the dataset:")
print([Link]())
# Step 3: Preprocess Data
# Drop unnecessary columns
data = [Link](['User ID'], axis=1)
# Convert 'Gender' to numeric
data['Gender'] = data['Gender'].map({'Male': 1, 'Female': 0})
# Separate features and target
X = data[['Age', 'EstimatedSalary', 'Gender']]
y = data['Purchased']
# Step 4: Split Data into Training and Testing Sets
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0 )
# Step 5: Train Decision Tree Model
clf = DecisionTreeClassifier(criterion='entropy', random_state=0)
[Link](X_train, y_train)
# Step 6: Make Predictions
y_pred = [Link](X_test)
# Step 7: Evaluate the Model
print("\nModel Accuracy:", accuracy_score(y_test, y_pred))
print("\nConfusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))
# Step 8: Visualize the Decision Tree
[Link](figsize=(18,10))
plot_tree(
clf,
filled=True,
feature_names=list([Link]),
class_names=['Not Purchased', 'Purchased'],
rounded=True,
fontsize=10
)
[Link]("Decision Tree Visualization", fontsize=16)
[Link]()
5. To create model using Random forest (Dataset:
[Link]
import pandas as pd
import numpy as np
import [Link] as plt
from sklearn.model_selection import train_test_split
from [Link] import RandomForestClassifier
from [Link] import accuracy_score, classification_report, confusion_matrix
# Load the CSV file
data = pd.read_csv('Social_Network_Ads.csv')
print([Link]())
# Drop the 'User ID' column
data = [Link](['User ID'], axis=1)
# Convert 'Gender' to numeric (optional)
data['Gender'] = data['Gender'].map({'Male': 1, 'Female': 0})
# Define features and target
X = data[['Age', 'EstimatedSalary', 'Gender']] # You may exclude 'Gender' if needed
y = data['Purchased']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
# Create Random Forest model
rf_model = RandomForestClassifier(n_estimators=100, criterion='entropy', random_state=42)
rf_model.fit(X_train, y_train)
y_pred = rf_model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("Classification Report:\n", classification_report(y_test, y_pred))
Output-
Assignment No:– 15
Source Code:
import pandas as pd
data = pd.read_csv('[Link]')
# Step 2: Preprocess
data['Age'].fillna(data['Age'].mean(), inplace=True)
data['Embarked'].fillna('S', inplace=True)
data['Fare'].fillna(data['Fare'].mean(), inplace=True)
X = data[features]
y = data['Survived']
X, y, test_size=0.2, random_state=42 )
model = LogisticRegression(max_iter=200)
[Link](X_train, y_train)
y_pred = [Link](X_test)
Output-
Assignment No:– 16
Source Code:
# Step 1: Import Libraries
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from [Link] import LabelEncoder
from [Link] import RandomForestRegressor
from [Link] import mean_squared_error, r2_score
# Step 2: Load Dataset
train = pd.read_csv('[Link]') # renamed for your dataset
test = pd.read_csv('[Link]') # renamed for your dataset
# Step 3: Basic Exploration
print([Link])
print([Link])
print(train['price'].describe())
# Step 4: Handle Missing Data
[Link]([Link](numeric_only=True), inplace=True)
[Link]([Link](numeric_only=True), inplace=True)
# Step 5: Encode Categorical Features
cat_cols = train.select_dtypes(include=['object']).columns
for col in cat_cols:
le = LabelEncoder()
train[col] = le.fit_transform(train[col].astype(str))
# Apply same transformation to test set
if col in [Link]:
test[col] = [Link](test[col].astype(str))
# Step 6: Feature Selection
X = [Link](['price', 'date'], axis=1) # 'date' dropped as feature
y = train['price']
# Step 7: Split Data
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.2, random_state=42 )
# Step 8: Train Random Forest Regressor
model = RandomForestRegressor(n_estimators=100, random_state=42)
[Link](X_train, y_train)
# Step 9: Evaluation
y_pred = [Link](X_val)
mse = mean_squared_error(y_val, y_pred)
r2 = r2_score(y_val, y_pred)
print(f'MSE: {mse}')
print(f'R2 Score: {r2}')
# Step 10: Predict on Test Set
X_test = [Link](['date', 'price'], axis=1, errors='ignore') # drop date & price if present
predictions = [Link](X_test)
# Step 11: Save Submission
submission = [Link]({
'date': test['date'] if 'date' in [Link] else [Link](len(predictions)),
'price': predictions })
submission.to_csv('[Link]', index=False)
print("Submission saved as [Link]")
Output-