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

ML Record

The document outlines various experiments involving machine learning algorithms, including the Candidate-Elimination algorithm, ID3 decision tree, Backpropagation for neural networks, and Naïve Bayesian classifiers. Each experiment includes aims, procedures, and sample programs demonstrating the implementation and results using training datasets. The conclusions indicate successful implementation and output generation for each algorithm.

Uploaded by

sachinlucifer603
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 views38 pages

ML Record

The document outlines various experiments involving machine learning algorithms, including the Candidate-Elimination algorithm, ID3 decision tree, Backpropagation for neural networks, and Naïve Bayesian classifiers. Each experiment includes aims, procedures, and sample programs demonstrating the implementation and results using training datasets. The conclusions indicate successful implementation and output generation for each algorithm.

Uploaded by

sachinlucifer603
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

EXP - 1

Aim:
For a given set of training data examples stored in a .CSV file, implement and
demonstrate the Candidate-Elimination algorithm to output a description of the set of
all hypotheses consistent with the training examples.

Procedure:

1. Initialize G to the set of maximally general hypotheses in H


2. Initialize S to the set of maximally specific hypotheses in H
3. For each training example d, do
a. If d is a positive example
i. Remove from G any hypothesis inconsistent with d
ii. For each hypothesis s in S that is not consistent with d
iii. Remove s from S
iv. Add to S all minimal generalizations h of s such that
1. h is consistent with d, and some member of G is more
general than h
v. Remove from S any hypothesis that is more general than another
hypothesis in S
b. If d is a negative example
i. Remove from S any hypothesis inconsistent with d
ii. For each hypothesis g in G that is not consistent with d
1. Remove g from G
2. Add to G all minimal specializations h of g such that
a. h is consistent with d, and some member of S is more
specific than h
iii. Remove from G any hypothesis that is less general than another
hypothesis in G

Training Example:
Program:

import numpy as np
import pandas as pd
data = [Link](data=pd.read_csv('[Link]'))
concepts = [Link]([Link][:,0:-1])
print(concepts)
target = [Link]([Link][:,-1])
print(target)
def learn(concepts, target):
specific_h = concepts[0].copy()
print("initialization of specific_h and general_h")
print(specific_h)
general_h = [["?" for i in range(len(specific_h))] for i in range(len(specific_h))]
print(general_h)
for i, h in enumerate(concepts):
if target[i] == "yes":
for x in range(len(specific_h)):
if h[x]!= specific_h[x]:
specific_h[x] ='?'
general_h[x][x] ='?'
print(specific_h)
print(specific_h)
if target[i] == "no":
for x in range(len(specific_h)):
if h[x]!= specific_h[x]:
general_h[x][x] = specific_h[x]
else:
general_h[x][x] = '?'
print(" steps of Candidate Elimination Algorithm",i+1)
print(specific_h)
print(general_h)
indices = [i for i, val in enumerate(general_h) if val == ['?', '?', '?', '?', '?', '?']]
for i in indices:
general_h.remove(['?', '?', '?', '?', '?', '?'])
return specific_h, general_h

s_final, g_final = learn(concepts, target)


print("Final Specific_h:", s_final, sep="\n")
print("Final General_h:", g_final, sep="\n")
Output:

Inference:
We have learnt how to use the candidate-elimination algorithm for examples stored in
a .CSV file to output a description of the set of all hypotheses consistent with the
training examples.

Conclusion:
The program for candidate-elimination algorithm for examples stored in a .CSV file to
output a description of the set of all hypotheses consistent with the training examples
has been implemented and the output has been obtained successfully.
EXP - 2

Aim:
To write a program to demonstrate the working of the decision tree based ID3 algorithm.
Use an appropriate data set for building the decision tree and apply this knowledge to
classify a new sample.

Formulas Used:

Procedure:
Input Dataset:
Program:
import math
import csv

def load_csv(filename):
lines = [Link](open(filename, "r"))
dataset = list(lines)
headers = [Link](0)
return dataset, headers

class Node:
def __init__(self, attribute):
[Link] = attribute
[Link] = []
[Link] = ""

def subtables(data, col, delete):


dic = {}
coldata = [row[col] for row in data]
attr = list(set(coldata))
counts = [0] * len(attr)
r = len(data)
c = len(data[0])
for x in range(len(attr)):
for y in range(r):
if data[y][col] == attr[x]:
counts[x] += 1
for x in range(len(attr)):
dic[attr[x]] = [[0 for i in range(c)] for j in range(counts[x])]
pos = 0
for y in range(r):
if data[y][col] == attr[x]:
if delete:
del data[y][col]
dic[attr[x]][pos] = data[y]
pos += 1
return attr, dic
Output:

