markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Let's find all the nifti images for subject 02 session 02
cci.search('ds000255/sub-02/ses-02/func/*.nii.gz') # note that the beggining of the file name is cut off in the printed output. # this occurs because the object names are very long. nifti_files = cci.glob('ds000255/sub-02/ses-02/func/*.nii.gz') print(nifti_files[0]) # the full object name
cottoncandy/examples/ccexample_openneuro.ipynb
gallantlab/cottoncandy
bsd-2-clause
Compute temporal SNR images for individual nifti runs
for fl in nifti_files[:5]: print('Working on: %s'%fl) # Use the function defined at the beginning nii = download_nifti(fl, cci) arr = nii.get_data().T tsnr = arr.mean(0)/arr.std(0) plt.matshow(tsnr[15], cmap='inferno') plt.grid(False) description = fl.split('/')[-1] __ = plt.title...
cottoncandy/examples/ccexample_openneuro.ipynb
gallantlab/cottoncandy
bsd-2-clause
Part 1: What pylearn2 is doing for you in this example In this part, we won't get into any specifics of pylearn2 yet. We'll just discuss what a convolutional network is. If you already know about convolutional networks, feel free to skip to part 2. Review of multilayer perceptrons, and how convolutional networks are si...
!wget https://raw.githubusercontent.com/lisa-lab/pylearn2/master/pylearn2/scripts/tutorials/convolutional_network/conv.yaml train = open('conv.yaml', 'r').read() train_params = {'train_stop': 50000, 'valid_stop': 60000, 'test_stop': 10000, 'batch_size': 100, ...
notebooks/tutorials/convolutional_network.ipynb
Neuroglycerin/neukrill-net-work
mit
Now, we use pylearn2's yaml_parse.load to construct the Train object, and run its main loop. The same thing could be accomplished by running pylearn2's train.py script on a file containing the yaml string. Execute the next cell to train the model. This will take several minutes and possible as much as a few hours depen...
%%bash mkdir -p /disk/scratch/neuroglycerin/mnist/ cd /disk/scratch/neuroglycerin/mnist/ wget http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz wget http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz wget http://yann.lecun.com/exdb/mnist...
notebooks/tutorials/convolutional_network.ipynb
Neuroglycerin/neukrill-net-work
mit
And make sure the pylearn2 environment variable for it is set:
%env PYLEARN2_DATA_PATH=/disk/scratch/neuroglycerin !echo $PYLEARN2_DATA_PATH %pdb from pylearn2.config import yaml_parse train = yaml_parse.load(train) train.main_loop()
notebooks/tutorials/convolutional_network.ipynb
Neuroglycerin/neukrill-net-work
mit
Giving up on that yaml file. Trying the mnist.yaml that is supplied with the repo:
%pdb %run /afs/inf.ed.ac.uk/user/s08/s0805516/repos/pylearn2/pylearn2/scripts/train.py --time-budget 600 ~/repos/pylearn2/pylearn2/scripts/papers/maxout/mnist.yaml !du -h /afs/inf.ed.ac.uk/user/s08/s0805516/repos/pylearn2/pylearn2/scripts/papers/maxout/mnist_best.pkl !rm /afs/inf.ed.ac.uk/user/s08/s0805516/repos/pyl...
notebooks/tutorials/convolutional_network.ipynb
Neuroglycerin/neukrill-net-work
mit
Compiling the theano functions used to run the network will take a long time for this example. This is because the number of theano variables and ops used to specify the computation is relatively large. There is no single theano op for doing max pooling with overlapping pooling windows, so pylearn2 builds a large expre...
!print_monitor.py convolutional_network_best.pkl | grep test_y_misclass
notebooks/tutorials/convolutional_network.ipynb
Neuroglycerin/neukrill-net-work
mit
The test set error has dropped to 0.74%! This is a big improvement over the standard MLP. We can also look at the convolution kernels learned by the first layer, to see that the network is looking for shifted versions of small pieces of penstrokes.
!show_weights.py convolutional_network_best.pkl
notebooks/tutorials/convolutional_network.ipynb
Neuroglycerin/neukrill-net-work
mit
Numerical Features
corr = df.select_dtypes(include = ['float64', 'int64']).iloc[:, 1:].corr() plt.figure(figsize=(12, 12)) sns.heatmap(corr, vmax=1, square=True) cor_dict = corr['SalePrice'].to_dict() del cor_dict['SalePrice'] print("List the numerical features decendingly by their correlation with Sale Price:\n") for ele in sorted(cor_...
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
The housing price correlates strongly with OverallQual, GrLivArea(GarageCars), GargeArea, TotalBsmtSF, 1stFlrSF, FullBath, TotRmsAbvGrd, YearBuilt, YearRemodAdd, GargeYrBlt, MasVnrArea and Fireplaces. But some of those features are highly correlated among each others.
sns.regplot(x = 'OverallQual', y = 'SalePrice', data = df, color = 'Orange') plt.figure(1) f, axarr = plt.subplots(3, 2, figsize=(10, 9)) price = df.SalePrice.values axarr[0, 0].scatter(df.GrLivArea.values, price) axarr[0, 0].set_title('GrLiveArea') axarr[0, 1].scatter(df.GarageArea.values, price) axarr[0, 1].set_titl...
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
Categorical Features
print(df.select_dtypes(include=['object']).columns.values)
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
Neighborhood
plt.figure(figsize = (12, 6)) sns.boxplot(x = 'Neighborhood', y = 'SalePrice', data = df) xt = plt.xticks(rotation=45) plt.figure(figsize = (12, 6)) sns.countplot(x = 'Neighborhood', data = df) xt = plt.xticks(rotation=45)
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
Could group those Neighborhoods with similar housing price into a same bucket for dimension-reduction. Housing Price vs Sales Sale Type & Condition Sales Seasonality
fig, ax = plt.subplots(2, 1, figsize = (10, 6)) sns.boxplot(x = 'SaleType', y = 'SalePrice', data = df, ax = ax[0]) sns.boxplot(x = 'SaleCondition', y = 'SalePrice', data = df, ax = ax[1]) plt.tight_layout() g = sns.FacetGrid(df, col = 'YrSold', col_wrap = 3) g.map(sns.boxplot, 'MoSold', 'SalePrice', palette='Set2', o...
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
Sale's timing does not seem to hugely affect the house. Housing Style
fig, ax = plt.subplots(2, 1, figsize = (10, 8)) sns.boxplot(x = 'BldgType', y = 'SalePrice', data = df, ax = ax[0]) sns.boxplot(x = 'HouseStyle', y = 'SalePrice', data = df, ax = ax[1])
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
Housing Condition
fig, ax = plt.subplots(2, 1, figsize = (10, 8)) sns.boxplot(x = 'Condition1', y = 'SalePrice', data = df, ax = ax[0]) sns.boxplot(x = 'Exterior1st', y = 'SalePrice', data = df, ax = ax[1]) x = plt.xticks(rotation = 45) plt.show()
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
Basement Conditions
fig, ax = plt.subplots(2, 2, figsize = (10, 8)) sns.boxplot('BsmtCond', 'SalePrice', data = df, ax = ax[0, 0]) sns.boxplot('BsmtQual', 'SalePrice', data = df, ax = ax[0, 1]) sns.boxplot('BsmtExposure', 'SalePrice', data = df, ax = ax[1, 0]) sns.boxplot('BsmtFinType1', 'SalePrice', data = df, ax = ax[1, 1])
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
Home Functionality
sns.violinplot('Functional', 'SalePrice', data = df)
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
FirePlaceQu
sns.factorplot('FireplaceQu', 'SalePrice', data = df, color = 'm', \ estimator = np.median, order = ['Ex', 'Gd', 'TA', 'Fa', 'Po'], size = 4.5, aspect=1.35) pd.crosstab(df.Fireplaces, df.FireplaceQu) g = sns.FacetGrid(df, col = 'FireplaceQu', col_wrap = 3, col_order=['Ex', 'Gd', 'TA', 'Fa', 'Po']) g.m...
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
Heating Ames is a cold place in winter, so heating (as well as fireplace qualities) are quite important.
pd.crosstab(df.HeatingQC, df.CentralAir) pd.crosstab(df.HeatingQC, df.FireplaceQu) sns.factorplot('HeatingQC', 'SalePrice', hue = 'CentralAir', estimator = np.mean, data = df, size = 4.5, aspect = 1.4)
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
Clearly, having AC or not has a big impact on housing price.
fig, ax = plt.subplots(1, 2, figsize = (10, 4)) sns.boxplot('Electrical', 'SalePrice', data = df, ax = ax[0]).set(ylim = (0, 400000)) sns.countplot('Electrical', data = df) plt.tight_layout()
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
Kitchen Quality
sns.factorplot('KitchenQual', 'SalePrice', estimator = np.mean, size = 4.5, aspect = 1.4, data = df, order = ['Ex', 'Gd', 'TA', 'Fa'])
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
MSZonig
sns.boxplot(x = 'MSZoning', y = 'SalePrice', data = df)
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
Street & Alley Access
fig, ax = plt.subplots(1, 2, figsize = (10, 4)) sns.boxplot(x = 'Street', y = 'SalePrice', data = df, ax = ax[0]) sns.boxplot(x = 'Alley', y = 'SalePrice', data = df, ax = ax[1]) plt.tight_layout() print("The NA's in Alley is: ", df['Alley'].isnull().sum()) print("\nThere are so many NA's in Alley. When Alley is NA, ...
examples/detailed-data-exploration.ipynb
samuelsinayoko/kaggle-housing-prices
mit
Como véis, en la gráfica anterior hay varios problemas pero como esta es una MicroEntrada solo nos vamos a centrar en el problema de las etiquetas repetidas en la leyenda. ¿Cómo podríamos evitar el meter tantas veces una etiqueta repetida? Mi problema es que el bucle es o podría ser 'infinito' y tengo que inicializar l...
plt.figure(figsize = (12, 6)) for i in range(10): x = np.arange(i * 10, i * 10 + 10) y_var1 = np.random.randint(1, 5, 10) y_var2 = np.random.randint(5, 8, 10) plt.plot(x, y_var1, color = 'k', label = 'variable1' if i == 0 else "_esto_no_se_pintará") plt.plot(x, y_var2, color = 'g', label = 'variable...
Microentradas - Evitar ciertas etiquetas en la leyenda en Matplotlib.ipynb
Pybonacci/notebooks
bsd-2-clause
Now suppose that the prior probability is 0.5 that the orientation of the connector is correct, and you have been trying for 0.9 seconds. What is the likelihood that you would have to try so long? If you are on the wrong side, it is 100%. If you are on the right side, it's given by the survival function (complement...
import numpy as np def expo_sf(t, lam): """Survival function of the exponential distribution.""" return np.exp(-lam * t)
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
We can use this function to compute the likelihood of trying for 0.9 seconds or more, given an exponential distribution with mean 1.1.
t = 0.9 mu = 1.1 lam = 1/mu expo_sf(t, lam)
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
The result is the likelihood of the data, given that the orientation of the connector is correct. Now let's make a Bayes table with two hypotheses -- the connector is either the right way or the wrong way -- with equal prior probabilities.
hypos = ['Right way', 'Wrong way'] prior = [1/2, 1/2]
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
And here is the likelihood of the data for each hypothesis:
likelihood = [expo_sf(t, lam), 1]
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
Putting it together, here's the Bayes table.
bayes_table(hypos, prior, likelihood)
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
After 0.9 seconds, the probability is about 69% that the orientation of the connector is wrong, so you might want to think about trying the other side. But if it takes 0.1 seconds to flip, maybe you should keep trying a little longer. To figure out when to flip, let's do the same analysis again for general values of $\...
from sympy import symbols, exp t, lam, p, q, r = symbols('t lam p q r')
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
Here's the likelihood again, using the symbols.
likelihood = [exp(-lam * t), 1] likelihood
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
And here's the Bayes table, using $p$ and $q$ for the prior probabilities of the hypotheses.
prior = [p, q] table = bayes_table(hypos, prior, likelihood) table
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
From the table I'll select the posterior probability that the orientation is correct.
expr = table.loc['Right way', 'posterior'] expr.simplify()
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
You might recognize this as a form of the logistic function; we can compute it like this:
def logistic(p, lam, t): q = 1-p return p / (p + q * np.exp(lam * t))
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
Let's see what that looks like for a range of values of t, assuming that the prior probability is p=0.5.
import matplotlib.pyplot as plt ts = np.linspace(0, 4) ps = logistic(p=0.5, lam=1/mu, t=ts) plt.plot(ts, ps) plt.xlabel("How long you've been trying (seconds)") plt.ylabel("Probability the orientation is right");
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
After a few seconds of fiddling, you should be reasonably convinced that the orientation is wrong. Strategy Now, let's think about turning belief into action. Let me start with a conjecture: I suspect that the best strategy is to try on the first side until the probability of correct orientation drops below some thresh...
from sympy import Eq, solve eqn = Eq(expr, r) eqn
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
And here's the solution for t in terms of p, q, r, and lam.
solve(eqn, t)[0]
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
And here's how we can express this solution in terms of the prior and posterior odds.
def wait_time(p, lam, r): q = 1-p prior_odds = p / q posterior_odds = r / (1-r) return np.log(prior_odds / posterior_odds) / lam
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
Let's see what that looks like for a range of values of r, assuming that the prior probability is p=0.5.
rs = np.linspace(0.05, 0.5) ts = wait_time(p=0.5, lam=1/mu, r=rs) plt.plot(rs, ts, color='C2') plt.xlabel("Probability the orientation is right") plt.ylabel("How long to keep trying (seconds)");
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
When the threshold is low, we have to wait a few seconds to reach it. As the threshold increases, the time to reach it decreases. We'll use this function in the next section to simulate the strategy. Simulation As a step toward optimization, let's run a simulation. The following function takes as parameters: correct: ...
def simulate(correct, p, lam, r, flip, trace): # figure out the maximum time we should try before flipping wait = wait_time(p, lam, r) # if we're on the correct side, see if we succeed before time's up if correct: t = np.random.exponential(1/lam) if t < wait: # if so, up...
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
Here's a test run, starting on the correct side.
simulate(correct=True, p=0.5, lam=1/mu, r=0.2, flip=0.1, trace=[])
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
And here's a run where we start on the wrong side.
simulate(correct=False, p=0.5, lam=1/mu, r=0.2, flip=0.1, trace=[])
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
The following function runs the simulation many times with initial probability p=0.5, starting in the right orientation half the time. It returns two arrays, containing the length of the trace and the total duration for each simulation.
def run_simulations(lam, r, flip, iters=20000, flag=None): res = [] for i in range(iters): correct = i%2 if flag is None else flag trace = simulate(correct, 0.5, lam, r, flip, []) res.append((len(trace), sum(trace))) return np.transpose(res)
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
Here's the average total duration with threshold probability r=0.25.
lengths, totals = run_simulations(lam=1/mu, r=0.25, flip=0.1) totals.mean()
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
With this threshold, it takes about 2 seconds to connect, on average. Optimization Now let's see how the average duration varies as we sweep through a range of values for the threshold probability, r:
rs = np.linspace(0.15, 0.4, 21) rs np.random.seed(17) res = [] for r in rs: lengths, totals = run_simulations(lam=1/mu, r=r, flip=0.1) res.append((r, totals.mean())) from statsmodels.nonparametric.smoothers_lowess import lowess def make_lowess(series): """Use LOWESS to compute a smooth line. series...
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
Here's what the results look like.
rs, ts = np.transpose(res) series = pd.Series(ts, rs) plot_series_lowess(series, 'C1') plt.xlabel("Threshold probability where you flip (r)") plt.ylabel("Average total duration (seconds)");
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
The optimal value of r is close to 0.3. With that threshold we can see how long we should try on the first side, starting with prior probability p=0.5.
r_opt = 0.3 wait_time(p=0.5, lam=1/mu, r=r_opt)
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
With the given values of lam and flip, it turns out the optimal time to wait is about 0.9 seconds. If we have to flip, the prior probability for the second side is p=1-r, so we have to wait twice as long for the posterior probability to get down to r.
wait_time(p=1-r_opt, lam=1/mu, r=r_opt)
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
How many flips? Now let's run the simulations with the optimal value of r and see what the distributions look like for the total time and the number of flips.
lengths1, totals1 = run_simulations(lam=1/mu, r=r_opt, flip=0.1, flag=True) lengths2, totals2 = run_simulations(lam=1/mu, r=r_opt, flip=0.1, flag=False)
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
Here's the distribution of total time, represented as a CDF.
try: import empiricaldist except ImportError: !pip install empiricaldist from empiricaldist import Cdf Cdf.from_seq(totals1).plot(lw=2, label='Right the first time') Cdf.from_seq(totals2).plot(lw=2, label='Wrong the first time') plt.xlabel('Total time to connect (seconds)') plt.ylabel('CDF') plt.title('Distr...
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
The average is about 2.4 seconds, but occasionally it takes much longer! And here's the distribution for the total number of flips.
from empiricaldist import Pmf flips1 = (lengths1-1) // 2 pmf1 = Pmf.from_seq(flips1) / 2 pmf1.bar(alpha=0.7, label='Right the first time') flips2 = (lengths2-1) // 2 pmf2 = Pmf.from_seq(flips2) / 2 pmf2.bar(alpha=0.7, label='Right the second time') plt.xlabel('How many times you have to flip') plt.ylabel('PMF') plt....
examples/usb.ipynb
AllenDowney/ThinkBayes2
mit
Quiz Question: The code block above computed $\color{red}{\sum_{s = i}^{i+B}}\partial\ell_{s}(\mathbf{w})/{\partial w_j}$ for j = 10, i = 10, and B = 10. Is this a scalar or a 194-dimensional vector? Quiz Question: For what value of B is the term $\color{red}{\sum_{s = 1}^{B}}\partial\ell_{s}(\mathbf{w})/\partial w_...
from math import sqrt def logistic_regression_SG(feature_matrix, sentiment, initial_coefficients, step_size, batch_size, max_iter): log_likelihood_all = [] # make sure it's a numpy array coefficients = np.array(initial_coefficients) # set seed=1 to produce consistent results np.random.seed(seed...
coursera/ml-classification/assignments/module-10-online-learning-assignment-blank.ipynb
jinntrance/MOOC
cc0-1.0
Quiz Question. When you set batch_size = len(train_data), as each iteration passes, how does the average log likelihood in the batch change? * Increases * Decreases * Fluctuates Make "passes" over the dataset To make a fair comparison betweeen stochastic gradient ascent and batch gradient ascent, we measure the avera...
2*50000/100
coursera/ml-classification/assignments/module-10-online-learning-assignment-blank.ipynb
jinntrance/MOOC
cc0-1.0
Data Wrangling with Python and Pandas (tutorial) Introduction: http://pandas.pydata.org/pandas-docs/stable/10min.html Tutorial on data wrangling: https://github.com/jvns/pandas-cookbook
# Run some exploration on tutorial %matplotlib inline import pandas as pd import matplotlib matplotlib.style.use('ggplot') #montreal weather weather_url = "https://raw.githubusercontent.com/jvns/pandas-cookbook/master/data/weather_2012.csv" weather_2012_final = pd.read_csv(weather_url, parse_dates='Date/Time', index_c...
EverythingData.ipynb
LucaFoschini/IGERTbootcamp2016
mit
Why is my code slow? Look under the hood: Memory hiearchies. Python is magic, magic isn't free: how built-in types are implemented and efficiency consideration Profiling and monitoring If everything else fails: go parallel. Example of vectorization and timing http://nbviewer.jupyter.org/github/rossant/ipython-minibo...
# Run the example above def closest(position, positions): x0, y0 = position dbest, ibest = None, None for i, (x, y) in enumerate(positions): d = (x - x0) ** 2 + (y - y0) ** 2 if dbest is None or d < dbest: dbest, ibest = d, i return ibest import random positions = [(random....
EverythingData.ipynb
LucaFoschini/IGERTbootcamp2016
mit
One benchmark a day Goldmine: https://github.com/rasbt/One-Python-benchmark-per-day/tree/master/ Try: 6 different ways for counting elements using a dictionary Python vs Cython vs Numba Memory, cores, I/O Latency: Register, Cache, RAM, Disk (SSD/HDD), network Out of core vs distributed Embarrassingly parallel p...
from IPython.display import Image Image(url='http://i.imgur.com/k0t1e.png')
EverythingData.ipynb
LucaFoschini/IGERTbootcamp2016
mit
Scale: Parallel : doc and example Multiprocess : http://sebastianraschka.com/Articles/2014_multiprocessing_intro.html Big Data (Spark and BDAS) https://spark.apache.org/examples.html
!pip install ipyparallel # Example: Run some parallel code from ipyparallel import Client client = Client(profile='mycluster') %px print("Hello from the cluster engines!")
EverythingData.ipynb
LucaFoschini/IGERTbootcamp2016
mit
How to deal with big data? be smart: (sampling/approximation algorithms, divide-and-conquer) be rich: rent-a-cloud, Digital Ocean, Cloud9 Network analysis with NetworkX Intro and examples here
%matplotlib inline import networkx as nx import matplotlib.pyplot as plt from IPython.display import Image n = 10 m = 20 rgraph1 = nx.gnm_random_graph(n,m) print "Nodes: ", rgraph1.nodes() print "Edges: ", rgraph1.edges() if nx.is_connected(rgraph1): print "Graph is connected" else: print "Graph is not connect...
EverythingData.ipynb
LucaFoschini/IGERTbootcamp2016
mit
For a particular parameter, the corresponding function of the given family is represented as heatmap of its argument, which illustrates its zeros and poles position. Define tickvals and ticktext for the heatmap colorbar
tickvals = [-np.pi, -2*np.pi/3, -np.pi/3, 0, np.pi/3, 2*np.pi/3, np.pi] ticktext=['-\u03c0', '-2\u03c0/3', '-\u03c0/3', '0', '\u03c0/3', '2\u03c0/3', '\u03c0']
Imags/Animating a family-of-complex-functions.ipynb
empet/Math
bsd-3-clause
Define a family of complex functions, depending on the parameter t. To animate the motion of function zeros and poles, as t varies, we use functools.partial to get the function corresponding to a particular parameter:
from functools import partial def func(t, z): return z**4+np.exp(2*t*1j)/z**2*np.exp(1j*t) f0 = partial(func, 0) x, y, z = evaluate_function(f0, re=(-1.5, 1.5), im=(-1.5,1.5), N=50) w = f0(z) argument = np.angle(w) fig = go.Figure(go.Heatmap(x=x, y=y, z=argument, colorscale=pl_hsv, colorb...
Imags/Animating a family-of-complex-functions.ipynb
empet/Math
bsd-3-clause
Random Numbers: Uniformly Distributed Random Numbers
import random random.uniform(0.0,1.0) random.uniform(0.0,1.0) random.uniform(0.0,1.0) random.uniform(0.0,1.0)
pi_monte_carlo/Monte Carlo Lecture Code.ipynb
stephensekula/smu-honors-physics
mit
Generating "dots" - random x, random y, and r
import math import random Ntotal = 100 Nin = 0 x = random.uniform(0.0,1.0) y = random.uniform(0.0,1.0) r = math.sqrt(x**2 + y**2) print(x) print(y) print(r)
pi_monte_carlo/Monte Carlo Lecture Code.ipynb
stephensekula/smu-honors-physics
mit
The range() sequence type If you want to generate a series of numbers in a sequence, e.g. 1,2,3,4..., then you want the range() immutable sequence type (or its equivalent in some other Python library). See the example below. range() doesn't directly create a list of numbers; it is its own type in Python. To get a list ...
list_of_numbers=list(range(1,5)) print(list_of_numbers) # Note that the list EXCLUDES the endpoint. If you want to get a list of 5 numbers, from 1-5, # then you need to extend the endpoint by 1: list_of_numbers=list(range(1,6)) print(list_of_numbers) # or this list_of_numbers=list(range(0,5)) print(list_of_numbers...
pi_monte_carlo/Monte Carlo Lecture Code.ipynb
stephensekula/smu-honors-physics
mit
Putting things together: "looping" 100 times and printing r each time Let's put things together now. We can create a variable that stores the number of iterations ("loops") of the calculation we want to do. Let's call that Ntotal. Let's then loop 100 times and each time make a random x, random y, and from that compute ...
import math Ntotal = 100 Nin = 0 for i in range(0,Ntotal): x = random.uniform(0.0,1.0) y = random.uniform(0.0,1.0) r = math.sqrt(x**2 + y**2) print("x=%f, y=%f, r=%f" % (x,y,r))
pi_monte_carlo/Monte Carlo Lecture Code.ipynb
stephensekula/smu-honors-physics
mit
Monte Carlo - Accept/Reject Now that we can make random "dots" in x,y and compute the radius (relative to 0,0) of each dot, let's employ "Accept/Reject" to see if something is in/on the circle or outside the circle. All we have to do is, for each $r$, test whether $r \le R$ or $r > R$. If the former, we have a dot in t...
Ntotal = 100 Nin = 0 R = 1.0 for i in range(0,Ntotal): x = random.uniform(0.0,1.0) y = random.uniform(0.0,1.0) r = math.sqrt(x**2 + y**2) if r <= R: Nin = Nin + 1 # alternatively, Nin += 1 (auto-increment by 1) print("Number of dots: %d" % Ntotal) print("Number of hits: %d" % Nin) prin...
pi_monte_carlo/Monte Carlo Lecture Code.ipynb
stephensekula/smu-honors-physics
mit
Precision in Monte Carlo Simulation The number above is probably close to what you know as $\pi$, but likely not very precise. After all, we only threw 100 dots. We can increase precision by increasing the number of dots. In the code block below, feel free to play with Ntotal, trying different values. Observe how the c...
Ntotal = 100 Nin = 0 R = 1.0 for i in range(0,Ntotal): x = random.uniform(0.0,1.0) y = random.uniform(0.0,1.0) r = math.sqrt(x**2 + y**2) if r <= R: Nin = Nin + 1 # alternatively, Nin += 1 (auto-increment by 1) my_pi = 4.0*float(Nin)/float(Ntotal) my_pi_uncertainty = my_pi * math.sqrt(...
pi_monte_carlo/Monte Carlo Lecture Code.ipynb
stephensekula/smu-honors-physics
mit
Text Classification of Movie Reviews Unpack data - this only works on linux and (maybe?) OS X. Unpack using 7zip on Windows.
#! tar -xf data/aclImdb.tar.bz2 --directory data from sklearn.datasets import load_files reviews_train = load_files("data/aclImdb/train/") text_train, y_train = reviews_train.data, reviews_train.target print("Number of documents in training data: %d" % len(text_train)) print(np.bincount(y_train)) reviews_test = loa...
06 - Working With Text Data.ipynb
amueller/odscon-sf-2015
cc0-1.0
N-Grams
text_pipe = make_pipeline(CountVectorizer(), LinearSVC()) param_grid = {'linearsvc__C': np.logspace(-3, 2, 6), "countvectorizer__ngram_range": [(1, 1), (1, 2)]} grid = GridSearchCV(text_pipe, param_grid, cv=5) grid.fit(text_train, y_train) scores = np.array([score.mean_validation_score for score in gr...
06 - Working With Text Data.ipynb
amueller/odscon-sf-2015
cc0-1.0
Looking at files in a repo A repository is just a directory. Let's poke around.
# What files are in the repo? !ls -lh # What about hidden files? !ls -alh
sp17/disc/disc03/disc03.ipynb
DS-100/sp17-materials
gpl-3.0
The special .git directory is where git stores all its magic. If you delete it (or this whole directory), the repository won't be a repository any more.
# What's the current status, according to git? !git status # What's the history of the repo? !git log # What does README.md look like currently? !cat README.md
sp17/disc/disc03/disc03.ipynb
DS-100/sp17-materials
gpl-3.0
Making changes: Our first commit Suppose we want to add a file. You could create a Jupyter notebook or download an image. For simplicity, we'll just add a text file.
# We can use Python to compute the filename. # Then we can reference Python variables in # ! shell commands using {}, because Jupyter # is magic. import datetime our_id = datetime.datetime.now().microsecond filename = "our_file_{:d}.txt".format(our_id) filename !echo "The quick brown fox \ jumped over the lzy dog." > ...
sp17/disc/disc03/disc03.ipynb
DS-100/sp17-materials
gpl-3.0
Creating the file only changed the local filesystem. We can go to the repository page on Github to verify that the file hasn't been added yet. You probably wouldn't want your changes to be published immediately to the world!
!git add "{filename}"
sp17/disc/disc03/disc03.ipynb
DS-100/sp17-materials
gpl-3.0
If you check again, our file still hasn't been published to the world. In git, you package together your new files and updates to old files, and then you create a new version called a "commit." Git maintains a "staging" or "index" area for files that you've marked for committing with git add.
!git status !git commit -m 'Added our new file, "{filename}"' !git status !git log
sp17/disc/disc03/disc03.ipynb
DS-100/sp17-materials
gpl-3.0
Now our local repository has this new commit in it. Notice that the log shows the message we wrote when we made the commit. It is very tempting to write something like "stuff" here. But then it will be very hard to understand your history, and you'll lose some of the benefits of git. For the same reason, try to make...
!git remote -v !git help push !git push origin
sp17/disc/disc03/disc03.ipynb
DS-100/sp17-materials
gpl-3.0
Now our commit is finally visible on Github. Even if we spill coffee on our laptop, our new state will be safely recorded in the remote repository. Going back Oops, we didn't want that file! In fact, if you look at the history, people have been adding a bunch of silly files. We don't want any of them. Once a commit ...
!git help branch !git branch --list # Let's make a new name for the first commit, "going-back", # with our ID in there so we don't conflict with other # sections. !git branch going-back-{our_id} first !git branch --list !git checkout going-back-{our_id} !ls !git status !git log --graph --decorate first going-bac...
sp17/disc/disc03/disc03.ipynb
DS-100/sp17-materials
gpl-3.0
Note: we can always get back to the commit we made with: git checkout master Branches and commits Git informs us that we've switched to the going-back "branch," and in the local filesystem, neither the file we created nor any other files, other than README.md, are there any more. What do you think would happen if we ...
new_filename = "our_second_file_{}.txt".format(our_id) new_filename !echo "Text for our second file!" > {new_filename} !ls !git add {new_filename} !git commit -m'Adding our second file!' !git status !git log --graph --decorate first going-back-{our_id} master
sp17/disc/disc03/disc03.ipynb
DS-100/sp17-materials
gpl-3.0
How does committing work? Every commit is a snapshot of some files. A commit can never be changed. It has a unique ID assigned by git, like 20f97c1. Humans can't work with IDs like that, so git lets us give names like master or first to commits, using git branch &lt;name&gt; &lt;commit ID&gt;. These names are called...
!git push origin going-back-{our_id}
sp17/disc/disc03/disc03.ipynb
DS-100/sp17-materials
gpl-3.0
Here origin is the name (according to git remote -v) of the repository you want to push to. If you omit a remote name, origin is also the default. Normally that's what you want. going-back-{our_id} (whatever the value of {our_id}) is a branch in your repository. If you omit a branch name here, your current branch (t...
cd /tmp !git clone https://github.com/DS-100/git-intro git-intro-2 cd /tmp/git-intro-2 !git checkout going-back-{our_id} third_filename = "our_third_file_{}.txt".format(our_id) third_filename !echo "Someone else added this third file!" > {third_filename} !git add {third_filename} !git commit -m"Adding a third file...
sp17/disc/disc03/disc03.ipynb
DS-100/sp17-materials
gpl-3.0
Now we go back to our original repo.
cd /tmp/git-intro
sp17/disc/disc03/disc03.ipynb
DS-100/sp17-materials
gpl-3.0
You might just want the update. Or maybe you want to push your own commit to the same branch, and your git push failed. Git has a command called pull that you could use. But it's complicated, and it's easier to break it down into two steps: fetching and merging. Since git commits are never destroyed, it's always safe...
!git help fetch !git fetch origin !git log --graph --decorate going-back-{our_id} origin/going-back-{our_id}
sp17/disc/disc03/disc03.ipynb
DS-100/sp17-materials
gpl-3.0
Now we need to update our ref to the newer commit. In this case, it's easy, because we didn't have any further commits. Git calls that a "fast-forward" merge.
!git merge origin/going-back-{our_id} --ff-only !git log --graph --decorate
sp17/disc/disc03/disc03.ipynb
DS-100/sp17-materials
gpl-3.0
Plotting the full vector-valued MNE solution The source space that is used for the inverse computation defines a set of dipoles, distributed across the cortex. When visualizing a source estimate, it is sometimes useful to show the dipole directions in addition to their estimated magnitude. This can be accomplished by c...
# Author: Marijn van Vliet <w.m.vanvliet@gmail.com> # # License: BSD-3-Clause import numpy as np import mne from mne.datasets import sample from mne.minimum_norm import read_inverse_operator, apply_inverse print(__doc__) data_path = sample.data_path() subjects_dir = data_path / 'subjects' smoothing_steps = 7 # Read...
stable/_downloads/7b89f7dac105a44e25d2fbdd898b911f/vector_mne_solution.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Plot the source estimate:
brain = stc.plot( initial_time=peak_time, hemi='lh', subjects_dir=subjects_dir, smoothing_steps=smoothing_steps) # You can save a brain movie with: # brain.save_movie(time_dilation=20, tmin=0.05, tmax=0.16, framerate=10, # interpolation='linear', time_viewer=True)
stable/_downloads/7b89f7dac105a44e25d2fbdd898b911f/vector_mne_solution.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Plot the activation in the direction of maximal power for this data:
stc_max, directions = stc.project('pca', src=inv['src']) # These directions must by design be close to the normals because this # inverse was computed with loose=0.2 print('Absolute cosine similarity between source normals and directions: ' f'{np.abs(np.sum(directions * inv["source_nn"][2::3], axis=-1)).mean()}')...
stable/_downloads/7b89f7dac105a44e25d2fbdd898b911f/vector_mne_solution.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
The normal is very similar:
brain_normal = stc.project('normal', inv['src'])[0].plot( initial_time=peak_time, hemi='lh', subjects_dir=subjects_dir, time_label='Normal', smoothing_steps=smoothing_steps)
stable/_downloads/7b89f7dac105a44e25d2fbdd898b911f/vector_mne_solution.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
You can also do this with a fixed-orientation inverse. It looks a lot like the result above because the loose=0.2 orientation constraint keeps sources close to fixed orientation:
fname_inv_fixed = ( meg_path / 'sample_audvis-meg-oct-6-meg-fixed-inv.fif') inv_fixed = read_inverse_operator(fname_inv_fixed) stc_fixed = apply_inverse( evoked, inv_fixed, lambda2, 'dSPM', pick_ori='vector') brain_fixed = stc_fixed.plot( initial_time=peak_time, hemi='lh', subjects_dir=subjects_dir, smo...
stable/_downloads/7b89f7dac105a44e25d2fbdd898b911f/vector_mne_solution.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Contents A. View the crystal structure B. Build the biomolecular assembly C. Isolate the DNA D. Prep for simulation E. Dynamics - equilibration F. Dynamics - production A. View the crystal structure We start by downloading the 1KBU crystal structure. It will generate several warnings. Especially note that it contain...
xtal = mdt.from_pdb('1kbu') xtal.draw()
moldesign/_notebooks/Example 3. Simulating a crystal structure.ipynb
Autodesk/molecular-design-toolkit
apache-2.0
B. Build the biomolecular assembly As you can read in the warning, 1KBU only has one biomolecular assembly, conveniently named '1'. This cell builds and views it:
assembly = mdt.build_assembly(xtal, 1) assembly.draw()
moldesign/_notebooks/Example 3. Simulating a crystal structure.ipynb
Autodesk/molecular-design-toolkit
apache-2.0
By evaulating the assembly object (it's a normal instance of the moldesign.Molecule class), we can get some information about it's content:
assembly
moldesign/_notebooks/Example 3. Simulating a crystal structure.ipynb
Autodesk/molecular-design-toolkit
apache-2.0
Because we're only interested in DNA, we'll create a new molecule using only the DNA residues, and then assign a forcefield to it. C. Isolate the DNA This example will focus only on the DNA components of this structure, so we'll isolate the DNA atoms and create a new molecule from them. We could do this with a list com...
dna_atoms = assembly.get_atoms('dna') dna_only = mdt.Molecule(dna_atoms) dna_only.draw3d(display=True) dna_only
moldesign/_notebooks/Example 3. Simulating a crystal structure.ipynb
Autodesk/molecular-design-toolkit
apache-2.0
D. Prep for simulation Next, we'll assign a forcefield and energy model, then minimize the structure.
ff = mdt.forcefields.DefaultAmber() dna = ff.create_prepped_molecule(dna_only) dna.set_energy_model(mdt.models.OpenMMPotential, implicit_solvent='obc') dna.configure_methods() minimization = dna.minimize() minimization.draw()
moldesign/_notebooks/Example 3. Simulating a crystal structure.ipynb
Autodesk/molecular-design-toolkit
apache-2.0
E. Dynamics - equilibration The structure is ready. We'll associate an integrator with the molecule, then do a 2 step equilibration - first freezing the peptide backbone and running 300K dynamics, then unfreezing and continuing dyanmics.
# Freeze the backbone: for residue in dna.residues: for atom in residue.backbone: dna.constrain_atom(atom) dna.set_integrator(mdt.integrators.OpenMMLangevin, timestep=2.0*u.fs, frame_interval=1.0*u.ps, remove_rotation=True) dna.integrator.configure()
moldesign/_notebooks/Example 3. Simulating a crystal structure.ipynb
Autodesk/molecular-design-toolkit
apache-2.0
And now we run it. This is may take a while, depending on your hardware.
equil1 = dna.run(20.0*u.ps) equil1.draw()
moldesign/_notebooks/Example 3. Simulating a crystal structure.ipynb
Autodesk/molecular-design-toolkit
apache-2.0
Next, we'll remove the constraints and do full dynamics:
dna.clear_constraints() equil2 = dna.run(20.0*u.ps) equil = equil1 + equil2 equil.draw() plot(equil2.time, equil2.rmsd()) xlabel('time / fs'); ylabel(u'rmsd / Å'); grid()
moldesign/_notebooks/Example 3. Simulating a crystal structure.ipynb
Autodesk/molecular-design-toolkit
apache-2.0
NOTE: THIS IS NOT A SUFFICIENT EQUILIBRATION FOR PRODUCTION MOLECULAR DYNAMICS! In practice, before going to "production", we would at least want to run dynamics until the RMSD and thermodynamic observabled have converged. A variety of equilibration protocols are used in practice, including slow heating, reduced coupl...
trajectory = dna.run(40.0*u.ps) trajectory.draw()
moldesign/_notebooks/Example 3. Simulating a crystal structure.ipynb
Autodesk/molecular-design-toolkit
apache-2.0
G. Save your results Any MDT object can be saved to disk. We recommend saving objects with the "Pickle" format to make sure that all the data is preserved. This cell saves the final trajectory to disk as a compressed pickle file:
trajectory.write('holliday_traj.P.gz')
moldesign/_notebooks/Example 3. Simulating a crystal structure.ipynb
Autodesk/molecular-design-toolkit
apache-2.0
To load the saved object, use:
traj = mdt.read('holliday_traj.P.gz') traj.draw()
moldesign/_notebooks/Example 3. Simulating a crystal structure.ipynb
Autodesk/molecular-design-toolkit
apache-2.0
Create datasets In addition to the provided data, we will be using external datasets put together by participants in the Kaggle competition. You can download all of them here. For completeness, the implementation used to put them together is included below.
def concat_csvs(dirname): path = f'{PATH}{dirname}' filenames=glob.glob(f"{path}/*.csv") wrote_header = False with open(f"{path}.csv","w") as outputfile: for filename in filenames: name = filename.split(".")[0] with open(filename) as f: line = f.readline(...
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Feature Space: * train: Training set provided by competition * store: List of stores * store_states: mapping of store to the German state they are in * List of German state names * googletrend: trend of certain google keywords over time, found by users to correlate well w/ given data * weather: weather * test: testing ...
table_names = ['train', 'store', 'store_states', 'state_names', 'googletrend', 'weather', 'test']
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
We'll be using the popular data manipulation framework pandas. Among other things, pandas allows you to manipulate tables/data frames in python as one would in a database. We're going to go ahead and load all of our csv's as dataframes into the list tables.
tables = [pd.read_csv(f'{PATH}{fname}.csv', low_memory=False) for fname in table_names] from IPython.display import HTML
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0