markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Implementation: Model Performance Metrics With the predefined functions above, you will now import the three supervised learning models of your choice and run the train_predict function for each one. Remember that you will need to train and predict on each classifier for three different training set sizes: 100, 200, an...
# TODO: Import the three supervised learning models from sklearn # from sklearn import model_A # from sklearn import model_B # from skearln import model_C # TODO: Initialize the three models clf_A = None clf_B = None clf_C = None # TODO: Set up the training set sizes X_train_100 = None y_train_100 = None X_train_200...
Machine learning Nanodegree/student_intervention/student_intervention.ipynb
isamu-isozaki/Machine-Learning
mit
Tabular Results Edit the cell below to see how a table can be designed in Markdown. You can record your results from above in the tables provided. Classifer 1 - ? | Training Set Size | Training Time | Prediction Time (test) | F1 Score (train) | F1 Score (test) | | :---------------: | :---------------------: | :-----...
# TODO: Import 'GridSearchCV' and 'make_scorer' # TODO: Create the parameters list you wish to tune parameters = None # TODO: Initialize the classifier clf = None # TODO: Make an f1 scoring function using 'make_scorer' f1_scorer = None # TODO: Perform grid search on the classifier using the f1_scorer as the scorin...
Machine learning Nanodegree/student_intervention/student_intervention.ipynb
isamu-isozaki/Machine-Learning
mit
Adding Narrative - Markdown Cells Add a new cell to the notebook: click the + button on the toolbar Change the cell type using the drop down list in the toolbar or by using the ESC-M keyboard shortcut. To "open" or select a markdown cell for editing, double click the cell. View the rendered markdown by running the cell...
# Simple Markdown 1 Markdown cells use markdown to generate formatted text: - inline styles - *emphasise text* - __strongly emphasise__ text ## Sub-headings Markdown can also show `inline code` styles as well as code blocks: ```` def mycode(): ''' Here is my non-executable code ''' pass ````
notebooks/Workshop slides - using the notebooks.ipynb
Reproducible-Science-Curriculum/introduction-RR-Jupyter
cc0-1.0
Simple Markdown 2 Markdown can include weblinks, eg to Data Carpentry, as well as links to named elements in the same notebook, or other notebooks. Markdown can embed images: Jupyter logo So how do we do that?
<a name=""></a> # Simple Markdown 2 Markdown can include weblinks, eg to [Data Carpentry](https://datacarpentry.org), as well as links to named elements [in the same notebook](#navlink), or [other notebooks](path/example.ipynb#exampleNavlink). Markdown can embed images: [Jupyter logo](./jupyter-logo.png)
notebooks/Workshop slides - using the notebooks.ipynb
Reproducible-Science-Curriculum/introduction-RR-Jupyter
cc0-1.0
Markdown cells can include Latex Expressions Mathematical expessions can be rendered inline by wrapping a LaTeX expression (no spaces) with a $ either side. $e^x=\sum_{i=0}^\infty \frac{1}{i!}x^i$ is rendered inline: $e^x=\sum_{i=0}^\infty \frac{1}{i!}x^i$ Use $$ to render in the centre of a new line: $$e^x=\sum_{i=0}^...
a=1 b=2 a+b
notebooks/Workshop slides - using the notebooks.ipynb
Reproducible-Science-Curriculum/introduction-RR-Jupyter
cc0-1.0
We Can Run a Cell Multiple Times Each time the cell us run, the state of the underlying python process is updated, even if the visual display of other cells in the notebook is not.
print(a) #Run this cell multiple times a=a+1 a
notebooks/Workshop slides - using the notebooks.ipynb
Reproducible-Science-Curriculum/introduction-RR-Jupyter
cc0-1.0
Working code cells harder We can import packages as you might expect:
import numpy as np np.pi
notebooks/Workshop slides - using the notebooks.ipynb
Reproducible-Science-Curriculum/introduction-RR-Jupyter
cc0-1.0
Code cells also act as a commandline prompt - prefix with a !
! ls *.ipynb # Linux / Mac; #for windows: ! dir *.ipynb
notebooks/Workshop slides - using the notebooks.ipynb
Reproducible-Science-Curriculum/introduction-RR-Jupyter
cc0-1.0
Line numbering in code cells can be toggled with ESC-L. IPython Cell Magics %matplotlib inline: enable inline display of matplotlib generated graphics %whos: display a list of variables and their values as set in the kernel %env: display a list of environment variables and their current values in the host environment....
import pandas as pd pd.DataFrame({'col1':['x','y'],'col2':[1,2]}) %matplotlib inline import matplotlib.pyplot as plt # Create 1000 evenly-spaced values from 0 to 2 pi x = np.linspace(0, 2*np.pi, 1000) #Plot a sine wave over those values y = np.sin(x) plt.plot(x, y) #You can prevent the display of object detail...
notebooks/Workshop slides - using the notebooks.ipynb
Reproducible-Science-Curriculum/introduction-RR-Jupyter
cc0-1.0
Notebooks Can be Support Interactive Widgets that Help You Explore a Dataset If you reate a function that accepts one or more parameters, you may be able to use it as the basis of an automatically generated application. For example, suppose we have a function that will plot a sine wave over the range 0..2 pi for a spec...
#If no frequency value is specified, use the default setting: f=1 def sinplot(f=1): #Define a range of x values x = np.linspace(0, 2*np.pi, 1000) #Plot a sine wave with the specified frequency over that range y = np.sin(f*x) #Plot the chart plt.plot(x, y) sinplot(f=3)
notebooks/Workshop slides - using the notebooks.ipynb
Reproducible-Science-Curriculum/introduction-RR-Jupyter
cc0-1.0
Using ipywidgets interact() Pass the name of your function, and the default values of the parameters, to the ipywidgets interact() function to automatically create interactive widgets to control the parameter values.
from ipywidgets import interact interact(sinplot, f=5)
notebooks/Workshop slides - using the notebooks.ipynb
Reproducible-Science-Curriculum/introduction-RR-Jupyter
cc0-1.0
You can also specify the range of values Applied to an interact() slider: interact(sinplot, f=[0,20]) Or the range of values and the step size: interact(sinplot, f=[0,20,5]) Checking Reproducibility Clear the output of a selected cell: Cell -&gt; Current Output -&gt; Clear Clear the output of all cells in the notebook:...
pd.DataFrame?
notebooks/Workshop slides - using the notebooks.ipynb
Reproducible-Science-Curriculum/introduction-RR-Jupyter
cc0-1.0
2- Aplique paso a paso el método de mínimos cuadrados de tal forma que le permita obtener la mejor curva lineal de ajuste de los datos anteriores, y determine las incertezas asociadas a los parámetros. Determine los coeficientes de correlación $ \chi ^{2} $ y $ R ^{2} $. Reporte correctamente los parámetros con su in...
#n: n=len(X1) #suma xi cuadrado: suma_xi2=0 for i in xrange(0,n): suma_xi2+=(X1[i]*X1[i]) #suma yi cuadrado: suma_yi2=0 for i in xrange(0,n): suma_yi2+=(Y1[i]*Y1[i]) #suma xi simple: suma_xi=0 for i in xrange(0,n): suma_xi+=(X1[i]) #suma yi simple: suma_yi=0 for i in xrange(0,n): suma_yi...
Minimos_Cuadrados/.ipynb_checkpoints/Minimos_Cuadrados-checkpoint.ipynb
cosmolejo/Fisica-Experimental-3
gpl-3.0
b) $$a_{1}= \frac{n\sum x_{i}y_{i} - (\sum x_{i})(\sum y_{i})}{n\sum x_{i}^{2} - (\sum x_{i})^{2}}$$
a1=((n*suma_xiyi)-(suma_xi*suma_yi))/(n*suma_xi2-(suma_xi*suma_xi)) print 'a1 = %.1f'%a1
Minimos_Cuadrados/.ipynb_checkpoints/Minimos_Cuadrados-checkpoint.ipynb
cosmolejo/Fisica-Experimental-3
gpl-3.0
c) $$y= a_{0}+a_{1}x$$
x=np.linspace(X1[0],X1[-1],n) y=(a0 +a1*x) print print 'grafica de los puntos con ajuste: ' fig=plt.figure() ax=fig.add_subplot(111) ax.plot(X1,Y1,'ro') ax.plot(x,y,'b-') ax.set_xlim(xmin=0.0, xmax=8) ax.set_ylim(ymin=0.0, ymax=8) plt.show()
Minimos_Cuadrados/.ipynb_checkpoints/Minimos_Cuadrados-checkpoint.ipynb
cosmolejo/Fisica-Experimental-3
gpl-3.0
$$S_{y} = \sqrt{\frac{1}{n-2}\sum_{i=1}^{n}(y_{i}-a_{0}-a_{1}x_{i})^{2}}$$ $$S_{my} = \frac{S_{y}}{n^{1/2}}$$ $$S_{ma0}^{2}= \frac{S_{my}^{2}\sum x_{i}^{2}}{n\sum x_{i}^{2} - (\sum x_{i})^{2}}$$ $$ S_{ma1}^{2}= \frac{n S_{my}^{2}}{n\sum x_{i}^{2} - (\sum x_{i})^{2}}$$
#desviacion estandar Sy=0 for i in xrange(0,len(y)): Sy+= (y[i]-a0-a1*x[i])**2 #print Sy Sy*=(1/(len(y)-2.)) #print Sy Sy=Sy**(1/2) print 'Sy %.1f'%Sy #error en y raiz= np.sqrt(n) Smy=Sy/(raiz) print 'Smy %.1f'%Smy #error en a0 S2_ma0=(Smy*Smy*suma_xi2)/(n*suma_xi2-(suma_xi*suma_xi)) print 'S2_ma0 %f'%S2_ma0...
Minimos_Cuadrados/.ipynb_checkpoints/Minimos_Cuadrados-checkpoint.ipynb
cosmolejo/Fisica-Experimental-3
gpl-3.0
$$a_{0}\pm S_{ma0} $$ $$ a_{1}\pm S_{ma1} $$
print 'a0 ± sma0: %f ± %f'%(a0,np.sqrt(S2_ma0)) print 'a1 ± sma1: %f ± %f'%(a1,np.sqrt(S2_ma1))
Minimos_Cuadrados/.ipynb_checkpoints/Minimos_Cuadrados-checkpoint.ipynb
cosmolejo/Fisica-Experimental-3
gpl-3.0
3- Grafique todas las posibles curvas de la regresión lineal teniendo en cuenta el error determinado para los parámetros. Concluya al respecto.
err_a0= np.sqrt(S2_ma0) err_a1= np.sqrt(S2_ma1) y=(a0 +a1*x) y1=((a0+err_a0) +(a1+err_a1)*x) y2=((a0-err_a0) +(a1-err_a1)*x) y3=((a0+err_a0) +(a1-err_a1)*x) y4=((a0-err_a0) +(a1+err_a1)*x) print print 'grafica de los puntos con ajustes y errores: ' print 'es facil observar que todas las curvas posibles variando los e...
Minimos_Cuadrados/.ipynb_checkpoints/Minimos_Cuadrados-checkpoint.ipynb
cosmolejo/Fisica-Experimental-3
gpl-3.0
$ \chi ^{2} $ : $$ \chi ^{2} = \sum_{i}^{n} \frac{(Y_{observada}-Y_{teorica})^{2}}{Y_{teorica}}$$y $ R ^{2} $
#chi2 chi2=0 for i in xrange(0,n): chi2=((y[i]-Y1[i])**2)/Y1[i] print 'chi^2 = ',chi2 # r2 b=a1 bprima=a1=((n*suma_xiyi)-(suma_xi*suma_yi))/(n*suma_yi2-(suma_yi*suma_yi)) r2=b*bprima print 'r^2 = ',r2
Minimos_Cuadrados/.ipynb_checkpoints/Minimos_Cuadrados-checkpoint.ipynb
cosmolejo/Fisica-Experimental-3
gpl-3.0
Importing packages uses some RAM
import numpy as np # note that importing a package will increase total RAM usage a little import pandas as pd # note that importing Pandas uses more RAM than importing numpy import string
src/ipython_memory_usage/examples/example_usage_np_pd.ipynb
ianozsvald/ipython_memory_usage
bsd-2-clause
Making a large array uses a predictable amount of RAM
# if we make a big array - 100M items * 8 byte floats, this cell # uses circa 800MB (often 760 MiB - note mibi-bytes as used in the underlying memory_profiler tool) # The total RAM usage grows by roughly this amount arr = np.ones(100_000_000) # deleting arr reduces RAM usage by roughly the expected amount and # total...
src/ipython_memory_usage/examples/example_usage_np_pd.ipynb
ianozsvald/ipython_memory_usage
bsd-2-clause
Making a big random array takes RAM + time
# creating random items takes some time, after "used ... RAM" note "3s" or so for several seconds arr = np.random.normal(size=100_000_000) print(arr[:5], arr.dtype)
src/ipython_memory_usage/examples/example_usage_np_pd.ipynb
ianozsvald/ipython_memory_usage
bsd-2-clause
Intermediate calculations can cost additional temporary RAM NOTE this section may work different if you're on Windows (if so - please report back to Ian by raising a bug and noting the difference. On some platforms, e.g. Linux as used here, temporary intermediates can be reused in-place reducing the overall memory allo...
pass # arr*2 and arr*3 both have to be stored somewhere before the division can occur # so two more circa 762MiB arrays are made temporarily, this is reported # as "peaked 762MiB above current" # before they can be discard. arr_result references the final result # so overall we add 762MiB to the process # we only add ...
src/ipython_memory_usage/examples/example_usage_np_pd.ipynb
ianozsvald/ipython_memory_usage
bsd-2-clause
Pandas DataFrames can be costly on RAM Example with deleting columns Props to Jamie Brunning for this example
pass arr_several_cols = np.random.normal(size=(100_000_000, 4)) arr_several_cols.shape f"Cost per column {int(arr_several_cols.data.nbytes / arr_several_cols.shape[1]):,} bytes" # The DataFrame in this case is a thin wrapper over the numpy array # and costs little extra RAM df = pd.DataFrame(arr_several_cols, colum...
src/ipython_memory_usage/examples/example_usage_np_pd.ipynb
ianozsvald/ipython_memory_usage
bsd-2-clause
Diagnostics %xdel my_df will delete all references of my_df from the namespace including those in the Out[] history buffer, this does more cleaning than just using del my_df. %reset will reset all variables and imported modules, it is like starting a new kernel.
# %whos shows what's in the local namespace %whos # we can use %xdel to safely remove all references including those that might be (but not in this case) # in the Out[] history buffer %xdel df %ipython_memory_usage_stop
src/ipython_memory_usage/examples/example_usage_np_pd.ipynb
ianozsvald/ipython_memory_usage
bsd-2-clause
final output should be [('AFG', 'Afganistan'), ('NPL', 'Nepal') ...]
csvfile = open('untitled.txt', 'r') csvfile csvreader = csv.DictReader(csvfile) country_list = [] for country in csvreader: if country['iso3'] and country['country']: country_tup = (country['iso3'], country['country']) country_list.append(country_tup) country_list fp.close() csvfile.close() w...
session3.ipynb
idwaker/git_python_session
unlicense
Classes and Objects Dogs | ------------------- | | Domestic Wild ------------------ | | Semi Wild Feral ... Transport...
class Animal: age = None class Dog(Animal): pass german_shepherd = Dog() german_shepherd german_shepherd = Dog() german_shepherd german_shepherd.age = 22 german_shepherd.age class Dog(Animal): age = 18 german_shepherd = Dog() german_shepherd.age german_shepherd.age = 21 german_shepherd.age tibe...
session3.ipynb
idwaker/git_python_session
unlicense
CaseStudy: Library Management
class Patron: firstname = None lastname = None address = None books = [] def __repr__(self): return '{} {}'.format(self.firstname, self.lastname) def has_book(self, bookid): return bookid in self.books class Student(Patron): faculty = None year = None ...
session3.ipynb
idwaker/git_python_session
unlicense
1 Creating an instance of the solow.Model class In this notebook I will walk you through the creation of an instance of the solow.Model class. To create an instance of the solow.Model we must define two primitives: an aggregate production function and a dictionary of model parameter values. 1.1 Defining the production ...
solow.Model.output?
examples/1 Getting started.ipynb
solowPy/solowPy
mit
Examples: A common functional form for aggregate production in a Solow model that satisies the above assumptions is the Cobb-Douglas production function \begin{equation} \lim_{\rho \rightarrow 0} Y(t) = K(t)^{\alpha}(A(t)L(t))^{1-\alpha}. \tag{1.1.3} \end{equation} The Cobb-Douglas production function is actually a s...
# define model variables A, K, L = sym.symbols('A, K, L') # define production parameters alpha, sigma = sym.symbols('alpha, sigma') # define a production function cobb_douglas_output = K**alpha * (A * L)**(1 - alpha) rho = (sigma - 1) / sigma ces_output = (alpha * K**rho + (1 - alpha) * (A * L)**rho)**(1 / rho)
examples/1 Getting started.ipynb
solowPy/solowPy
mit
1.2 Defining model parameters A generic Solow growth model has several parameters that need to be specified. To see which parameters are required, we can check the docstring of the solow.Model.params attribute.
solow.Model.params?
examples/1 Getting started.ipynb
solowPy/solowPy
mit
In addition to the standard parameters $g, n, s, \delta$, one will also need to specify any required parameters for the production function. In order to make sure that parameter values are consistent with the models assumptions some basic validation of the solow.Model.params attribute is done when ever the attribute is...
# these parameters look fishy...why? default_params = {'A0': 1.0, 'L0': 1.0, 'g': 0.0, 'n': -0.03, 's': 0.15, 'delta': 0.01, 'alpha': 0.33} # ...raises an AttributeError model = solowpy.Model(output=cobb_douglas_output, params=default_params)
examples/1 Getting started.ipynb
solowPy/solowPy
mit
Examples: Here are some examples of how one successfully creates an instance of the solow.Model class...
cobb_douglas_params = {'A0': 1.0, 'L0': 1.0, 'g': 0.02, 'n': 0.03, 's': 0.15, 'delta': 0.05, 'alpha': 0.33} cobb_douglas_model = solow.Model(output=cobb_douglas_output, params=cobb_douglas_params) ces_params = {'A0': 1.0, 'L0': 1.0, 'g': 0.02, 'n': 0.03, 's': 0....
examples/1 Getting started.ipynb
solowPy/solowPy
mit
1.3 Other attributes of the solow.Model class The intensive form of the production function The assumption of constant returns to scale allows us to work with the intensive form of the aggregate production function, $F$. Defining $c=1/AL$ one can write $$ F\bigg(\frac{K}{AL}, 1\bigg) = \frac{1}{AL}F(A, K, L) \tag{1.3.1...
solowpy.Model.intensive_output? ces_model.intensive_output
examples/1 Getting started.ipynb
solowPy/solowPy
mit
One can numerically evaluate the intensive output for various values of capital stock (per unit effective labor) as follows...
ces_model.evaluate_intensive_output(np.linspace(1.0, 10.0, 25))
examples/1 Getting started.ipynb
solowPy/solowPy
mit
The marginal product of capital The marginal product of capital is defined as follows: $$ \frac{\partial F(K, AL)}{\partial K} \equiv f'(k) \tag{1.3.3}$$ where $k=K/AL$ is capital stock (per unit effective labor).
solowpy.Model.marginal_product_capital? ces_model.marginal_product_capital
examples/1 Getting started.ipynb
solowPy/solowPy
mit
One can numerically evaluate the marginal product of capital for various values of capital stock (per unit effective labor) as follows...
ces_model.evaluate_mpk(np.linspace(1.0, 10.0, 25))
examples/1 Getting started.ipynb
solowPy/solowPy
mit
Equation of motion for capital (per unit effective labor) Because the economy is growing over time due to technological progress, $g$, and population growth, $n$, it makes sense to focus on the capital stock per unit effective labor, $k$, rather than aggregate physical capital, $K$. Since, by definition, $k=K/AL$, we c...
solowpy.Model.k_dot? ces_model.k_dot
examples/1 Getting started.ipynb
solowPy/solowPy
mit
One can numerically evaluate the equation of motion for capital (per unit effective labor) for various values of capital stock (per unit effective labor) as follows...
ces_model.evaluate_k_dot(np.linspace(1.0, 10.0, 25))
examples/1 Getting started.ipynb
solowPy/solowPy
mit
1.4 Sub-classing the solow.Model class Several commonly used functional forms for aggregate production, including both the Cobb-Douglas and Constant Elasticity of Substitution (CES) production functions, have been sub-classed from solow.Model. For these functional forms, one only needs to specify a valid dictionary of ...
solowpy.cobb_douglas? cobb_douglas_model = solowpy.CobbDouglasModel(params=cobb_douglas_params) solowpy.ces? ces_model = solowpy.CESModel(params=ces_params)
examples/1 Getting started.ipynb
solowPy/solowPy
mit
2. Set environment parameters Be sure to set env_name to the name of the Unity environment file you want to launch.
env_name = "3DBall" # Name of the Unity environment binary to launch train_mode = True # Whether to run the environment in training or inference mode
python/Basics.ipynb
dracolytch/ml-agents
apache-2.0
3. Start the environment UnityEnvironment launches and begins communication with the environment when instantiated. Environments contain brains which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling f...
env = UnityEnvironment(file_name=env_name) # Examine environment parameters print(str(env)) # Set the default brain to work with default_brain = env.brain_names[0] brain = env.brains[default_brain]
python/Basics.ipynb
dracolytch/ml-agents
apache-2.0
4. Examine the observation and state spaces We can reset the environment to be provided with an initial set of observations and states for all the agents within the environment. In ML-Agents, states refer to a vector of variables corresponding to relevant aspects of the environment for an agent. Likewise, observations ...
# Reset the environment env_info = env.reset(train_mode=train_mode)[default_brain] # Examine the state space for the default brain print("Agent state looks like: \n{}".format(env_info.states[0])) # Examine the observation space for the default brain for observation in env_info.observations: print("Agent observati...
python/Basics.ipynb
dracolytch/ml-agents
apache-2.0
5. Take random actions in the environment Once we restart an environment, we can step the environment forward and provide actions to all of the agents within the environment. Here we simply choose random actions based on the action_space_type of the default brain.
for episode in range(10): env_info = env.reset(train_mode=train_mode)[default_brain] done = False episode_rewards = 0 while not done: if brain.action_space_type == 'continuous': env_info = env.step(np.random.randn(len(env_info.agents), ...
python/Basics.ipynb
dracolytch/ml-agents
apache-2.0
6. Close the environment when finished When we are finished using an environment, we can close it with the function below.
env.close()
python/Basics.ipynb
dracolytch/ml-agents
apache-2.0
3. Create a simple circuit, and sample from it. In Stim, circuits are instances of the stim.Circuit class. You create a new empty circuit with stim.Circuit(), and add operations to it by calling append_operation(name_of_gate, list_of_targets). You can find the name of the gate you want from the stim gates reference. Mo...
circuit = stim.Circuit() # First, the circuit will initialize a Bell pair. circuit.append_operation("H", [0]) circuit.append_operation("CNOT", [0, 1]) # Then, the circuit will measure both qubits of the Bell pair in the Z basis. circuit.append_operation("M", [0, 1]) # Let's see the circuit's representation using sti...
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
You can sample from the circuit using the circuit.compile_sampler() method to get a sampler object, and then calling sample on that object. For large circuits (thousands of qubits, millions of operations), it may take a few seconds to create the sampler (because it involves performing a stabilizer tableau simulation of...
sampler = circuit.compile_sampler() print(sampler.sample(shots=10))
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
Notice how there are ten rows (because you took ten shots) with two results per row (because there were two measurements in the circuit). Also notice how the results are random from row to row, but always agree within each row. That makes sense; that's what's supposed to happen when you repeatedly prepare and measure t...
# Indicate the two previous measurements are supposed to consistently agree. circuit.append_operation("DETECTOR", [stim.target_rec(-1), stim.target_rec(-2)]) print(repr(circuit))
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
A slightly subtle point about detectors is that they only assert the parity is consistent. A detector doesn't say what the parity should be. You annotate that a pair of measurements is always different in the same way that you annotate that a pair of measurements is always the same; it's the consistency that's key. Any...
sampler = circuit.compile_detector_sampler() print(sampler.sample(shots=5))
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
There are 5 rows in the results, because you took 5 shots. There's one entry per row, because you put one detector in the circuit. Notice how the results are always 0. The detector is never producing a detection event. That's because there's no noise in the circuit; nothing to disturb the peace and quiet of a perfectly...
circuit = stim.Circuit(""" H 0 CX 0 1 X_ERROR(0.2) 0 1 M 0 1 DETECTOR rec[-1] rec[-2] """)
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
Now that you've put noise before the measurements, try sampling some more detector shots and see what happens:
sampler = circuit.compile_detector_sampler() print(sampler.sample(shots=10))
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
It's no longer all zeroes (...unless you got pretty lucky). There are 1s appearing amongst the 0s. The detection fraction of the circuit is how often detectors fire on average. Given that an X error is being applied to each qubit with 20% probability, and the detector will fire when one of the qubits is hit (but not bo...
import numpy as np print(np.sum(sampler.sample(shots=10**6)) / 10**6)
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
As you can see, the directly estimate value is close to the expected value $0.32$. 5. Generate example error correction circuits. Now it's time for you to work with a real error correcting circuit. Well... a classical error correcting circuit. The repetition code. You could generate a repetition code circuit for yourse...
circuit = stim.Circuit.generated( "repetition_code:memory", rounds=100, distance=9, before_round_data_depolarization=0.03) print(repr(circuit))
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
The circuits generated by Stim include a lot of "nice to have" features. Of course it annotates the measurements to compare (as DETECTORs), but the DETECTOR instructions also include optional space and time coordinates (which have no effect but could be useful when debugging or drawing the circuit). The circuit also ha...
sampler = circuit.compile_sampler() one_sample = sampler.sample(shots=1)[0] for k in range(0, len(one_sample), 9): timeslice = one_sample[k:k+9] print("".join("_1"[e] for e in timeslice))
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
See how the 1s seem to come in pairs of streaks? That's because once a data qubit is flipped it stays flipped, and the measurements to its left and right permanently change parity. If you sample the circuit's detectors, instead of its measurements, the streaks are replaced by spackle. You get much sparser data:
detector_sampler = circuit.compile_detector_sampler() one_sample = detector_sampler.sample(shots=1)[0] for k in range(0, len(one_sample), 9): timeslice = one_sample[k:k+9] print("".join("_1"[e] for e in timeslice))
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
Notice how the 1s tend to come in pairs, except near the sides. Note that the logical observable is annotated to be a measurement of the leftmost data qubit. The number of 1s that match to the left boundary tells you how many times that data qubit was flipped. If you just had a syndrome decoder, you could use it to sol...
print(repr(circuit.detector_error_model()))
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
This format is easier for decoders to consume than a raw circuit, because everything is explained in terms of observable symptoms and hidden symptoms, which is how decoders usually conceptualize of the problem space. To use this error model with a decoder, you need a decoder that can consume this format. Unfortunately,...
!pip install pymatching ########################################################## #################### BEGIN GLUE CODE ##################### ########################################################## import math import networkx as nx import pymatching from typing import Callable, List def predict_observable_errors...
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
A notable detail about this glue code is that it calls circuit.detector_error_model(decompose_errors=True) on the circuit you give it, instead of just circuit.detector_error_model(). Specifying decompose_errors=True tells Stim it has to output a graph-like error model, where errors are decomposed into pieces with exact...
def count_logical_errors(circuit: stim.Circuit, num_shots: int) -> int: shots = circuit.compile_detector_sampler().sample(num_shots, append_observables=True) detector_parts = shots[:, :circuit.num_detectors] actual_observable_parts = shots[:, circuit.num_detectors:] predicted_observable_parts = predict...
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
And then try it on your repetition code circuit:
circuit = stim.Circuit.generated("repetition_code:memory", rounds=100, distance=9, before_round_data_depolarization=0.03) num_shots = 1000 num_logical_errors = count_logical_errors(circuit, num_shots) print("logical_error_rate at 3%:", num_logical_errors / num_shots)
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
Contrast this smooth sailing with what you get from doing no error correction, and just assuming that the logical observable is correct:
num_naive_logical_errors = np.sum(circuit.compile_detector_sampler().sample(shots=num_shots, append_observables=True)[:, -1]) print("naive logical error rate at 3%:", num_naive_logical_errors / num_shots)
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
Wow, the correction is working a whole lot better than the naive approach. Actually, with the physical error rate so low, the correction is almost working too well. There's a decent chance you didn't see any logical errors at all! It's not very interesting for things to always work. You should try bumping the physical ...
circuit = stim.Circuit.generated( "repetition_code:memory", rounds=100, distance=9, before_round_data_depolarization=0.13) num_shots = 1000 num_logical_errors = count_logical_errors(circuit, num_shots) print("logical_error_rate at 13%:", num_logical_errors / num_shots)
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
Ah. The existence of failure. Perfect. 7. Estimate the threshold of an error correcting code. Estimating the threshold of an error correcting code really just comes down to trying a bunch of physical error rates and code distances. You plot out the logical error rate vs physical error rate curve for each distance, and ...
import matplotlib.pyplot as plt num_shots = 1000 for d in [3, 5, 7]: xs = [] ys = [] for noise in [0.1, 0.2, 0.3, 0.4, 0.5]: circuit = stim.Circuit.generated( "repetition_code:memory", rounds=d * 3, distance=d, before_round_data_depolarization=noise) ...
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
From the results here you can see that the repetition code has an amazingly high threshold! Somewhere around 30%-40%. Well... it's not quite so amazing when you remember that you're using a phenomenological noise model (instead of a circuit level noise model) and also that you're inserting depolarizing errors instead o...
print(stim.Circuit.generated( "surface_code:unrotated_memory_z", rounds=100, distance=3, after_clifford_depolarization=0.001, after_reset_flip_probability=0.001, before_measure_flip_probability=0.001, before_round_data_depolarization=0.001))
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
You're specifying several more error parameters now, in order to get circuit level noise instead of phenomenological noise. Because of that, and because this is a quantum code instead of a classical code, the threshold is going to be noticeably lower. You're also going to start noticing some performance issues. Stim is...
num_shots = 1000 for d in [3, 5, 7]: xs = [] ys = [] for noise in [0.0025, 0.0050, 0.0075, 0.0100]: circuit = stim.Circuit.generated( "surface_code:unrotated_memory_z", rounds=d * 3, distance=d, after_clifford_depolarization=noise, after_re...
doc/getting_started.ipynb
quantumlib/Stim
apache-2.0
Saving and loading fields In addition to creating random turbulent fields, we can also load and save custom magnetic field grids. As input and output we currently support binary files in single precision and ASCII files.
# save the field # format: (Bx, By, Bz)(x, y, z) with z changing the quickest. #dumpGrid(BField.getGrid(), 'myfield.dat') # binary, single precision #dumpGridToTxt(Bfield.getGrid(), 'myfield.txt') # ASCII # load your own field #vgrid=Grid3f(gridprops) #loadGrid(vgrid, 'myfield.dat') #loadGridFromTxt(vgrid, 'myfi...
doc/pages/example_notebooks/trajectories/trajectories.v4.ipynb
lukasmerten/CRPropa3
gpl-3.0
Running the simulation Now that we have our magnetic field ready we can fire up our simulation and hope that something visually interesting is going to happen.
sim = ModuleList() sim.add(PropagationCK(BField)) sim.add(PhotoPionProduction(CMB())) sim.add(PhotoPionProduction(IRB_Kneiske04())) sim.add(PhotoDisintegration(CMB())) sim.add(PhotoDisintegration(IRB_Kneiske04())) sim.add(ElectronPairProduction(CMB())) sim.add(ElectronPairProduction(IRB_Kneiske04())) sim.add(NuclearDec...
doc/pages/example_notebooks/trajectories/trajectories.v4.ipynb
lukasmerten/CRPropa3
gpl-3.0
(Optional) Plotting We plot the trajectory of our oxygen-16 nucleus. To distinguish between secondary nuclei the following colors are used: protons are blue, alpha particles are green, everthing heavier is red.
%matplotlib inline from pylab import * from mpl_toolkits.mplot3d import axes3d output.close() data = genfromtxt('trajectory.txt', names=True) # trajectory points x, y, z = data['X'], data['Y'], data['Z'] # translate particle ID to charge number Z = [chargeNumber(int(Id)) for Id in data['ID'].astype(int)] # translat...
doc/pages/example_notebooks/trajectories/trajectories.v4.ipynb
lukasmerten/CRPropa3
gpl-3.0
NOTE: You need to have the directory where you saved the BayesPSD code in your PYTHONPATH variable for the following to work! If you haven't set your variable externally, you can do it in the following way:
import sys sys.path.append("/Users/danielahuppenkothen/work/repositories/BayesPSD")
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
Be aware that you need to replace the directory structure with your own, and that you need to add the path to the directory in which the BayesPSD folder is located. In my case, that's in my repositories folder in my work directory on my home folder, but it will be different for you! Also, when importing below, bayespsd...
from BayesPSD import Lightcurve, PowerSpectrum
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
The data are saved in a simple text file:
## the directory where we've stored the data datadir = "../data/" data = np.loadtxt(datadir+"090122283_+071.87300_eventfile.dat") print("Data shape : " + str(data.shape))
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
The result is a numpy-array with 130001 rows and 2 columns. Each row is a photon, the first column contains the photon arrival times, the second column the energies. For now, let's not care about the energies (don't worry, we'll get back to that later!). Let's make a light curve and plot it:
timestep = 0.001 ##the time resolution for the light curve lc = Lightcurve(data[:,0], timestep=timestep) plt.figure() plt.plot(lc.time, lc.counts)
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
There you go, it's a burst. The class Lightcurve has several useful attributes. Have a look at the code if you're interested. It works both with time tagges arrival times (in which case it takes a value timestep for the output time resolution) or with counts, in which case you should use the keyword times for time bins...
ps = PowerSpectrum(lc, norm="leahy") plt.loglog(ps.freq[1:], ps.ps[1:], lw=2, linestyle="steps-mid")
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
The PowerSpectrum class comes with three normalizations built-in: leahy for the Leahy normalization, rms for a rms-normalized periodogram and variance for a periodogram that is normalized to the total variance. For most purposes here, the Leahy normalization (default) is probably what you want, but the other options ar...
from BayesPSD import pl, bpl, const, qpo
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
We can now, for example, fit one of these models to the data. This kind of fitting is implemented in the class PerMaxLike, which, despite its name actually usually does maximum-a-posteriori estimates rather than maximum likelihood estimates.
from BayesPSD import PerMaxLike psfit = PerMaxLike(ps, obs=True, fitmethod="bfgs")
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
PerMaxLike takes a PowerSpectrum object. The variable obs controls whether output plots and logs are produced (set True if you want those!) and fitmethod sets one of the optimization algorithms specified in scipy.optimize. My recommendation is to set to bfgs unless you have a good reason not to. In order to actually fi...
## starting parameters pars = [2,10,np.log(2.0)] fitparams = psfit.mlest(pl, pars, obs=True, m=1, map=True)
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
The fitting routine returns a dictionary with lots of interesting and useful information. Let's have a look at the dictionary keys:
print(fitparams.keys())
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
Here are the most interesting ones:
print("The best-fit parameters are " + str(fitparams["popt"])) print("The covariance matrix for the parameters is: " + str(fitparams["cov"])) print("The MAP estimate (or Maximum Likelihood estimate) is %.3f"%fitparams["result"]) print("The deviance (-2*log(maximum likelihood)) is %.3f"%fitparams["deviance"]) print("The...
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
A side note: likelihoods, priors and posteriors are implemented in Posterior and its subclasses. Currently (fairly uninformative) priors are hard-coded. If you need different priors, my suggestion is to fork the repository and implement them in a separate branch. Or you could subclass Posterior to make your own. Bayes...
from BayesPSD import Bayes bb = Bayes(ps, namestr='demo', plot=True, m=1)
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
The variable namestr allows you do set a string identifier for all output plots and text files. This is especially useful if you run many bursts and need to save each in its own separate file. The variable plot controls whether the code produces output plots for diagnostic purposes. This is usually a useful feature to ...
## the two noise models model1 = pl model2 = bpl ## input parameters for both par1 = [1.,4.,np.log(2.0)] par2 = [1.,3.,2.,3., np.log(2.0)] ## parameters for the MCMC run nchain = 200 ## number of emcee walkers niter = 200 ## number of iterations per chain nsim = 100 ## number of simulations to run psfit, fakeper, su...
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
Running this code will print a lot of diagnostics on the screen (and also to a log file): the results of the MAP fitting for both models, mean, standard deviations and quantiles for the three parameters and more. It also returns a bunch of objects useful for further analysis: * psfit contains a PerMaxLike object. In it...
noise_model = bpl par = [1,3,2,3,np.log(2.0)] nchain = 200 niter = 1000 nsim = 1000 results = bb.find_periodicity(noise_model, par, nchain=nchain, niter=niter, nsim=nsim)
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
Much like the choose_noise_model method above, this code prints a bunch of useful information to the screen (and a log file) and makes some figures. Most importantly, it prints a bunch of blocks that start with "The posterior p-value for the maximum residual power [...]". Each of these blocks details the results for t...
from BayesPSD import GBMBurst ## load data data = np.loadtxt('../data/090122283_+071.87300_eventfile.dat') times = data[:,0] ## photon arrival times events = data[:,1] ## photon energies ## we can get ObsID and start time from the file name in this case ## for others, we might need to read it from a file #split file...
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
Note that for convenience, the code adds 20% of the burst duration on either side of the light curve, to make sure the light curve goes back to the background on either side (anything can cause funny effects in the Fourier transform!). We can now look at the light curve:
lc = burst.lc plt.figure() plt.plot(lc.time, lc.counts)
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
Or the periodogram:
ps = burst.ps plt.figure() plt.loglog(ps.freq[1:], ps.ps[1:], lw=2, linestyle="steps-mid")
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
Or we can run the entire Bayesian QPO search:
namestr = "%s_%.3f_test"%(bid, bst) ## a string identifier for output files nchain = 500 ## number of emcee walkers niter = 100 ## number of iterations in the Markov chain nsim = 100 ## number of simulations m = 1 ## periodogram not averaged fitmethod = "bfgs" ## use BFGS for optimization burst.bayesian_analysis(name...
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
And then it goes through the entire analysis above. Running Many Bursts I've provided you with two files: * sgr1550_burstdata.dat has some burst IDs, start times and durations as specified above * 090122037a_tte_combined.dat contains the photon arrival times and energies needed to run the bursts in the file above. The ...
def read_burstdata(filename, datadir="./"): """ Run Bayesian QPO search on all bursts in file filename. Parameters ---------- filename: string Name of a file with minimal burst data. Needs to have columns: 1. ObsID 2. MET trigger time 3. Seconds since trigger ...
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
Now run the function above on the example file:
## now run the function above on the example file obsids, trigtime, bstart, blength = read_burstdata("sgr1550_burstdata.dat", datadir="../data/")
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
Next, we'll need to load the data, snip out the parts of the light curve that have bursts and make a GBMBurst object, so that we can then easily run the QPO search. We'll loop over the ObsIDs first, because if there is more than one burst in a single observation, it makes no sense reading in the data several times! Th...
## empty list to store all burst objects in allbursts = [] ## which energy range do we want to run over? energies = [8.,200.] ## what's the Nyquist frequency supposed to be? ## This depends on the time resolution of your instrument ## and the frequencies where you expect QPOs to appear fnyquist = 4096. ## get the un...
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
Now that we have all bursts in a list, running the Bayesian QPO search is easy:
nchain = 500 ## number of chains niter = 200 ## number of iterations per chain nsim = 100 ## number of simulations, small to make it run fast for demo purposes fitmethod = "bfgs" ## scipy.optimize minimization algorithm ## we'll just run 1 burst for brevity; delete [:1] if you want to run ## on all bursts for burst ...
docs/Demo.ipynb
dhuppenkothen/BayesPSD
bsd-2-clause
K-Nearest-Neighbors (KNN) The k-nearest neighbors (KNN) algorithm is a simple concept: define some distance metric between the items in your dataset, and find the K closest items. You can then use those items to predict some property of a test item. This prediction is achieved by having them somehow "vote" on it. KNN f...
! chmod 600 kaggle.json && (ls ~/.kaggle 2>/dev/null || mkdir ~/.kaggle) && mv kaggle.json ~/.kaggle/ && echo 'Done' ! kaggle datasets download uciml/pima-indians-diabetes-database ! ls
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
Unzip the dataset.
! unzip pima-indians-diabetes-database.zip
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
And then load the dataset into a DataFrame.
import pandas as pd diabetes = pd.read_csv('diabetes.csv') diabetes.sample(n=10)
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
Take a quick look at the data to see how many rows and columns we are dealing with.
diabetes.describe()
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
Our features are: - Pregnancies - Glucose - BloodPressure - SkinThickness - Insulin - BMI - DiabetesPedigreeFunction - Age Our target is Outcome, which is currently encoded with a 1 for a positive diagnosis and 0 for a negative diagnosis.
print(diabetes.groupby('Outcome').size())
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
Notice there are several zeros in the feature columns (check the min values). These are likely cases where the data simply wasn't collected or stored properly. (For example, a blood pressure of 0 does not make sense.) We need to clean these up or they will have an incorrect effect on the outcome of our KNN.
import numpy as np no_zero = ['Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI'] for column in no_zero: diabetes[column] = diabetes[column].replace(0, np.NaN) mean = int(diabetes[column].mean(skipna=True)) diabetes[column] = diabetes[column].replace(np.NaN, mean) diabetes.describe()
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
We create training and testing sets (20% for testing), remembering to separate 'Outcome' as our target value.
from sklearn.model_selection import train_test_split X = diabetes.iloc[:,0:8] y = diabetes.iloc[:,8] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
Now we scale our features using StandardScaler.
from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test= sc_X.transform(X_test)
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
Finally, we use the scikit-learn KNN model.
from sklearn.neighbors import KNeighborsClassifier n_neighbors = 14 KNN = KNeighborsClassifier(n_neighbors=n_neighbors, p=2, metric='euclidean') KNN.fit(X_train, y_train) y_pred = KNN.predict(X_test)
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
We now evaluate our model in terms of the confusion matrix, F1 score, and accuracy.
from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from sklearn.metrics import accuracy_score cm = confusion_matrix(y_test,y_pred) f1 = f1_score(y_test,y_pred) accuracy = accuracy_score(y_test,y_pred) print('The confusion matrix is', cm) print('The F1 score is', f1) print('The accuracy...
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
K-Nearest-Neighbors for Regression We can also use KNN for regression. In this example we'll actually build the model from scratch in order to demonstrate its simplicity. For our model we'll use MovieLens data. MovieLens data is available in relation to the following paper: text F. Maxwell Harper and Joseph A. Konstan....
! wget http://files.grouplens.org/datasets/movielens/ml-latest-small.zip ! unzip ml-latest-small.zip
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
We'll use KNN to guess the rating of a movie by looking at the 10 movies that are closest to it in terms of genres and popularity. To start, let's load up every rating in the dataset into a Pandas DataFrame:
import pandas as pd ratings = pd.read_csv('./ml-latest-small/ratings.csv') ratings.sample(n=10)
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0