0% found this document useful (0 votes)
15 views8 pages

Python Lab Programs-23pca017 & 23pca018

Uploaded by

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

Python Lab Programs-23pca017 & 23pca018

Uploaded by

23pca016
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

1.

PCA PROGRAM

AIM:

To Write A Python Program For Classification of IRIS Flower Using PCA.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Import necessary libraries including NumPy, Matplotlib, and scikit-learn's PCA.

STEP 3: Load the Iris dataset using load_iris() function.

STEP 4: Extract features and target labels from the dataset.

STEP 5: Standardize the feature data to have a mean of 0 and a standard deviation of 1.

STEP 6: Initialize PCA with 2 components and fit it to the standardized data to obtain
principal components.

STEP 7: Compute the explained variance ratio for each principal component.

STEP 8: Plot the data points in a 2D scatter plot using the principal components. Color each
point based on its corresponding Iris species.

STEP 9: Set the title, x-axis label, y-axis label, and legend for the plot.

Display the plot: Show the scatter plot to visualize the PCA-transformed data.

STEP 10: Terminate the process.


CODING:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
iris = load_iris()
data = iris.data
target = iris.target
scaler = StandardScaler()
data_standardized = scaler.fit_transform(data)
pca = PCA(n_components=2)
principal_components = pca.fit_transform(data_standardized)
explained_variance_ratio = pca.explained_variance_ratio_
print("Explained variance ratio:", explained_variance_ratio)
plt.figure(figsize=(5,5))
for i, color in zip(range(len(np.unique(target))), ['plum', 'purple','green']):
plt.scatter(principal_components[target == i, 0],
principal_components[target == i, 1],
label=iris.target_names[i],
color=color)
plt.title('PCA of Iris Dataset')
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.legend()
plt.show()
OUTPUT:

Explained Variance Ratio:[0.72962445 0.22850762]


2.FORECASTING STOCK PRICES

AIM:

To Write A Python Program For Forecasting Stock Prices Using Time Series Analysis
(TSA).

ALGORITHM:

STEP 1: Start the program.

STEP 2: Import Libraries-Import numpy, pandas, and matplotlib libraries.

STEP 3: Set Random Seed-Set the random seed for reproducibility.

STEP 4: Generate Components-

a. Create time steps array t.

b. Compute trend, seasonality, and noise components.

c. Combine components to obtain simulated stock prices.

STEP 5: Create DataFrame –

a. Generate date index.

b. Create Data Frame df with dates and stock prices.

c. Set date column as index.

STEP 6: Plot Historical Data-

a. Plot historical stock prices against dates.

b. Set plot attributes: title, xlabel, ylabel.

c. Display plot.

STEP 7: Forecast Future Data-

a. Generate future dates.

b. Forecast future trend and seasonality components.

c. Combine components to obtain forecasted stock prices.


STEP 8: Plot Forecasted Data-

a. Plot historical stock prices with a label.

b. Plot forecasted stock prices with a dashed line and label.

c. Set plot attributes: title, xlabel, ylabel, legend. d. Display plot.

STEP 9: Terminate the program


CODING:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(0)
t = np.arange(100)
trend = 0.5 * t
seasonality = 10 * np.sin(2 * np.pi * t / 12)
noise = np.random.normal(0, 5, 100)
stock_prices = trend + seasonality + noise
dates = pd.date_range(start='2022-01-01', periods=len(t), freq='MS')
df = pd.DataFrame({'Date': dates, 'Price': stock_prices})
df.set_index('Date', inplace=True)
plt.figure(figsize=(10, 6))
plt.plot(df.index, df['Price'])
plt.title('Simulated Stock Prices')
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()
trend_component = trend
seasonality_component = seasonality
residual_component = noise
future_dates = pd.date_range(start='2024-05-01', periods=12, freq='MS')
future_trend = 0.5 * np.arange(101, 113)
future_seasonality = 10 * np.sin(2 * np.pi * np.arange(101, 113) / 12)
future_stock_prices = future_trend + future_seasonality
plt.figure(figsize=(10, 6))
plt.plot(df.index, df['Price'], label='Historical Data')
plt.plot(future_dates, future_stock_prices, label='Forecast', linestyle='--')
plt.title('Forecasted Stock Prices')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()
OUTPUT:

You might also like