103 KiB
103 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.2310524795427768 3.1831903689627863 [[0.86117632 2.59603122] [2.59603122 9.06044826]]
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.08745913868064381 2.1128123336365077 [[1. 0.6798478] [0.6798478 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)[[ 1.21030078 4.50152769]
[ 0.85231126 2.49259646]
[-0.27754082 -0.99161035]
[-0.05499028 -0.95681341]
[ 0.65405197 0.57844946]
[ 0.12802926 0.88441436]
[ 0.43424077 1.60051748]
[-1.57205214 -3.89834457]
[-0.77949144 -1.89899948]
[-0.59485937 -2.31173763]]
0 1
0 1.210301 4.501528
1 0.852311 2.492596
2 -0.277541 -0.991610
3 -0.054990 -0.956813
4 0.654052 0.578449
5 0.128029 0.884414
6 0.434241 1.600517
7 -1.572052 -3.898345
8 -0.779491 -1.898999
9 -0.594859 -2.311738
0 1
0 1.000000 0.957565
1 0.957565 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.091583 0.077830 0.092209 0.086333 0.080182 0.084446 0.080360
2 0.0 0.077830 0.067325 0.077735 0.073465 0.068967 0.071391 0.068389
3 0.0 0.092209 0.077735 0.099350 0.092714 0.085784 0.094735 0.090145
4 0.0 0.086333 0.073465 0.092714 0.086992 0.080974 0.088533 0.084586
5 0.0 0.080182 0.068967 0.085784 0.080974 0.075877 0.082067 0.078752
6 0.0 0.084446 0.071391 0.094735 0.088533 0.082067 0.092739 0.088427
7 0.0 0.080360 0.068389 0.090145 0.084586 0.078752 0.088427 0.084585
8 0.0 0.076446 0.065511 0.085713 0.080765 0.075532 0.084250 0.080847
9 0.0 0.072627 0.062704 0.081361 0.076998 0.072349 0.080136 0.077151
10 0.0 0.076483 0.065094 0.088105 0.082612 0.076881 0.087850 0.084014
11 0.0 0.073208 0.062649 0.084453 0.079459 0.074213 0.084413 0.080946
12 0.0 0.070145 0.060358 0.081016 0.076483 0.071690 0.081166 0.078040
13 0.0 0.067263 0.058198 0.077760 0.073657 0.069286 0.078077 0.075268
14 0.0 0.064527 0.056149 0.074647 0.070949 0.066978 0.075114 0.072600
8 9 10 11 12 13 14
0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1 0.076446 0.072627 0.076483 0.073208 0.070145 0.067263 0.064527
2 0.065511 0.062704 0.065094 0.062649 0.060358 0.058198 0.056149
3 0.085713 0.081361 0.088105 0.084453 0.081016 0.077760 0.074647
4 0.080765 0.076998 0.082612 0.079459 0.076483 0.073657 0.070949
5 0.075532 0.072349 0.076881 0.074213 0.071690 0.069286 0.066978
6 0.084250 0.080136 0.087850 0.084413 0.081166 0.078077 0.075114
7 0.080847 0.077151 0.084014 0.080946 0.078040 0.075268 0.072600
8 0.077525 0.074225 0.080285 0.077563 0.074977 0.072501 0.070112
9 0.074225 0.071304 0.076603 0.074208 0.071924 0.069731 0.067608
10 0.080285 0.076603 0.084360 0.081287 0.078374 0.075595 0.072921
11 0.077563 0.074208 0.081287 0.078509 0.075868 0.073341 0.070901
12 0.074977 0.071924 0.078374 0.075868 0.073479 0.071184 0.068960
13 0.072501 0.069731 0.075595 0.073341 0.071184 0.069105 0.067084
14 0.070112 0.067608 0.072921 0.070901 0.068960 0.067084 0.065252
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.923640 1.961854 1 1.961854 1.947452 [[3.92363958 1.96185372] [1.96185372 1.94745179]]
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.92363958 1.96185372] [1.96185372 1.94745179]]
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.132179379442221 0.7389119925478163 First eigenvector [0.85141702 0.52448933] Second eigenvector [-0.52448933 0.85141702]
Eigenvector of largest eigenvalue [0.85141702 0.52448933]
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.95 Train set accuracy scaled data: 0.99 Train set accuracy scaled and PCA data: 0.96
/Users/mhjensen/opt/anaconda3/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: 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)