Inference:
We have learnt how to write a program to demonstrate the working of the decision tree
based ID3 algorithm. Use an appropriate data set for building the decision tree and apply
this knowledge to classify a new sample.

Conclusion:
The program to demonstrate the working of the decision tree based ID3 algorithm. Use
an appropriate data set for building the decision tree and apply this knowledge to
classify a new sample has been implemented and the output has been obtained
successfully.
EXP-3

AIM:
To build an Artificial Neural Network by implementing the Backpropagation algorithm
and test the same using appropriate data sets.

Procedure:
Training Inputs:

Program:
import numpy as np

X = [Link]([[2, 9], [1, 5], [3, 6]], dtype=float)


y = [Link]([[92], [86], [89]], dtype=float)

X = X / [Link](X, axis=0) # maximum of X array longitudinally


y = y / 100

# Sigmoid Function
def sigmoid(x):
return 1 / (1 + [Link](-x))

# Derivative of Sigmoid Function


def derivatives_sigmoid(x):
return x * (1 - x)

# Variable initialization
epoch = 5000 # Setting training iterations
lr = 0.1 # Setting learning rate
input_layer_neurons = 2
hidden_layer_neurons = 3
output_neurons = 1
# number of features in data set
# number of hidden layers neurons
# number of neurons at output layer

# weight and bias initialization


wh = [Link](size=(input_layer_neurons, hidden_layer_neurons))
bh = [Link](size=(1, hidden_layer_neurons))
wout = [Link](size=(hidden_layer_neurons, output_neurons))
bout = [Link](size=(1, output_neurons))

# draws a random range of numbers uniformly of dim x*y


for i in range(epoch):
# Forward Propagation
hinpl = [Link](X, wh)
hinp = hinpl + bh
hlayer_act = sigmoid(hinp)

outinpl = [Link](hlayer_act, wout)


outinp = outinpl + bout
output = sigmoid(outinp)

# Backpropagation
EO = y - output
outgrad = derivatives_sigmoid(output)
d_output = EO * outgrad

EH = d_output.dot(wout.T)
# how much hidden layer wts contributed to error
hiddengrad = derivatives_sigmoid(hlayer_act)
d_hidden_layer = EH * hiddengrad

# dotproduct of next layer error and current layer op


wout += hlayer_act.[Link](d_output) * lr
wh += [Link](d_hidden_layer) * lr

print("Input: \n" + str(X))


print("Actual Output: \n" + str(y))
print("Predicted Output: \n", output)
Output:
Input:
[[0.66666667 1. ]
[0.33333333 0.55555556]
[1. 0.66666667]]

Actual Output:
[[0.92]
[0.86]
[0.89]]

Predicted Output:
[[0.89726759]
[0.87196896]
[0.9000671 ]]

Inference:
We have learnt how to build an Artificial Neural Network by implementing the
Backpropagation algorithm and test the same using appropriate data sets.

Conclusion:
The program to build an Artificial Neural Network by implementing the
Backpropagation algorithm and test the same using appropriate data sets has been
implemented and the output has been obtained successfully.
EXP-4

AIM:
To write a program to implement the naïve Bayesian classifier for a sample training
data set stored as a .CSV file and compute the accuracy with a few test data sets.

Procedure:
Input dataset:

Program:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn import metrics

# Read the CSV file


msg = pd.read_csv('[Link]', names=['message', 'label'])

# Print dataset dimensions


print('The dimensions of the dataset:', [Link])

# Map labels to numeric values


msg['labelnum'] = [Link]({'pos': 1, 'neg': 0})
X = [Link]
y = [Link]
print(X)
print(y)

# Splitting the dataset into train and test data


xtrain, xtest, ytrain, ytest = train_test_split(X, y)
print('\nThe total number of Training Data:', [Link])
print('\nThe total number of Test Data:', [Link])

# Output of count vectorizer is a sparse matrix


count_vect = CountVectorizer()
xtrain_dtm = count_vect.fit_transform(xtrain)
xtest_dtm = count_vect.transform(xtest)

print('\nThe words or Tokens in the text documents:')


print(count_vect.get_feature_names())

# Training Naive Bayes (NB) classifier on training data.


clf = MultinomialNB().fit(xtrain_dtm, ytrain)
predicted = [Link](xtest_dtm)

