Machine learning code related to variance and covariance using python?

All QuestionsCategory: Artificial Intelligence, Machine Learning, & Deep LearningMachine learning code related to variance and covariance using python?
Chetan Shidling Staff asked 5 years ago

I need code.

1 Answers
Chetan Shidling Staff answered 5 years ago

Code:

import numpy as np
import matplotlib.pyplot as plt
xs = np.array([1, 2, 3, 4, 5, 6], dtype = float)
ys = np.array([5, 4, 6, 5, 6, 7], dtype = float)
def my_avg(x):
avg = np.sum(x)/len(x)
return(avg)
xbar = my_avg(xs)
ybar = my_avg(ys)
cv = (np.sum((xs-xbar)*(ys-ybar)))
covariance = (cv)/len(xs)
variance = np.sum((xs-xbar)**2)/len(xs)
print(‘variance’, variance)
print(‘covariance’, covariance)
slope = covariance/variance
print(‘slope’, slope)
intercept = ybar – (slope*xbar)
print(‘intercept’, intercept)
sd = np.sqrt(variance)
print(‘standard deviation’, sd)
m = slope
c = intercept
ypredict = m*xs+c
print(‘predicted values’, ypredict)
print(‘actual values’, ys)
regression_line = [(m*x)+c for x in xs] predict_x = 8
predict_y = (m*predict_x)+c
print(‘predicted y’, predict_y)
t1 = np.sum(xs*ys)
t2 = np.sum(xs)
t3 = np.sum(ys)
t4 = np.sum(xs*ys)
t5 = t2*t2
t6 = np.sum(ys*ys)
t7 = t3*t3
n = 6
r = ((n*t1)-(t2*t3))/((np.sqrt((n*t4)-t5))*
(np.sqrt((n*t6)-t7)))
rsq = r*r
print(‘rsquare’, rsq)
plt.scatter(xs, ys)
plt.scatter(predict_x, predict_y, color=’r’)
plt.plot(xs, regression_line)
plt.show()