299 KiB
299 KiB
In [1]:
import numpy as npIn [2]:
n = 10
x = np.random.normal(size=n)
print(x)
print(x[1])[-1.40156441 -0.28390886 -0.77030319 1.72164112 -0.05756168 -0.77474089 1.24566209 1.96410269 0.04055138 0.38110718] -0.2839088573652084
In [3]:
import numpy as np
x = np.array([1, 2, 3])
print(x)[1 2 3]
In [4]:
import numpy as np
x = np.log(np.array([4, 7, 8]))
print(x)[1.38629436 1.94591015 2.07944154]
In [5]:
import numpy as np
from math import log
x = np.array([4, 7, 8])
for i in range(0, len(x)):
x[i] = log(x[i])
print(x)[1 1 2]
In [6]:
import numpy as np
x = np.log(np.array([4, 7, 8], dtype = np.float64))
print(x)[1.38629436 1.94591015 2.07944154]
In [8]:
import numpy as np
x = np.log(np.array([4.0, 7.0, 8.0]))
print(x)[1.38629436 1.94591015 2.07944154]
In [10]:
import numpy as np
x = np.log(np.array([4.0, 7.0, 8.0]))
print(x.itemsize)8
In [11]:
import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
print(A)[[1.38629436 1.94591015 2.07944154] [1.09861229 2.30258509 2.39789527] [1.38629436 1.60943791 1.94591015]]
In [12]:
import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
# print the first column, row-major order and elements start with 0
print(A[:,0])[1.38629436 1.09861229 1.38629436]
In [13]:
import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
# print the first column, row-major order and elements start with 0
print(A[1,:])[1.09861229 2.30258509 2.39789527]
In [14]:
import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to zero
A = np.zeros( (n, n) )
print(A)[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
In [41]:
import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to one
A = np.eye( n )
print(A)[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 1. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 1. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 1. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 1. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 1. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 1. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]
In [16]:
import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \in [0, 1]
A = np.random.rand(n, n)
print(A)[[0.13883235 0.16578794 0.83591324 0.53093229 0.43828658 0.44147294 0.81058042 0.90471242 0.75985306 0.65015412] [0.5367777 0.62064869 0.5730995 0.44783891 0.55254031 0.22916951 0.62502415 0.72544464 0.28186865 0.24079007] [0.87309444 0.39639182 0.48916514 0.37108014 0.70819769 0.30059633 0.50624688 0.97434081 0.08628836 0.07529887] [0.93778677 0.80013962 0.75663638 0.52493405 0.91289002 0.62967827 0.18833956 0.69572614 0.63064934 0.58702011] [0.38917221 0.40771118 0.52341532 0.086439 0.41964853 0.82852196 0.75017796 0.72808162 0.80634896 0.85284583] [0.50492119 0.70610108 0.6424576 0.99407265 0.37489802 0.06411849 0.49740309 0.64476141 0.80370131 0.20204962] [0.99276881 0.97391374 0.10766979 0.76043228 0.38014282 0.33403001 0.33157174 0.44297261 0.35781497 0.1575419 ] [0.98529248 0.56354013 0.72044581 0.26099864 0.20825739 0.90771836 0.54856735 0.31785249 0.7272262 0.38895366] [0.74084311 0.31846284 0.34420921 0.43345144 0.05781962 0.35254955 0.4309125 0.84639667 0.63585381 0.89812415] [0.64935106 0.15417975 0.0916722 0.85895396 0.39864154 0.1850318 0.76465137 0.4577945 0.075374 0.93877457]]
In [17]:
# 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))
z = x**3+np.random.normal(size=n)
print(np.mean(z))
W = np.vstack((x, y, z))
Sigma = np.cov(W)
print(Sigma)
Eigvals, Eigvecs = np.linalg.eig(Sigma)
print(Eigvals)0.20381774252138393 4.6822329078411125 0.4103425751132706 [[ 0.94483537 2.78661332 2.62703645] [ 2.78661332 8.9863123 7.90574506] [ 2.62703645 7.90574506 11.15801875]] [18.86323713 0.06809913 2.15783016]
In [19]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import sparse
eye = np.eye(4)
print(eye)
sparse_mtx = sparse.csr_matrix(eye)
print(sparse_mtx)
x = np.linspace(-10,10,100)
y = np.sin(x)
plt.plot(x,y,marker='x')
plt.show()[[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]] (0, 0) 1.0 (1, 1) 1.0 (2, 2) 1.0 (3, 3) 1.0
In [21]:
import pandas as pd
from IPython.display import display
data = {'First Name': ["Frodo", "Bilbo", "Aragorn II", "Samwise"],
'Last Name': ["Baggins", "Baggins","Elessar","Gamgee"],
'Place of birth': ["Shire", "Shire", "Eriador", "Shire"],
'Date of Birth T.A.': [2968, 2890, 2931, 2980]
}
data_pandas = pd.DataFrame(data)
display(data_pandas)| First Name | Last Name | Place of birth | Date of Birth T.A. | |
|---|---|---|---|---|
| 0 | Frodo | Baggins | Shire | 2968 |
| 1 | Bilbo | Baggins | Shire | 2890 |
| 2 | Aragorn II | Elessar | Eriador | 2931 |
| 3 | Samwise | Gamgee | Shire | 2980 |
In [22]:
data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])
display(data_pandas)| First Name | Last Name | Place of birth | Date of Birth T.A. | |
|---|---|---|---|---|
| Frodo | Frodo | Baggins | Shire | 2968 |
| Bilbo | Bilbo | Baggins | Shire | 2890 |
| Aragorn | Aragorn II | Elessar | Eriador | 2931 |
| Sam | Samwise | Gamgee | Shire | 2980 |
In [23]:
display(data_pandas.loc['Aragorn'])First Name Aragorn II Last Name Elessar Place of birth Eriador Date of Birth T.A. 2931 Name: Aragorn, dtype: object
In [24]:
new_hobbit = {'First Name': ["Peregrin"],
'Last Name': ["Took"],
'Place of birth': ["Shire"],
'Date of Birth T.A.': [2990]
}
data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))
display(data_pandas)| First Name | Last Name | Place of birth | Date of Birth T.A. | |
|---|---|---|---|---|
| Frodo | Frodo | Baggins | Shire | 2968 |
| Bilbo | Bilbo | Baggins | Shire | 2890 |
| Aragorn | Aragorn II | Elessar | Eriador | 2931 |
| Sam | Samwise | Gamgee | Shire | 2980 |
| Pippin | Peregrin | Took | Shire | 2990 |
In [6]:
import numpy as np
import pandas as pd
from IPython.display import display
np.random.seed(100)
# setting up a 10 x 5 matrix
rows = 10
cols = 5
a = np.random.randn(rows,cols)
df = pd.DataFrame(a)
display(df)
print(df.mean())
print(df.std())
display(df**2)
print(df-df.mean())
| 0 | 1 | 2 | 3 | 4 | |
|---|---|---|---|---|---|
| 0 | -1.749765 | 0.342680 | 1.153036 | -0.252436 | 0.981321 |
| 1 | 0.514219 | 0.221180 | -1.070043 | -0.189496 | 0.255001 |
| 2 | -0.458027 | 0.435163 | -0.583595 | 0.816847 | 0.672721 |
| 3 | -0.104411 | -0.531280 | 1.029733 | -0.438136 | -1.118318 |
| 4 | 1.618982 | 1.541605 | -0.251879 | -0.842436 | 0.184519 |
| 5 | 0.937082 | 0.731000 | 1.361556 | -0.326238 | 0.055676 |
| 6 | 0.222400 | -1.443217 | -0.756352 | 0.816454 | 0.750445 |
| 7 | -0.455947 | 1.189622 | -1.690617 | -1.356399 | -1.232435 |
| 8 | -0.544439 | -0.668172 | 0.007315 | -0.612939 | 1.299748 |
| 9 | -1.733096 | -0.983310 | 0.357508 | -1.613579 | 1.470714 |
0 -0.175300 1 0.083527 2 -0.044334 3 -0.399836 4 0.331939 dtype: float64 0 1.069584 1 0.965548 2 1.018232 3 0.793167 4 0.918992 dtype: float64
| 0 | 1 | 2 | 3 | 4 | |
|---|---|---|---|---|---|
| 0 | 3.061679 | 0.117430 | 1.329492 | 0.063724 | 0.962990 |
| 1 | 0.264421 | 0.048920 | 1.144993 | 0.035909 | 0.065026 |
| 2 | 0.209789 | 0.189367 | 0.340583 | 0.667239 | 0.452553 |
| 3 | 0.010902 | 0.282259 | 1.060349 | 0.191963 | 1.250636 |
| 4 | 2.621102 | 2.376547 | 0.063443 | 0.709698 | 0.034047 |
| 5 | 0.878123 | 0.534362 | 1.853835 | 0.106431 | 0.003100 |
| 6 | 0.049462 | 2.082875 | 0.572069 | 0.666597 | 0.563167 |
| 7 | 0.207888 | 1.415201 | 2.858185 | 1.839818 | 1.518895 |
| 8 | 0.296414 | 0.446453 | 0.000054 | 0.375694 | 1.689345 |
| 9 | 3.003620 | 0.966899 | 0.127812 | 2.603636 | 2.162999 |
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
In [26]:
df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
df.index = np.arange(10)
display(df)
print(df['Second'].mean() )
print(df.info())
print(df.describe())
from pylab import plt, mpl
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'
df.cumsum().plot(lw=2.0, figsize=(10,6))
plt.show()
df.plot.bar(figsize=(10,6), rot=15)
plt.show()| First | Second | Third | Fourth | Fifth | |
|---|---|---|---|---|---|
| 0 | -1.749765 | 0.342680 | 1.153036 | -0.252436 | 0.981321 |
| 1 | 0.514219 | 0.221180 | -1.070043 | -0.189496 | 0.255001 |
| 2 | -0.458027 | 0.435163 | -0.583595 | 0.816847 | 0.672721 |
| 3 | -0.104411 | -0.531280 | 1.029733 | -0.438136 | -1.118318 |
| 4 | 1.618982 | 1.541605 | -0.251879 | -0.842436 | 0.184519 |
| 5 | 0.937082 | 0.731000 | 1.361556 | -0.326238 | 0.055676 |
| 6 | 0.222400 | -1.443217 | -0.756352 | 0.816454 | 0.750445 |
| 7 | -0.455947 | 1.189622 | -1.690617 | -1.356399 | -1.232435 |
| 8 | -0.544439 | -0.668172 | 0.007315 | -0.612939 | 1.299748 |
| 9 | -1.733096 | -0.983310 | 0.357508 | -1.613579 | 1.470714 |
0.08352721390288316
<class 'pandas.core.frame.DataFrame'>
Int64Index: 10 entries, 0 to 9
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 First 10 non-null float64
1 Second 10 non-null float64
2 Third 10 non-null float64
3 Fourth 10 non-null float64
4 Fifth 10 non-null float64
dtypes: float64(5)
memory usage: 480.0 bytes
None
First Second Third Fourth Fifth
count 10.000000 10.000000 10.000000 10.000000 10.000000
mean -0.175300 0.083527 -0.044334 -0.399836 0.331939
std 1.069584 0.965548 1.018232 0.793167 0.918992
min -1.749765 -1.443217 -1.690617 -1.613579 -1.232435
25% -0.522836 -0.633949 -0.713163 -0.785061 0.087887
50% -0.280179 0.281930 -0.122282 -0.382187 0.463861
75% 0.441264 0.657041 0.861676 -0.205231 0.923602
max 1.618982 1.541605 1.361556 0.816847 1.470714
In [27]:
b = np.arange(16).reshape((4,4))
print(b)
df1 = pd.DataFrame(b)
print(df1)[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
3 12 13 14 15
In [4]:
# Importing various packages
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
x = np.random.rand(100,1)
y = 2*x+0.01*np.random.randn(100,1)
linreg = LinearRegression()
linreg.fit(x,y)
#ynew = linreg.predict(x)
#xnew = np.array([[0],[1]])
ypredict = linreg.predict(x)
plt.plot(x, ypredict, "r-")
plt.plot(x, y ,'ro')
plt.axis([0,1.0,0, 5.0])
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
plt.title(r'Simple Linear Regression')
plt.show()In [30]:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
x = np.random.rand(100,1)
y = 5*x+0.01*np.random.randn(100,1)
linreg = LinearRegression()
linreg.fit(x,y)
ypredict = linreg.predict(x)
plt.plot(x, np.abs(ypredict-y)/abs(y), "ro")
plt.axis([0,1.0,0.0, 0.5])
plt.xlabel(r'$x$')
plt.ylabel(r'$\epsilon_{\mathrm{relative}}$')
plt.title(r'Relative error')
plt.show()In [31]:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error
x = np.random.rand(100,1)
y = 2.0+ 5*x+0.5*np.random.randn(100,1)
linreg = LinearRegression()
linreg.fit(x,y)
ypredict = linreg.predict(x)
print('The intercept alpha: \n', linreg.intercept_)
print('Coefficient beta : \n', linreg.coef_)
# The mean squared error
print("Mean squared error: %.2f" % mean_squared_error(y, ypredict))
# Explained variance score: 1 is perfect prediction
print('Variance score: %.2f' % r2_score(y, ypredict))
# Mean squared log error
print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )
# Mean absolute error
print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))
plt.plot(x, ypredict, "r-")
plt.plot(x, y ,'ro')
plt.axis([0.0,1.0,1.5, 7.0])
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
plt.title(r'Linear Regression fit ')
plt.show()The intercept alpha: [1.92115887] Coefficient beta : [[5.06920615]] Mean squared error: 0.26 Variance score: 0.89 Mean squared log error: 0.01 Mean absolute error: 0.39
In [27]:
import matplotlib.pyplot as plt
import numpy as np
import random
from sklearn.linear_model import Ridge
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression
x=np.linspace(0.02,0.98,200)
noise = np.asarray(random.sample((range(200)),200))
y=x**3*noise
yn=x**3*100
poly3 = PolynomialFeatures(degree=3)
X = poly3.fit_transform(x[:,np.newaxis])
clf3 = LinearRegression()
clf3.fit(X,y)
Xplot=poly3.fit_transform(x[:,np.newaxis])
poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit')
plt.plot(x,yn, color='red', label="True Cubic")
plt.scatter(x, y, label='Data', color='orange', s=15)
plt.legend()
plt.show()
def error(a):
for i in y:
err=(y-yn)/yn
return abs(np.sum(err))/len(err)
print (error(y))Warning:
Output truncated. This notebook contains too many cells to display efficiently.