# Printing accuracy, Confusion matrix, Precision, and Recall


print('\nAccuracy of the classifer is:', metrics.accuracy_score(ytest, predicted))
print('\nConfusion matrix:')
print(metrics.confusion_matrix(ytest, predicted))
print('\nThe value of Precision:', metrics.precision_score(ytest, predicted))
print('\nThe value of Recall:', metrics.recall_score(ytest, predicted))

Output:
Inference:
We have learnt how to write a program to implement the naïve Bayesian classifier for
a sample training data set stored as a .CSV file and compute the accuracy with a few
test data sets.

Conclusion:
The program to write a program to implement the naïve Bayesian classifier for a sample
training data set stored as a .CSV file and compute the accuracy with a few test data sets
has been implemented and the output has been obtained successfully.
EXP-5

AIM:
To write a program to implement a naïve Bayesian Classifier model to classify a set of
documents and measure the accuracy, precision, and recall.

Procedure:
Input dataset:

Program:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn import metrics

# Read the CSV file


msg = pd.read_csv('[Link]', names=['message', 'label'])

# Print dataset dimensions


print('The dimensions of the dataset:', [Link])

# Map labels to numeric values


msg['labelnum'] = [Link]({'pos': 1, 'neg': 0})
X = [Link]
y = [Link]
print(X)
print(y)

# Splitting the dataset into train and test data


xtrain, xtest, ytrain, ytest = train_test_split(X, y)
print('\nThe total number of Training Data:', [Link])
print('\nThe total number of Test Data:', [Link])

# Output of count vectorizer is a sparse matrix


count_vect = CountVectorizer()
xtrain_dtm = count_vect.fit_transform(xtrain)
xtest_dtm = count_vect.transform(xtest)

print('\nThe words or Tokens in the text documents:')


print(count_vect.get_feature_names())

# Training Naive Bayes (NB) classifier on training data.


clf = MultinomialNB().fit(xtrain_dtm, ytrain)
predicted = [Link](xtest_dtm)

# Printing accuracy, Confusion matrix, Precision, and Recall


print('\nAccuracy of the classifer is:', metrics.accuracy_score(ytest, predicted))
print('\nConfusion matrix:')
print(metrics.confusion_matrix(ytest, predicted))
print('\nThe value of Precision:', metrics.precision_score(ytest, predicted))
print('\nThe value of Recall:', metrics.recall_score(ytest, predicted))

Output:
Inference:
We have learnt how to write a program to implement a naïve Bayesian Classifier model
to classify a set of documents and measure the accuracy, precision, and recall.

Conclusion:
The program to implement a naïve Bayesian Classifier model to classify a set of
documents and measure the accuracy, precision, and recall has been implemented and
the output has been obtained successfully.
Exp-6:

Aim:
To write a program to construct a Bayesian network to diagnose CORONA infection
using standard WHO Data Set.

Algorithm:

1. Import necessary libraries:


○ pandas for data manipulation.
○ BayesianNetwork, MaximumLikelihoodEstimator, and
VariableElimination from [Link] and [Link] for
Bayesian network modeling.
2. Load the WHO dataset from a CSV file using pd.read_csv().
3. Define the structure of the Bayesian network:
○ Define the nodes (variables) and their relationships in the network.
4. Initialize a Bayesian network model with the defined structure using
BayesianNetwork().
5. Initialize the Maximum Likelihood Estimator and fit it to the data using
[Link]().
6. Perform inference using Variable Elimination to calculate probabilities given the
evidence provided.
7. Define a function diagnose() to interpret the probability of CORONA infection:
○ If the probability is greater than or equal to 0.5, advise consultation with
a healthcare professional immediately.
○ Otherwise, recommend consulting a healthcare professional for further
evaluation.
8. Provide evidence of symptoms for a test case.
9. Query the Bayesian network model to get the probability of CORONA infection
given the provided symptoms.
10. Print the probability of CORONA infection based on the symptoms.
11. Perform diagnosis based on the probability and print the diagnosis message.

Sample input dataset:

| Fever | Cough | Fatigue | BreathingDifficulty | CORONA | Diagnosis |

|----------|-------------|---------|---------------------|--------|-----------|

| Low | None | Mild | No | No | No |

| High | Persistent | Severe | Yes | Yes | CORONA |

| Low | Persistent | Moderate| Yes | No | No |

| High | Mild | Severe | Yes | Yes | CORONA |

