markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
You can read all about numpy datatypes in the documentation. Array math Basic mathematical functions operate elementwise on arrays, and are available both as operator overloads and as functions in the numpy module:
x = np.array([[1,2],[3,4]], dtype=np.float64) y = np.array([[5,6],[7,8]], dtype=np.float64) # Elementwise sum; both produce the array print(x + y) print(np.add(x, y)) # Elementwise difference; both produce the array print(x - y) print(np.subtract(x, y)) # Elementwise product; both produce the array print(x * y) prin...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Note that unlike MATLAB, * is elementwise multiplication, not matrix multiplication. We instead use the dot function to compute inner products of vectors, to multiply a vector by a matrix, and to multiply matrices. dot is available both as a function in the numpy module and as an instance method of array objects:
x = np.array([[1,2],[3,4]]) y = np.array([[5,6],[7,8]]) v = np.array([9,10]) w = np.array([11, 12]) # Inner product of vectors; both produce 219 print(v.dot(w)) print(np.dot(v, w))
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
You can also use the @ operator which is equivalent to numpy's dot operator.
print(v @ w) # Matrix / vector product; both produce the rank 1 array [29 67] print(x.dot(v)) print(np.dot(x, v)) print(x @ v) # Matrix / matrix product; both produce the rank 2 array # [[19 22] # [43 50]] print(x.dot(y)) print(np.dot(x, y)) print(x @ y)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Numpy provides many useful functions for performing computations on arrays; one of the most useful is sum:
x = np.array([[1,2],[3,4]]) print(np.sum(x)) # Compute sum of all elements; prints "10" print(np.sum(x, axis=0)) # Compute sum of each column; prints "[4 6]" print(np.sum(x, axis=1)) # Compute sum of each row; prints "[3 7]"
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
You can find the full list of mathematical functions provided by numpy in the documentation. Apart from computing mathematical functions using arrays, we frequently need to reshape or otherwise manipulate data in arrays. The simplest example of this type of operation is transposing a matrix; to transpose a matrix, simp...
print(x) print("transpose\n", x.T) v = np.array([[1,2,3]]) print(v ) print("transpose\n", v.T)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Broadcasting Broadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array. For example, suppos...
# We will add the vector v to each row of the matrix x, # storing the result in the matrix y x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]]) v = np.array([1, 0, 1]) y = np.empty_like(x) # Create an empty matrix with the same shape as x # Add the vector v to each row of the matrix x with an explicit loop for ...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
This works; however when the matrix x is very large, computing an explicit loop in Python could be slow. Note that adding the vector v to each row of the matrix x is equivalent to forming a matrix vv by stacking multiple copies of v vertically, then performing elementwise summation of x and vv. We could implement this ...
vv = np.tile(v, (4, 1)) # Stack 4 copies of v on top of each other print(vv) # Prints "[[1 0 1] # [1 0 1] # [1 0 1] # [1 0 1]]" y = x + vv # Add x and vv elementwise print(y)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Numpy broadcasting allows us to perform this computation without actually creating multiple copies of v. Consider this version, using broadcasting:
import numpy as np # We will add the vector v to each row of the matrix x, # storing the result in the matrix y x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]]) v = np.array([1, 0, 1]) y = x + v # Add v to each row of x using broadcasting print(y)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
The line y = x + v works even though x has shape (4, 3) and v has shape (3,) due to broadcasting; this line works as if v actually had shape (4, 3), where each row was a copy of v, and the sum was performed elementwise. Broadcasting two arrays together follows these rules: If the arrays do not have the same rank, prep...
# Compute outer product of vectors v = np.array([1,2,3]) # v has shape (3,) w = np.array([4,5]) # w has shape (2,) # To compute an outer product, we first reshape v to be a column # vector of shape (3, 1); we can then broadcast it against w to yield # an output of shape (3, 2), which is the outer product of v and w...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Broadcasting typically makes your code more concise and faster, so you should strive to use it where possible. This brief overview has touched on many of the important things that you need to know about numpy, but is far from complete. Check out the numpy reference to find out much more about numpy. Matplotlib Matplotl...
import matplotlib.pyplot as plt
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
By running this special iPython command, we will be displaying plots inline:
%matplotlib inline
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Plotting The most important function in matplotlib is plot, which allows you to plot 2D data. Here is a simple example:
# Compute the x and y coordinates for points on a sine curve x = np.arange(0, 3 * np.pi, 0.1) y = np.sin(x) # Plot the points using matplotlib plt.plot(x, y)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
With just a little bit of extra work we can easily plot multiple lines at once, and add a title, legend, and axis labels:
y_sin = np.sin(x) y_cos = np.cos(x) # Plot the points using matplotlib plt.plot(x, y_sin) plt.plot(x, y_cos) plt.xlabel('x axis label') plt.ylabel('y axis label') plt.title('Sine and Cosine') plt.legend(['Sine', 'Cosine'])
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Subplots You can plot different things in the same figure using the subplot function. Here is an example:
# Compute the x and y coordinates for points on sine and cosine curves x = np.arange(0, 3 * np.pi, 0.1) y_sin = np.sin(x) y_cos = np.cos(x) # Set up a subplot grid that has height 2 and width 1, # and set the first such subplot as active. plt.subplot(2, 1, 1) # Make the first plot plt.plot(x, y_sin) plt.title('Sine')...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
The Button is not used to represent a data type. Instead the button widget is used to handle mouse clicks. The on_click method of the Button can be used to register function to be called when the button is clicked. The doc string of the on_click can be seen below.
from IPython.html import widgets print(widgets.Button.on_click.__doc__)
GSOC/notebooks/ipython/examples/Interactive Widgets/Widget Events.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Example Since button clicks are stateless, they are transmitted from the front-end to the back-end using custom messages. By using the on_click method, a button that prints a message when it has been clicked is shown below.
from IPython.display import display button = widgets.Button(description="Click Me!") display(button) def on_button_clicked(b): print("Button clicked.") button.on_click(on_button_clicked)
GSOC/notebooks/ipython/examples/Interactive Widgets/Widget Events.ipynb
OSGeo-live/CesiumWidget
apache-2.0
on_sumbit The Text also has a special on_submit event. The on_submit event fires when the user hits return.
text = widgets.Text() display(text) def handle_submit(sender): print(text.value) text.on_submit(handle_submit)
GSOC/notebooks/ipython/examples/Interactive Widgets/Widget Events.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Traitlet events Widget properties are IPython traitlets and traitlets are eventful. To handle changes, the on_trait_change method of the widget can be used to register a callback. The doc string for on_trait_change can be seen below.
print(widgets.Widget.on_trait_change.__doc__)
GSOC/notebooks/ipython/examples/Interactive Widgets/Widget Events.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Signatures Mentioned in the doc string, the callback registered can have 4 possible signatures: callback() callback(trait_name) callback(trait_name, new_value) callback(trait_name, old_value, new_value) Using this method, an example of how to output an IntSlider's value as it is changed can be seen below.
int_range = widgets.IntSlider() display(int_range) def on_value_change(name, value): print(value) int_range.on_trait_change(on_value_change, 'value')
GSOC/notebooks/ipython/examples/Interactive Widgets/Widget Events.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Linking Widgets Often, you may want to simply link widget attributes together. Synchronization of attributes can be done in a simpler way than by using bare traitlets events. The first method is to use the link and directional_link functions from the traitlets module. Linking traitlets attributes from the server side
from IPython.utils import traitlets caption = widgets.Latex(value = 'The values of slider1, slider2 and slider3 are synchronized') sliders1, slider2, slider3 = widgets.IntSlider(description='Slider 1'),\ widgets.IntSlider(description='Slider 2'),\ widgets.IntSl...
GSOC/notebooks/ipython/examples/Interactive Widgets/Widget Events.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Function traitlets.link returns a Link object. The link can be broken by calling the unlink method.
# l.unlink()
GSOC/notebooks/ipython/examples/Interactive Widgets/Widget Events.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Linking widgets attributes from the client side When synchronizing traitlets attributes, you may experience a lag because of the latency dues to the rountrip to the server side. You can also directly link widgets attributes, either in a unidirectional or a bidirectional fashion using the link widgets.
caption = widgets.Latex(value = 'The values of range1, range2 and range3 are synchronized') range1, range2, range3 = widgets.IntSlider(description='Range 1'),\ widgets.IntSlider(description='Range 2'),\ widgets.IntSlider(description='Range 3') l = widgets.jslink((range1...
GSOC/notebooks/ipython/examples/Interactive Widgets/Widget Events.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Function widgets.jslink returns a Link widget. The link can be broken by calling the unlink method.
# l.unlink()
GSOC/notebooks/ipython/examples/Interactive Widgets/Widget Events.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Format: 7zipped Files: badges.xml UserId, e.g.: "420" Name, e.g.: "Teacher" Date, e.g.: "2008-09-15T08:55:03.923" comments.xml Id PostId Score Text, e.g.: "@Stu Thompson: Seems possible to me - why not try it?" CreationDate, e.g.:"2008-09-06T08:07:10.730" UserId posts.xml Id PostTypeId 1: Question 2: Answer Paren...
import os import os.path as path from urllib.request import urlretrieve def download_csv_upper_dir(baseurl, filename): file = path.abspath(path.join(os.getcwd(),os.pardir,filename)) if not os.path.isfile(file): urlretrieve(baseurl + '/' + filename, file) baseurl = 'http://neuromancer.inf.um.es...
sql/sesion1.ipynb
dsevilla/bdge
mit
Se tiene que habilitar esto para que se permita importar CSVs.
%%sql SET GLOBAL local_infile = true; %%sql DROP TABLE IF EXISTS Posts; CREATE TABLE Posts ( Id INT, AcceptedAnswerId INT NULL DEFAULT NULL, AnswerCount INT DEFAULT 0, Body TEXT, ClosedDate DATETIME(6) NULL DEFAULT NULL, CommentCount INT DEFAULT 0, CommunityOwnedDate DATETIME(6) NULL DEFAUL...
sql/sesion1.ipynb
dsevilla/bdge
mit
Añadimos las claves ajenas para que todas las tablas estén referenciadas correctamente Usaremos los comandos alter table.
%%sql ALTER TABLE Posts ADD FOREIGN KEY (ParentId) REFERENCES Posts(Id); ALTER TABLE Posts ADD FOREIGN KEY (OwnerUserId) REFERENCES Users(Id); ALTER TABLE Posts ADD FOREIGN KEY (LastEditorUserId) REFERENCES Users(Id); ALTER TABLE Posts ADD FOREIGN KEY (AcceptedAnswerId) REFERENCES Posts(Id); %%sql ALTER TABLE Tags A...
sql/sesion1.ipynb
dsevilla/bdge
mit
EJERCICIO: Eliminar de Votes las entradas que se refieran a Posts inexistentes
%%sql -- DELETE FROM Votes WHERE ...; %%sql -- Y ahora sí ALTER TABLE Votes ADD FOREIGN KEY (PostId) REFERENCES Posts(Id); ALTER TABLE Votes ADD FOREIGN KEY (UserId) REFERENCES Users(Id); %sql use stackoverflow %%sql SHOW TABLES; %%sql DESCRIBE Posts; top_tags = %sql SELECT Id, TagName, Count FROM Tags ORDER BY Co...
sql/sesion1.ipynb
dsevilla/bdge
mit
¡¡Los resultados de %sql se pueden convertir a un DataFrame!!
top_tags_df = top_tags.DataFrame() # invert_y_axis() hace que el más usado aparezca primero. Por defecto es al revés. top_tags_df.plot(kind='barh',x='TagName', y='Count', figsize=(14,14*2/3)).invert_yaxis() top_tags %%sql select Id,TagName,Count from Tags WHERE Count > 5 ORDER BY Count ASC LIMIT 40;
sql/sesion1.ipynb
dsevilla/bdge
mit
Para comparación con HBase Voy a hacer unas consultas para comparar la eficiencia con HBase. Calcularé el tamaño medio del texto de los comentarios de un post en particular (he seleccionado el 7251, que es el que más tiene comentarios, 32). Hago el cálculo en local porque aunque existe la función AVG de SQL, es posible...
%%sql SELECT p.Id, MAX(p.CommentCount) AS c FROM Posts p GROUP BY p.Id ORDER BY c DESC LIMIT 1; %sql SELECT AVG(CHAR_LENGTH(Text)) from Comments WHERE PostId = 7251; from functools import reduce def doit(): q = %sql select Text from Comments WHERE PostId = 7251; (s,n) = reduce(lambda res, e: (res[0]+len(e[0]...
sql/sesion1.ipynb
dsevilla/bdge
mit
EJERCICIO: Calcular las preguntas con más respuestas En la casilla siguiente:
%%sql -- Preguntas con más respuestas (20 primeras) %%sql select Title from Posts where Id = 5;
sql/sesion1.ipynb
dsevilla/bdge
mit
Código de suma de posts de cada Tag
# Calcular la suma de posts cada Tag de manera eficiente import re # Obtener los datos iniciales de los Tags results = %sql SELECT Id, Tags FROM Posts where Tags IS NOT NULL; tagcount = {} for result in results: # Inserta las tags en la tabla Tag tags = re.findall('<(.*?)>', result[1]) for tag in tags: ...
sql/sesion1.ipynb
dsevilla/bdge
mit
Problem statement We are interested in solving $$x^* = \arg \min_x f(x)$$ under the constraints that $f$ is a black box for which no closed form is known (nor its gradients); $f$ is expensive to evaluate; evaluations $y = f(x)$ of may be noisy. Disclaimer. If you do not have these constraints, then there is certainly...
noise_level = 0.1 def f(x, noise_level=noise_level): return np.sin(5 * x[0]) * (1 - np.tanh(x[0] ** 2)) + np.random.randn() * noise_level
examples/bayesian-optimization.ipynb
glouppe/scikit-optimize
bsd-3-clause
Bayesian optimization based on gaussian process regression is implemented in skopt.gp_minimize and can be carried out as follows:
from skopt import gp_minimize from skopt.acquisition import gaussian_lcb from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import Matern # Note that we have fixed the hyperparameters of the kernel, because it is # sufficient for this easy problem. gp = GaussianProcessR...
examples/bayesian-optimization.ipynb
glouppe/scikit-optimize
bsd-3-clause
For further inspection of the results, attributes of the res named tuple provide the following information: x [float]: location of the minimum. fun [float]: function value at the minimum. models: surrogate models used for each iteration. x_iters [array]: location of function evaluation for each iteration. func_vals...
for key, value in sorted(res.items()): print(key, "=", value) print()
examples/bayesian-optimization.ipynb
glouppe/scikit-optimize
bsd-3-clause
Together these attributes can be used to visually inspect the results of the minimization, such as the convergence trace or the acquisition function at the last iteration:
from skopt.plots import plot_convergence plot_convergence(res)
examples/bayesian-optimization.ipynb
glouppe/scikit-optimize
bsd-3-clause
Let us visually examine The approximation of the fit gp model to the original function. The acquistion values (The lower confidence bound) that determine the next point to be queried. At the points closer to the points previously evaluated at, the variance dips to zero. The first column shows the following: 1. The tr...
plt.rcParams["figure.figsize"] = (20, 20) x = np.linspace(-2, 2, 400).reshape(-1, 1) fx = np.array([f(x_i, noise_level=0.0) for x_i in x]) # Plot first five iterations. for n_iter in range(5): gp = res.models[n_iter] curr_x_iters = res.x_iters[: n_iter+1] curr_func_vals = res.func_vals[: n_iter+1] # ...
examples/bayesian-optimization.ipynb
glouppe/scikit-optimize
bsd-3-clause
Finally, as we increase the number of points, the GP model approaches the actual function. The final few points are cluttered around the minimum because the GP does not gain anything more by further exploration.
# Plot f(x) + contours plt.rcParams["figure.figsize"] = (10, 6) x = np.linspace(-2, 2, 400).reshape(-1, 1) fx = [f(x_i, noise_level=0.0) for x_i in x] plt.plot(x, fx, "r--", label="True (unknown)") plt.fill(np.concatenate([x, x[::-1]]), np.concatenate(([fx_i - 1.9600 * noise_level for fx_i in fx], ...
examples/bayesian-optimization.ipynb
glouppe/scikit-optimize
bsd-3-clause
DataFrame を array に変換する例です。
data = {'City': ['Tokyo','Osaka','Nagoya','Okinawa'], 'Temperature': [25.0,28.2,27.3,30.9], 'Humidity': [44,42,np.nan,62]} cities = DataFrame(data) cities cities.as_matrix()
07-pandas DataFrame-03.ipynb
enakai00/jupyter_ml4se_commentary
apache-2.0
Series を array に変換する例です。
cities['City'].as_matrix()
07-pandas DataFrame-03.ipynb
enakai00/jupyter_ml4se_commentary
apache-2.0
トランプのカードを集めた DataFrame を定義して、カードのシャッフルを行う例です。
face = ['king','queen','jack','ten','nine','eight', 'seven','six','five','four','three','two','ace'] suit = ['spades', 'clubs', 'diamonds', 'hearts'] value = range(13,0,-1) deck = DataFrame({'face': np.tile(face,4), 'suit': np.repeat(suit,13), 'value': np.tile(value,4)}) ...
07-pandas DataFrame-03.ipynb
enakai00/jupyter_ml4se_commentary
apache-2.0
permutation 関数で、index の順番をランダムにシャッフルします。
np.random.permutation(deck.index)
07-pandas DataFrame-03.ipynb
enakai00/jupyter_ml4se_commentary
apache-2.0
ランダムにシャッフルした index を用いて行を並べ替えます。
deck = deck.reindex(np.random.permutation(deck.index)) deck.head()
07-pandas DataFrame-03.ipynb
enakai00/jupyter_ml4se_commentary
apache-2.0
reset_index メソッドで index に通し番号を付け直します。
deck = deck.reset_index(drop=True) deck.head()
07-pandas DataFrame-03.ipynb
enakai00/jupyter_ml4se_commentary
apache-2.0
DataFrame のグラフ描画機能を使用する例です。 3回分のランダムウォークのデータを並べた DataFrame を作成します。
result = DataFrame() for c in range(3): y = 0 t = [] for delta in np.random.normal(loc=0.0, scale=1.0, size=100): y += delta t.append(y) result['Trial %d' % c] = t result.head()
07-pandas DataFrame-03.ipynb
enakai00/jupyter_ml4se_commentary
apache-2.0
DataFrame の polot メソッドでグラフを描きます。
result.plot(title='Random walk')
07-pandas DataFrame-03.ipynb
enakai00/jupyter_ml4se_commentary
apache-2.0
練習問題 次の関数 coin_game は、所持金と掛け金を引数に渡すと、1/2の確率で掛け金の分だけ所持金が増減した値が返ります。
from numpy.random import randint def coin_game(money, bet): coin = randint(2) if coin == 0: money += bet else: money -= bet return money
07-pandas DataFrame-03.ipynb
enakai00/jupyter_ml4se_commentary
apache-2.0
次は、1000円の所持金において、100円を賭けた場合の結果を示します。
money = 1000 money = coin_game(money, 100) money
07-pandas DataFrame-03.ipynb
enakai00/jupyter_ml4se_commentary
apache-2.0
Read the hematopoiesis data. This has been simplified to a small subset of 23 genes found to be branching. We have also performed Monocle2 (version 2.1) - DDRTree on this data. The results loaded include the Monocle estimated pseudotime, branching assignment (state) and the DDRTree latent dimensions.
Y = pd.read_csv("singlecelldata/hematoData.csv", index_col=[0]) monocle = pd.read_csv("singlecelldata/hematoMonocle.csv", index_col=[0]) Y.head() monocle.head() # Plot Monocle DDRTree space genelist = ["FLT3", "KLF1", "MPO"] f, ax = plt.subplots(1, len(genelist), figsize=(10, 5), sharex=True, sharey=True) for ig, g ...
notebooks/Hematopoiesis.ipynb
ManchesterBioinference/BranchedGP
apache-2.0
Fit BGP model Notice the cell assignment uncertainty is higher for cells close to the branching point.
def FitGene(g, ns=20): # for quick results subsample data t = time.time() Bsearch = list(np.linspace(0.05, 0.95, 5)) + [ 1.1 ] # set of candidate branching points GPy = (Y[g].iloc[::ns].values - Y[g].iloc[::ns].values.mean())[ :, None ] # remove mean from gene expression data ...
notebooks/Hematopoiesis.ipynb
ManchesterBioinference/BranchedGP
apache-2.0
Then we can construct a DAgger trainer und use it to train the policy on the cartpole environment.
import tempfile import gym from stable_baselines3.common.vec_env import DummyVecEnv from imitation.algorithms import bc from imitation.algorithms.dagger import SimpleDAggerTrainer venv = DummyVecEnv([lambda: gym.make("CartPole-v1")]) bc_trainer = bc.BC( observation_space=env.observation_space, action_space=...
examples/2_train_dagger.ipynb
HumanCompatibleAI/imitation
mit
Finally, the evaluation shows, that we actually trained a policy that solves the environment (500 is the max reward).
from stable_baselines3.common.evaluation import evaluate_policy reward, _ = evaluate_policy(dagger_trainer.policy, env, 10) print(reward)
examples/2_train_dagger.ipynb
HumanCompatibleAI/imitation
mit
Step 4A: Sample data from null
pow_null = np.array((), dtype=np.dtype('float64')) # compute this statistic for various sizes of datasets for s in S: s0 = s/2 s1 = s - s0 # compute this many times for each operating point to get average pval = np.array((), dtype=np.dtype('float64')) for _ in itertools.repeat(None,N): ...
code/inferential_simulation.ipynb
Upward-Spiral-Science/grelliam
apache-2.0
Step 4B: Sample data from alternate
pow_alt = np.array((), dtype=np.dtype('float64')) # compute this statistic for various sizes of datasets for s in S: s0 = s/2 s1 = s - s0 # compute this many times for each operating point to get average pval = np.array((), dtype=np.dtype('float64')) for _ in itertools.repeat(None,N): g...
code/inferential_simulation.ipynb
Upward-Spiral-Science/grelliam
apache-2.0
Step 5: Plot power vs n on null set
plt.figure(figsize=(8, 5)) plt.scatter(S, pow_null, hold=True, label='null') plt.scatter(S, pow_alt, color='green', hold=True, label='alt') plt.xscale('log') plt.xlabel('Number of Samples') plt.xlim((0,10000)) plt.ylim((-0.05, 1.05)) plt.ylabel('Power') plt.title('Strength of Gender Classification Using Wilcoxon Test')...
code/inferential_simulation.ipynb
Upward-Spiral-Science/grelliam
apache-2.0
Step 6: Apply the above to data
# Initializing dataset names dnames = list(['../data/desikan/KKI2009']) print "Dataset: " + ", ".join(dnames) # Getting graph names fs = list() for dd in dnames: fs.extend([root+'/'+file for root, dir, files in os.walk(dd) for file in files]) fs = fs[:] def loadGraphs(filenames, rois, printer=False): A = ...
code/inferential_simulation.ipynb
Upward-Spiral-Science/grelliam
apache-2.0
The function definition takes the following, minimal form: python def NAME_OF_FUNCTION(): #Code block - there must be at least one line of code #That said, we can use a null (do nothing) statement pass Set up the notebook to use the simulator and see if you can think of a way to use functions to call the li...
%run 'Set-up.ipynb' %run 'Loading scenes.ipynb' %run 'vrep_models/PioneerP3DX.ipynb' %%vrepsim '../scenes/OU_Pioneer.ttt' PioneerP3DX #Your code - using functions - here
robotVM/notebooks/Demo - Square N - Functions.ipynb
psychemedia/ou-robotics-vrep
apache-2.0
How did you get on? Could you work out how to use the functions? Here's how I used them:
%%vrepsim '../scenes/OU_Pioneer.ttt' PioneerP3DX import time side_speed=2 side_length_time=1 turn_speed=1.8 turn_time=0.45 number_of_sides=4 def traverse_side(): pass def turn(): pass for side in range(number_of_sides): #side robot.move_forward(side_speed) time.sleep(side_leng...
robotVM/notebooks/Demo - Square N - Functions.ipynb
psychemedia/ou-robotics-vrep
apache-2.0
McWilliams performed freely-evolving 2D turbulence ($R_d = \infty$, $\beta =0$) experiments on a $2\pi\times 2\pi$ periodic box.
# create the model object m = pyqg.BTModel(L=2.*np.pi, nx=256, beta=0., H=1., rek=0., rd=None, tmax=40, dt=0.001, taveint=1, ntd=4) # in this example we used ntd=4, four threads # if your machine has more (or fewer) cores available, you could try changing it
docs/examples/barotropic.ipynb
pyqg/pyqg
mit
Initial condition The initial condition is random, with a prescribed spectrum $$ |\hat{\psi}|^2 = A \,\kappa^{-1}\left[1 + \left(\frac{\kappa}{6}\right)^4\right]^{-1}\,, $$ where $\kappa$ is the wavenumber magnitude. The constant A is determined so that the initial energy is $KE = 0.5$.
# generate McWilliams 84 IC condition fk = m.wv != 0 ckappa = np.zeros_like(m.wv2) ckappa[fk] = np.sqrt( m.wv2[fk]*(1. + (m.wv2[fk]/36.)**2) )**-1 nhx,nhy = m.wv2.shape Pi_hat = np.random.randn(nhx,nhy)*ckappa +1j*np.random.randn(nhx,nhy)*ckappa Pi = m.ifft( Pi_hat[np.newaxis,:,:] ) Pi = Pi - Pi.mean() Pi_hat = m.f...
docs/examples/barotropic.ipynb
pyqg/pyqg
mit
Runing the model Here we demonstrate how to use the run_with_snapshots feature to periodically stop the model and perform some action (in this case, visualization).
for _ in m.run_with_snapshots(tsnapstart=0, tsnapint=10): plot_q(m)
docs/examples/barotropic.ipynb
pyqg/pyqg
mit
The genius of McWilliams (1984) was that he showed that the initial random vorticity field organizes itself into strong coherent vortices. This is true in significant part of the parameter space. This was previously suspected but unproven, mainly because people did not have computer resources to run the simulation long...
energy = m.get_diagnostic('KEspec') enstrophy = m.get_diagnostic('Ensspec') # this makes it easy to calculate an isotropic spectrum from pyqg import diagnostic_tools as tools kr, energy_iso = tools.calc_ispec(m,energy.squeeze()) _, enstrophy_iso = tools.calc_ispec(m,enstrophy.squeeze()) ks = np.array([3.,80]) es = 5*...
docs/examples/barotropic.ipynb
pyqg/pyqg
mit
Checking this answer with Wolfram Alpha, we get approximately the same result: [Image in Blog Post] Let's try this on another, more complicated integral: $\int_{1}^{4} \frac{e^{x}}{x} + e^{1/x}$ In this case, it's harder to determine a proper f_max. The most straightforward way is to plot the function over the limits o...
import matplotlib.pyplot as plt %matplotlib inline x = np.linspace(1,4,1000) y = (np.exp(x)/x) + np.exp(1/x) plt.plot(x,y) plt.ylabel('F(x)') plt.xlabel('x');
20170414_CalculatingAnIntegralWithMonteCarloUsingTheRejectionMethod.ipynb
drericstrong/Blog
agpl-3.0
From the above figure, we can see that the maximum is about 15. But what if we decided not to plot the function? Consider a situation where it's computationally expensive to plot the function over the entire limits of the integral. It's okay for us to choose an f_max that is too large, as long as we are sure that all p...
@jit def MCHist2(n_hist, a, b, fmax): score = (b - a)*fmax tot_score = 0 for n in range(1, n_hist): x = random.uniform(a, b) f = random.uniform(0, fmax) f_x = (np.exp(x)/x) + np.exp(1/x) # Check if the point falls inside the integral if f < f_x: tot_...
20170414_CalculatingAnIntegralWithMonteCarloUsingTheRejectionMethod.ipynb
drericstrong/Blog
agpl-3.0
Again, we check our work with Wolfram Alpha, and we get approximately the same result: [Image in Blog Post] Would we have less variance if we used the same number of histories, but an f_max closer to the true value (15)?
num_hist3 = 1e8 results3 = MCHist2(num_hist2, 1.0, 4.0, 15) integral_val3 = round(results3 / num_hist3, 6) print("The calculated integral is {}".format(integral_val3))
20170414_CalculatingAnIntegralWithMonteCarloUsingTheRejectionMethod.ipynb
drericstrong/Blog
agpl-3.0
The storage bucket was created earlier. We'll re-declare it here, so we can use it.
storage_bucket = 'gs://' + datalab.Context.default().project_id + '-datalab-workspace/' storage_region = 'us-central1' workspace_path = os.path.join(storage_bucket, 'census') training_path = os.path.join(workspace_path, 'training')
samples/ML Toolbox/Regression/Census/4 Service Evaluate.ipynb
googledatalab/notebooks
apache-2.0
Model Lets take a quick look at the model that was previously produced as a result of the training job.
!gsutil ls -r {training_path}/model
samples/ML Toolbox/Regression/Census/4 Service Evaluate.ipynb
googledatalab/notebooks
apache-2.0
Batch Prediction We'll submit a batch prediction Dataflow job, to use this model by loading it into TensorFlow, and running it in evaluation mode (the mode that expects the input data to contain a value for target). The other mode, prediction, is used to predict over data where the target column is missing. NOTE: Batch...
eval_data_path = os.path.join(workspace_path, 'data/eval.csv') evaluation_path = os.path.join(workspace_path, 'evaluation') regression.batch_predict(training_dir=training_path, prediction_input_file=eval_data_path, output_dir=evaluation_path, mode='evaluation', ...
samples/ML Toolbox/Regression/Census/4 Service Evaluate.ipynb
googledatalab/notebooks
apache-2.0
Once prediction is done, the individual predictions will be written out into Cloud Storage.
!gsutil ls {evaluation_path} !gsutil cat {evaluation_path}/csv_schema.json !gsutil -q -m cp -r {evaluation_path}/ /tmp !head -n 5 /tmp/evaluation/predictions-00000*
samples/ML Toolbox/Regression/Census/4 Service Evaluate.ipynb
googledatalab/notebooks
apache-2.0
Analysis with BigQuery We're going to use BigQuery to do evaluation. BigQuery can directly work against CSV data in Cloud Storage. However, if you have very large evaluation results, or you're going to be running multiple queries, it is advisable to first load the results into a BigQuery table.
%bq datasource --name eval_results --paths gs://cloud-ml-users-datalab-workspace/census/evaluation/predictions* { "schema": [ { "type": "STRING", "mode": "nullable", "name": "SERIALNO" }, { "type": "FLOAT", "mode": "nullable", "name": "predicted_target" }, ...
samples/ML Toolbox/Regression/Census/4 Service Evaluate.ipynb
googledatalab/notebooks
apache-2.0
Sci-kit learn does not implement LDA with Yelp: An Example This is based on the paper by McAuley & Leskovec (2013). References https://www.cs.princeton.edu/~blei/papers/BleiNgJordan2003.pdf LDA Notes Only for text corpora? No but it was the main thing that it was decided for. Seen as an alternative to tf-idf di...
%pylab inline import numpy as np s = np.random.dirichlet((10, 5, 3), 50).transpose() plt.barh(range(50), s[0]) plt.barh(range(50), s[1], left=s[0], color='g') plt.barh(range(50), s[2], left=s[0]+s[1], color='r') _ = plt.title("Lengths of Strings") [i.mean() for i in s] #Mean of each of the lengths of the string [i/...
How to think about Latent Dirichlet Allocation.ipynb
Will-So/yelp-workbook
mit
scikit-learn Training on AI Platform This notebook uses the Census Income Data Set to demonstrate how to train a model on Ai Platform. How to bring your model to AI Platform Getting your model ready for training can be done in 3 steps: 1. Create your python model file 1. Add code to download your data from Google C...
%env PROJECT_ID <PROJECT_ID> %env BUCKET_NAME <BUCKET_NAME> %env REGION us-central1 %env TRAINER_PACKAGE_PATH ./census_training %env MAIN_TRAINER_MODULE census_training.train %env JOB_DIR gs://<BUCKET_NAME>/scikit_learn_job_dir %env RUNTIME_VERSION 1.9 %env PYTHON_VERSION 3.5 ! mkdir census_training
notebooks/scikit-learn/TrainingWithScikitLearnInCMLE.ipynb
GoogleCloudPlatform/cloudml-samples
apache-2.0
The data The Census Income Data Set that this sample uses for training is provided by the UC Irvine Machine Learning Repository. We have hosted the data on a public GCS bucket gs://cloud-samples-data/ml-engine/sklearn/census_data/. Training file is adult.data Evaluation file is adult.test (not used in this notebook) ...
%%writefile ./census_training/train.py # [START setup] import datetime import pandas as pd from google.cloud import storage from sklearn.ensemble import RandomForestClassifier from sklearn.externals import joblib from sklearn.feature_selection import SelectKBest from sklearn.pipeline import FeatureUnion from sklearn....
notebooks/scikit-learn/TrainingWithScikitLearnInCMLE.ipynb
GoogleCloudPlatform/cloudml-samples
apache-2.0
[Optional] StackDriver Logging You can view the logs for your training job: 1. Go to https://console.cloud.google.com/ 1. Select "Logging" in left-hand pane 1. Select "Cloud ML Job" resource from the drop-down 1. In filter by prefix, use the value of $JOB_NAME to view the logs [Optional] Verify Model File in GCS View t...
! gsutil ls gs://$BUCKET_NAME/census_*
notebooks/scikit-learn/TrainingWithScikitLearnInCMLE.ipynb
GoogleCloudPlatform/cloudml-samples
apache-2.0
Podemos visualizar que la temperatura minima es -2.08 y la maxima 19.02
""" Generemos una grafica de puntos, modificando el ancho y largo de la grafica para poder tener una mejor visualizacion de la informacion """ plt.figure(figsize = (15, 5)) plt.scatter(x = data['LandAverageTemperature'].index, y = data['LandAverageTemperature']) plt.title("Temperatura promedio de la tierra 1750-2015")...
algoritmos/data_science_regression.ipynb
jorgemauricio/INIFAP_Course
mit
Modelado de datos
# Para modelar los datos, vamos a necesitar de la libreria sklearn from sklearn.linear_model import LinearRegression as LinReg x = grouped.index.values.reshape(-1, 1) y = grouped['LandAverageTemperature'].values reg = LinReg() reg.fit(x, y) y_preds = reg.predict(x) print("Certeza: " + str(reg.score(x, y))) plt.figur...
algoritmos/data_science_regression.ipynb
jorgemauricio/INIFAP_Course
mit
Temperatura por ciudad (Aguascalientes)
# Leer la informacion data = pd.read_csv('../data/GlobalLandTemperaturesByCity.csv') data.head() # Cuantas ciudades estan disponibles data['City'].nunique() # Verificamos que nuestra ciudad de interes este disponible ciudades = np.array(data['City']) "Aguascalientes" in ciudades # Filtramos la informacion para la ci...
algoritmos/data_science_regression.ipynb
jorgemauricio/INIFAP_Course
mit
Modelado de datos
# Usaremos el valor previo validado para llenar las observaciones nulas data['AverageTemperature'] = data['AverageTemperature'].fillna(method='ffill') # Reagrupamos la informacion y graficamos grouped = data.groupby([times.year]).mean() # La grafica se ve mejor, aunque no es perfecta plt.figure(figsize = (15, 5)) plt...
algoritmos/data_science_regression.ipynb
jorgemauricio/INIFAP_Course
mit
Vamos a pedecir la temperatura promedio para el 2018
reg.predict(2018)
algoritmos/data_science_regression.ipynb
jorgemauricio/INIFAP_Course
mit
Vamos a pedecir la temperatura promedio para el 2050
reg.predict(2050)
algoritmos/data_science_regression.ipynb
jorgemauricio/INIFAP_Course
mit
Display the same with Python (matplotlib)
import m8r gather = m8r.File('gather.rsf') %matplotlib inline import matplotlib.pylab as plt import numpy as np plt.imshow(np.transpose(gather[:,888:1280]),aspect='auto')
Swan.ipynb
sfomel/ipython
gpl-2.0
Apply moveout with incorrect velocity
%%file nmo.scons Flow('nmo','gather','nmostretch half=n v0=1800') Result('nmo','window f1=888 n1=200 | grey title=NMO') view('nmo')
Swan.ipynb
sfomel/ipython
gpl-2.0
Slope estimation
%%file slope.scons Flow('slope','nmo','dip rect1=100 rect2=5 order=2') Result('slope','grey color=linearlfb mean=y scalebar=y title=Slope') view('slope')
Swan.ipynb
sfomel/ipython
gpl-2.0
Non-physical flattening by predictive painting
%%file flat.scons Flow('paint','slope','pwpaint order=2') Result('paint','window f1=888 n1=200 | contour title=Painting') Flow('flat','nmo paint','iwarp warp=${SOURCES[1]}') Result('flat','window f1=888 n1=200 | grey title=Flattening') view('paint') view('flat')
Swan.ipynb
sfomel/ipython
gpl-2.0
Velocity estimation by time warping Predictive painting produces $t_0(t,x)$. Time warping converts it into $t(t_0,x)$.
%%file twarp.scons Flow('twarp','paint','math output=x1 | iwarp warp=$SOURCE') Result('twarp','window j1=20 | transp | graph yreverse=y min2=0.888 max2=1.088 pad=n title="Time Warping" ') view('twarp')
Swan.ipynb
sfomel/ipython
gpl-2.0
We now want to fit $t^2(t_0,x)-t_0^2 \approx \Delta S\,x^2$, where $\Delta S = \frac{1}{v^2} - \frac{1}{v_0^2}$. The least-squares fit is $\Delta S = \displaystyle \frac{\int x^2\left[t^2(t_0,x)-t_0^2\right]\,dx}{\int x^4\,dx}$. The velocity estimate is $v = \displaystyle \frac{v_0}{\sqrt{\Delta S\,v_0^2 + 1}}$.
%%file lsfit.scons Flow('num','twarp','math output="(input*input-x1*x1)*x2^2" | stack norm=n') Flow('den','twarp','math output="x2^4" | stack norm=n') Flow('vel','num den','div ${SOURCES[1]} | math output="1800/sqrt(1800*1800*input+1)" ') Result('vel', ''' window f1=888 n1=200 | graph yreverse=y...
Swan.ipynb
sfomel/ipython
gpl-2.0
Last step - physical flattening
%%file nmo2.scons Flow('nmo2','gather vel','nmo half=n velocity=${SOURCES[1]}') Result('nmo2','window f1=888 n1=200 | grey title="Physical Flattening" ') view('nmo2')
Swan.ipynb
sfomel/ipython
gpl-2.0
The number of Sobol samples to use at each order is arbitrary, but for compare, we select them to be the same as the Gauss nodes:
from monte_carlo_integration import sobol_samples sobol_nodes = [sobol_samples[:, :nodes.shape[1]] for nodes in gauss_nodes] from matplotlib import pyplot pyplot.rc("figure", figsize=[12, 4]) pyplot.subplot(121) pyplot.scatter(*gauss_nodes[4]) pyplot.title("Gauss quadrature nodes") pyplot.subplot(122) pyplot.scatt...
docs/user_guide/main_usage/point_collocation.ipynb
jonathf/chaospy
mit
Evaluating model solver Like in the case of problem formulation again, evaluation is straight forward:
import numpy from problem_formulation import model_solver gauss_evals = [ numpy.array([model_solver(node) for node in nodes.T]) for nodes in gauss_nodes ] sobol_evals = [ numpy.array([model_solver(node) for node in nodes.T]) for nodes in sobol_nodes ] from problem_formulation import coordinates pypl...
docs/user_guide/main_usage/point_collocation.ipynb
jonathf/chaospy
mit
Select polynomial expansion Unlike pseudo spectral projection, the polynomial in point collocations are not required to be orthogonal. But stability wise, orthogonal polynomials have still been shown to work well. This can be achieved by using the chaospy.generate_expansion() function:
import chaospy from problem_formulation import joint expansions = [chaospy.generate_expansion(order, joint) for order in range(1, 10)] expansions[0].round(10)
docs/user_guide/main_usage/point_collocation.ipynb
jonathf/chaospy
mit
Solve the linear regression problem With all samples $Q_1, ..., Q_N$, model evaluations $U_1, ..., U_N$ and polynomial expansion $\Phi_1, ..., \Phi_M$, we can put everything together to solve the equations: $$ U_n = \sum_{m=1}^M c_m(t)\ \Phi_m(Q_n) \qquad n = 1, ..., N $$ with respect to the coefficients $c_1, ...,...
gauss_model_approx = [ chaospy.fit_regression(expansion, samples, evals) for expansion, samples, evals in zip(expansions, gauss_nodes, gauss_evals) ] sobol_model_approx = [ chaospy.fit_regression(expansion, samples, evals) for expansion, samples, evals in zip(expansions, sobol_nodes, sobol_evals) ] py...
docs/user_guide/main_usage/point_collocation.ipynb
jonathf/chaospy
mit
Descriptive statistics The expected value and variance is calculated as follows:
expected = chaospy.E(gauss_model_approx[-2], joint) std = chaospy.Std(gauss_model_approx[-2], joint) expected[:4].round(4), std[:4].round(4) pyplot.rc("figure", figsize=[6, 4]) pyplot.xlabel("coordinates") pyplot.ylabel("model approximation") pyplot.fill_between( coordinates, expected-2*std, expected+2*std, alph...
docs/user_guide/main_usage/point_collocation.ipynb
jonathf/chaospy
mit
Error analysis It is hard to assess how well these models are doing from the final estimation alone. They look about the same. So to compare results, we do error analysis. To do so, we use the reference analytical solution and error function as defined in problem formulation.
from problem_formulation import error_in_mean, error_in_variance error_in_mean(expected), error_in_variance(std**2)
docs/user_guide/main_usage/point_collocation.ipynb
jonathf/chaospy
mit
The analysis can be performed as follows:
sizes = [nodes.shape[1] for nodes in gauss_nodes] eps_gauss_mean = [ error_in_mean(chaospy.E(model, joint)) for model in gauss_model_approx ] eps_gauss_var = [ error_in_variance(chaospy.Var(model, joint)) for model in gauss_model_approx ] eps_sobol_mean = [ error_in_mean(chaospy.E(model, joint)) ...
docs/user_guide/main_usage/point_collocation.ipynb
jonathf/chaospy
mit
<h2>Example: Symmetric IPVP</h2> After a bit of algebra, see <a href="https://github.com/davidrpugh/zice-2014/blob/master/solving-auctions/Hubbard%20and%20Paarsch%20(2013).pdf">Hubbard and Parsch (2013)</a> for details, all Symmetric Independent Private Values Paradigm (IPVP) models can be reduced down to a single non...
import functools class SymmetricIPVPModel(pycollocation.problems.IVP): def __init__(self, f, F, params): rhs = self._rhs_factory(f, F) super(SymmetricIPVPModel, self).__init__(self._initial_condition, 1, 1, params, rhs) @staticmethod def _initial_condition(v, sigma, v_lower, ...
examples/auction-models.ipynb
davidrpugh/pyCollocation
mit
<h2>Solving the model with pyCollocation</h2> Finding a good initial guess for $\sigma(v)$ Theory tells us that bidding function should be monotonically increasing in the valuation? Higher valuations lead to higher bids?
def initial_mesh(v_lower, v_upper, num, problem): """Guess that all participants bid their true valuations.""" vs = np.linspace(v_lower, v_upper, num) return vs, vs
examples/auction-models.ipynb
davidrpugh/pyCollocation
mit
Solving the model
pycollocation.solvers.LeastSquaresSolver? polynomial_basis = pycollocation.basis_functions.PolynomialBasis() solver = pycollocation.solvers.LeastSquaresSolver(polynomial_basis) # compute the initial mesh boundary_points = (symmetric_ipvp_ivp.params['v_lower'], symmetric_ipvp_ivp.params['v_upper']) vs, sigmas = initia...
examples/auction-models.ipynb
davidrpugh/pyCollocation
mit
<h2>Example: Asymmetric IPVP</h2> After a bit of algebra, see <a href="https://github.com/davidrpugh/zice-2014/blob/master/solving-auctions/Hubbard%20and%20Paarsch%20(2013).pdf">Hubbard and Parsch (2013)</a> for details, all Asymmetric Independent Private Values Paradigm (IPVP) models can be reduced down to a system o...
def rhs_bidder_n(n, s, phis, f, F, N, **params): A = (F(phis[n], **params) / f(phis[n], **params)) B = ((1 / (N - 1)) * sum(1 / (phi(s) - s) for phi in phis) - (1 / phis[n])) return A * B def asymmetric_ipvp_model(s, *phis, fs=None, Fs=None, N=2, **params): return [rhs_bidder(n, s, phi, f, F, N, **para...
examples/auction-models.ipynb
davidrpugh/pyCollocation
mit
This notebook shows a typical workflow to query a Catalog Service for the Web (CSW) and creates a request for data endpoints that are suitable for download. The catalog of choice is the NGCD geoportal (http://www.ngdc.noaa.gov/geoportal/csw) and we want to query it using a geographical bounding box, a time range, and ...
from datetime import datetime, timedelta event_date = datetime(2015, 8, 15) start = event_date - timedelta(days=4) stop = event_date + timedelta(days=4)
content/downloads/notebooks/2015-10-12-fetching_data.ipynb
ioos/system-test
unlicense
The bounding box is slightly larger than the Boston harbor to assure we get some data.
spacing = 0.25 bbox = [-71.05-spacing, 42.28-spacing, -70.82+spacing, 42.38+spacing]
content/downloads/notebooks/2015-10-12-fetching_data.ipynb
ioos/system-test
unlicense
The CF_names object is just a Python dictionary whose keys are SOS names and the values contain all possible combinations of temperature variables names in the CF conventions. Note that we also define a units object. We use the object units to coerce all data to celcius.
import iris from utilities import CF_names sos_name = 'sea_water_temperature' name_list = CF_names[sos_name] units = iris.unit.Unit('celsius')
content/downloads/notebooks/2015-10-12-fetching_data.ipynb
ioos/system-test
unlicense