Python Lab Programs-23pca017 & 23pca018
Python Lab Programs-23pca017 & 23pca018
PCA PROGRAM
AIM:
ALGORITHM:
STEP 2: Import necessary libraries including NumPy, Matplotlib, and scikit-learn's PCA.
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.
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:
AIM:
To Write A Python Program For Forecasting Stock Prices Using Time Series Analysis
(TSA).
ALGORITHM:
c. Display plot.
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: