markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Function with state
For the solvers which have the option "rhs_with_state"
the QobjEvo can take coefficient function with the signature (for backward compatibility):
def coeff(t, psi. args)
or use advanced args: args={"psi=vec":psi0} | def coeff_state(t, args):
return np.max(args["psi"])*args["w"]
td_state = QobjEvo([Id, [destroy, coeff_state]],args={"w":1, "psi=vec":qt.basis(N,0)})
td_state(2,state=vec) | development/development-qobjevo-adv.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
Cython object and "Compiling"
There is a cython version of the qobjevo for fast call:
- qutip.cy.cqobjevo.CQobjEvo
The cython is created when the "compile" method is created.
The cython object contain fast version of the call, expect and rhs (spmv) methods. | td_str.compiled = False
print("Before compilation")
%timeit td_str(2, data=True)
%timeit td_str.mul_vec(2,vec)
%timeit td_str.mul_mat(2,mat_c)
%timeit td_str.mul_mat(2,mat_f)
%timeit td_str.expect(2,vec,0)
td_str.compile()
print("After compilation")
%timeit td_str(2, data=True)
%timeit td_str.mul_vec(2,vec)
%timeit td_... | development/development-qobjevo-adv.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
apply
Pass a function ( Qobj, *args, **kwargs) -> Qobj to act on each component of the qobjevo.
Will only be mathematicaly valid if the transformation is linear. | def multiply(qobj, b, factor = 3.):
return qobj*b*factor
print(td_func.apply(multiply,2)(2) == td_func(2)*6)
print(td_func.apply(multiply,2,factor=2)(2) == td_func(2)*4) | development/development-qobjevo-adv.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
apply_decorator
Transform the functions containing the time dependence using a decorator.
The decorator must return a function of (t, **kwargs).
Do not modify the constant part (the contant part do not have a function f(t) = 1). | def rescale_time_and_scale(f_original, time_scale, factor=2.):
def f(t, *args, **kwargs):
return f_original(time_scale*t, *args, **kwargs)*factor
return f
print(td_func.apply_decorator(rescale_time_and_scale, 2)(2) == td_func(4)*2-Id)
print(td_func.apply_decorator(rescale_time_and_scale, 3, factor=3)(2... | development/development-qobjevo-adv.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
QobjEvo based on string and np.array are changed to a function then the decorator is applied. There are option so that the type of coefficient stay unchanged:
str_mod : change the string -> str_mod[0] + str + str_mod[1]
inplace_np : modify the array (array[i] = decorator(lambda v: v)(array[i]))
*any modifica... | td_func_1 = QobjEvo([[create,exp_i]],args={"w":2})
td_str_1 = QobjEvo([[create,"exp(-1j*t)"]],args={'w':2.})
td_array_1 = QobjEvo([[create,np.exp(-1j*tlist)]],tlist=tlist)
def square_qobj(qobj):
return qobj*qobj
def square_f(f_original):
def f(t, *args, **kwargs):
return f_original(t, *args, **kwargs)... | development/development-qobjevo-adv.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
Removing redundant Qobj
When multiple components of the QobjEvo are made from the same Qobj, you can unite them with the "compress" method.
It is only done with the same form of time dependance: | small = qt.destroy(2)
def f1(t,args):
return np.sin(t)
def f2(t,args):
return np.cos(args["w"]*t)
def f3(t,args):
return np.sin(args["w"]*t)
def f4(t,args):
return np.cos(t)
td_redoundance = QobjEvo([qt.qeye(2),[small,"sin(t)"],[small,"cos(w*t)"],[small,"sin(w*t)"],
[s... | development/development-qobjevo-adv.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
cimport cython object
The cython object can be 'cimported'.
cdef class CQobjEvo:
cdef void _mul_vec(self, double t, complex* vec, complex* out)
cdef void _mul_matf(self, double t, complex* mat, complex* out,int nrow, int ncols)
cdef void _mul_matc(self, double t, complex* mat, complex* out,int nrow, int nc... | %%cython
from qutip.cy.cqobjevo cimport CQobjEvo
cimport numpy as np
def rhs_call_from_cy(CQobjEvo qobj, double t, np.ndarray[complex, ndim=1] vec, np.ndarray[complex, ndim=1] out):
qobj._mul_vec(t,&vec[0],&out[0])
def expect_call_from_cy(CQobjEvo qobj, double t, np.ndarray[complex, ndim=1] vec, int ish... | development/development-qobjevo-adv.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
Compiled string code | td_str.compiled = False
print(td_str.compile(code=True))
qt.about() | development/development-qobjevo-adv.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
Determining movie recommendations.
We'll now use the users_feats tensor we computed above to determine the movie ratings and recommendations for each user.
To compute the projected ratings for each movie, we compute the similarity measure between the user's feature vector and the corresponding movie feature vector.
W... | users_ratings = tf.matmul(users_feats, tf.transpose(movies_feats))
users_ratings | courses/machine_learning/deepdive2/recommendation_systems/solutions/content_based_by_hand.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Now we'll make a list of all the residue contacts that are made, keeping only those that occur more than 20% of the time. We'll put that into a ResidueContactConcurrence object, and plot it! | %%time
contacts = ContactFrequency(traj, query=yyg, haystack=protein)
contact_list = [(contact_pair, freq)
for contact_pair, freq in contacts.residue_contacts.most_common()
if freq >= 0.2]
%%time
concurrence = ResidueContactConcurrence(traj, contact_list, select="")
# optionally, crea... | examples/concurrences.ipynb | dwhswenson/contact_map | lgpl-2.1 |
This plot shows when each contact occurred. The x-axis is time. Each dot represents that a specific contact pair is present at that time. The contact pairs are separated along the vertical axis, listed in the order from contact_list (here, decreasing order of frequency of the contact). The contacts are also listed in t... | # for visualization, we need to clean up the trajectory:
traj.topology.create_standard_bonds() # required for image_molecules
traj = traj.image_molecules().superpose(traj)
import nglview as nv
view = nv.show_mdtraj(traj)
view.remove_cartoon()
view.add_cartoon('protein', color='#0000BB', opacity=0.3)
view.add_ball_and... | examples/concurrences.ipynb | dwhswenson/contact_map | lgpl-2.1 |
Migrating model checkpoints
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/migrate/migrating_checkpoints"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https:/... | import tensorflow as tf
import tensorflow.compat.v1 as tf1
def print_checkpoint(save_path):
reader = tf.train.load_checkpoint(save_path)
shapes = reader.get_variable_to_shape_map()
dtypes = reader.get_variable_to_dtype_map()
print(f"Checkpoint at '{save_path}':")
for key in shapes:
print(f" (key='{key}'... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Changes from TF1 to TF2
This section is included if you are curious about what has changed between TF1 and TF2, and what we mean by "name-based" (TF1) vs "object-based" (TF2) checkpoints.
The two types of checkpoints are actually saved in the same format, which is essentially a key-value table. The difference lies in ... | with tf.Graph().as_default() as g:
a = tf1.get_variable('a', shape=[], dtype=tf.float32,
initializer=tf1.zeros_initializer())
b = tf1.get_variable('b', shape=[], dtype=tf.float32,
initializer=tf1.zeros_initializer())
c = tf1.get_variable('scoped/c', shape=[], dtype=... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
If you look at the keys in tf2-ckpt, they all refer to the object paths of each variable. For example, variable a is the first element in the variables list, so its key becomes variables/0/... (feel free to ignore the .ATTRIBUTES/VARIABLE_VALUE constant).
A closer inspection of the Checkpoint object below: | a = tf.Variable(0.)
b = tf.Variable(0.)
c = tf.Variable(0.)
root = ckpt = tf.train.Checkpoint(variables=[a, b, c])
print("root type =", type(root).__name__)
print("root.variables =", root.variables)
print("root.variables[0] =", root.variables[0]) | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Try experimenting with the below snippet and see how the checkpoint keys change with the object structure: | module = tf.Module()
module.d = tf.Variable(0.)
test_ckpt = tf.train.Checkpoint(v={'a': a, 'b': b},
c=c,
module=module)
test_ckpt_path = test_ckpt.save('root-tf2-ckpt')
print_checkpoint(test_ckpt_path) | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Why does TF2 use this mechanism?
Because there is no more global graph in TF2, variable names are unreliable and can be inconsistent between programs. TF2 encourages the object-oriented modelling approach where variables are owned by layers, and layers are owned by a model:
variable = tf.Variable(...)
layer.variable_n... | with tf.Graph().as_default() as g:
a = tf1.get_variable('a', shape=[], dtype=tf.float32,
initializer=tf1.zeros_initializer())
b = tf1.get_variable('b', shape=[], dtype=tf.float32,
initializer=tf1.zeros_initializer())
c = tf1.get_variable('scoped/c', shape=[], dtype=... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
The example below uses tf.compat.v1.Saver to load the checkpoint while in eager mode: | a = tf.Variable(0.0, name='a')
b = tf.Variable(0.0, name='b')
with tf.name_scope('scoped'):
c = tf.Variable(0.0, name='c')
# With the removal of collections in TF2, you must pass in the list of variables
# to the Saver object:
saver = tf1.train.Saver(var_list=[a, b, c])
saver.restore(sess=None, save_path=save_path)
... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
The next snippet loads the checkpoint using the TF2 API tf.train.Checkpoint: | a = tf.Variable(0.0, name='a')
b = tf.Variable(0.0, name='b')
with tf.name_scope('scoped'):
c = tf.Variable(0.0, name='c')
# Without the name_scope, name="scoped/c" works too:
c_2 = tf.Variable(0.0, name='scoped/c')
print("Variable names: ")
print(f" a.name = {a.name}")
print(f" b.name = {b.name}")
print(f" c.na... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Variable names in TF2
Variables still all have a name argument you can set.
Keras models also take a name argument as which they set as the prefix for their variables.
The v1.name_scope function can be used to set variable name prefixes. This is very different from tf.variable_scope. It only affects names, and doesn't... | print_checkpoint('tf1-ckpt') | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Loading with init_from_checkpoint
tf1.train.init_from_checkpoint must be called while in a Graph/Session, because it places the values in the variable initializers instead of creating an assign op.
You can use the assignment_map argument to configure how the variables are loaded. From the documentation:
Assignment ma... | # Restoring with tf1.train.init_from_checkpoint:
# A new model with a different scope for the variables.
with tf.Graph().as_default() as g:
with tf1.variable_scope('new_scope'):
a = tf1.get_variable('a', shape=[], dtype=tf.float32,
initializer=tf1.zeros_initializer())
b = tf1.get_var... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Loading with tf1.train.Saver
Unlike init_from_checkpoint, tf.compat.v1.train.Saver runs in both graph and eager mode. The var_list argument optionally accepts a dictionary, except it must map variable names to the tf.Variable object. | # Restoring with tf1.train.Saver (works in both graph and eager):
# A new model with a different scope for the variables.
with tf1.variable_scope('new_scope'):
a = tf1.get_variable('a', shape=[], dtype=tf.float32,
initializer=tf1.zeros_initializer())
b = tf1.get_variable('b', shape=[], dtype... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Loading with tf.train.load_checkpoint
This option is for you if you need precise control over the variable values. Again, this works in both graph and eager modes. | # Restoring with tf.train.load_checkpoint (works in both graph and eager):
# A new model with a different scope for the variables.
with tf.Graph().as_default() as g:
with tf1.variable_scope('new_scope'):
a = tf1.get_variable('a', shape=[], dtype=tf.float32,
initializer=tf1.zeros_initiali... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Maintaining a TF2 Checkpoint object
If the variable and scope names may change a lot during the migration, then use tf.train.Checkpoint and TF2 checkpoints. TF2 uses the object structure instead of variable names (more details in Changes from TF1 to TF2).
In short, when creating a tf.train.Checkpoint to save or restore... | with tf.Graph().as_default() as g:
a = tf1.get_variable('a', shape=[], dtype=tf.float32,
initializer=tf1.constant_initializer(1))
b = tf1.get_variable('b', shape=[], dtype=tf.float32,
initializer=tf1.constant_initializer(2))
with tf1.variable_scope('scoped'):
c ... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
You can keep using tf.train.Checkpoint even if the variable/scope names change: | with tf.Graph().as_default() as g:
a = tf1.get_variable('a_different_name', shape=[], dtype=tf.float32,
initializer=tf1.zeros_initializer())
b = tf1.get_variable('b_different_name', shape=[], dtype=tf.float32,
initializer=tf1.zeros_initializer())
with tf1.variable_s... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
And in eager mode: | a = tf.Variable(0.)
b = tf.Variable(0.)
c = tf.Variable(0.)
print("Initialized [a, b, c]: ", [a.numpy(), b.numpy(), c.numpy()])
# The keys "scoped" and "unscoped" are no longer relevant, but are used to
# maintain compatibility with the saved checkpoints.
ckpt = tf.train.Checkpoint(unscoped=[a, b], scoped=[c])
ckpt.r... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
TF2 checkpoints in Estimator
The sections above describe how to maintain checkpoint compatiblity while migrating your model. These concepts also apply for Estimator models, although the way the checkpoint is saved/loaded is slightly different. As you migrate your Estimator model to use TF2 APIs, you may want to switch ... | # A model_fn that saves a TF1 checkpoint
def model_fn_tf1_ckpt(features, labels, mode):
# This model adds 2 to the variable `v` in every train step.
train_step = tf1.train.get_or_create_global_step()
v = tf1.get_variable('var', shape=[], dtype=tf.float32,
initializer=tf1.constant_initializ... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
The final value of v should be 16, after being warm-started from est-tf1, then trained for an additional 5 steps. The train step value doesn't carry over from the warm_start checkpoint.
Checkpointing Keras
Models built with Keras still use tf1.train.Saver and tf.train.Checkpoint to load pre-existing weights. When your ... | a = tf.Variable(1.0, name='a')
b = tf.Variable(2.0, name='b')
with tf.name_scope('scoped'):
c = tf.Variable(3.0, name='c')
saver = tf1.train.Saver(var_list=[a, b, c])
path = saver.save(sess=None, save_path='tf1-ckpt-saved-in-eager')
print_checkpoint(path) | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Load a TF1 checkpoint in TF2
<a name="load-tf1-in-tf2"></a> | a = tf.Variable(0., name='a')
b = tf.Variable(0., name='b')
with tf.name_scope('scoped'):
c = tf.Variable(0., name='c')
print("Initialized [a, b, c]: ", [a.numpy(), b.numpy(), c.numpy()])
saver = tf1.train.Saver(var_list=[a, b, c])
saver.restore(sess=None, save_path='tf1-ckpt-saved-in-eager')
print("Restored [a, b, c... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Save a TF2 checkpoint in TF1 | with tf.Graph().as_default() as g:
a = tf1.get_variable('a', shape=[], dtype=tf.float32,
initializer=tf1.constant_initializer(1))
b = tf1.get_variable('b', shape=[], dtype=tf.float32,
initializer=tf1.constant_initializer(2))
with tf1.variable_scope('scoped'):
c ... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Load a TF2 checkpoint in TF1 | with tf.Graph().as_default() as g:
a = tf1.get_variable('a', shape=[], dtype=tf.float32,
initializer=tf1.constant_initializer(0))
b = tf1.get_variable('b', shape=[], dtype=tf.float32,
initializer=tf1.constant_initializer(0))
with tf1.variable_scope('scoped'):
c ... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Checkpoint conversion
<a name="checkpoint-conversion"></a>
You can convert checkpoints between TF1 and TF2 by loading and re-saving the checkpoints. An alternative is tf.train.load_checkpoint, shown in the code below.
Convert TF1 checkpoint to TF2 | def convert_tf1_to_tf2(checkpoint_path, output_prefix):
"""Converts a TF1 checkpoint to TF2.
To load the converted checkpoint, you must build a dictionary that maps
variable names to variable objects.
```
ckpt = tf.train.Checkpoint(vars={name: variable})
ckpt.restore(converted_ckpt_path)
```
Args:
... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Convert the checkpoint saved in the snippet Save a TF1 checkpoint in TF2: | # Make sure to run the snippet in `Save a TF1 checkpoint in TF2`.
print_checkpoint('tf1-ckpt-saved-in-eager')
converted_path = convert_tf1_to_tf2('tf1-ckpt-saved-in-eager',
'converted-tf1-to-tf2')
print("\n[Converted]")
print_checkpoint(converted_path)
# Try loading the converted ... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Convert TF2 checkpoint to TF1 | def convert_tf2_to_tf1(checkpoint_path, output_prefix):
"""Converts a TF2 checkpoint to TF1.
The checkpoint must be saved using a
`tf.train.Checkpoint(var_list={name: variable})`
To load the converted checkpoint with `tf.compat.v1.Saver`:
```
saver = tf.compat.v1.train.Saver(var_list={name: variable})
... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
Convert the checkpoint saved in the snippet Save a TF2 checkpoint in TF1: | # Make sure to run the snippet in `Save a TF2 checkpoint in TF1`.
print_checkpoint('tf2-ckpt-saved-in-session-1')
converted_path = convert_tf2_to_tf1('tf2-ckpt-saved-in-session-1',
'converted-tf2-to-tf1')
print("\n[Converted]")
print_checkpoint(converted_path)
# Try loading the conv... | site/en/guide/migrate/migrating_checkpoints.ipynb | tensorflow/docs | apache-2.0 |
In the above example plot, one of the clusters is linearly seperable and at a good seperation from other two clusters. Two of the clusters are close by and not linearly seperable.
Also the dataset is 4-dimensional i.e. it has 4 features, but for the sake of visualization using matplotlib, one of dimensions has been ign... | # Instantiate the clustering model and visualizer
model = KMeans()
visualizer = KElbowVisualizer(model, k=(2,11))
visualizer.fit(X) # Fit the data to the visualizer
visualizer.poof() # Draw/show/poof the data | examples/gokriznastic/Iris - clustering example.ipynb | pdamodaran/yellowbrick | apache-2.0 |
By default, the scoring parameter metric is set to distortion, which computes the sum of squared distances from each point to its assigned center. However, two other metrics can also be used with the KElbowVisualizer—silhouette and calinski_harabaz. The silhouette score is the mean silhouette coefficient for all ... | # Instantiate the clustering model and visualizer
model = KMeans()
visualizer = KElbowVisualizer(model, k=(2,11), metric='calinski_harabaz', timings=False)
visualizer.fit(X) # Fit the data to the visualizer
visualizer.poof() # Draw/show/poof the data | examples/gokriznastic/Iris - clustering example.ipynb | pdamodaran/yellowbrick | apache-2.0 |
It is important to remember that the Elbow method does not work well if the data is not very clustered. In such cases, you might see a smooth curve and the optimal value of $K$ will be unclear.
You can learn more about the Elbow method at Robert Grove's Blocks.
Silhouette Visualizer
Silhouette analysis can be used to e... | # Instantiate the clustering model and visualizer
model = KMeans(3)
visualizer = SilhouetteVisualizer(model)
visualizer.fit(X) # Fit the data to the visualizer
visualizer.poof() # Draw/show/poof the data | examples/gokriznastic/Iris - clustering example.ipynb | pdamodaran/yellowbrick | apache-2.0 |
For the next example, let's see what happens when using a non-optimal value for $K$, in this case, 6.
Now we see that the width of clusters 1 to 6 have become narrow, of unequal width and their silhouette coefficient scores have dropped. This occurs because the width of each silhouette is proportional to the number of... | # Instantiate the clustering model and visualizer
model = KMeans(6)
visualizer = SilhouetteVisualizer(model)
visualizer.fit(X) # Fit the data to the visualizer
visualizer.poof() # Draw/show/poof the data | examples/gokriznastic/Iris - clustering example.ipynb | pdamodaran/yellowbrick | apache-2.0 |
After Gopal's improvements to Silhouette Visualizer | import numpy as np
import matplotlib.pyplot as plt
from yellowbrick.style import color_palette
from yellowbrick.cluster.base import ClusteringScoreVisualizer
from sklearn.metrics import silhouette_score, silhouette_samples
## Packages for export
__all__ = [
"SilhouetteVisualizer"
]
###########################... | examples/gokriznastic/Iris - clustering example.ipynb | pdamodaran/yellowbrick | apache-2.0 |
Equation of motion - SDE to be solved
$\ddot{q}(t) + \Gamma_0\dot{q}(t) + \Omega_0^2 q(t) - \dfrac{1}{m} F(t) = 0 $
where q = x, y or z
Where $F(t) = \mathcal{F}{fluct}(t) + F{feedback}(t)$
Taken from page 46 of 'Dynamics of optically levitated nanoparticles in high vacuum' - Thesis by Jan Gieseler
Using $\mathcal{F}... | def a_q(t, v, q):
return v
def a_v(t, v, q):
return -(Gamma0 - Omega0*eta*q**2)*v - Omega0**2*q
def b_v(t, v, q):
return np.sqrt(2*Gamma0*k_b*T_0/m)
| SDE_Solution_Derivation.ipynb | AshleySetter/datahandling | mit |
Using values obtained from fitting to data from a real particle we set the following constant values describing the system. Cooling has been assumed to be off by setting $\eta = 0$. | Gamma0 = 4000 # radians/second
Omega0 = 75e3*2*np.pi # radians/second
eta = 0.5e7
T_0 = 300 # K
k_b = scipy.constants.Boltzmann # J/K
m = 3.1e-19 # KG | SDE_Solution_Derivation.ipynb | AshleySetter/datahandling | mit |
partition the interval [0, T] into N equal subintervals of width $\Delta t>0$:
$ 0=\tau {0}<\tau {1}<\dots <\tau {N}=T{\text{ with }}\tau {n}:=n\Delta t{\text{ and }}\Delta t={\frac {T}{N}}$ | dt = 1e-10
tArray = np.arange(0, 100e-6, dt)
print("{} Hz".format(1/dt)) | SDE_Solution_Derivation.ipynb | AshleySetter/datahandling | mit |
set $Y_{0}=x_{0}$ | q0 = 0
v0 = 0
q = np.zeros_like(tArray)
v = np.zeros_like(tArray)
q[0] = q0
v[0] = v0 | SDE_Solution_Derivation.ipynb | AshleySetter/datahandling | mit |
Generate independent and identically distributed normal random variables with expected value 0 and variance dt | np.random.seed(88)
dwArray = np.random.normal(0, np.sqrt(dt), len(tArray)) # independent and identically distributed normal random variables with expected value 0 and variance dt | SDE_Solution_Derivation.ipynb | AshleySetter/datahandling | mit |
Apply Milstein's method (Euler Maruyama if $b'(Y_{n}) = 0$ as is the case here):
recursively define $Y_{n}$ for $ 1\leq n\leq N $ by
$ Y_{{n+1}}=Y_{n}+a(Y_{n})\Delta t+b(Y_{n})\Delta W_{n}+{\frac {1}{2}}b(Y_{n})b'(Y_{n})\left((\Delta W_{n})^{2}-\Delta t\right)$
Perform this for the 2 first order differential equations... | #%%timeit
for n, t in enumerate(tArray[:-1]):
dw = dwArray[n]
v[n+1] = v[n] + a_v(t, v[n], q[n])*dt + b_v(t, v[n], q[n])*dw + 0
q[n+1] = q[n] + a_q(t, v[n], q[n])*dt + 0
| SDE_Solution_Derivation.ipynb | AshleySetter/datahandling | mit |
We now have an array of positions, $v$, and velocities $p$ with time $t$. | plt.plot(tArray*1e6, v)
plt.xlabel("t (us)")
plt.ylabel("v")
plt.plot(tArray*1e6, q)
plt.xlabel("t (us)")
plt.ylabel("q") | SDE_Solution_Derivation.ipynb | AshleySetter/datahandling | mit |
Alternatively we can use a derivative-free version of Milsteins method as a two-stage kind-of Runge-Kutta method, documented in wikipedia (https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_method_%28SDE%29) or the original in arxiv.org https://arxiv.org/pdf/1210.0933.pdf. | q0 = 0
v0 = 0
X = np.zeros([len(tArray), 2])
X[0, 0] = q0
X[0, 1] = v0
def a(t, X):
q, v = X
return np.array([v, -(Gamma0 - Omega0*eta*q**2)*v - Omega0**2*q])
def b(t, X):
q, v = X
return np.array([0, np.sqrt(2*Gamma0*k_b*T_0/m)])
%%timeit
S = np.array([-1,1])
for n, t in enumerate(tArray[:-1]):
... | SDE_Solution_Derivation.ipynb | AshleySetter/datahandling | mit |
The form of $F_{feedback}(t)$ is still questionable
On page 49 of 'Dynamics of optically levitated nanoparticles in high vacuum' - Thesis by Jan Gieseler he uses the form: $F_{feedback}(t) = \Omega_0 \eta q^2 \dot{q}$
On page 2 of 'Parametric feeedback cooling of levitated optomechancs in a parabolic mirror trap' Paper... | def a_q(t, v, q):
return v
def a_v(t, v, q):
return -(Gamma0 + deltaGamma)*v - Omega0**2*q
def b_v(t, v, q):
return np.sqrt(2*Gamma0*k_b*T_0/m)
| SDE_Solution_Derivation.ipynb | AshleySetter/datahandling | mit |
values below are taken from a ~1e-2 mbar cooled save | Gamma0 = 15 # radians/second
deltaGamma = 2200
Omega0 = 75e3*2*np.pi # radians/second
eta = 0.5e7
T_0 = 300 # K
k_b = scipy.constants.Boltzmann # J/K
m = 3.1e-19 # KG
dt = 1e-10
tArray = np.arange(0, 100e-6, dt)
q0 = 0
v0 = 0
q = np.zeros_like(tArray)
v = np.zeros_like(tArray)
q[0] = q0
v[0] = v0
np.random.seed(88)
... | SDE_Solution_Derivation.ipynb | AshleySetter/datahandling | mit |
이 시계열 자료에서 입력 순서열과 target 값을 만든다. 입력 순서열은 3 스텝 크기의 순서열을 사용하고 target으로는 그 다음 시간 스텝의 값을 사용한다. 즉, 3개의 순서열을 입력한 다음 마지막 출력값이 target과 일치하게 만드는 sequence-to-value (many-to-one) 문제를 풀어보도록 한다.
Keras 에서 RNN 을 사용하려면 입력 데이터는 (nb_samples, timesteps, input_dim) 크기를 가지는 ndim=3인 3차원 텐서(tensor) 형태이어야 한다.
nb_samples: 자료의 수
timesteps: 순서... | from scipy.linalg import toeplitz
S = np.fliplr(toeplitz(np.r_[s[-1], np.zeros(s.shape[0] - 2)], s[::-1]))
S[:5, :3]
X_train = S[:-1, :3][:, :, np.newaxis]
Y_train = S[:-1, 3]
X_train.shape, Y_train.shape
X_train[:2]
Y_train[:2]
plt.subplot(211)
plt.plot([0, 1, 2], X_train[0].flatten(), 'bo-', label="input sequence... | 30. 딥러닝/07. RNN 기본 구조와 Keras를 사용한 RNN 구현.ipynb | zzsza/Datascience_School | mit |
Keras의 SimpleRNN 클래스
Keras에서 신경망 모형은 다음과 같은 순서로 만든다.
Sequential 클래스 객체인 모형을 생성한다.
add 메서드로 다양한 레이어를 추가한다.
compile 메서드로 목적함수 및 최적화 방법을 지정한다.
fit 메서드로 가중치를 계산한다.
우선 가장 단순한 신경망 구조인 SimpleRNN 클래스를 사용하는 방법은 다음 코드와 같다.
여기에서는 SimpleRNN 클래스 객체로 10개의 뉴런을 가지는 RNN 층을 만든다. 첫번째 인수로는 뉴런의 크기, input_dim 인수로는 벡터의 크기, input_length 인수... | from keras.models import Sequential
from keras.layers import SimpleRNN, Dense
np.random.seed(0)
model = Sequential()
model.add(SimpleRNN(10, input_dim=1, input_length=3))
model.add(Dense(1))
model.compile(loss='mse', optimizer='sgd') | 30. 딥러닝/07. RNN 기본 구조와 Keras를 사용한 RNN 구현.ipynb | zzsza/Datascience_School | mit |
일단 학습을 시키기 이전에 나오는 출력을 살펴보자. | plt.plot(Y_train, 'ro-', label="target")
plt.plot(model.predict(X_train[:,:,:]), 'bs-', label="output")
plt.xlim(-0.5, 20.5)
plt.ylim(-1.1, 1.1)
plt.legend()
plt.title("Before training")
plt.show() | 30. 딥러닝/07. RNN 기본 구조와 Keras를 사용한 RNN 구현.ipynb | zzsza/Datascience_School | mit |
fit 메서드로 학습을 한다. | history = model.fit(X_train, Y_train, nb_epoch=100, verbose=0)
plt.plot(history.history["loss"])
plt.title("Loss")
plt.show() | 30. 딥러닝/07. RNN 기본 구조와 Keras를 사용한 RNN 구현.ipynb | zzsza/Datascience_School | mit |
학습을 마친 후의 출력은 다음과 같다. | plt.plot(Y_train, 'ro-', label="target")
plt.plot(model.predict(X_train[:,:,:]), 'bs-', label="output")
plt.xlim(-0.5, 20.5)
plt.ylim(-1.1, 1.1)
plt.legend()
plt.title("After training")
plt.show() | 30. 딥러닝/07. RNN 기본 구조와 Keras를 사용한 RNN 구현.ipynb | zzsza/Datascience_School | mit |
SimpleRNN 클래스 생성시 return_sequences 인수를 True로 하면 출력 순서열 중 마지막 값만 출력하는 것이 아니라 전체 순서열을 3차원 텐서 형태로 출력하므로 sequence-to-sequence 문제로 풀 수 있다. 다만 입력 순서열과 출력 순서열의 크기는 같아야 한다.
다만 이 경우에는 다음에 오는 Dense 클래스 객체를 TimeDistributed wrapper를 사용하여 3차원 텐서 입력을 받을 수 있게 확장해 주어야 한다. | from keras.layers import TimeDistributed
model2 = Sequential()
model2.add(SimpleRNN(20, input_dim=1, input_length=3, return_sequences=True))
model2.add(TimeDistributed(Dense(1)))
model2.compile(loss='mse', optimizer='sgd') | 30. 딥러닝/07. RNN 기본 구조와 Keras를 사용한 RNN 구현.ipynb | zzsza/Datascience_School | mit |
이 번에는 출력값도 3개짜리 순서열로 한다. | X_train2 = S[:-3, 0:3][:, :, np.newaxis]
Y_train2 = S[:-3, 3:6][:, :, np.newaxis]
X_train2.shape, Y_train2.shape
X_train2[:2]
Y_train2[:2]
plt.subplot(211)
plt.plot([0, 1, 2], X_train2[0].flatten(), 'bo-', label="input sequence")
plt.plot([3, 4, 5], Y_train2[0].flatten(), 'ro-', label="target sequence")
plt.xlim(-0.... | 30. 딥러닝/07. RNN 기본 구조와 Keras를 사용한 RNN 구현.ipynb | zzsza/Datascience_School | mit |
학습 결과는 다음과 같다. | plt.subplot(211)
plt.plot([1, 2, 3], X_train2[1].flatten(), 'bo-', label="input sequence")
plt.plot([4, 5, 6], Y_train2[1].flatten(), 'ro-', label="target sequence")
plt.plot([4, 5, 6], model2.predict(X_train2[1:2,:,:]).flatten(), 'gs-', label="output sequence")
plt.xlim(-0.5, 7.5)
plt.ylim(-1.1, 1.1)
plt.legend()
plt.... | 30. 딥러닝/07. RNN 기본 구조와 Keras를 사용한 RNN 구현.ipynb | zzsza/Datascience_School | mit |
Load, explore, and prepare the dataset
The first critical step is preparing the data correctly.
Variables/values on different scales make it difficult for the NN to efficiently learn the correct parameters (e.g. weights and biases). | # To check the data in the Terminal/Konsole
% ls data/bike_data/
data_path = 'data/bike_data/hour.csv'
rides = pd.read_csv(data_path)
# # The new historical/time-seri data to visualize
# data_path_watch = 'data/watch_multisensor_data/2_Year_Data_Basis_Watch/2-year_data/Basis_Watch_Data.csv'
# watch = pd.read_csv(data_... | impl-dl/etc/misc/nn.ipynb | arasdar/DL | unlicense |
Downloading/ checking out the bike sharing dataset
Bike sharing dataset has the number of riders for each hour of each day from January 1 2011 to December 31 2012.
The number of riders is split between casual and registered, summed up in the cnt column.
You can see the first few rows of the data above.
Below is a plo... | rides.head()
rides[:10]
rides[:24*10].plot(x='dteday', y='cnt')
# watch[:1000].plot() | impl-dl/etc/misc/nn.ipynb | arasdar/DL | unlicense |
Dummy variables
Here we have some categorical variables such as season, weather, and month.
To include these in our model, we'll need to make binary dummy variables.
This is simple to do with Pandas thanks to get_dummies(). | dummy_fields = ['season', 'weathersit', 'mnth', 'hr', 'weekday']
for each in dummy_fields:
dummies = pd.get_dummies(rides[each], prefix=each, drop_first=False)
rides = pd.concat([rides, dummies], axis=1)
fields_to_drop = ['instant', 'dteday', 'season', 'weathersit',
'weekday', 'atemp', 'mnth... | impl-dl/etc/misc/nn.ipynb | arasdar/DL | unlicense |
Batch normalization for standardizing the dataset using mean and variance/ scaling the data
To training NN easier and more efficiently, we should standardize each of the continuous variables.
we'll shift and scale the variables such that they have zero-mean and a standard deviation of 1.
These scaling factors are save... | quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed']
# Store scalings in a dictionary so we can convert back later
scaled_features = {}
for each in quant_features:
mean, std = data[each].mean(), data[each].std()
scaled_features[each] = [mean, std]
data.loc[:, each] = (data[each] - m... | impl-dl/etc/misc/nn.ipynb | arasdar/DL | unlicense |
Splitting the dataset into training, validation, and testing sets
We'll save the data for the last approximately 21 days to use as test set after we've trained the network.
We'll use this set to make predictions and compare them with the actual number of riders. | # Save data for approximately the last 21 days * 24 hours-per-day (24 hours/day)
test_data = data[-21*24:]
# Now remove the test data from the data set
data = data[:-21*24]
# Separate the data into features and targets
target_fields = ['cnt', 'casual', 'registered']
features, targets = data.drop(target_fields, axis... | impl-dl/etc/misc/nn.ipynb | arasdar/DL | unlicense |
Dividing the entire training data into training and validation sets to avoid overfitting and underfitting during the training
We'll split the entire training data into two sets: one for training and one for validating as NN is being trained. Since this is a time-series dataset, we'll train on historical data, then try ... | # Hold out the last 60 days for validation set
# txn: t is time/row (num of records) and n is space/col (input feature space dims)
# txm: t is time/row (num of records) and m is space/col (output feature space dims)
train_features_txn, train_targets_txm = features[:-60*24], targets[:-60*24]
valid_features_txn, valid_ta... | impl-dl/etc/misc/nn.ipynb | arasdar/DL | unlicense |
Training the NN
At first, we'll set the hyperparameters for the NN.
The strategy here is to find hyperparameters such that the error on the training set is the low enough, but you're not underfitting or overfitting to the training set.
If you train the NN too long or NN has too many hidden nodes, it can become overly... | ### Set the hyperparameters here ###
num_epochs = 100 # updating NN parameters (w, b)
learning_rate = 2 * 1/train_features_txn.shape[0] # train_features = x_txn, t: number of recorded samples/records
hidden_nodes = 5
output_nodes = 1 # y_tx1
input_nodes = train_features_txn.shape[1] # x_txn
# Buidlingthe NN by initial... | impl-dl/etc/misc/nn.ipynb | arasdar/DL | unlicense |
Test predictions
Here, we test our NN on the test data to view how well the NN is modeling/predicting the test dataset.
If something is wrong, the NN is NOT implemented correctly. | fig, ax = plt.subplots(figsize=(8,4))
mean, std = scaled_features['cnt']
predictions_tx1 = nn.run(test_features_txn).T*std + mean
ax.plot(predictions_tx1[0], label='Prediction')
ax.plot((test_targets_txm['cnt']*std + mean).values, label='Data')
ax.set_xlim(right=len(predictions_tx1))
ax.legend()
dates = pd.to_datetim... | impl-dl/etc/misc/nn.ipynb | arasdar/DL | unlicense |
Path and file definitions | os.name
if os.name == 'posix':
baseDir = r'/home/hase/Documents/ZHAW/InfoEng/Lectures/Information_Retrieval/Exercises/PT_5_MiniRetrieve/'
doc_path = r'/home/hase/Documents/ZHAW/InfoEng/Lectures/Information_Retrieval/Exercises/PT_5_MiniRetrieve/documents/'
query_path = r'/home/hase/Documents/ZHAW/InfoEng/L... | scripting/exercises/Mini+Retrieve.ipynb | pandastrail/InfoEng | gpl-3.0 |
Read files | # First, read the entire document as a string
def readDoc(dir_path, file):
path = dir_path + file
with open(path, 'r') as f:
string = f.read()
return string
# Reading document and create a string
string = readDoc(doc_path, '1')
#string | scripting/exercises/Mini+Retrieve.ipynb | pandastrail/InfoEng | gpl-3.0 |
Simple Tokenize | # Define regex to parse the string, and perform a simple tokenize
# Later will need a proper tokenize function to remove stopwords
split_regex = r'\W+'
def simpleTokenize(string):
""" A simple implementation of input string tokenization
Args:
string (str): input string
Returns:
list: a list... | scripting/exercises/Mini+Retrieve.ipynb | pandastrail/InfoEng | gpl-3.0 |
Remove Stopwords | # File with stopwords
stopfile = os.path.join(baseDir, STOPWORDS_PATH)
print(stopfile)
# Create list of stopwords
stopwords = []
with open(stopfile, 'r') as s:
stopwords_string = s.read()
stopwords = re.split(split_regex, stopwords_string)
type(stopwords), len(stopwords)
def tokenize(string):
""" An i... | scripting/exercises/Mini+Retrieve.ipynb | pandastrail/InfoEng | gpl-3.0 |
Inverted and Non-Inverted index
for each document 'doc' in the list of documents D:
get tokens by tokenizing 'd'
for each token in tokens:
inverted index dict {token_one:[doc with token_one, frequency of token_one in doc with token_one],
token_two:[doc with token two, frequency of token_two... | def noninvIndex(dir_path, num_files):
""" A simple implementation of non-inverted index
i.e. token frequency found in document
Args:
dir_path (string): path were all the documents are stored
num_files (string): number of files stored in dir_path; assuming the name is a number
Returns:
... | scripting/exercises/Mini+Retrieve.ipynb | pandastrail/InfoEng | gpl-3.0 |
Annotate
You can add new fields to a table with annotate. As an example, let's create a new column called cleaned_occupation that replaces missing entries in the occupation field labeled as 'other' with 'none.' | missing_occupations = hl.set(['other', 'none'])
t = users.annotate(
cleaned_occupation = hl.cond(missing_occupations.contains(users.occupation),
hl.null('str'),
users.occupation))
t.show() | hail/python/hail/docs/tutorials/05-filter-annotate.ipynb | cseed/hail | mit |
transmute replaces any fields mentioned on the right-hand side with the new fields, but leaves unmentioned fields unchanged. transmute is useful for transforming data into a new form. Compare the following two snippts of code. The second is identical to the first with transmute replacing select. | missing_occupations = hl.set(['other', 'none'])
t = users.select(
cleaned_occupation = hl.cond(missing_occupations.contains(users.occupation),
hl.null('str'),
users.occupation))
t.show()
missing_occupations = hl.set(['other', 'none'])
t = users.tr... | hail/python/hail/docs/tutorials/05-filter-annotate.ipynb | cseed/hail | mit |
Collections | ## Tuple - immutable
my_tuple = (2, 3, 4, 5)
print('A tuple:', my_tuple)
print('First element of tuple:', my_tuple[0])
## List
my_list = [2, 3, 4, 5]
print('A list:', my_list)
print('First element of list:', my_list[0])
my_list.append(12)
print('Appended list:', my_list)
my_list[0] = 45
print('Modified list:', my_list... | python_basic_2_intro.ipynb | pycam/python-basic | unlicense |
Functions used so far... | my_list = ['A', 'C', 'A', 'T', 'G']
print('There are', len(my_list), 'elements in the list', my_list)
print('There are', my_list.count('A'), 'letter A in the list', my_list)
print("ATG TCA CCG GGC".split()) | python_basic_2_intro.ipynb | pycam/python-basic | unlicense |
While the temperature ratio appears fixed in Equations (7) and (8), variation in the derived values can be estimated from the variation in $\gamma = c_p / c_v$. There will also be variation in the specific relation between the gas internal energy and the gas pressure, but this is more difficult to quantify from stellar... | %matplotlib inline
import matplotlib.pyplot as plt
Teffs = np.arange(3000., 6100., 250.)
Tspot_fixed_gamma = Teffs*(0.4)**0.4
# gamma where tau ~ 1 (note, no 0.2 Msun point)
Gammas = np.array([1.22, 1.29, 1.30, 1.29, 1.36, 1.55, 1.63, 1.65])
ModelT = np.array([3.51, 3.57, 3.59, 3.61, 3.65, 3.71, 3.74, 3.77]) # tau = ... | Daily/20150803_pressure_reduc_spots.ipynb | gfeiden/Notebook | mit |
Results of this simple model indicate that equilibration of a polytropic gas within a magnetic structure located near the photosphere ($\tau_{\rm ross} = 1$) provides a reasonable approximation to observed spot temperatures from low-mass M dwarfs up to solar-type stars. Above 5400 K, the gas is sufficiently ideal that ... | # log(Pressure)
p_gas = np.array([6.37, 5.90, 5.80, 5.70, 5.60, 5.45, 5.30, 5.15])
B_field_Eeq = np.sqrt(12.*np.pi*0.4*10**p_gas)/1.0e3 # in kG
B_field_Peq = np.sqrt( 8.*np.pi*10**p_gas)/1.0e3
# smooth curves
icurve = interp1d(ModelT, B_field_Eeq, kind='cubic')
B_field_Eeq_smooth = icurve(np.arange(3240., 5880., 20.)... | Daily/20150803_pressure_reduc_spots.ipynb | gfeiden/Notebook | mit |
The two curves represent two different approximations, one is energy equipartition (red curve) and the other that the magnetic pressure is precisely equal to the gas pressure (blue curve). These values do not represent surface averaged magnetic field strengths, but the strengths of local concentrations of magnetic flux... | B_field_strengths = np.arange(0.1, 8.1, 0.1)*1.0e3
log_P_phot = np.array([5.15, 5.60, 5.90])
Gamma_phot = np.array([1.65, 1.36, 1.29])
Exponents = (Gamma_phot - 1.0)/Gamma_phot
print Exponents
fig, ax = plt.subplots(3, 1, figsize=(8, 12), sharex=True)
i = 0
ax[2].set_xlabel('Spot Magnetic Field (kG)', fontsize=20.)
f... | Daily/20150803_pressure_reduc_spots.ipynb | gfeiden/Notebook | mit |
M Dwarfs
Shulyak et al. (2010, 2014) have measured distribution of magnetic fields on the surfaces of M dwarfs by modeling FeH bands in high resolution, high S/N Stokes I sectra. They find M dwarf spectra are typically best fit by a uniform 1 kG magnetic field everywhere on the star, but with the addition of local conc... | Shulyak_max_B = np.array([[3400., 100., 6.5, 0.5],
[3400., 100., 6.0, 0.5],
[3300., 100., 7.5, 0.5],
[3100., 100., 6.5, 0.5],
[3100., 50., 1.0, 0.5]])
fig, ax = plt.subplots(1, 1, figsize=(8,4))
ax.set_xlabel('... | Daily/20150803_pressure_reduc_spots.ipynb | gfeiden/Notebook | mit |
We find that the data from Shulyak et al. (2014) for the maximum mangetic field strengths (in local concentrations) of active stars are on the order of those expected from either energy of pressure equipartition. The fact that two have weaker magnetic fields only indicates that the there were no strong local concentrat... | Shulyak_max_B = np.array([[3685., 100., 6.5, 0.5],
[3685., 100., 6.0, 0.5],
[3578., 100., 7.5, 0.5],
[3379., 100., 6.5, 0.5],
[3379., 50., 1.0, 0.5]])
fig, ax = plt.subplots(1, 1, figsize=(8,4))
ax.set_xlabel('... | Daily/20150803_pressure_reduc_spots.ipynb | gfeiden/Notebook | mit |
The loss function
You can linearly reweight the chaos into doing very useful computation. We call this learner the readout readout unit.
Model an output or readout unit for the network as:
$$z = \mathbf{w}^T \tanh[\mathbf{x}]$$
The output $z$ is a scalar formed by the dot product of two N-dimensional vectors ($\mathbf{... | target = lambda t0: cos(2 * pi * t0 / 50) # target pattern
def f3(t0, x):
return -x + g * dot(J, tanh_x) + dot(w, tanh_x) * u
dt = 1 # time step
tmax = 800 # simulation length
tstop = 300
N = 300
J = normal(0, sqrt(1 / N), (N, N))
x0 = uniform(-0.5, 0.5, N)
t = linspace(0, 50, 500)
g = 1.5
u = uniform(... | .ipynb_checkpoints/DFORCE-checkpoint.ipynb | avicennax/jedi | mit |
The binary loss function
Now let's learn, with binary codes. | target = lambda t0: cos(2 * pi * t0 / 50) # target pattern
def f3(t0, x):
return -x + g * dot(J, tanh_x) + dot(w, tanh_x) * u
dt = 1 # time step
tmax = 800 # simulation length
tstop = 500
N = 300
J = normal(0, sqrt(1 / N), (N, N))
x0 = uniform(-0.5, 0.5, N)
t = linspace(0, 50, 500)
rho = 0.1 # Set an... | .ipynb_checkpoints/DFORCE-checkpoint.ipynb | avicennax/jedi | mit |
MNIST SGD
Get the 'pickled' MNIST dataset from http://deeplearning.net/data/mnist/mnist.pkl.gz. We're going to treat it as a standard flat dataset with fully connected layers, rather than using a CNN. | path = Config().data/'mnist'
path.ls()
with gzip.open(path/'mnist.pkl.gz', 'rb') as f:
((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding='latin-1')
plt.imshow(x_train[0].reshape((28,28)), cmap="gray")
x_train.shape
x_train,y_train,x_valid,y_valid = map(torch.tensor, (x_train,y_train,x_valid,... | dev_nbs/course/lesson5-sgd-mnist.ipynb | fastai/fastai | apache-2.0 |
In lesson2-sgd we did these things ourselves:
python
x = torch.ones(n,2)
def mse(y_hat, y): return ((y_hat-y)**2).mean()
y_hat = x@a
Now instead we'll use PyTorch's functions to do it for us, and also to handle mini-batches (which we didn't do last time, since our dataset was so small). | from torch.utils.data import TensorDataset
bs=64
train_ds = TensorDataset(x_train, y_train)
valid_ds = TensorDataset(x_valid, y_valid)
train_dl = TfmdDL(train_ds, bs=bs, shuffle=True)
valid_dl = TfmdDL(valid_ds, bs=2*bs)
dls = DataLoaders(train_dl, valid_dl)
x,y = dls.one_batch()
x.shape,y.shape
class Mnist_Logistic... | dev_nbs/course/lesson5-sgd-mnist.ipynb | fastai/fastai | apache-2.0 |
Zaporedje je padajoče, če je naslednji člen manjši od prejšnjega: $a_n>a_{n+1}$. Iz grafa vidimo, da je od približno 15 člena naprej zaporedje padajoče. Poiščimo $n$ pri katerem se to zgodi še s programom. | n = 0
while a(n)<a(n+1):
n += 1
n | 02a_zaporedja.ipynb | mrcinv/matpy | gpl-2.0 |
Graf in program seveda nista dokaz, da je zaporedje padajoče za vse $n>14$. Lahko pa to preverimo, tako da rešimo neenačbo
$$ a_n>a_{n+1}$$
$$ \frac{n^{10}}{2^n}>\frac{(n+1)^{10}}{2^{n+1}}$$ | import sympy as sym
sym.init_printing() # lepši izpis formul
from sympy.solvers.inequalities import solve_univariate_inequality
from sympy import Symbol
n = Symbol('n', real=True) # n simbol, ki je realno število
neenacba = a(n) > a(n+1)
sym.simplify(neenacba)
solve_univariate_inequality(neenacba,n) | 02a_zaporedja.ipynb | mrcinv/matpy | gpl-2.0 |
Neenačba je previsoke stopnje, zato je SymPy ne zna rešiti. Rešitev lahko poiščemo sami, tako da najprej rešimo enačbo. Nato določimo, na katerih intervalih neeančba velja. | from sympy.solvers import solve
resitve = solve(neenacba.lhs-neenacba.rhs)
resitve
[float(x) for x in resitve]
neenacba.subs(n,15) # v enačbo vstavimo n=15 | 02a_zaporedja.ipynb | mrcinv/matpy | gpl-2.0 |
Rekurzivna zaporedja
Zaporedje lahko podamo tudi z rekurzivno formulo
$$a_{n+1}=f(a_n)$$
in prvim členom
$a_0$.
Primer
Zaporedje je dano z rekurzivno formulo
$$a_{n+1}=1+\frac{1}{a_n}$$
in začetnim členom $a_0=\frac{1}{2}$.
Nariši nekaj členov zaporedja
Pokaži, da sta zaporedji $a_{2n}$ in $a_{2n+1}$ monotoni in o... | # narišemo nekaj prvih členov
n0 = 20
a = n0*[0]
a[0] = 1/2
for n in range(n0-1):
a[n+1] = 1+1./a[n]
print("Prvih %d členov zaporedja\n" % n0)
print((n0*"%0.8f\n")%tuple(a))
from matplotlib import pyplot as plt
%matplotlib inline
plt.plot(range(n0),a,'o')
plt.title("Členi zaporedja $a_n$")
plt.show() | 02a_zaporedja.ipynb | mrcinv/matpy | gpl-2.0 |
Prvih nekaj členov nam razkrije, da je zaporedje lihih členov $a_{2n+1}$ padajoče, zaporedje sodih členov $a_{2n}$ pa naraščajoče. Da bi to preverili/dokazali, zapišimo rekurzivno enačbo, ki ji zadoščata podzaporedji $a_{2n+1}$ in $a_{2n}$.
Rekurzivna enačba
$$a_{n+1}=f(a_n)=1+\frac{1}{a_n}$$
je določena s funkcijo $... | import sympy as sym
sym.init_printing()
# zaporedje je podano s funkcijo f(x) = 1+1/x
f = lambda x: 1+1/x
n = sym.Symbol('n')
a_n = sym.Symbol('a_n')
f(f(a_n))
sym.simplify(f(f(a_n))) | 02a_zaporedja.ipynb | mrcinv/matpy | gpl-2.0 |
Zaporedji lihih členov in sodih členov zadoščata rekurzivni formuli
$$a_{n+2}=\frac{2 a_{n} + 1}{a_{n} + 1}.$$
Zaporedje $a_{2n}$ bo naraščalo, če bo veljalo
$$a_{2n+2} > a_{2n}$$
oziroma
$$\frac{2 a_{2n} + 1}{a_{2n} + 1} > a_{2n}.$$ | ff = lambda x: f(f(x))
a_2n = sym.Symbol('a_2n')
sym.simplify(ff(a_2n) > a_2n)
sym.solve_univariate_inequality(ff(a_2n)>a_2n,a_2n) | 02a_zaporedja.ipynb | mrcinv/matpy | gpl-2.0 |
Zaporedje sodih členov $a_{2n}$ bo padajoče, če so členi
$$a_{2n}>\frac{1}{2}+\frac{\sqrt{5}}{2}$$
in naraščajoče, če so členi
$$a_{2n}<\frac{1}{2}+\frac{\sqrt{5}}{2}.$$
Podobno velja za zaporedje lihih členov $a_{2n+1}$. | neenacba = ff(a_2n)<1/sym.Integer(2)+sym.sqrt(sym.Integer(5))/2
neenacba
sym.solve_univariate_inequality(neenacba,a_2n) | 02a_zaporedja.ipynb | mrcinv/matpy | gpl-2.0 |
Vidimo, da je
$$a_{2n}<\frac{1}{2}+\frac{\sqrt{5}}{2}\implies a_{2n+2}<\frac{1}{2}+\frac{\sqrt{5}}{2}.$$
Po indukciji sklepamo, da so vsi členi $a_{2n}<\frac{1}{2}+\frac{\sqrt{5}}{2}$, če to velja za prvi člen
$$a_0= \frac{1}{2}<\frac{1}{2}+\frac{\sqrt{5}}{2}.$$
Ker so vsi členi $a_{2n}<\frac{1}{2}+\frac{\sqrt{5}}{... | resitve = sym.solve(sym.Eq(a_n,f(a_n)),a_n)
resitve | 02a_zaporedja.ipynb | mrcinv/matpy | gpl-2.0 |
Rešitvi sta nam že poznani iz predhodne analize. Limita je očitno enaka prvi rešitvi $$\frac{1}{2}+\frac{\sqrt{5}}{2},$$
saj je $a_n>0$. | resitve[0].evalf() # numerični približek za limito se ujema s prej izračunanimi členi zaporedja | 02a_zaporedja.ipynb | mrcinv/matpy | gpl-2.0 |
Grafična predstavitev rekurzivnega zaporedja
Rekurzivno podano zaporedje z rekurzivno formulo
$$a_{n+1}=f(a_n)$$
si lahko predstavljamo tudi grafično. Limita zaporedja $a_n$ je rešitev enačbe
$$a=f(a)$$
Grafično prestavlja limita presečišče grafa funkcije $y=f(x)$ in simetrale lihih kvadrantov $y=x$. | import numpy as np
t=np.linspace(0.4,4)
l1, = plt.plot(t,t,label="$y=x$")
l2, = plt.plot(t,f(t),label="$y=f(x)$")
x = sym.Symbol('x')
resitve = sym.solve(sym.Eq(x,f(x)),x) # limita/rešitev enačbe x=f(x)
plt.plot(resitve[0],f(resitve[0]),'o')
# oznake in legenda
plt.annotate("$x=f(x)$",xy=(resitve[0],resitve[0]),xytext=... | 02a_zaporedja.ipynb | mrcinv/matpy | gpl-2.0 |
Zaporedje grafično konstruiramo v več korakih. Za vsak nov člen zaporedja $a_{n+1}$ izvedemo naslednje korake:
na grafu funkcije odčitamo $f(a_n)$ (navpična črta)
vrednost $a_{n+1}=f(a_n)$ prenesemo na premico $y=x$ (vodoravna črta)
iz premice $y=x$ prenesemo vrednost $a_{n+1}$ na $x$-os (navpična črta)
Dodatek: Zapr... | def gen_rekurzijo(a0,fun):
"""Funkcija definira rekurzivno zaporedje z rekurzivno formulo
a(n+1)=fun(a(n)) in začetnim členom
a(0)=a0"""
zaporedje = [a0]
def a(n):
if len(zaporedje)-1<n: # če člen zaporedja še ni izračunam
vrednost = fun(a(n-1)) # rekurzivna formula
... | 02a_zaporedja.ipynb | mrcinv/matpy | gpl-2.0 |
Primer
Zaporedje za računanje $\sqrt{2}$ je dano z rekurzivno formulo
$$a_{n+1}=\frac{1}{2}\left(a_n+\frac{2}{a_n}\right).$$
Izračunaj $\sqrt{2}$ na 12 decimalk natančno. | koren2 = gen_rekurzijo(2,lambda x:(x+2/x)/2)
koren2(1)
koren2(3)
n = 0
while abs(koren2(n)**2-2)>1e-12:
n += 1
print("n: %d, koren: %1.12f" % (n,koren2(n))) | 02a_zaporedja.ipynb | mrcinv/matpy | gpl-2.0 |
>> naprej: vrste | import disqus
%reload_ext disqus
%disqus matpy | 02a_zaporedja.ipynb | mrcinv/matpy | gpl-2.0 |
Data
The data used in this notebook is also available on FigShare:
Geers AJ, Larrabide I, Radaelli AG, Bogunovic H, Kim M, Gratama van Andel HAF, Majoie CB, VanBavel E, Frangi AF. Reproducibility of hemodynamic simulations of cerebral aneurysms across imaging modalities 3DRA and CTA: Geometric and hemodynamic data. Fig... | df_input = pd.read_csv(os.path.join('data', '3dracta.csv'), index_col=[0, 1])
df_input | data_analysis.ipynb | ajgeers/3dracta | bsd-2-clause |
Extract separate dataframes for 3DRA and CTA. | df_3dra = df_input.xs('3dra', level='modality')
df_cta = df_input.xs('cta', level='modality') | data_analysis.ipynb | ajgeers/3dracta | bsd-2-clause |
Statistics
Calculate the relative difference between 3DRA and CTA wrt 3DRA. Per variable, get the mean and standard error of this relative difference over all aneurysms. | df_reldiff = 100 * abs(df_3dra - df_cta)/df_3dra
s_mean = df_reldiff.mean()
s_standarderror = pd.Series(stats.sem(df_reldiff), index=df_input.columns) | data_analysis.ipynb | ajgeers/3dracta | bsd-2-clause |
Test differences between 3DRA and CTA with the Wilcoxon signed rank test.
Note: MATLAB was used to perform this test for the paper. Its 'signrank' function defaults to using the 'exact method' if a dataset has 15 or fewer observations and the 'approximate method' otherwise. See the documentation for more details. SciPy... | pvalue = np.empty(len(df_input.columns))
for i, variable in enumerate(df_input.columns):
pvalue[i] = stats.wilcoxon(df_3dra[variable], df_cta[variable])[1]
s_pvalue = pd.Series(pvalue, index=df_input.columns) | data_analysis.ipynb | ajgeers/3dracta | bsd-2-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.