74 KiB
74 KiB
In [1]:
%matplotlib inline
# Common imports
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn.linear_model as skl
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer
from sklearn.svm import SVR
# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"
if not os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
if not os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
if not os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
def image_path(fig_id):
return os.path.join(FIGURE_ID, fig_id)
def data_path(dat_id):
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
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 = 5
N = 1000
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)
# split in training and test data
X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2)
svm = SVR(gamma='auto',C=10.0)
svm.fit(X_train, y_train)
# The mean squared error and R2 score
print("MSE before scaling: {:.2f}".format(mean_squared_error(svm.predict(X_test), y_test)))
print("R2 score before scaling {:.2f}".format(svm.score(X_test,y_test)))
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
print("Feature min values before scaling:\n {}".format(X_train.min(axis=0)))
print("Feature max values before scaling:\n {}".format(X_train.max(axis=0)))
print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0)))
print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0)))
svm = SVR(gamma='auto',C=10.0)
svm.fit(X_train_scaled, y_train)
print("MSE after scaling: {:.2f}".format(mean_squared_error(svm.predict(X_test_scaled), y_test)))
print("R2 score for scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test)))MSE before scaling: 0.01 R2 score before scaling 0.93 Feature min values before scaling: [1.00000000e+00 1.41420107e-03 2.88341734e-03 1.99996467e-06 4.07773189e-06 8.31409558e-06 2.82835217e-09 5.76673281e-09 1.17578029e-08 2.39730074e-08 3.99985867e-12 8.15531971e-12 1.66278974e-11 3.39026527e-11 6.91241853e-11 5.65660442e-15 1.15332619e-14 2.35151903e-14 4.79451678e-14 9.77554968e-14 1.99313875e-13] Feature max values before scaling: [1. 0.9994806 0.99903305 0.99896146 0.99851415 0.99806703 0.9984426 0.99799552 0.99754863 0.99710195 0.997924 0.99747715 0.9970305 0.99658405 0.9961378 0.99740568 0.99695906 0.99651264 0.99606642 0.99562041 0.99517459] Feature min values after scaling: [ 0. -1.65817693 -1.7043535 -1.08982318 -1.1013048 -1.11354553 -0.87460357 -0.87831229 -0.88217902 -0.88621939 -0.75382462 -0.75510587 -0.75642697 -0.75779143 -0.75920312 -0.67290142 -0.67326895 -0.6736462 -0.67403422 -0.67443411 -0.6748471 ] Feature max values after scaling: [0. 1.69545566 1.70876564 2.17466648 2.18694689 2.19919391 2.57142322 2.5827454 2.59390318 2.60490087 2.91823029 2.92902231 2.9396287 2.95004914 2.96028359 3.22926284 3.23980194 3.25015794 3.26032989 3.27031695 3.28011835] MSE after scaling: 0.01 R2 score for scaled data: 0.97
In [2]:
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.svm import SVC
cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
print(X_train.shape)
print(X_test.shape)
svm = SVC(C=100)
svm.fit(X_train, y_train)
print("Test set accuracy: {:.2f}".format(svm.score(X_test,y_test)))
from sklearn.preprocessing import MinMaxScaler, StandardScaler
scaler = MinMaxScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
print("Feature min values before scaling:\n {}".format(X_train.min(axis=0)))
print("Feature max values before scaling:\n {}".format(X_train.max(axis=0)))
print("Feature min values before scaling:\n {}".format(X_train_scaled.min(axis=0)))
print("Feature max values before scaling:\n {}".format(X_train_scaled.max(axis=0)))
svm.fit(X_train_scaled, y_train)
print("Test set accuracy scaled data with Min-Max scaling: {:.2f}".format(svm.score(X_test_scaled,y_test)))
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
svm.fit(X_train_scaled, y_train)
print("Test set accuracy scaled data with Standar Scaler: {:.2f}".format(svm.score(X_test_scaled,y_test)))In [3]:
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()
# Set up training data
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("Test set accuracy: {:.2f}".format(logreg.score(X_test,y_test)))
# Scale 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)
logreg.fit(X_train_scaled, y_train)
print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))In [4]:
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()
import pandas as pd
# Making a data frame
cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
fig, axes = plt.subplots(15,2,figsize=(10,20))
malignant = cancer.data[cancer.target == 0]
benign = cancer.data[cancer.target == 1]
ax = axes.ravel()
for i in range(30):
_, bins = np.histogram(cancer.data[:,i], bins =50)
ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)
ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)
ax[i].set_title(cancer.feature_names[i])
ax[i].set_yticks(())
ax[0].set_xlabel("Feature magnitude")
ax[0].set_ylabel("Frequency")
ax[0].legend(["Malignant", "Benign"], loc ="best")
fig.tight_layout()
plt.show()
import seaborn as sns
correlation_matrix = cancerpd.corr().round(1)
# use the heatmap function from seaborn to plot the correlation matrix
# annot = True to print the values inside the square
sns.heatmap(data=correlation_matrix, annot=True)
plt.show()
#print eigvalues of correlation matrix
EigValues, EigVectors = np.linalg.eig(correlation_matrix)
print(EigValues)In [5]:
cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)In [6]:
correlation_matrix = cancerpd.corr().round(1)In [2]:
# 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.027415807918754646 3.8865565426978175 [[0.89127346 2.52218052] [2.52218052 7.86214718]]
In [3]:
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.08559532554586834 2.099398759180611 [[1. 0.69599747] [0.69599747 1. ]]
In [4]:
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)[[-4.56954296e-01 -6.51205883e-01]
[ 1.15881900e-01 -1.04911886e-03]
[ 4.32592682e-01 1.22706123e+00]
[ 2.99502923e-01 2.12443057e+00]
[ 1.91693148e-01 2.80749264e-01]
[-1.18324359e-01 -7.94852518e-01]
[ 2.75201645e-01 2.07100110e-01]
[-1.33418344e+00 -3.25900251e+00]
[-1.18763012e+00 -5.66423819e+00]
[ 1.78221992e+00 6.53100705e+00]]
0 1
0 -0.456954 -0.651206
1 0.115882 -0.001049
2 0.432593 1.227061
3 0.299503 2.124431
4 0.191693 0.280749
5 -0.118324 -0.794853
6 0.275202 0.207100
7 -1.334183 -3.259003
8 -1.187630 -5.664238
9 1.782220 6.531007
0 1
0 1.000000 0.958509
1 0.958509 1.000000
In [5]:
# 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.073769 0.075606 0.074790 0.077649 0.080534 0.067305 0.069987
2 0.0 0.075606 0.079673 0.073762 0.077595 0.081684 0.064664 0.067826
3 0.0 0.074790 0.073762 0.080813 0.082450 0.083826 0.075685 0.077834
4 0.0 0.077649 0.077595 0.082450 0.084689 0.086778 0.076249 0.078777
5 0.0 0.080534 0.081684 0.083826 0.086778 0.089716 0.076396 0.079358
6 0.0 0.067305 0.064664 0.075685 0.076249 0.076396 0.072828 0.074274
7 0.0 0.069987 0.067826 0.077834 0.078777 0.079358 0.074274 0.075995
8 0.0 0.072867 0.071304 0.080034 0.081429 0.082530 0.075660 0.077697
9 0.0 0.075957 0.075138 0.082265 0.084197 0.085924 0.076945 0.079349
10 0.0 0.059604 0.056221 0.068849 0.068718 0.068102 0.067542 0.068448
11 0.0 0.061833 0.058690 0.070868 0.070975 0.070625 0.069105 0.070202
12 0.0 0.064246 0.061408 0.072997 0.073388 0.073356 0.070706 0.072022
13 0.0 0.066863 0.064410 0.075240 0.075969 0.076320 0.072335 0.073906
14 0.0 0.069708 0.067735 0.077599 0.078730 0.079541 0.073979 0.075847
8 9 10 11 12 13 14
0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
1 0.072867 0.075957 0.059604 0.061833 0.064246 0.066863 0.069708
2 0.071304 0.075138 0.056221 0.058690 0.061408 0.064410 0.067735
3 0.080034 0.082265 0.068849 0.070868 0.072997 0.075240 0.077599
4 0.081429 0.084197 0.068718 0.070975 0.073388 0.075969 0.078730
5 0.082530 0.085924 0.068102 0.070625 0.073356 0.076320 0.079541
6 0.075660 0.076945 0.067542 0.069105 0.070706 0.072335 0.073979
7 0.077697 0.079349 0.068448 0.070202 0.072022 0.073906 0.075847
8 0.079768 0.081851 0.069226 0.071196 0.073268 0.075446 0.077729
9 0.081851 0.084440 0.069828 0.072043 0.074402 0.076918 0.079600
10 0.069226 0.069828 0.063552 0.064718 0.065872 0.066996 0.068070
11 0.071196 0.072043 0.064718 0.066026 0.067341 0.068649 0.069932
12 0.073268 0.074402 0.065872 0.067341 0.068840 0.070359 0.071884
13 0.075446 0.076918 0.066996 0.068649 0.070359 0.072121 0.073926
14 0.077729 0.079600 0.068070 0.069932 0.071884 0.073926 0.076059
In [11]:
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 [12]:
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 [13]:
print(df.cov())
print(np.cov(X_centered.T))In [14]:
# 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()In [15]:
# 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])Warning:
Output truncated. This notebook contains too many cells to display efficiently.