106 KiB
106 KiB
In [1]:
# Importing various packages
import numpy as np
n = 100
x = np.random.normal(size=n)
print(np.mean(x))
y = 4+3*x+np.random.normal(size=n)
print(np.mean(y))
W = np.vstack((x, y))
C = np.cov(W)
print(C)0.022443845445495113 4.000760768324305 [[ 1.00052738 3.04596527] [ 3.04596527 10.40546987]]
In [2]:
import numpy as np
n = 100
# define two vectors
x = np.random.random(size=n)
y = 4+3*x+np.random.normal(size=n)
#scaling the x and y vectors
x = x - np.mean(x)
y = y - np.mean(y)
variance_x = np.sum(x@x)/n
variance_y = np.sum(y@y)/n
print(variance_x)
print(variance_y)
cov_xy = np.sum(x@y)/n
cov_xx = np.sum(x@x)/n
cov_yy = np.sum(y@y)/n
C = np.zeros((2,2))
C[0,0]= cov_xx/variance_x
C[1,1]= cov_yy/variance_y
C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
C[1,0]= C[0,1]
print(C)0.08808936438772381 1.8955512810801536 [[1. 0.66003687] [0.66003687 1. ]]
In [3]:
import numpy as np
import pandas as pd
n = 10
x = np.random.normal(size=n)
x = x - np.mean(x)
y = 4+3*x+np.random.normal(size=n)
y = y - np.mean(y)
X = (np.vstack((x, y))).T
print(X)
Xpd = pd.DataFrame(X)
print(Xpd)
correlation_matrix = Xpd.corr()
print(correlation_matrix)[[-0.72540078 -2.98990574]
[ 0.96045962 2.58951054]
[ 0.77755709 1.47011271]
[-0.60907896 -0.58087521]
[-0.27034896 -0.53030696]
[-0.22425043 -0.07533845]
[-2.15767447 -6.91457183]
[ 0.95668475 3.51161154]
[ 0.25664022 0.84460603]
[ 1.03541191 2.67515735]]
0 1
0 -0.725401 -2.989906
1 0.960460 2.589511
2 0.777557 1.470113
3 -0.609079 -0.580875
4 -0.270349 -0.530307
5 -0.224250 -0.075338
6 -2.157674 -6.914572
7 0.956685 3.511612
8 0.256640 0.844606
9 1.035412 2.675157
0 1
0 1.000000 0.974962
1 0.974962 1.000000
In [4]:
# Common imports
import numpy as np
import pandas as pd
def FrankeFunction(x,y):
term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
return term1 + term2 + term3 + term4
def create_X(x, y, n ):
if len(x.shape) > 1:
x = np.ravel(x)
y = np.ravel(y)
N = len(x)
l = int((n+1)*(n+2)/2) # Number of elements in beta
X = np.ones((N,l))
for i in range(1,n+1):
q = int((i)*(i+1)/2)
for k in range(i+1):
X[:,q+k] = (x**(i-k))*(y**k)
return X
# Making meshgrid of datapoints and compute Franke's function
n = 4
N = 100
x = np.sort(np.random.uniform(0, 1, N))
y = np.sort(np.random.uniform(0, 1, N))
z = FrankeFunction(x, y)
X = create_X(x, y, n=n)
Xpd = pd.DataFrame(X)
# subtract the mean values and set up the covariance matrix
Xpd = Xpd - Xpd.mean()
covariance_matrix = Xpd.cov()
print(covariance_matrix) 0 1 2 3 4 5 6 7 \
0 0.0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1 0.0 0.087010 0.083890 0.089681 0.085024 0.080592 0.082783 0.078206
2 0.0 0.083890 0.081567 0.087183 0.083033 0.079041 0.080807 0.076604
3 0.0 0.089681 0.087183 0.098391 0.093630 0.089065 0.094407 0.089439
4 0.0 0.085024 0.083033 0.093630 0.089365 0.085248 0.090084 0.085550
5 0.0 0.080592 0.079041 0.089065 0.085248 0.081539 0.085918 0.081782
6 0.0 0.082783 0.080807 0.094407 0.090084 0.085918 0.092964 0.088281
7 0.0 0.078206 0.076604 0.089439 0.085550 0.081782 0.088281 0.084004
8 0.0 0.073941 0.072667 0.084787 0.081289 0.077882 0.083881 0.079972
9 0.0 0.069966 0.068980 0.080432 0.077288 0.074206 0.079747 0.076174
10 0.0 0.075203 0.073623 0.088019 0.084189 0.080482 0.088274 0.084012
11 0.0 0.071049 0.069761 0.083356 0.079897 0.076533 0.083777 0.079875
12 0.0 0.067191 0.066160 0.079008 0.075885 0.072831 0.079572 0.075997
13 0.0 0.063604 0.062799 0.074953 0.072133 0.069360 0.075638 0.072360
14 0.0 0.060267 0.059662 0.071167 0.068621 0.066104 0.071955 0.068949
8 9 10 11 12 13 14
0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1 0.073941 0.069966 0.075203 0.071049 0.067191 0.063604 0.060267
2 0.072667 0.068980 0.073623 0.069761 0.066160 0.062799 0.059662
3 0.084787 0.080432 0.088019 0.083356 0.079008 0.074953 0.071167
4 0.081289 0.077288 0.084189 0.079897 0.075885 0.072133 0.068621
5 0.077882 0.074206 0.080482 0.076533 0.072831 0.069360 0.066104
6 0.083881 0.079747 0.088274 0.083777 0.079572 0.075638 0.071955
7 0.079972 0.076174 0.084012 0.079875 0.075997 0.072360 0.068949
8 0.076277 0.072786 0.079993 0.076185 0.072607 0.069244 0.066082
9 0.072786 0.069575 0.076206 0.072699 0.069396 0.066284 0.063352
10 0.079993 0.076206 0.084959 0.080794 0.076889 0.073225 0.069785
11 0.076185 0.072699 0.080794 0.076957 0.073349 0.069958 0.066767
12 0.072607 0.069396 0.076889 0.073349 0.070015 0.066874 0.063912
13 0.069244 0.066284 0.073225 0.069958 0.066874 0.063961 0.061211
14 0.066082 0.063352 0.069785 0.066767 0.063912 0.061211 0.058654
In [5]:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display
n = 10000
mean = (-1, 2)
cov = [[4, 2], [2, 2]]
X = np.random.multivariate_normal(mean, cov, n)In [6]:
df = pd.DataFrame(X)
# Pandas does the centering for us
df = df -df.mean()
# we center it ourselves
X_centered = X - X.mean(axis=0)In [7]:
print(df.cov())
print(np.cov(X_centered.T))0 1 0 3.935482 1.945984 1 1.945984 1.962204 [[3.93548177 1.94598372] [1.94598372 1.96220435]]
In [8]:
# extract the relevant columns from the centered design matrix of dim n x 2
x = X_centered[:,0]
y = X_centered[:,1]
Cov = np.zeros((2,2))
Cov[0,1] = np.sum(x.T@y)/(n-1.0)
Cov[0,0] = np.sum(x.T@x)/(n-1.0)
Cov[1,1] = np.sum(y.T@y)/(n-1.0)
Cov[1,0]= Cov[0,1]
print("Centered covariance using own code")
print(Cov)
plt.plot(x, y, 'x')
plt.axis('equal')
plt.show()Centered covariance using own code [[3.93548177 1.94598372] [1.94598372 1.96220435]]
In [9]:
# diagonalize and obtain eigenvalues, not necessarily sorted
EigValues, EigVectors = np.linalg.eig(Cov)
# sort eigenvectors and eigenvalues
#permute = EigValues.argsort()
#EigValues = EigValues[permute]
#EigVectors = EigVectors[:,permute]
print("Eigenvalues of Covariance matrix")
for i in range(2):
print(EigValues[i])
FirstEigvector = EigVectors[:,0]
SecondEigvector = EigVectors[:,1]
print("First eigenvector")
print(FirstEigvector)
print("Second eigenvector")
print(SecondEigvector)
#thereafter we do a PCA with Scikit-learn
from sklearn.decomposition import PCA
pca = PCA(n_components = 2)
X2Dsl = pca.fit_transform(X)
print("Eigenvector of largest eigenvalue")
print(pca.components_.T[:, 0])Eigenvalues of Covariance matrix 5.130656204495118 0.7670299149882235 First eigenvector [0.85211808 0.52334957] Second eigenvector [-0.52334957 0.85211808]
Eigenvector of largest eigenvalue [0.85211808 0.52334957]
In [10]:
import numpy as np
import pandas as pd
from IPython.display import display
np.random.seed(100)
# setting up a 10 x 5 vanilla matrix
rows = 10
cols = 5
X = np.random.randn(rows,cols)
df = pd.DataFrame(X)
# Pandas does the centering for us
df = df -df.mean()
display(df)
# we center it ourselves
X_centered = X - X.mean(axis=0)
# Then check the difference between pandas and our own set up
print(X_centered-df)
#Now we do an SVD
U, s, V = np.linalg.svd(X_centered)
c1 = V.T[:, 0]
c2 = V.T[:, 1]
W2 = V.T[:, :2]
X2D = X_centered.dot(W2)
print(X2D)| 0 | 1 | 2 | 3 | 4 | |
|---|---|---|---|---|---|
| 0 | -1.574465 | 0.259153 | 1.197370 | 0.147400 | 0.649382 |
| 1 | 0.689519 | 0.137652 | -1.025709 | 0.210340 | -0.076938 |
| 2 | -0.282727 | 0.351636 | -0.539261 | 1.216683 | 0.340782 |
| 3 | 0.070889 | -0.614808 | 1.074067 | -0.038300 | -1.450257 |
| 4 | 1.794282 | 1.458078 | -0.207545 | -0.442600 | -0.147420 |
| 5 | 1.112383 | 0.647473 | 1.405890 | 0.073598 | -0.276263 |
| 6 | 0.397700 | -1.526744 | -0.712018 | 1.216290 | 0.418506 |
| 7 | -0.280647 | 1.106095 | -1.646283 | -0.956563 | -1.564374 |
| 8 | -0.369139 | -0.751699 | 0.051649 | -0.213103 | 0.967809 |
| 9 | -1.557795 | -1.066837 | 0.401842 | -1.213743 | 1.138775 |
0 1 2 3 4 0 0.0 0.0 0.0 0.0 0.0 1 0.0 0.0 0.0 0.0 0.0 2 0.0 0.0 0.0 0.0 0.0 3 0.0 0.0 0.0 0.0 0.0 4 0.0 0.0 0.0 0.0 0.0 5 0.0 0.0 0.0 0.0 0.0 6 0.0 0.0 0.0 0.0 0.0 7 0.0 0.0 0.0 0.0 0.0 8 0.0 0.0 0.0 0.0 0.0 9 0.0 0.0 0.0 0.0 0.0 [[-1.5378811 0.94639099] [ 0.86145244 -0.89288636] [-0.00445655 -0.81633628] [ 0.07145103 1.00433417] [ 2.03707133 0.48476997] [ 0.72174172 1.4557763 ] [-0.55854694 -1.60673226] [ 1.6999536 -0.43766686] [-1.10405456 -0.31718909] [-2.18673098 0.17953942]]
In [11]:
W2 = V.T[:, :2]
X2D = X_centered.dot(W2)In [12]:
#thereafter we do a PCA with Scikit-learn
from sklearn.decomposition import PCA
pca = PCA(n_components = 2)
X2D = pca.fit_transform(X)
print(X2D)[[-1.5378811 0.94639099] [ 0.86145244 -0.89288636] [-0.00445655 -0.81633628] [ 0.07145103 1.00433417] [ 2.03707133 0.48476997] [ 0.72174172 1.4557763 ] [-0.55854694 -1.60673226] [ 1.6999536 -0.43766686] [-1.10405456 -0.31718909] [-2.18673098 0.17953942]]
In [13]:
pca.components_.T[:, 0]Out [13]:
array([ 0.62373464, 0.5303329 , -0.317367 , -0.01873344, -0.47815203])
In [14]:
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
logreg = LogisticRegression()
logreg.fit(X_train, y_train)
print("Train set accuracy from Logistic Regression: {:.2f}".format(logreg.score(X_train,y_train)))
# We scale the data
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Then perform again a log reg fit
logreg.fit(X_train_scaled, y_train)
print("Train set accuracy scaled data: {:.2f}".format(logreg.score(X_train_scaled,y_train)))
#thereafter we do a PCA with Scikit-learn
from sklearn.decomposition import PCA
pca = PCA(n_components = 2)
X2D_train = pca.fit_transform(X_train_scaled)
# and finally compute the log reg fit and the score on the training data
logreg.fit(X2D_train,y_train)
print("Train set accuracy scaled and PCA data: {:.2f}".format(logreg.score(X2D_train,y_train)))Train set accuracy from Logistic Regression: 0.96 Train set accuracy scaled data: 0.99 Train set accuracy scaled and PCA data: 0.96
/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/linear_model/_logistic.py:465: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
In [15]:
pca = PCA()
pca.fit(X)
cumsum = np.cumsum(pca.explained_variance_ratio_)
d = np.argmax(cumsum >= 0.95) + 1In [16]:
pca = PCA(n_components=0.95)
X_reduced = pca.fit_transform(X)In [17]:
from sklearn.decomposition import KernelPCA
rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
X_reduced = rbf_pca.fit_transform(X)