| Low | Mild | Mild | No | No | No |


| High | Persistent | Severe | Yes | Yes | CORONA |

| High | None | Moderate| No | No | No |

| Low | Persistent | Severe | Yes | Yes | CORONA |

Program:
import pandas as pd
from [Link] import BayesianNetwork
from [Link] import MaximumLikelihoodEstimator
from [Link] import VariableElimination

data = pd.read_csv('WHO_dataset.csv')
model = BayesianNetwork([('Fever', 'CORONA'),
('Cough', 'CORONA'),
('Fatigue', 'CORONA'),
('BreathingDifficulty', 'CORONA'),
('CORONA', 'Diagnosis')])
[Link](data, estimator=MaximumLikelihoodEstimator)
infer = VariableElimination(model)
def diagnose(corona_prob):
if corona_prob >= 0.5:
return "You are likely to have CORONA infection. Please consult a healthcare
professional immediately."
else:
return "Your symptoms are not indicative of CORONA infection, but it's still
recommended to consult a healthcare professional for further evaluation."

evidence = {'Fever': 'High', 'Cough': 'Persistent', 'Fatigue': 'Severe',


'BreathingDifficulty': 'Yes'}
query = [Link](variables=['CORONA'], evidence=evidence)

corona_prob = [Link][1]
print(f"The probability of CORONA infection given the symptoms is:
{corona_prob:.2f}")

diagnosis = diagnose(corona_prob)
print(diagnosis)
Output:
The probability of CORONA infection given the symptoms is: 0.80
You are likely to have CORONA infection. Please consult a healthcare professional
immediately.

Inference:
We have learnt how to write a program to construct a Bayesian network to diagnose
CORONA infection using standard WHO Data Set.

Conclusion:
The program to write a program to construct a Bayesian network to diagnose CORONA
infection using standard WHO Data Set.
EXP 7:

Aim:
To apply an EM algorithm to cluster a set of data stored in a .CSV file. Use the same
data set for clustering using the k-Means algorithm.

Algorithm:

1. Import necessary libraries:


○ [Link] for plotting.
○ datasets module from sklearn to load the Iris dataset.
○ KMeans from [Link] for K-Means clustering.
○ [Link] for evaluation metrics.
○ pandas and numpy for data manipulation.
2. Load the Iris dataset using datasets.load_iris().
3. Create a DataFrame X to store the features (sepal length, sepal width, petal
length, petal width) and a DataFrame y to store the target labels.
4. Initialize a KMeans clustering model with n_clusters=3 and fit it to the data.
5. Plot the original classifications and K-Means classifications:
○ Scatter plot the petal length against petal width.
○ Use colormap to distinguish between different target classes
(colormap[[Link]] for original classifications,
colormap[model.labels_] for K-Means classifications).
6. Print the accuracy score and confusion matrix of the K-Means model.
7. Standardize the features using StandardScaler() from [Link].
8. Initialize a Gaussian Mixture Model (GMM) with n_components=3 and fit it to
the standardized features.
9. Predict the cluster labels using the trained GMM.
10. Plot the GMM classifications:
○ Scatter plot the petal length against petal width.
○ Use colormap to distinguish between different predicted clusters
(colormap[y_gmm]).
11. Print the accuracy score and confusion matrix of the GMM model.
Program:
import [Link] as plt
from sklearn import datasets
from [Link] import KMeans
import [Link] as sm
import pandas as pd
import numpy as np

# Load the Iris dataset


iris = datasets.load_iris()
X = [Link]([Link])
[Link] = ['Sepal Length', 'Sepal Width', 'Petal Length', 'Petal Width']
y = [Link]([Link])
[Link] = ['Targets']

# Apply KMeans clustering


model = KMeans(n_clusters=3)
[Link](X)

# Plot the Original Classifications


[Link](figsize=(14, 7))
colormap = [Link](['red', 'lime', 'black'])

[Link](1, 2, 1)
[Link](X['Petal Length'], X['Petal Width'], c=colormap[y['Targets']], s=40)
[Link]('Real Classification')
[Link]('Petal Length')
[Link]('Petal Width')

# Plot the Models Classifications


[Link](1, 2, 2)
[Link](X['Petal Length'], X['Petal Width'], c=colormap[model.labels_], s=40)
[Link]('K Mean Classification')
[Link]('Petal Length')
[Link]('Petal Width')

# Evaluate KMeans
print('The accuracy score of K-Means:', sm.accuracy_score(y, model.labels_))
print('The Confusion matrix of K-Means:', sm.confusion_matrix(y, model.labels_))
# Standardize features
from sklearn import preprocessing
scaler = [Link]()
[Link](X)
xsa = [Link](X)
XS = [Link](xsa, columns=[Link])

# Apply Gaussian Mixture Model


from [Link] import GaussianMixture
gmm = GaussianMixture(n_components=3)
[Link](XS)
y_gmm = [Link](XS)

# Plot the GMM Classifications


[Link](2, 2, 3)
[Link](X['Petal Length'], X['Petal Width'], c=colormap[y_gmm], s=40)
[Link]('GMM Classification')
[Link]('Petal Length')
[Link]('Petal Width')

# Evaluate Gaussian Mixture Model


print('The accuracy score of EM:', sm.accuracy_score(y, y_gmm))
print('The Confusion matrix of EM:', sm.confusion_matrix(y, y_gmm))

[Link]()

Output:
Inference:
We have learnt how to write a program to apply an EM algorithm to cluster a set of data
stored in a .CSV file by using the same data set for clustering using the k-Means
algorithm.

Conclusion:
The program to apply an EM algorithm to cluster a set of data stored in a .CSV file by
using the same data set for clustering using the k-Means algorithm has been obtained
successfully.
EXP-8

Aim:
To write a program to implement k-Nearest Neighbour algorithm to classify the iris data
set. Print both correct and wrong predictions.

Algorithm:

Dataset:

Program:
from sklearn.model_selection import train_test_split
from [Link] import KNeighborsClassifier
from [Link] import classification_report, confusion_matrix
from sklearn import datasets

# Load Iris plants dataset


iris = datasets.load_iris()
# The x variable contains the first four columns of the dataset (i.e. attributes) while
y contains the labels.
X = [Link]
y = [Link]

print('sepal-length', 'sepal-width', 'petal-length', 'petal-width')


print(X)
print('class: 0-Iris-Setosa, 1-Iris-Versicolour, 2-Iris-Virginica')
print(y)

# Splits the dataset into 70% train data and 30% test data.
# This means that out of total 150 records, the training set will contain 105 records
and the test set contains 45 of those records.
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

# Training the model using K-Nearest Neighbors with K=5


classifier = KNeighborsClassifier(n_neighbors=5)
[Link](x_train, y_train)

# Make predictions on the test data


y_pred = [Link](x_test)

# For evaluating an algorithm, confusion matrix, precision, recall, and F1-score are
the most commonly used metrics.
print('Confusion Matrix:')
print(confusion_matrix(y_test, y_pred))
print('Accuracy Metrics:')
print(classification_report(y_test, y_pred))

Output:

sepal-length sepal-width petal-length petal-width


[[5.1 3.5 1.4 0.2]
[4.9 3.0 1.4 0.2]
[4.7 3.2 1.3 0.2]
[4.6 3.1 1.5 0.2]
[5. 3.6 1.4 0.2]
...........................
...........................
[6.2 3.4 5.4 2.3]
[5.9 3. 5.1 1.8]]
class: 0-Iris-Setosa, 1- Iris-Versicolour, 2- Iris-Virginica [0 0 0.0 0 1 1 1 1 1 2 2 2 2 2]
Confusion Matrix
[[20 0 0]
[ 0 10 0]
[0 1 14]]
Accuracy Metrics
Precision Recall fl-score support
0 1.00 1.00 1.00 20
1 0.91 1.00 0.95 10
2 1.00 0.93 0.97 15
Avg / total 0.98 0.98 0.98 45

Inference:
We have learnt how to write a program to implement k-Nearest Neighbour algorithm to
classify the iris data set and to print both correct and wrong predictions.

Conclusion:
The program to implement k-Nearest Neighbour algorithm to classify the iris data set
and to print both correct and wrong predictions has been obtained successfully.
EXP-9:

Aim:
To write a program to implement the non-parametric Locally Weighted Regression
algorithm in order to fit data points. Select an appropriate data set for your experiment
and draw graphs.

Algorithm:

Program:
import numpy as np
from [Link] import figure, show
from [Link] import gridplot

def local_regression(x0, X, Y, tau):


# Add bias term
x0 = np.r_[1, x0]
# Add one to avoid the loss in information
X = np.c_[[Link](len(X)), X]
# Fit model: normal equations with kernel
XW = X.T * radial_kernel(x0, X, tau)
# XTranspose * W
beta = [Link](XW @ X) @ XW @ Y
# Matrix Multiplication or Dot Product
# Predict value
return x0 @ beta # Matrix Multiplication or Dot Product for prediction
def radial_kernel(x0, X, tau):
return [Link](-[Link]((X - x0) ** 2, axis=1) / (2 * tau * tau))
# Weight or Radial Kernel Bias Function

# Generate dataset
n = 1000
X = [Link](-3, 3, num=n)
print("The Data Set (10 Samples) X:\n", X[1:10])
Y = [Link]([Link](X ** 21) ** 0.5)
print("The Fitting Curve Data Set (10 Samples) Y :\n", Y[1:10])
# Jitter X
X += [Link](scale=.1, size=n)
print("Normalized (10 Samples) X:\n", X[1:10])
domain = [Link](-3, 3, num=300)
print("Xo Domain Space (10 Samples):\n", domain[1:10])

def plot_lwr(tau):
# Prediction through regression
prediction = [local_regression(x0, X, Y, tau) for x0 in domain]
plot = figure(plot_width=400, plot_height=400)
[Link] = 'tau=%g' % tau
[Link](X, Y, alpha=.3)
[Link](domain, prediction, line_width=2, color='red')
return plot

show(gridplot([[plot_lwr(10.), plot_lwr(1.)], [plot_lwr(0.1), plot_lwr(0.01)]]))

Output:
Inference:
We have learnt how to write a program to implement the non-parametric Locally
Weighted Regression algorithm in order to fit data points.

Conclusion:
The program to implement the non-parametric Locally Weighted Regression algorithm
in order to fit data points has been implemented and the output has been obtained
successfully.
EXP-10

Aim:
To implement the financial risk analysis using Monte Carlo method.

Algorithm:
1. Define the parameters of the simulation:
- initial_investment: The initial investment amount.
- expected_return: The expected annual return rate (mean).
- volatility: The annual volatility of the investment (standard deviation).
- num_simulations: Number of simulation runs to perform.
- num_years: Number of years for the simulation.
2. Calculate the daily expected return and volatility based on the annual values.
3. Perform the Monte Carlo simulation for each simulation run:
- Initialize the investment value.
- For each year:
- Generate random daily returns based on a normal distribution.
- Calculate the investment value for the next year based on the compounded daily
returns.
4. Analyze the simulation results:
- Compute statistics such as mean, median, and percentiles to understand the
distribution of possible investment values.
5. Output the analysis results.

Program:
import numpy as np

def monte_carlo_simulation(initial_investment, expected_return, volatility,


num_simulations, num_years):
# Calculate daily expected return and volatility
daily_return = expected_return / 252
daily_volatility = volatility / [Link](252)

simulation_results = []

for _ in range(num_simulations):
# Initialize the investment value for each simulation run
investment_value = initial_investment

# Simulate investment value for each year


for _ in range(num_years):
# Generate random daily returns based on normal distribution
daily_returns = [Link](daily_return, daily_volatility, 252)
# Calculate the investment value for the next year
investment_value *= [Link](1 + daily_returns)

simulation_results.append(investment_value)

return simulation_results

# Example parameters
initial_investment = 100000 # $100,000 initial investment
expected_return = 0.08 # 8% expected annual return
volatility = 0.15 # 15% annual volatility
num_simulations = 1000 # Number of simulation runs
num_years = 10 # Number of years for the simulation

# Perform Monte Carlo simulation


simulation_results = monte_carlo_simulation(initial_investment, expected_return,
volatility, num_simulations, num_years)

# Analyze results
mean_investment_value = [Link](simulation_results)
median_investment_value = [Link](simulation_results)
lower_percentile = [Link](simulation_results, 5)
upper_percentile = [Link](simulation_results, 95)

# Print analysis results


print("Mean Investment Value:", mean_investment_value)
print("Median Investment Value:", median_investment_value)
print("5th Percentile (95% Confidence Interval Lower Bound):", lower_percentile)
print("95th Percentile (95% Confidence Interval Upper Bound):", upper_percentile)

Output:
Mean Investment Value: 230208.5987385319
Median Investment Value: 166409.52401170017
5th Percentile (95% Confidence Interval Lower Bound): 78819.26528309725
95th Percentile (95% Confidence Interval Upper Bound): 454439.1850727672

Inference:
We have learnt how to write a program to implement the financial risk analysis using
Monte Carlo method.
Conclusion:
The program to apply an EM algorithm to implement the financial risk analysis using
Monte Carlo method.

You might also like