0% found this document useful (0 votes)
6 views18 pages

NumPy and Matplotlib Usage Examples

python practical lab manual

Uploaded by

alfaiz.r.saiyad
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views18 pages

NumPy and Matplotlib Usage Examples

python practical lab manual

Uploaded by

alfaiz.r.saiyad
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

240183107005

Practical:9
Aim : Develop a program that shows usage of following NumPy library
vector functions. a) arrange() b) reshape() c) linspace() d) randint() e) dot()

Implementation

Prog:
import numpy as np

# a) arange() → create array with range of values


arr1 = [Link](1, 11) # numbers from 1 to 10
print("a) arange(1, 11):\n", arr1, "\n")

# b) reshape() → reshape array into matrix


arr2 = [Link](1, 13) # numbers 1 to 12
reshaped = [Link](3, 4) # 3x4 matrix
print("b) reshape to 3x4 matrix:\n", reshaped, "\n")

# c) linspace() → evenly spaced values in a range


arr3 = [Link](0, 1, 5) # 5 values from 0 to 1
print("c) linspace(0, 1, 5):\n", arr3, "\n")

# d) randint() → generate random integers


arr4 = [Link](1, 20, 5) # 5 random numbers between 1 and 20
print("d) randint(1, 20, 5):\n", arr4, "\n")
240183107005

# e) dot() → dot product of two vectors/matrices


vec1 = [Link]([1, 2, 3])
vec2 = [Link]([4, 5, 6])
dot_product = [Link](vec1, vec2) # (1*4 + 2*5 + 3*6)
print("e) dot product of [1,2,3] and [4,5,6]:\n", dot_product, "\n")

Output:
240183107005

Practical:10
Aim : Write a program to display below plot using matplotlib library. For
Values of X:[1,2,3,...,49], Values of Y (thrice of X):[3,6,9,12,...,144,147]

Implementation

Prog:

import [Link] as plt


import numpy as np

# X values from 1 to 49
X = [Link](1, 50)
# Y values are 3 times X
Y=3*X

print("X values:", X)
print("Y values:", Y)

# Plot
[Link](X, Y, marker='o', color='b', linestyle='-', label="Y = 3X")

# Labels and title


[Link]("X values")
[Link]("Y values")
[Link]("Plot of Y = 3X for X = 1 to 49")
[Link]()
[Link](True)
240183107005

# Show plot
[Link]()

Output:
240183107005

Practical:11
Aim : Write a program to display below bar plot using matplotlib library.
For value Languages = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
Popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]

Implementation

Prog:

import [Link] as plt

# Data
Languages = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
Popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]

# Create bar plot


[Link](Languages, Popularity, color=['red', 'blue', 'green', 'orange', 'purple', 'cyan'])

# Labels and title


[Link]("Programming Languages")
[Link]("Popularity (%)")
[Link]("Popularity of Programming Languages")

# Show plot
[Link]()
240183107005

Output:
240183107005

Practical:12
Aim : Write a program to display below bar plot using matplotlib library
For below data display pie plot
Languages = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
Popuratity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
Colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
"#8c564b"]

Implementation

Prog:
import [Link] as plt

# Data
Languages = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
Popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
Colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"]

# Create pie plot


[Link](Popularity, labels=Languages, colors=Colors, autopct='%1.1f%%',
startangle=140)

# Title
[Link]("Popularity of Programming Languages")

# Show plot
[Link]()
240183107005

Output:
240183107005

Practical:13
Aim : Write a program to display below bar plot using matplotlib library
For 200 random points for both X and Y display scatter plot.

Implementation

Prog:
import [Link] as plt
import numpy as np

# Generate 200 random points for X and Y


x = [Link](200) # random values between 0 and 1
y = [Link](200)

# Create scatter plot


[Link](x, y, color="blue", marker="o", alpha=0.7)

# Title and labels


[Link]("Scatter Plot of 200 Random Points")
[Link]("X Values")
[Link]("Y Values")

# Show plot
[Link]()
240183107005

Output:
240183107005

Practical:14
Aim : Develop a program that reads .csv and plot the data of the dataset
stored in the .csv file file from the url:
([Link]
[Link]?raw=true)

Implementation
Prog :
import pandas as pd
import [Link] as plt

# Corrected URL for the Excel file


# Using the raw GitHub content URL format instead of the repository browser URL
url = "[Link]
[Link]"
# Note: Changed from "sample%[Link]?raw=true" to "[Link]"

