markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
However, addition increases the rank: | op2 = op + op + op
op2.ranks | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
Matrix multiplication multiplies the individual ranks: | op3 = mp.dot(op2, op2)
op3.ranks | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
(NB: compress or compression below can call canonicalize on the MPA, which in turn could already reduce the rank to 1 in case the rank can be compressed without error. Keep that in mind.)
Keep in mind that the operator represented by op3 is still the identity operator, i.e. a tensor product operator. This means that ... | op3 /= mp.norm(op3.copy()) # normalize to make overlap meaningful
copy = op3.copy()
overlap = copy.compress(method='svd', rank=1)
copy.ranks | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
Calling compress on an MPA replaces the MPA in place with a version with smaller bond dimension. Overlap gives the absolute value of the (Hilbert-Schmidt) inner product between the original state and the output: | overlap | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
Instead of in-place compression, we can also obtain a compressed copy: | compr, overlap = op3.compression(method='svd', rank=2)
overlap, compr.ranks, op3.ranks | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
SVD compression can also be told to meet a certain truncation error (see the documentation of mp.MPArray.compress for details). | compr, overlap = op3.compression(method='svd', relerr=1e-6)
overlap, compr.ranks, op3.ranks | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
We can also use variational compression instead of SVD compression: | compr, overlap = op3.compression(method='var', rank=2, num_sweeps=10, var_sites=2)
# Convert overlap from numpy array with shape () to float for nicer display:
overlap = overlap.flat[0]
complex(overlap), compr.ranks, op3.ranks | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
As a reminder, it is always advisable to check whether the overlap between the input state and the compression is large enough. In an involved algorithm, it can be useful to store the compression error at each invocation of compression.
MPO sum of local terms
A frequent task is to compute the MPO representation of a l... | zeros = np.zeros((2, 2))
zeros
idm = np.eye(2)
idm
# Create a float array instead of an int array to avoid problems later
Z = np.diag([1., -1])
Z
h = np.kron(Z, Z)
h | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
First, we have to convert the local term h to an MPO: | h_arr = h.reshape((2, 2, 2, 2))
h_mpo = mp.MPArray.from_array_global(h_arr, ndims=2)
h_mpo.ranks | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
h_mpo has rank 4 even though h is a tensor product. This is far from optimal. We improve things as follows: (We could also compress h_mpo.) | h_mpo = mp.MPArray.from_kron([Z, Z])
h_mpo.ranks | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
The most simple way is to implement the formula from above with MPOs: First we compute the $h_{i, i+1}$ from the $h'_{i, i+1}$: | width = 2
sites = 6
local_terms = []
for startpos in range(sites - width + 1):
left = [mp.MPArray.from_kron([idm] * startpos)] if startpos > 0 else []
right = [mp.MPArray.from_kron([idm] * (sites - width - startpos))] \
if sites - width - startpos > 0 else []
h_at_startpos = mp.chain(left + [h_mpo]... | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
Next, we compute the sum of all the local terms and check the bond dimension of the result: | H = local_terms[0]
for local_term in local_terms[1:]:
H += local_term
H.ranks | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
The ranks are explained by the ranks of the local terms: | [local_term.ranks for local_term in local_terms] | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
We just have to add the ranks at each position.
mpnum provides a function which constructs H from h_mpo, with an output MPO with smaller rank by taking into account the trivial action on some sites: | H2 = mp.local_sum([h_mpo] * (sites - width + 1))
H2.ranks | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
Without additional arguments, mp.local_sum() just adds the local terms with the first term starting on site 0, the second on site 1 and so on. In addition, the length of the chain is chosen such that the last site of the chain coincides with the last site of the last local term. Other constructions can be obtained by... | mp.normdist(H, H2) | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
Of course, this means that we could just compress H: | H_comp, overlap = H.compression(method='svd', rank=3)
overlap / mp.norm(H)**2
H_comp.ranks | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
We can also check the minimal bond dimension which can be achieved with SVD compression with small error: | H_comp, overlap = H.compression(method='svd', relerr=1e-6)
overlap / mp.norm(H)**2
H_comp.ranks | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
MPS, MPOs and PMPS
We can represent vectors (e.g. pure quantum states) as MPS, we can represent arbitrary matrices as MPO and we can represent positive semidefinite matrices as purifying matrix product states (PMPS). For mixed quantum states, we can thus choose between the MPO and PMPS representations.
As mentioned in... | mps = mp.random_mpa(sites=5, ldim=2, rank=3, normalized=True)
mps_mpo = mp.mps_to_mpo(mps)
mps_mpo.ranks | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
As expected, the rank of mps_mpo is the square of the rank of mps.
Now we create a PMPS with system site dimension 2 and ancilla site dimension 3: | pmps = mp.random_mpa(sites=5, ldim=(2, 3), rank=3, normalized=True)
pmps.shape
pmps_mpo = mp.pmps_to_mpo(pmps)
pmps_mpo.ranks | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
Again, the rank is squared, as expected. We can verify that the first physical leg of each site of pmps is indeed the system site by checking the shape of pmps_mpo: | pmps_mpo.shape | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
Local reduced states
For state tomography applications, we frequently need the local reduced states of an MPS, MPO or PMPS. We provide the following functions for this task:
mp.reductions_mps_as_pmps(): Input: MPS, output: local reductions as PMPS
mp.reductions_mps_as_mpo(): Input: MPS, output: local reductions as MPO... | width = 3
startsites = range(len(pmps) - width + 1)
for startsite, red in zip(startsites, mp.reductions_pmps(pmps, width, startsites)):
print('Reduction starting on site', startsite)
print('bdims:', red.ranks)
red_mpo = mp.pmps_to_mpo(red)
print('trace:', mp.trace(red_mpo))
print() | examples/mpnum_intro.ipynb | dseuss/mpnum | bsd-3-clause |
Gaussian process regression
Lecture 1
Suzanne Aigrain, University of Oxford
LSST DSFP Session 4, Seattle, Sept 2017
Lecture 1: Introduction and basics
Tutorial 1: Write your own GP code
Lecture 2: Examples and practical considerations
Tutorial 3: Useful GP modules
Lecture 3: Advanced applications
Why GPs?
... | def gauss1d(x,mu,sig):
return np.exp(-(x-mu)**2/sig*2/2.)/np.sqrt(2*np.pi)/sig
def pltgauss1d(sig=1):
mu=0
x = np.r_[-4:4:101j]
pl.figure(figsize=(10,7))
pl.plot(x, gauss1d(x,mu,sig),'k-');
pl.axvline(mu,c='k',ls='-');
pl.axvline(mu+sig,c='k',ls='--');
pl.axvline(mu-sig,c='k',ls='--');
... | Sessions/Session04/Day2/GPLecture1.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Now let us consider a pair of variables $y_1$ and $y_2$, drawn from a bivariate Gaussian distribution. The joint probability density for $y_1$ and $y_2$ is:
$$
\left[ \begin{array}{l} y_1 \ y_2 \end{array} \right] \sim \mathcal{N} \left(
\left[ \begin{array}{l} \mu_1 \ \mu_2 \end{array} \right] ,
\left[ \begin{array}... | def gauss2d(x1,x2,mu1,mu2,sig1,sig2,rho):
z = (x1-mu1)**2/sig1**2 + (x2-mu2)**2/sig2**2 - 2*rho*(x1-mu1)*(x2-mu2)/sig1/sig2
e = np.exp(-z/2/(1-rho**2))
return e/(2*np.pi*sig1*sig2*np.sqrt(1-rho**2))
def pltgauss2d(rho=0,show_cond=0):
mu1, sig1 = 0,1
mu2, sig2 = 0,1
y2o = -1
x1 = np.r_[-4... | Sessions/Session04/Day2/GPLecture1.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
To make the relation to time-series data a bit more obvious, let's plot the two variables side by side, then see what happens to one variable when we observe (fix) the other. | def SEKernel(par, x1, x2):
A, Gamma = par
D2 = cdist(x1.reshape(len(x1),1), x2.reshape(len(x2),1),
metric = 'sqeuclidean')
return A * np.exp(-Gamma*D2)
A = 1.0
Gamma = 0.01
x = np.array([-1,1])
K = SEKernel([A,Gamma],x,x)
m = np.zeros(len(x))
sig = np.sqrt(np.diag(K))
pl.figure(figsize=(15,7... | Sessions/Session04/Day2/GPLecture1.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Now consider $N$ variables drawn from a multivariate Gaussian distribution:
$$
\boldsymbol{y} \sim \mathcal{N} (\boldsymbol{m},K)
$$
where $y = (y_1,y_2,\ldots,y_N)^T$, $\boldsymbol{m} = (m_1,m_2,\ldots,m_N)^T$ is the mean vector, and $K$ is an $N \times N$ positive semi-definite covariance matrix, with elements $K_{ij... | xobs = np.array([-1,1,2])
yobs = np.array([1,-1,0])
eobs = np.array([0.0001,0.1,0.1])
pl.figure(figsize=(15,7))
pl.subplot(121)
pl.errorbar(xobs,yobs,yerr=eobs,capsize=0,fmt='k.')
Gamma = 0.5
x = np.array([-2.5,-2,-1.5,-0.5, 0.0, 0.5,1.5,2.5])
m,C=Pred_GP(SEKernel,[A,Gamma],xobs,yobs,eobs,x)
sig = np.sqrt(np.diag(C))
f... | Sessions/Session04/Day2/GPLecture1.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Textbooks
A good, detailed reference is Gaussian Processes for Machine Learning by C. E. Rasmussen & C. Williams, MIT Press, 2006.
The examples in the book are generated using the Matlab package GPML.
A more formal definition
A Gaussian process is completely specified by its mean function and covariance function.
We d... | def kernel_SE(X1,X2,par):
p0 = 10.0**par[0]
p1 = 10.0**par[1]
D2 = cdist(X1,X2,'sqeuclidean')
K = p0 * np.exp(- p1 * D2)
return np.matrix(K)
def kernel_Mat32(X1,X2,par):
p0 = 10.0**par[0]
p1 = 10.0**par[1]
DD = cdist(X1, X2, 'euclidean')
arg = np.sqrt(3) * abs(DD) / p1
K = p0 * (... | Sessions/Session04/Day2/GPLecture1.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
The Matern family
The Matern 3/2 kernel
$$
k_{3/2}(x,x')= A \left( 1 + \frac{\sqrt{3}r}{l} \right) \exp \left( - \frac{\sqrt{3}r}{l} \right),
$$
where $r =|x-x'|$.
It produces somewhat rougher behaviour, because it is only differentiable once w.r.t. $r$ (whereas the SE kernel is infinitely differentiable). There is a w... | # Function to plot samples from kernel
def pltsamples2(par2=0.5, kernel_shortname='SE'):
x = np.r_[-5:5:201j]
X = np.matrix([x]).T # scipy.spatial.distance expects matrices
kernel = get_kernel(kernel_shortname)
K = kernel(X,X,[0.0,0.0,par2])
fig=pl.figure(figsize=(10,4))
ax1 = pl.subplot2grid((1... | Sessions/Session04/Day2/GPLecture1.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Periodic kernels...
...can be constructed by replacing $r$ in any of the above by a periodic function of $r$. For example, the cosine kernel:
$$
k_{\cos}(x,x') = A \cos\left(\frac{2\pi r}{P}\right),
$$
[which follows the dynamics of a simple harmonic oscillator], or...
...the "exponential sine squared" kernel, obtained... | # Function to plot samples from kernel
def pltsamples3(par2=2.0, par3=2.0,kernel_shortname='Per'):
x = np.r_[-5:5:201j]
X = np.matrix([x]).T # scipy.spatial.distance expects matrices
kernel = get_kernel(kernel_shortname)
K = kernel(X,X,[0.0,0.0,par2,par3])
fig=pl.figure(figsize=(10,4))
ax1 = pl.... | Sessions/Session04/Day2/GPLecture1.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Combining kernels
Any affine tranform, sum or product of valid kernels is a valid kernel.
For example, a quasi-periodic kernel can be constructed by multiplying a periodic kernel with a non-periodic one. The following is frequently used to model stellar light curves:
$$
k_{\mathrm{QP}}(x,x') = A \exp \left[ -\Gamma_1 ... | import george
x2d, y2d = np.mgrid[-3:3:0.1,-3:3:0.1]
x = x2d.ravel()
y = y2d.ravel()
N = len(x)
X = np.zeros((N,2))
X[:,0] = x
X[:,1] = y
k1 = george.kernels.ExpSquaredKernel(1.0,ndim=2)
s1 = george.GP(k1).sample(X).reshape(x2d.shape)
k2 = george.kernels.ExpSquaredKernel(1.0,ndim=2,axes=1) + george.kernels.ExpSquared... | Sessions/Session04/Day2/GPLecture1.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
You can list what is contained in the request: | karthaus | docs/notebooks/Data_Catalog.ipynb | mroberge/hydrofunctions | mit |
The basic NWIS object will provide a list of every parameter collected at the site, the frequency of observations for that parameter, the name of the parameter, and the units of the observations. It also tells you the date and time of the first and last observation in the request.
This is great, but it doesn't tell you... | output = hf.data_catalog('01585200') | docs/notebooks/Data_Catalog.ipynb | mroberge/hydrofunctions | mit |
Our new 'output' is a hydroRDB object. It has several useful properties, including:
.table, which returns a dataframe of the data. Each row corresponds to a different parameter.
.header, which is the original descriptive header provided by the USGS. It lists and describes the variables in the dataset.
.columns, whic... | print(output.header)
# Transposing the table to show all of the columns as rows:
output.table.T | docs/notebooks/Data_Catalog.ipynb | mroberge/hydrofunctions | mit |
From 1D to 2D acoustic finite difference modelling
The 1D acoustic wave equation is very useful to introduce the general concept and problems related to FD modelling. However, for realistic modelling and seismic imaging/inversion applications we have to solve at least the 2D acoustic wave equation.
In the class we will... | # Import Libraries
# ----------------
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from pylab import rcParams
# Ignore Warning Messages
# -----------------------
import warnings
warnings.filterwarnings("ignore")
# Definition of modelling parameters
# ----------------------------------
xmax = ... | 05_2D_acoustic_FD_modelling/1_From_1D_to_2D_acoustic_FD_modelling_final.ipynb | daniel-koehn/Theory-of-seismic-waves-II | gpl-3.0 |
Comparison of 2D finite difference with analytical solution
In the function below we solve the homogeneous 2D acoustic wave equation by the 3-point spatial/temporal difference operator and compare the numerical results with the analytical solution:
\begin{equation}
G_{analy}(x,z,t) = G_{2D} * S \nonumber
\end{equatio... | # 2D Wave Propagation (Finite Difference Solution)
# ------------------------------------------------
def FD_2D_acoustic(dt,dx,dz):
nx = (int)(xmax/dx) # number of grid points in x-direction
print('nx = ',nx)
nz = (int)(zmax/dz) # number of grid points in x-direction
print('nz = ',nz)
... | 05_2D_acoustic_FD_modelling/1_From_1D_to_2D_acoustic_FD_modelling_final.ipynb | daniel-koehn/Theory-of-seismic-waves-II | gpl-3.0 |
Let's consider precipitation/dissolution of NaCl:
$$
\rm NaCl(s) \rightleftharpoons Na^+(aq) + Cl^-(aq)
$$ | init_concs = iNa_p, iCl_m, iNaCl = [sp.Symbol('i_'+str(i), real=True, negative=False) for i in range(3)]
c = Na_p, Cl_m, NaCl = [sp.Symbol('c_'+str(i), real=True, negative=False) for i in range(3)]
prod = lambda x: reduce(mul, x)
texnames = [r'\mathrm{%s}' % k for k in 'Na^+ Cl^- NaCl'.split()] | examples/conditional.ipynb | bjodah/pyneqsys | bsd-2-clause |
if the solution is saturated, then the solubility product will be constant:
$$
K_{\rm sp} = \mathrm{[Na^+][Cl^-]}
$$
in addition to this (conditial realtion) we can write equations for the preservation of atoms and charge: | stoichs = [[1, 1, -1]]
Na = [1, 0, 1]
Cl = [0, 1, 1]
charge = [1, -1, 0]
preserv = [Na, Cl, charge]
eq_constants = [Ksp] = [sp.Symbol('K_{sp}', real=True, positive=True)]
def get_f(x, params, saturated):
init_concs = params[:3] if saturated else params[:2]
eq_constants = params[3:]
le = linear_exprs(preser... | examples/conditional.ipynb | bjodah/pyneqsys | bsd-2-clause |
Our two sets of reactions are then: | get_f(c, init_concs + eq_constants, False)
f_true = get_f(c, init_concs + eq_constants, True)
f_false = get_f(c, init_concs + eq_constants, False)
f_true, f_false | examples/conditional.ipynb | bjodah/pyneqsys | bsd-2-clause |
We have one condition (a boolean describing whether the solution is saturated or not). We provide two conditionals, one for going from non-saturated to saturated (forward) and one going from saturated to non-saturated (backward): | from pyneqsys.core import ConditionalNeqSys
cneqsys = ConditionalNeqSys(
[
(lambda x, p: (x[0] + x[2]) * (x[1] + x[2]) > p[3], # forward condition
lambda x, p: x[2] >= 0) # backward condition
],
lambda conds: SymbolicSys(
c, f_true if conds[0] else f_fal... | examples/conditional.ipynb | bjodah/pyneqsys | bsd-2-clause |
Solving for inital concentrations below the solubility product: | cneqsys.solve([0.5, 0.5, 0], params) | examples/conditional.ipynb | bjodah/pyneqsys | bsd-2-clause |
no surprises there (it is of course trivial).
In order to illustrate its usefulness, let us consider addition of a more soluable sodium salt (e.g. NaOH) to a chloride rich solution (e.g. HCl): | %matplotlib inline
ax_out = plt.subplot(1, 2, 1)
ax_err = plt.subplot(1, 2, 2)
xres, sols = cneqsys.solve_and_plot_series(
c0, params, np.linspace(0, 3), 0, 'kinsol',
{'ax': ax_out}, {'ax': ax_err}, fnormtol=1e-14)
_ = ax_out.legend() | examples/conditional.ipynb | bjodah/pyneqsys | bsd-2-clause |
We will be using the water level data from a fixed station in Kotzebue, AK.
Below we create a simple Quality Assurance/Quality Control (QA/QC) configuration that will be used as input for ioos_qc. All the interval values are in the same units as the data.
For more information on the tests and recommended values for QA/... | variable_name = "sea_surface_height_above_sea_level_geoid_mhhw"
qc_config = {
"qartod": {
"gross_range_test": {
"fail_span": [-10, 10],
"suspect_span": [-2, 3]
},
"flat_line_test": {
"tolerance": 0.001,
"suspect_threshold": 10800,
"fail_threshold": 21600
... | notebooks/2020-02-14-QARTOD_ioos_qc_Water-Level-Example.ipynb | ioos/notebooks_demos | mit |
Now we are ready to load the data, run tests and plot results!
We will get the data from the AOOS ERDDAP server. Note that the data may change in the future. For reproducibility's sake we will save the data downloaded into a CSV file. | from pathlib import Path
import pandas as pd
from erddapy import ERDDAP
path = Path().absolute()
fname = path.joinpath("data", "water_level_example.csv")
if fname.is_file():
data = pd.read_csv(fname, parse_dates=["time (UTC)"])
else:
e = ERDDAP(
server="http://erddap.aoos.org/erddap/",
protoc... | notebooks/2020-02-14-QARTOD_ioos_qc_Water-Level-Example.ipynb | ioos/notebooks_demos | mit |
The results are returned in a dictionary format, similar to the input configuration, with a mask for each test. While the mask is a masked array it should not be applied as such. The results range from 1 to 4 meaning:
data passed the QA/QC
did not run on this data point
flag as suspect
flag as failed
Now we can write... | %matplotlib inline
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
def plot_results(data, var_name, results, title, test_name):
time = data["time (UTC)"]
obs = data[var_name]
qc_test = results["qartod"][test_name]
qc_pass = np.ma.masked_where(qc_test != 1, obs)
... | notebooks/2020-02-14-QARTOD_ioos_qc_Water-Level-Example.ipynb | ioos/notebooks_demos | mit |
The gross range test test should fail data outside the $\pm$ 10 range and suspect data below -2, and greater than 3. As one can easily see all the major spikes are flagged as expected. | plot_results(
data,
"sea_surface_height_above_sea_level_geoid_mhhw (m)",
qc_results,
title,
"gross_range_test"
) | notebooks/2020-02-14-QARTOD_ioos_qc_Water-Level-Example.ipynb | ioos/notebooks_demos | mit |
An actual spike test, based on a data increase threshold, flags similar spikes to the gross range test but also indetifies other suspect unusual increases in the series. | plot_results(
data,
"sea_surface_height_above_sea_level_geoid_mhhw (m)",
qc_results,
title,
"spike_test"
) | notebooks/2020-02-14-QARTOD_ioos_qc_Water-Level-Example.ipynb | ioos/notebooks_demos | mit |
The flat line test identifies issues with the data where values are "stuck."
ioos_qc succefully identified a huge portion of the data where that happens and flagged a smaller one as suspect. (Zoom in the red point to the left to see this one.) | plot_results(
data,
"sea_surface_height_above_sea_level_geoid_mhhw (m)",
qc_results,
title,
"flat_line_test"
) | notebooks/2020-02-14-QARTOD_ioos_qc_Water-Level-Example.ipynb | ioos/notebooks_demos | mit |
The figure is part of a well patterns that extends to infinity in all directions. The thick lines are the boundaries of the river bed. The installed wells are plotted in blue. The focus well is red. All other wells are virtual or mirror wells that together guarantee that the flow across the river-bed boundaries is alwa... | # well pattern
kD = 1 * 30
S = 0.2
Q = 2 * 0.5 * 3.6 * 8# m3/d (0.5 L/s for 8h/d)
x0 = 0.
y0 = 0.
N = 10
x = np.linspace(-2* N * w, 2* N * w, 2 * N + 1)
y = np.linspace(-2* N * w, 2* N * w, 2 * N + 1)
X, Y = np.meshgrid(x, y)
rw = 0.1 # well radius
R = np.fmax(np.sqrt((X - x0)**2 + (Y - y0)**2), rw)
times = np.log... | exercises_notebooks/a_well_in_a_river_bed.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Balance
The decline of the water level is
$$ \frac {\partial h} {\partial t} = \frac {2 Q} { A S} = \frac {2 \times 14.4} {200\times200\times0.2} = 0.0036 \,m/d= 0.36 m/(100d)$$
Let's compare this with the decline in the graph above: | decline_rate = np.diff(np.interp([50, 100], times, s))[0]/50 # decline rate over last 50 days
print('Decline rate over the last 50 days is = {:.3g} m/(100d)'.format(100 * decline_rate)) | exercises_notebooks/a_well_in_a_river_bed.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
So we see that this matches the hand-calculation.
So the approach shows what happens of you install a well at one side of the 100 m wide river bed, you do that every 200 m, and extract 0.5 L/d for 8h/d from each of them. There is an initial rapid decline due to the fact that we have a well, which causes the steamlines ... | # situation with drain (circumference = 6 m)
N = 10
x = np.linspace(-2* N * w, 2* N * w, 2 * N + 1)
y = np.linspace(-2* N * w, 2* N * w, 2 * N + 1)
X, Y = np.meshgrid(x, y)
rw = 6 / (2 * np.pi) # well radius
R = np.fmax(np.sqrt((X - x0)**2 + (Y - y0)**2), rw)
times = np.logspace(-2, 2, 51)
s2 = np.zeros_like(times)
f... | exercises_notebooks/a_well_in_a_river_bed.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
whfast refers to the 2nd order symplectic integrator WHFast described by Rein & Tamayo (2015). By default, no symplectic correctors are used, but they can be easily turned on (see Advanced Settings for WHFast).
We are now ready to start the integration. Let's integrate the simulation for one orbit, i.e. until $t=2\pi$... | sim.integrate(6.28318530717959, exact_finish_time=0) # 6.28318530717959 is 2*pi | ipython_examples/WHFast.ipynb | cshankm/rebound | gpl-3.0 |
That looks much more like it. Let us finally plot the orbital elements as a function of time. | times = np.linspace(1000.*torb, 9000.*torb, Noutputs)
a = np.zeros(Noutputs)
e = np.zeros(Noutputs)
for i,time in enumerate(times):
sim.integrate(time, exact_finish_time=0)
orbits = sim.calculate_orbits()
a[i] = orbits[1].a
e[i] = orbits[1].e
fig = plt.figure(figsize=(15,5))
ax = plt.subplot(121)
... | ipython_examples/WHFast.ipynb | cshankm/rebound | gpl-3.0 |
First, let's consider:
<dl compact>
<dt>``f(x,y)``</dt><dd>a simple function that accepts a location in a 2D plane specified in millimeters (mm)</dd>
<dt>``region``</dt><dd>a 1mm×1mm square region of this 2D plane, centered at the origin, and</dd>
<dt>``coords``</dt><dd>a function returning a square (s×s) ... | def f(x,y):
return x+y/3.1
region=(-0.5,-0.5,0.5,0.5)
def coords(bounds,samples):
l,b,r,t=bounds
hc=0.5/samples
return np.meshgrid(np.linspace(l+hc,r-hc,samples),
np.linspace(b+hc,t-hc,samples)) | doc/Tutorials/Continuous_Coordinates.ipynb | mjabri/holoviews | bsd-3-clause |
We can visualize this array (and thus the function f) either using a Raster, which uses the array's own integer-based coordinate system (which we will call "array" coordinates), or an Image, which uses a continuous coordinate system, or as a HeatMap labelling each value explicitly: | r5 = hv.Raster(f5, label="R5")
i5 = hv.Image( f5, label="I5", bounds=region)
h5 = hv.HeatMap({(x, y): f5[4-y,x] for x in range(0,5) for y in range(0,5)}, label="H5")
r5+i5+h5 | doc/Tutorials/Continuous_Coordinates.ipynb | mjabri/holoviews | bsd-3-clause |
Both the Raster and Image Element types accept the same input data, but a visualization of the Raster type reveals the underlying raw array indexing, while the Image type has been labelled with the coordinate system from which we know the data has been sampled. All Image operations work with this continuous coordinate... | "r5[0,1]=%0.2f r5.data[0,1]=%0.2f i5[-0.2,0.4]=%0.2f i5[-0.24,0.37]=%0.2f i5.data[0,1]=%0.2f" % \
(r5[1,0], r5.data[0,1], i5[-0.2,0.4], i5[-0.24,0.37], i5.data[0,1]) | doc/Tutorials/Continuous_Coordinates.ipynb | mjabri/holoviews | bsd-3-clause |
You can see that the Raster and the underlying .data elements use Numpy's integer indexing, while the Image uses floating-point values that are then mapped onto the appropriate array element.
This diagram should help show the relationships between the Raster coordinate system in the plot (which ranges from 0 at the top... | f10=f(*coords(region,10))
f10
r10 = hv.Raster(f10, label="R10")
i10 = hv.Image(f10, label="I10", bounds=region)
r10+i10 | doc/Tutorials/Continuous_Coordinates.ipynb | mjabri/holoviews | bsd-3-clause |
The array-based indexes used by Raster and the Numpy array in .data still return the second item in the first row of the array, but this array element now corresponds to location (-0.35,0.4) in the continuous function, and so the value is different. These indexes thus do not refer to the same location in continuous sp... | sl10=i10[-0.275:0.025,-0.0125:0.2885]
sl10.data
sl10 | doc/Tutorials/Continuous_Coordinates.ipynb | mjabri/holoviews | bsd-3-clause |
Hopefully these examples make it clear that if you are using data that is sampled from some underlying continuous system, you should use the continuous coordinates offered by HoloViews objects like Image so that your programs can be independent of the resolution or sampling density of that data, and so that your axes a... | e10=i10.sample(x=-0.275, y=0.2885)
e10 | doc/Tutorials/Continuous_Coordinates.ipynb | mjabri/holoviews | bsd-3-clause |
We will look at an arbitrary expression $f(x, y)$:
$$
f(x, y) = 3 x^{2} + \log{\left (x^{2} + y^{2} + 1 \right )}
$$ | x, y = sym.symbols('x y')
expr = 3*x**2 + sym.log(x**2 + y**2 + 1)
expr | notebooks/22-lambdify.ipynb | sympy/scipy-2017-codegen-tutorial | bsd-3-clause |
One way to evaluate above expression numerically is to invoke the subs method followed by the evalf method: | expr.subs({x: 17, y: 42}).evalf() | notebooks/22-lambdify.ipynb | sympy/scipy-2017-codegen-tutorial | bsd-3-clause |
However, if we need to do this repeatedly it can be quite slow: | %timeit expr.subs({x: 17, y: 42}).evalf() | notebooks/22-lambdify.ipynb | sympy/scipy-2017-codegen-tutorial | bsd-3-clause |
even compared to a simple lambda function: | import math
f = lambda x, y: 3*x**2 + math.log(x**2 + y**2 + 1)
f(17, 42)
%timeit f(17, 42) | notebooks/22-lambdify.ipynb | sympy/scipy-2017-codegen-tutorial | bsd-3-clause |
SymPy can also create a function analogous to f above. The function for doing so is called lambdify: | g = sym.lambdify([x, y], expr, modules=['math'])
g(17, 42)
%timeit g(17, 42) | notebooks/22-lambdify.ipynb | sympy/scipy-2017-codegen-tutorial | bsd-3-clause |
Note how we specified modules above: it tells lambdify to use math.log, if we don't specify modules SymPy will (since v1.1) use numpy by default. This can be useful when dealing with arrays in the input: | import numpy as np
xarr = np.linspace(17, 18, 5)
h = sym.lambdify([x, y], expr)
out = h(xarr, 42)
out.shape | notebooks/22-lambdify.ipynb | sympy/scipy-2017-codegen-tutorial | bsd-3-clause |
NumPy's broadcasting (handling of different shapes) then works as expected: | yarr = np.linspace(42, 43, 7).reshape((1, 7))
out2 = h(xarr.reshape((5, 1)), yarr) # if we would try to use g() here, it would fail
out2.shape | notebooks/22-lambdify.ipynb | sympy/scipy-2017-codegen-tutorial | bsd-3-clause |
Behind the scenes lambdify constructs a string representation of the Python code and uses Python's eval function to compile the function.
Let's now look at how we can get a specific function signature from lambdify: | z = z1, z2, z3 = sym.symbols('z:3')
expr2 = x*y*(z1 + z2 + z3)
func2 = sym.lambdify([x, y, z], expr2)
func2(1, 2, (3, 4, 5)) | notebooks/22-lambdify.ipynb | sympy/scipy-2017-codegen-tutorial | bsd-3-clause |
Exercise: Create a function from a symbolic expression
Plot $z(x, y) = \frac{\partial^2 f(x,y)}{\partial x \partial y}$ from above ($f(x, y)$ is available as expr) as a surface plot for $-5 < x < 5, -5 < y < 5$. | xplot = np.outer(np.linspace(-5, 5, 100), np.ones(100))
yplot = xplot.T
%load_ext scipy2017codegen.exercise | notebooks/22-lambdify.ipynb | sympy/scipy-2017-codegen-tutorial | bsd-3-clause |
Use either the %exercise or %load magic to get the exercise / solution respecitvely | %exercise exercise_lambdify_expr.py | notebooks/22-lambdify.ipynb | sympy/scipy-2017-codegen-tutorial | bsd-3-clause |
Replace ??? with the correct expression above. | from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure(figsize=(15, 13))
ax = plt.axes(projection='3d')
ax.plot_surface(xplot, yplot, zplot, cmap=plt.cm.coolwarm)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('$%s$' % sym.latex(d2fdxdy)) | notebooks/22-lambdify.ipynb | sympy/scipy-2017-codegen-tutorial | bsd-3-clause |
Input | file_path = "../data/df_model01.pkl"
df = pd.read_pickle(file_path)
print(df.shape)
df.head() | EventDec/event_dec/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Binning | bins = [10, 40, 120, 180] # SR, LNZ, SZG, VIE, >VIE
df["binned_distance"] = np.digitize(df.distance.values, bins=bins) | EventDec/event_dec/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Conversion for Scikit-learn
Feature selection based on expert knowledge. Model-based hardly interpretable, at least confirmed "binned_distance" as relevant feature. | feature_names = ["buzzwordy_title", "main_topic_Daten", "binned_distance"]
X = df[feature_names].values
y = df.rating.map(lambda x: 1 if x>5 else 0).values # binary target: >5 (better as all the same) was worth attending
print("X:", X.shape, "y:", y.shape) | EventDec/event_dec/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Train-Test Split | from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=23,
test_size=0.5) # 50% split, small dataset size | EventDec/event_dec/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Modeling
Model | from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeClassifier
linreg = LinearRegression() # Benchmark model
dec_tree = DecisionTreeClassifier() # Actual model | EventDec/event_dec/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Benchmark
Linear Regression | # Benchmark
linreg.fit(X_train, y_train)
print("Score (r^2): {:.3f}".format(linreg.score(X_test, y_test)))
print("Coef: {}".format(linreg.coef_)) | EventDec/event_dec/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
=> Really bad perfomance
Model
Decision Tree CV
<= Ability to visualize, hasn't performed much worse than other applied models
Parameter Tuning | from sklearn.model_selection import GridSearchCV
parameter_grid = {"criterion": ["gini", "entropy"],
"max_depth": [None, 1, 2, 3, 4, 5, 6],
"min_samples_leaf": list(range(1, 14)),
"max_leaf_nodes": list(range(3, 25))}
grid_search = GridSearchCV(DecisionTreeClas... | EventDec/event_dec/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
=> Not that good accuracy, but at least better than random draw
Build Model | model = DecisionTreeClassifier(presort=True, criterion="gini", max_depth=None,
min_samples_leaf=2, max_leaf_nodes=5)
model.fit(X_train, y_train)
print("Score (Accuracy): {:.3f}".format(model.score(X_test, y_test))) | EventDec/event_dec/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Print Decision Tree | from sklearn.tree import export_graphviz
export_graphviz(model, class_names=True, feature_names=feature_names,
rounded=True, filled=True, label="root", impurity=False, proportion=True,
out_file="plots/dectree_Model_best.dot") | EventDec/event_dec/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Model Evaluation
Evaluation Scores | from sklearn.metrics import classification_report
y_pred = model.predict(X_test)
print(classification_report(y_test, y_pred)) | EventDec/event_dec/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
=> Not so good in predicting class 1 ("worth attending), better in predicting class 0. Weighted average of precision and recall 0.62 (F1 Score)
ROC Curve | from sklearn.metrics import roc_curve, roc_auc_score
fpr, tpr, thresholds = roc_curve(y_test, y_pred)
plt.plot(fpr, tpr, label="ROC")
plt.plot([0, 1], c="r", label="Chance level")
plt.title("ROC Curve")
plt.xlabel("False Positive Rate")
plt.ylabel("Recall")
plt.legend(loc=4)
plt.savefig("plots/ROC_Curve_Model.png", ... | EventDec/event_dec/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
=> Indeed only slightly better than random guess, ~ 0.05 percentage points (AUC) | from sklearn.model_selection import cross_val_score
scores_benchmark = cross_val_score(model, X, y, cv=5) # 5 folds
print("Cross-Val Scores (Accuracy): {}".format(scores_benchmark))
print("Cross-Val Mean (Accuracy): {}".format(scores_benchmark.mean())) | EventDec/event_dec/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
=> Generalization acceptable, but not good (as expected from a Decision Tree)
Persist Model | from sklearn.externals import joblib
file_path = "../data/model_trained.pkl"
joblib.dump(model, file_path) | EventDec/event_dec/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Utilizaremos a função head() para visualizar as primeiras linhas do dataframe. | data.head() | 2019/06-decision-tree/Tutorial 11 (scikitlearn) - Árvores de Classificação e Regressão.ipynb | InsightLab/data-science-cookbook | mit |
Se desejar visualizar todo o dataset executa a seguinte linha de código. | data
data.info() | 2019/06-decision-tree/Tutorial 11 (scikitlearn) - Árvores de Classificação e Regressão.ipynb | InsightLab/data-science-cookbook | mit |
2. Dividir o dataset
Iremos agora utilizar a função iloc do pandas para dividir o nosso dataset. Em X iremos guardar os valores da coluna 0 até a coluna 3 do dataset, em Y iremos guardar os valores da última coluna, que correspondem aos valores de saída. | X = data.iloc[:,[0,1,2,3]]
Y = data.iloc[:,4] | 2019/06-decision-tree/Tutorial 11 (scikitlearn) - Árvores de Classificação e Regressão.ipynb | InsightLab/data-science-cookbook | mit |
O próximo passo é dividir o conjunto de dados, em dados de treino e de teste. Para isso usaremos a função train_test_split da biblioteca sklearn. | from sklearn.model_selection import train_test_split | 2019/06-decision-tree/Tutorial 11 (scikitlearn) - Árvores de Classificação e Regressão.ipynb | InsightLab/data-science-cookbook | mit |
Dividiremos os dados da seguinte forma: 80% dos dados serão utilizados para treino e 20% para teste. Os dados de treino serão então separados e guardados em duas variáveis: o X_train guarda os valores da coluna 0 até a 4 e o y_train guarda os valores de saída correspondente a cada linha do X_train. A divisão acontecerá... | X_train, X_test, y_train, y_test = train_test_split(X, Y, train_size=0.8, test_size= 0.2, random_state=1) | 2019/06-decision-tree/Tutorial 11 (scikitlearn) - Árvores de Classificação e Regressão.ipynb | InsightLab/data-science-cookbook | mit |
3. Treinar o algoritmo | from sklearn.tree import DecisionTreeClassifier | 2019/06-decision-tree/Tutorial 11 (scikitlearn) - Árvores de Classificação e Regressão.ipynb | InsightLab/data-science-cookbook | mit |
Vamos utilizar a função DecisionTreeClassifier para modelar. O parâmetro criterion define a função utilizada para medir a qualidade da divisão. No nosso caso definimos o critério com 'gini'.
O coeficiente é uma função de custo utilizada para avaliar divisões no dataset. Uma divisão neste envolve um atributo de entrada... | model = DecisionTreeClassifier(criterion='gini', max_depth= 5, min_samples_split= 10) | 2019/06-decision-tree/Tutorial 11 (scikitlearn) - Árvores de Classificação e Regressão.ipynb | InsightLab/data-science-cookbook | mit |
Agora iremos treinar o nosso modelo, utilizando a função fit do sklearn, usaremos os conjuntos de dados de treino que tínhamos preparados anteriormente. | model.fit(X_train, y_train) | 2019/06-decision-tree/Tutorial 11 (scikitlearn) - Árvores de Classificação e Regressão.ipynb | InsightLab/data-science-cookbook | mit |
4. Fazer uma predição e avaliar o algoritmo
Vamos agora utilizar o nosso modelo para efetuar uma predição sobre o nosso dataset. Usaremos a função predict do sklearn e o nosso conjunto de dados X_test. | predicao = model.predict(X_test)
predicao | 2019/06-decision-tree/Tutorial 11 (scikitlearn) - Árvores de Classificação e Regressão.ipynb | InsightLab/data-science-cookbook | mit |
É natural querermos saber quão bom é o desempenho do modelo que desenvolvemos sobre o dataset. Para calcular a acurácia podemos utilizar a função score do sklearn.tree. | accuracy = model.score(X_test, y_test)*100
print('Accuracy: %s%%' % accuracy) | 2019/06-decision-tree/Tutorial 11 (scikitlearn) - Árvores de Classificação e Regressão.ipynb | InsightLab/data-science-cookbook | mit |
5. Avaliar o algortimo utilizando o K-fold Cross Validation
Podemos também usar o método da validação cruzada com k-fold para avaliar o nosso algoritmo. Iremos utilizar as funções KFold e cross_val_score, ambas terão de ser importadas da biblioteca sklearn.model_selection. | from sklearn.model_selection import KFold, cross_val_score
import numpy as np | 2019/06-decision-tree/Tutorial 11 (scikitlearn) - Árvores de Classificação e Regressão.ipynb | InsightLab/data-science-cookbook | mit |
Utilizaremos 5 folds. | k_fold = KFold(n_splits=5)
scores = cross_val_score(model, X, Y, cv=k_fold, n_jobs=-1) | 2019/06-decision-tree/Tutorial 11 (scikitlearn) - Árvores de Classificação e Regressão.ipynb | InsightLab/data-science-cookbook | mit |
Podemos então ver o desempenho do algoritmo quando avaliado sobre cada um dos folds. | scores | 2019/06-decision-tree/Tutorial 11 (scikitlearn) - Árvores de Classificação e Regressão.ipynb | InsightLab/data-science-cookbook | mit |
Por fim podemos calcular a média dos scores utilizando a função mean da biblioteca numpy, que já foi importada acima. | media = np.mean(scores) * 100
print('Media: %s%%' % media) | 2019/06-decision-tree/Tutorial 11 (scikitlearn) - Árvores de Classificação e Regressão.ipynb | InsightLab/data-science-cookbook | mit |
Range | # Imprimindo números pares entre 50 e 101
for i in range(50, 101, 2):
print(i)
for i in range(3, 6):
print (i)
for i in range(0, -20, -2):
print(i)
lista = ['Morango', 'Banana', 'Abacaxi', 'Uva']
lista_tamanho = len(lista)
for i in range(0, lista_tamanho):
print(lista[i])
# Tudo em Python é um objet... | Cap03/Notebooks/DSA-Python-Cap03-04-Range.ipynb | dsacademybr/PythonFundamentos | gpl-3.0 |
使用sklearn做logistic回归
王成军
wangchengjun@nju.edu.cn
计算传播网 http://computational-communication.com
logistic回归是一个分类算法而不是一个回归算法。
可根据已知的一系列因变量估计离散数值(比方说二进制数值 0 或 1 ,是或否,真或假)。
简单来说,它通过将数据拟合进一个逻辑函数(logistic function)来预估一个事件出现的概率。
因此,它也被叫做逻辑回归。因为它预估的是概率,所以它的输出值大小在 0 和 1 之间(正如所预计的一样)。
$$odds= \frac{p}{1-p} = \frac{probability\... | repost = []
for i in df.title:
if u'转载' in i.decode('utf8'):
repost.append(1)
else:
repost.append(0)
data_X = [[df.click[i], df.reply[i]] for i in range(len(df))]
data_X[:3]
from sklearn.linear_model import LogisticRegression
df['repost'] = repost
model.fit(data_X,df.repost)
model.score(data_X... | code/.ipynb_checkpoints/9.machine_learning_with_sklearn-checkpoint.ipynb | computational-class/computational-communication-2016 | mit |
The csv (comma separated values) data will be read into a Pandas dataframe (nyr) and the first 5 records are displayed using the 'head()' method.<br> | import pandas as pd
nyr = pd.read_csv(nyrdata)
nyr.head() | New York Restaurants Demo.ipynb | sharynr/notebooks | apache-2.0 |
Ingesting data can be as simple as using one line of code. Similarly, data can be ingested from Cloudant, DashDB, Object Storage, relational databases, and many others.
Another dataframe will be created that will only contain the columns that are pertinent. The 'head()' method will display the first 5 records of this... | nyrcols = nyr[['FACILITY','TOTAL # CRITICAL VIOLATIONS','Location1']]
nyrcols.head() | New York Restaurants Demo.ipynb | sharynr/notebooks | apache-2.0 |
The data will be transformed into a Spark dataframe 'nyrDF' and a table will be registered. Spark dataframes are conceptually equivalent to a table in a relational database or a dataframe in R/Python, but with richer optimizations under the hood. A table that is registered can be used in subsequent SQL statements. | nyrDF = spark.createDataFrame(nyrcols)
nyrDF.registerTempTable("nyrDF") | New York Restaurants Demo.ipynb | sharynr/notebooks | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.