# Read the Excel file into a DataFrame


df = pd.read_excel(url)

# Show first few rows to inspect


print("First 5 rows of the dataset:")
print([Link](), "\n")

# Convert the "date" column (if present) to datetime type


if 'date' in [Link]:
df['date'] = pd.to_datetime(df['date'], errors='coerce')

# Example 1: Plot total sales ("ext price") over date (time series)
240183107005

if 'date' in [Link] and 'ext price' in [Link]:


# Aggregate sales by date (sum)
daily = [Link]('date')['ext price'].sum().reset_index()

[Link](figsize=(10, 5))
[Link](daily['date'], daily['ext price'], marker='o', linestyle='-')
[Link]("Date")
[Link]("Total Sales (ext price)")
[Link]("Total Sales Over Time")
[Link](True)
plt.tight_layout()
[Link]()

# Example 2: Bar plot of top customers by total sales


if 'name' in [Link] and 'ext price' in [Link]:
top10 = ([Link]('name')['ext price']
.sum()
.sort_values(ascending=False)
.head(10))
[Link](figsize=(10, 6))
[Link](kind='bar', color='skyblue')
[Link]("Customer Name")
[Link]("Total Sales (ext price)")
[Link]("Top 10 Customers by Sales")
[Link](rotation=45, ha='right')
plt.tight_layout()
[Link]()
240183107005

Output:
240183107005

Practical:15
Aim : Write a text classification pipeline using a custom preprocessor and
CharNGramAnalyzer using data from Wikipedia articles as a training set.
Evaluate the performance on some held out test sets.

Implementation

Prog:

import re
import string
from [Link] import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from [Link] import Pipeline
from sklearn.model_selection import train_test_split
from [Link] import classification_report

def custom_preprocessor(text):
# Lowercase
text = [Link]()
# Remove punctuation
text = [Link]([Link]("", "", [Link]))
# Remove digits
text = [Link](r"\d+", "", text)
return text
240183107005

# (Since we don't have direct Wikipedia articles here, we'll simulate using newsgroups
dataset)
categories = ['[Link]', '[Link]', '[Link]', '[Link]']
data = fetch_20newsgroups(subset='all', categories=categories,
remove=('headers','footers','quotes'))

# Split into train & test


X_train, X_test, y_train, y_test = train_test_split([Link], [Link], test_size=0.2,
random_state=42)

pipeline = Pipeline([
("tfidf", TfidfVectorizer(
preprocessor=custom_preprocessor,
analyzer="char", # character-level analysis
ngram_range=(3, 5), # use char 3-5 grams
max_features=5000
)),
("clf", LogisticRegression(max_iter=1000))
])

# Train
[Link](X_train, y_train)

# Predict
y_pred = [Link](X_test)

print("Classification Report:\n")
print(classification_report(y_test, y_pred, target_names=data.target_names))
240183107005

Output:
240183107005

Practical:16
Aim : Write a text classification pipeline to classify movie reviews as either
positive or negative.
Find a good set of parameters using grid search.
Evaluate the performance on a held out test set.
Implementation

Prog:

import numpy as np
from [Link] import load_files
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from [Link] import Pipeline
from sklearn.model_selection import train_test_split, GridSearchCV
from [Link] import classification_report, accuracy_score

from [Link] import fetch_20newsgroups


categories = ['[Link]', '[Link]'] # binary classification stand-in
reviews = fetch_20newsgroups(subset="all", categories=categories,
remove=('headers','footers','quotes'))

X_train, X_test, y_train, y_test = train_test_split([Link], [Link],


test_size=0.2, random_state=42)

pipeline = Pipeline([
('tfidf', TfidfVectorizer(stop_words='english')),
('clf', LogisticRegression(max_iter=1000))
])
param_grid = {
240183107005

'tfidf__ngram_range': [(1,1), (1,2)], # unigrams, bigrams


'tfidf__max_df': [0.75, 1.0],
'clf__C': [0.1, 1, 10] # Regularization strength
}

grid = GridSearchCV(pipeline, param_grid, cv=3, scoring='accuracy', verbose=2,


n_jobs=-1)

# Train with grid search


[Link](X_train, y_train)
print("Best Parameters:", grid.best_params_)
print("Best CV Accuracy:", grid.best_score_)

# Evaluate on test set


y_pred = [Link](X_test)
print("\nTest Set Accuracy:", accuracy_score(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred,
target_names=reviews.target_names))

Output:

You might also like