markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
That's well past the Stanford paper's accuracy - another win for CNNs! | conv1.save_weights(model_path + 'conv1.h5')
conv1.load_weights(model_path + 'conv1.h5') | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
Pre-trained vectors
You may want to look at wordvectors.ipynb before moving on.
In this section, we replicate the previous CNN, but using <strong>pre-trained</strong> embeddings. | def load_vectors(loc):
return (load_array(loc+'.dat'),
pickle.load(open(loc+'_words.pkl','rb')),
pickle.load(open(loc+'_idx.pkl','rb')))
#vecs, words, wordidx = load_vectors('data/glove/results/6B.50d') ## JH's original
vecs, words, wordidx = load_vectors('data/glove/results/6B.100d') ## MDR's e... | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
The glove word ids and imdb word ids use different indexes. So we create a simple function that creates an embedding matrix using the indexes from imdb, and the embeddings from glove (where they exist). | def create_emb():
n_fact = vecs.shape[1]
emb = np.zeros((vocab_size, n_fact))
for i in range(1,len(emb)):
word = idx2word[i]
if word and re.match(r"^[a-zA-Z0-9\-]*$", word):
src_idx = wordidx[word]
emb[i] = vecs[src_idx]
else:
# If we can't find t... | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
We pass our embedding matrix to the Embedding constructor, and set it to non-trainable. | model = Sequential([
#Embedding(vocab_size, 50,
Embedding(vocab_size, 100,
input_length=seq_len, dropout=0.2, weights=[emb], trainable=False),
Dropout(0.25), ## JH (0.25)
Convolution1D(64, 5, border_mode='same', activation='relu'),
Dropout(0.25), ## JH (0.25)
MaxPooling1D(),
... | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
I get better results with the 100d embedding than I do with the 50d embedding, after 4 epochs. - MDR | # model.optimizer.lr = 1e-3 ## MDR: added to the 50d for marginally faster training than I was getting
set_gpu_fan_speed(90)
model.fit(trn, labels_train, validation_data=(test, labels_test), nb_epoch=4, batch_size=64)
set_gpu_fan_speed(0)
model.save_weights(model_path+'glove100_wt1.h5') ## care, with the weight count... | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
MDR: so my initial results were nowhere near as good, but we're not overfitting yet.
MDR: my results are nowhere near JH's! [] Investigate this!
We already have beaten our previous model! But let's fine-tune the embedding weights - especially since the words we couldn't find in glove just have random embeddings. | model.layers[0].trainable=True
model.optimizer.lr=1e-4
model.fit(trn, labels_train, validation_data=(test, labels_test), nb_epoch=4, batch_size=64) | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
"As expected, that's given us a nice little boost. :)" -
MDR: actually made it worse! For both 50d and 100d cases! | model.save_weights(model_path+'glove50.h5') | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
Multi-size CNN
This is an implementation of a multi-size CNN as shown in Ben Bowles' excellent blog post. | from keras.layers import Merge | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
We use the functional API to create multiple conv layers of different sizes, and then concatenate them. | #graph_in = Input ((vocab_size, 50))
graph_in = Input ((vocab_size, 100)) ## MDR - for 100d embedding
convs = [ ]
for fsz in range (3, 6):
x = Convolution1D(64, fsz, border_mode='same', activation="relu")(graph_in)
x = MaxPooling1D()(x)
x = Flatten()(x)
convs.append(x)
out = Merge(mode="concat")(co... | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
We then replace the conv/max-pool layer in our original CNN with the concatenated conv layers. | model = Sequential ([
#Embedding(vocab_size, 50,
Embedding(vocab_size, 100,
input_length=seq_len, dropout=0.2, weights=[emb]),
Dropout (0.2),
graph,
Dropout (0.5),
Dense (100, activation="relu"),
Dropout (0.7),
Dense (1, activation='sigmoid')
])
model.compile(loss='b... | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
MDR: it turns out that there's no improvement, in this expt, for using the 100d embedding over the 50d. | set_gpu_fan_speed(90)
model.fit(trn, labels_train, validation_data=(test, labels_test), nb_epoch=2, batch_size=64)
set_gpu_fan_speed(0) | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
Interestingly, I found that in this case I got best results when I started the embedding layer as being trainable, and then set it to non-trainable after a couple of epochs. I have no idea why!
MDR: (does it limit overfitting, maybe?) ... anyway, my running of the same code achieved nearly the same results, so much hap... | model.save_weights(model_path+'glove50_conv2_wt1.h5')
model.load_weights(model_path+'glove50_conv2_wt1.h5') | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
MDR: I want to test this statement from JH, above, by running another couple of epochs. First let's reduce the LR. | model.optimizer.lr = 1e-5
set_gpu_fan_speed(90)
model.fit(trn, labels_train, validation_data=(test, labels_test), nb_epoch=2, batch_size=64)
set_gpu_fan_speed(0) | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
Okay, so that didn't help. Reload the weights from before. | model.load_weights(model_path+'glove50_conv2_wt1.h5') | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
MDR: following JH's plan, from this point. | model.layers[0].trainable=False
model.optimizer.lr=1e-5
set_gpu_fan_speed(90)
model.fit(trn, labels_train, validation_data=(test, labels_test), nb_epoch=4, batch_size=64)
set_gpu_fan_speed(0) | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
This more complex architecture has given us another boost in accuracy.
MDR: although I didn't see a huge advantage, personally.
LSTM
We haven't covered this bit yet!
MDR: so, there's no preloaded embedding, here - it's a fresh, random set? | model = Sequential([
Embedding(vocab_size, 32, input_length=seq_len, mask_zero=True,
W_regularizer=l2(1e-6), dropout=0.2),
LSTM(100, consume_less='gpu'),
Dense(1, activation='sigmoid')])
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary() | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
MDR: hang on! These summary() outputs look quite different, to me! Not least that this is apparently the 13th lstm he's produced (in this session?) - and yet I've fot a higher numbered dense layer than him. Eh?
But then I reach better results in fewer epochs than he does, this time around. Compare the times, and the mo... | set_gpu_fan_speed(90)
model.fit(trn, labels_train, validation_data=(test, labels_test), nb_epoch=5, batch_size=64)
set_gpu_fan_speed(0)
model.save_weights(model_path+'glove50_lstm1_wt1.h5') | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
MDR: let's see if it's possible to improve on that. | model.optimizer.lr = 1e-5
model.fit(trn, labels_train, validation_data=(test, labels_test), nb_epoch=5, batch_size=64) | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
MDR: Conclusion: that may be all that's achievable with this dataset, of course. It's sentiment, after all!
MDR's lstm + preloaded embeddings
God knows whether this will work. Let's see if I can create an LSTM layer on top of pretrained embeddings... | model2 = Sequential([
Embedding(vocab_size, 100, input_length = seq_len,
#mask_zero=True, W_regularizer=l2(1e-6), ## used in lstm above - not needed?
dropout=0.2, weights=[emb], trainable = False),
LSTM(100, consume_less = 'gpu'),
Dense(100, activation = 'sigmoid')
])
model2.summ... | deeplearning1/nbs/lesson5.ipynb | Mdround/fastai-deeplearning1 | apache-2.0 |
The input data | # the simulated SNP database file
SNPS = "/tmp/oaks.snps.hdf5"
# download example hdf5 dataset (158Mb, takes ~2-3 minutes)
URL = "https://www.dropbox.com/s/x6a4i47xqum27fo/virentes_ref.snps.hdf5?raw=1"
ipa.download(url=URL, path=SNPS); | testdocs/analysis/cookbook-pca-empirical.ipynb | dereneaton/ipyrad | gpl-3.0 |
Make an IMAP dictionary (map popnames to list of samplenames) | IMAP = {
"virg": ["LALC2", "TXWV2", "FLBA140", "FLSF33", "SCCU3"],
"mini": ["FLSF47", "FLMO62", "FLSA185", "FLCK216"],
"gemi": ["FLCK18", "FLSF54", "FLWO6", "FLAB109"],
"bran": ["BJSL25", "BJSB3", "BJVL19"],
"fusi": ["MXED8", "MXGT4", "TXMD3", "TXGR3"],
"sagr": ["CUCA4", "CUSV6", "CUVN10"],
... | testdocs/analysis/cookbook-pca-empirical.ipynb | dereneaton/ipyrad | gpl-3.0 |
Initiate tool with filtering options | tool = ipa.pca(data=SNPS, minmaf=0.05, imap=IMAP, minmap=MINMAP, impute_method="sample") | testdocs/analysis/cookbook-pca-empirical.ipynb | dereneaton/ipyrad | gpl-3.0 |
Run PCA
Unlinked SNPs are automatically sampled from each locus. By setting nreplicates=N the subsampling procedure is repeated N times to show variation over the subsampled SNPs. The imap dictionary is used in the .draw() function to color points, and can be overriden to color points differently from the IMAP used in ... | tool.run(nreplicates=10)
tool.draw(imap=IMAP);
# a convenience function for plotting across three axes
tool.draw_panels(0, 1, 2, imap=IMAP); | testdocs/analysis/cookbook-pca-empirical.ipynb | dereneaton/ipyrad | gpl-3.0 |
Run TSNE
t-SNE is a manifold learning algorithm that can sometimes better project data into a 2-dimensional plane. The distances between points in this space are harder to interpret. | tool.run_tsne(perplexity=5, seed=333)
tool.draw(imap=IMAP); | testdocs/analysis/cookbook-pca-empirical.ipynb | dereneaton/ipyrad | gpl-3.0 |
Run UMAP
UMAP is similar to t-SNE but the distances between clusters are more representative of the differences betwen groups. This requires another package that if it is not yet installed it will ask you to install. | tool.run_umap(n_neighbors=13, seed=333)
tool.draw(imap=IMAP); | testdocs/analysis/cookbook-pca-empirical.ipynb | dereneaton/ipyrad | gpl-3.0 |
Missing data with imputation
Missing data has large effects on dimensionality reduction methods, and it is best to (1) minimize the amount of missing data in your input data set by using filtering, and (2) impute missing data values. In the examples above data is imputed using the 'sample' method, which probabilistical... | # allow very little missing data
import itertools
tool = ipa.pca(
data=SNPS,
imap={'samples': list(itertools.chain(*[i for i in IMAP.values()]))},
minmaf=0.05,
mincov=0.9,
impute_method="sample",
quiet=True,
)
tool.run(nreplicates=10, seed=123)
tool.draw(imap=IMAP); | testdocs/analysis/cookbook-pca-empirical.ipynb | dereneaton/ipyrad | gpl-3.0 |
Statistics | # variance explained by each PC axes in the first replicate run
tool.variances[0].round(2)
# PC loadings in the first replicate
tool.pcs(0) | testdocs/analysis/cookbook-pca-empirical.ipynb | dereneaton/ipyrad | gpl-3.0 |
Styling plots (see toyplot documentation)
The .draw() function returns a canvas and axes object from toyplot which can be further modified and styled. | # get plot objects, several styling options to draw
canvas, axes = tool.draw(imap=IMAP, size=8, width=400);
# various axes styling options shown for x axis
axes.x.ticks.show = True
axes.x.spine.style['stroke-width'] = 1.5
axes.x.ticks.labels.style['font-size'] = '13px'
axes.x.label.style['font-size'] = "15px"
axes.x.l... | testdocs/analysis/cookbook-pca-empirical.ipynb | dereneaton/ipyrad | gpl-3.0 |
Now for a bunch of helpers. We'll use these in a moment; skip over them for now. | def quantise(expr, quantise_to):
if isinstance(expr, sympy.Float):
return expr.func(round(float(expr) / quantise_to) * quantise_to)
elif isinstance(expr, sympy.Symbol):
return expr
else:
return expr.func(*[quantise(arg, quantise_to) for arg in expr.args])
class SymbolicFn(eqx.Modul... | examples/symbolic_regression.ipynb | patrick-kidger/diffrax | apache-2.0 |
Okay, let's get started.
We start by running the Neural ODE example.
Then we extract the learnt neural vector field, and symbolically regress across this.
Finally we fine-tune the resulting symbolic expression. | def main(
symbolic_dataset_size=2000,
symbolic_num_populations=100,
symbolic_population_size=20,
symbolic_migration_steps=4,
symbolic_mutation_steps=30,
symbolic_descent_steps=50,
pareto_coefficient=2,
fine_tuning_steps=500,
fine_tuning_lr=3e-3,
quantise_to=0.01,
):
#
# F... | examples/symbolic_regression.ipynb | patrick-kidger/diffrax | apache-2.0 |
Nesting If Statements
Any conditional statements within others are called 'nested' | if myVar > 5:
print('Above 10!')
if myVar > 20:
print('Above 20!') | public/tutorials/python/1_r2python-translation/3_controlFlow.ipynb | monicathieu/cu-psych-r-tutorial | mit |
Else Statements
It is also very helpful to specify code that we want to run if a condition is NOT met
Else statements in python always follow if statements, and consist of the following syntax
if (condition X):
actions...
else:
actions... | myVar2 = 'dog'
if myVar2 == 'cat':
print('meow')
else:
print('woof') | public/tutorials/python/1_r2python-translation/3_controlFlow.ipynb | monicathieu/cu-psych-r-tutorial | mit |
Else If & Sequential If Statements
We may also want to specify a series of conditions
Python always evaluates conditions on the same nest level in order, from top to bottom
Elif means 'else if' -- only run this statement if the previous if statement condition was not met, and the condition following is met
Sequential... | myVar2 = 'dog'
if len(myVar2) == 3:
print('3 letters long')
elif myVar2 == 'dog':
print('woof')
else:
print('unknown animal')
myVar2 = 'dog'
if len(myVar2) == 3:
print('3 letters long')
if myVar2 == 'dog':
print('woof')
else:
print('unknown animal') | public/tutorials/python/1_r2python-translation/3_controlFlow.ipynb | monicathieu/cu-psych-r-tutorial | mit |
Loops
Looping is a great way to apply the same operation to many pieces of data
Looping through a list | nums = [2,3,4,-1,7]
for number in nums:
print(number) | public/tutorials/python/1_r2python-translation/3_controlFlow.ipynb | monicathieu/cu-psych-r-tutorial | mit |
Looping a certain number of times | for i in range(10):
print(i) | public/tutorials/python/1_r2python-translation/3_controlFlow.ipynb | monicathieu/cu-psych-r-tutorial | mit |
Fancly looping with enumerate | stringList = ['banana', 'mango', 'kiwi', 'blackberry']
# fancy looping with enumerate()
for index, item in enumerate(stringList):
print(index, item) | public/tutorials/python/1_r2python-translation/3_controlFlow.ipynb | monicathieu/cu-psych-r-tutorial | mit |
Nested loops | for i in stringList:
for j in range(4):
print(i, j) | public/tutorials/python/1_r2python-translation/3_controlFlow.ipynb | monicathieu/cu-psych-r-tutorial | mit |
Load experimental data | datadirs = ['/Users/ckemere/Development/Data/Buzsaki']
fileroot = next( (dir for dir in datadirs if os.path.isdir(dir)), None)
# conda install pandas=0.19.2
if fileroot is None:
raise FileNotFoundError('datadir not found')
load_from_nel = True
# load from nel file:
if load_from_nel:
jar = nel.load_pkl(os.pat... | score_bayes_parallel-dask.ipynb | ckemere/CloudShuffles | gpl-3.0 |
Define subset of sessions to score | # restrict sessions to explore to a smaller subset
min_n_placecells = 16
min_n_PBEs = 27 # 27 total events ==> minimum 21 events in training set
df2_subset = df2[(df2.n_PBEs >= min_n_PBEs) & (df2.n_placecells >= min_n_placecells)]
sessions = df2_subset['time'].values.tolist()
segments = df2_subset['segment'].values.t... | score_bayes_parallel-dask.ipynb | ckemere/CloudShuffles | gpl-3.0 |
Parallel scoring
NOTE: it is relatively easy (syntax-wise) to score each session as a parallel task, but since the Bayesian scoring takes such a long time to compute, we can be more efficient (higher % utilization) by further parallelizing over events, and not just over sessions. This further level of parallelization m... | n_jobs = 20 # set this equal to number of cores
n_shuffles = 100 # 5000
n_samples = 35000 # 35000
w=3 # single sided bandwidth (0 means only include bin who's center is under line, 3 means a total of 7 bins)
import matplotlib.pyplot as plt
%matplotlib inline
# Parallelize by EVENT
import dask
import distributed.jobli... | score_bayes_parallel-dask.ipynb | ckemere/CloudShuffles | gpl-3.0 |
Save results to disk | jar = nel.ResultsContainer(results=results, description='gor01 and vvp01 speed restricted results for best 20 candidate sessions')
jar.save_pkl('score_bayes_all_sessions.nel') | score_bayes_parallel-dask.ipynb | ckemere/CloudShuffles | gpl-3.0 |
Figure 1. Schematics of the setup of a atomic force microscope (Adapted from reference 6)
In AFM the interacting probe is in general a rectangular cantilever (please check the image above that shows the AFM setup where you will be able to see the probe!).
Probably the most used dynamic technique in AFM is the Tappin... | fig2 = path + '/Fig2DHO.jpg'
Image(filename=fig2) | jupyter_notebooks/AFM_simulations/IntroductionToSimulations/IntroToAFMSimulations.ipynb | pycroscopy/pycroscopy | mit |
Figure 2. Schematics of a damped harmonic oscillator without tip-sample interactions
Analytical Solution
The motion of the probe can be derived using Euler-Bernoulli's equation. However that equation has partial derivatives (it depends on time and space) because it deals with finding the position of each point of the b... | k = 10.
fo = 45000
wo = 2.0*numpy.pi*fo
Q = 25.
period = 1./fo
m = k/(wo**2)
Ao = 60.e-9
Fd = k*Ao/Q
spp = 28. # time steps per period
dt = period/spp #Intentionally chosen to be quite big
#you can decrease dt by increasing the number of steps per period
simultime = 100.*period
N = int(simultime/dt)
#Analytical so... | jupyter_notebooks/AFM_simulations/IntroductionToSimulations/IntroToAFMSimulations.ipynb | pycroscopy/pycroscopy | mit |
Approximating through Euler's method
If we perform a Taylor series expansion of $z_{n+1}$ around $z_{n}$ we get:
$$z_{n+1} = z_{n} + \Delta t\frac{dz}{dt}\big|_n + {\mathcal O}(\Delta t^2)$$
The Euler formula neglects terms in the order of two or higher, ending up as:
$$\begin{equation}
z_{n+1} = z_{n} + \Delta t\frac{... | t= numpy.linspace(0,simultime,N) #time grid for Euler method
#Initializing variables for Euler
vdot_E = numpy.zeros(N)
v_E = numpy.zeros(N)
z_E = numpy.zeros(N)
#Initial conditions
z_E[0]= 0.0
v_E[0]=0.0
for i in range (N-1):
vdot_E[i] =( ( -k*z_E[i] - (m*wo/Q)*(v_E[i]) +\
Fd*numpy.cos(... | jupyter_notebooks/AFM_simulations/IntroductionToSimulations/IntroToAFMSimulations.ipynb | pycroscopy/pycroscopy | mit |
This looks totally unphysical! We were expecting to have a steady state oscillation of 60 nm and we got a huge oscillation that keeps growing. Can it be due to the scheme? The timestep that we have chosen is quite big with respect to the oscillation period. We have intentionally set it to ONLY 28 time steps per period ... | time_V = numpy.linspace(0,simultime,N)
#Initializing variables for Verlet
zdoubledot_V = numpy.zeros(N)
zdot_V = numpy.zeros(N)
z_V = numpy.zeros(N)
#Initial conditions Verlet. Look how we use Euler for the first step approximation!
z_V[0] = 0.0
zdot_V[0] = 0.0
zdoubledot_V[0] = ( ( -k*z_V[0] - (m*wo/Q)*zdot_V[0] +... | jupyter_notebooks/AFM_simulations/IntroductionToSimulations/IntroToAFMSimulations.ipynb | pycroscopy/pycroscopy | mit |
It WAS ABLE to capture the physics! Even with the big time step that we use with Euler scheme!
As you can see, and as we previously discussed the harmonic response is composed of a transient and a steady part. We are only concerned about the steady-state, since it is assumed that the probe achieves steady state motion ... | #Slicing the full response vector to get the steady state response
z_steady_V = z_V[int(90*period/dt):]
time_steady_V = time_V[int(90*period/dt):]
plt.title('Plot 3 Verlet approx. of steady state sol. of Eq 1', fontsize=20);
plt.xlabel('time, ms', fontsize=18);
plt.ylabel('z_Verlet, nm', fontsize=18);
plt.plot(time_... | jupyter_notebooks/AFM_simulations/IntroductionToSimulations/IntroToAFMSimulations.ipynb | pycroscopy/pycroscopy | mit |
Let's use now one of the most popular schemes... The Runge Kutta 4!
The Runge Kutta 4 (RK4) method is very popular for the solution of ODEs. This method is designed to solve 1st order differential equations. We have converted our 2nd order ODE to a system of two coupled 1st order ODEs when we implemented the Euler ... | #Definition of v, z, vectors
vdot_RK4 = numpy.zeros(N)
v_RK4 = numpy.zeros(N)
z_RK4 = numpy.zeros(N)
k1v_RK4 = numpy.zeros(N)
k2v_RK4 = numpy.zeros(N)
k3v_RK4 = numpy.zeros(N)
k4v_RK4 = numpy.zeros(N)
k1z_RK4 = numpy.zeros(N)
k2z_RK4 = numpy.zeros(N)
k3z_RK4 = numpy.zeros(N)
k4z_RK4 = numpy.zeros(N)
#calculation ... | jupyter_notebooks/AFM_simulations/IntroductionToSimulations/IntroToAFMSimulations.ipynb | pycroscopy/pycroscopy | mit |
Error Analysis
Let's plot together our solutions using the different schemes along with our analytical reference. | plt.title('Plot 4 Schemes comparison with analytical sol.', fontsize=20);
plt.plot(time_an_steady*1e3, z_an_steady*1e9, 'b--' );
plt.plot(time_steady_V*1e3, z_steady_V*1e9, 'g-' );
plt.plot(time_steady_RK4*1e3, z_steady_RK4*1e9, 'r-');
plt.xlim(2.0, 2.06);
plt.legend(['Analytical solution', 'Verlet method', 'Runge Kut... | jupyter_notebooks/AFM_simulations/IntroductionToSimulations/IntroToAFMSimulations.ipynb | pycroscopy/pycroscopy | mit |
It was pointless to include Euler in the last plot because it was not following the physics at all for this given time step. REMEMBER that Euler can give fair approximations, but you MUST decrease the time step in this particular case if you want to see the sinusoidal trajectory!
It seems our different schemes are givi... | fig3 = path + '/Fig3FDcurve.jpg'
Image(filename=fig3) | jupyter_notebooks/AFM_simulations/IntroductionToSimulations/IntroToAFMSimulations.ipynb | pycroscopy/pycroscopy | mit |
Figure 3. Force vs Distance profile depicting tip-sample interactions in AFM (Adapted from reference 6)
In Hertz contact mechanics, one central aspect is to consider that the contact area increases as the sphere is pressed against an elastic surface, and this increase of the contact area "modulates" the effective sti... | fig4 = path + '/Fig4Hertzspring.jpg'
Image(filename= fig4) | jupyter_notebooks/AFM_simulations/IntroductionToSimulations/IntroToAFMSimulations.ipynb | pycroscopy/pycroscopy | mit |
Figure 4. Conceptual representation of Hertz contact mechanics
This concept is represented mathematically by a non-linear spring whose elastic coefficient is a function of the contact area which at the same time depends on the sample indentation ( k(d) ).
$$F_{ts} = k(d)d$$
where
$$k(d) = 4/3E\sqrt{Rd}$$
being $\sqrt... | #DMT parameters (Hertz contact mechanics with long range Van der Waals forces added
a=0.2e-9 #intermolecular parameter
H=6.4e-20 #hamaker constant of sample
R=20e-9 #tip radius of the cantilever
Es=70e6 #elastic modulus of sample
Et=130e9 #elastic modulus of the tip
vt=0.3 #Poisson coefficient for tip
vs=0.3 #Poisson ... | jupyter_notebooks/AFM_simulations/IntroductionToSimulations/IntroToAFMSimulations.ipynb | pycroscopy/pycroscopy | mit |
Now let's declare the timestep, the simulation time and let's oscillate our probe! | #IMPORTANT distance where you place the probe above the sample
z_base = 40.e-9
spp = 280. # time steps per period
dt = period/spp
simultime = 100.*period
N = int(simultime/dt)
t = numpy.linspace(0,simultime,N)
#Initializing variables for RK4
v_RK4 = numpy.zeros(N)
z_RK4 = numpy.zeros(N)
k1v_RK4 = numpy.zeros(N)
... | jupyter_notebooks/AFM_simulations/IntroductionToSimulations/IntroToAFMSimulations.ipynb | pycroscopy/pycroscopy | mit |
Check that we have two sinusoidals. The one in green (the output) is the response signal of the tip (the tip trajectory in time) while the blue one (the input) is the cosinusoidal driving force that we are using to excite the tip. When the tip is excited in free air (without tip sample interactions) the phase lag betwe... | print('This cell takes a while to compute')
"""ERROR ANALYSIS EULER, VERLET AND RK4"""
# time-increment array
dt_values = numpy.array([8.0e-7, 2.0e-7, 0.5e-7, 1e-8, 0.1e-8])
# array that will contain solution of each grid
z_values_E = numpy.zeros_like(dt_values, dtype=numpy.ndarray)
z_values_V = numpy.zeros_like(dt_... | jupyter_notebooks/AFM_simulations/IntroductionToSimulations/IntroToAFMSimulations.ipynb | pycroscopy/pycroscopy | mit |
Let us plot the first five examples of the train data (first row) and test data (second row). | %matplotlib inline
import pylab as P
def plot_example(dat, lab):
for i in xrange(5):
ax=P.subplot(1,5,i+1)
P.title(int(lab[i]))
ax.imshow(dat[:,i].reshape((16,16)), interpolation='nearest')
ax.set_xticks([])
ax.set_yticks([])
_=P.figure(figsize=(17,6))
P.gra... | doc/ipython-notebooks/multiclass/KNN.ipynb | minxuancao/shogun | gpl-3.0 |
Then we import shogun components and convert the data to shogun objects: | from modshogun import MulticlassLabels, RealFeatures
from modshogun import KNN, EuclideanDistance
labels = MulticlassLabels(Ytrain)
feats = RealFeatures(Xtrain)
k=3
dist = EuclideanDistance()
knn = KNN(k, dist, labels)
labels_test = MulticlassLabels(Ytest)
feats_test = RealFeatures(Xtest)
knn.train(feats)
pred = knn... | doc/ipython-notebooks/multiclass/KNN.ipynb | minxuancao/shogun | gpl-3.0 |
Let's plot a few missclassified examples - I guess we all agree that these are notably harder to detect. | idx=np.where(pred != Ytest)[0]
Xbad=Xtest[:,idx]
Ybad=Ytest[idx]
_=P.figure(figsize=(17,6))
P.gray()
plot_example(Xbad, Ybad) | doc/ipython-notebooks/multiclass/KNN.ipynb | minxuancao/shogun | gpl-3.0 |
Now the question is - is 97.30% accuracy the best we can do? While one would usually re-train KNN with different values for k here and likely perform Cross-validation, we just use a small trick here that saves us lots of computation time: When we have to determine the $K\geq k$ nearest neighbors we will know the neares... | knn.set_k(13)
multiple_k=knn.classify_for_multiple_k()
print multiple_k.shape | doc/ipython-notebooks/multiclass/KNN.ipynb | minxuancao/shogun | gpl-3.0 |
We have the prediction for each of the 13 k's now and can quickly compute the accuracies: | for k in xrange(13):
print "Accuracy for k=%d is %2.2f%%" % (k+1, 100*np.mean(multiple_k[:,k]==Ytest)) | doc/ipython-notebooks/multiclass/KNN.ipynb | minxuancao/shogun | gpl-3.0 |
So k=3 seems to have been the optimal choice.
Accellerating KNN
Obviously applying KNN is very costly: for each prediction you have to compare the object against all training objects. While the implementation in SHOGUN will use all available CPU cores to parallelize this computation it might still be slow when you have... | from modshogun import Time, KNN_COVER_TREE, KNN_BRUTE
start = Time.get_curtime()
knn.set_k(3)
knn.set_knn_solver_type(KNN_BRUTE)
pred = knn.apply_multiclass(feats_test)
print "Standard KNN took %2.1fs" % (Time.get_curtime() - start)
start = Time.get_curtime()
knn.set_k(3)
knn.set_knn_solver_type(KNN_COVER_TREE)
pred ... | doc/ipython-notebooks/multiclass/KNN.ipynb | minxuancao/shogun | gpl-3.0 |
So we can significantly speed it up. Let's do a more systematic comparison. For that a helper function is defined to run the evaluation for KNN: | def evaluate(labels, feats, use_cover_tree=False):
from modshogun import MulticlassAccuracy, CrossValidationSplitting
import time
split = CrossValidationSplitting(labels, Nsplit)
split.build_subsets()
accuracy = np.zeros((Nsplit, len(all_ks)))
acc_train = np.zeros(accuracy.shape)
time_t... | doc/ipython-notebooks/multiclass/KNN.ipynb | minxuancao/shogun | gpl-3.0 |
Evaluate KNN with and without Cover Tree. This takes a few seconds: | labels = MulticlassLabels(Ytest)
feats = RealFeatures(Xtest)
print("Evaluating KNN...")
wo_ct = evaluate(labels, feats, use_cover_tree=False)
wi_ct = evaluate(labels, feats, use_cover_tree=True)
print("Done!") | doc/ipython-notebooks/multiclass/KNN.ipynb | minxuancao/shogun | gpl-3.0 |
Generate plots with the data collected in the evaluation: | import matplotlib
fig = P.figure(figsize=(8,5))
P.plot(all_ks, wo_ct['eout'].mean(axis=0), 'r-*')
P.plot(all_ks, wo_ct['ein'].mean(axis=0), 'r--*')
P.legend(["Test Accuracy", "Training Accuracy"])
P.xlabel('K')
P.ylabel('Accuracy')
P.title('KNN Accuracy')
P.tight_layout()
fig = P.figure(figsize=(8,5))
P.plot(all_ks, ... | doc/ipython-notebooks/multiclass/KNN.ipynb | minxuancao/shogun | gpl-3.0 |
Although simple and elegant, KNN is generally very resource costly. Because all the training samples are to be memorized literally, the memory cost of KNN learning becomes prohibitive when the dataset is huge. Even when the memory is big enough to hold all the data, the prediction will be slow, since the distances betw... | from modshogun import GaussianKernel, GMNPSVM
width=80
C=1
gk=GaussianKernel()
gk.set_width(width)
svm=GMNPSVM(C, gk, labels)
_=svm.train(feats) | doc/ipython-notebooks/multiclass/KNN.ipynb | minxuancao/shogun | gpl-3.0 |
Let's apply the SVM to the same test data set to compare results: | out=svm.apply(feats_test)
evaluator = MulticlassAccuracy()
accuracy = evaluator.evaluate(out, labels_test)
print "Accuracy = %2.2f%%" % (100*accuracy) | doc/ipython-notebooks/multiclass/KNN.ipynb | minxuancao/shogun | gpl-3.0 |
Since the SVM performs way better on this task - let's apply it to all data we did not use in training. | Xrem=Xall[:,subset[6000:]]
Yrem=Yall[subset[6000:]]
feats_rem=RealFeatures(Xrem)
labels_rem=MulticlassLabels(Yrem)
out=svm.apply(feats_rem)
evaluator = MulticlassAccuracy()
accuracy = evaluator.evaluate(out, labels_rem)
print "Accuracy = %2.2f%%" % (100*accuracy)
idx=np.where(out.get_labels() != Yrem)[0]
Xbad=Xrem[... | doc/ipython-notebooks/multiclass/KNN.ipynb | minxuancao/shogun | gpl-3.0 |
So maybe they're useful features (but not very). What about the fact they're magnitudes? | lrexp = sklearn.linear_model.LogisticRegression(C=100.0, class_weight='balanced')
lrexp.fit(features_exp[x_train], t_train)
cm = sklearn.metrics.confusion_matrix(t_test, lrexp.predict(features_exp[x_test]))
tp = cm[1, 1]
n, p = cm.sum(axis=1)
tn = cm[0, 0]
ba = (tp / p + tn / n) / 2
print('Exponentiated features, balan... | notebooks/56_nonlinear_astro_features.ipynb | chengsoonong/crowdastro | mit |
Those are promising results, but we need to rererun this a few times with different training and testing sets to get some error bars. | def balanced_accuracy(lr, x_test, t_test):
cm = sklearn.metrics.confusion_matrix(t_test, lr.predict(x_test))
tp = cm[1, 1]
n, p = cm.sum(axis=1)
tn = cm[0, 0]
ba = (tp / p + tn / n) / 2
return ba
def test_feature_set(features, x_train, t_train, x_test, t_test):
lr = sklearn.linear_model.Log... | notebooks/56_nonlinear_astro_features.ipynb | chengsoonong/crowdastro | mit |
Load and prepare data | # Download CSV from http://stats.oecd.org/index.aspx?DataSetCode=BLI
oecd_bli = pd.read_csv(datapath+"oecd_bli_2015.csv", thousands=',')
oecd_bli = oecd_bli[oecd_bli["INEQUALITY"]=="TOT"]
oecd_bli = oecd_bli.pivot(index="Country", columns="Indicator", values="Value")
oecd_bli.columns
oecd_bli["Life satisfaction"].hea... | labs/lab1-soln.ipynb | wzxiong/DAVIS-Machine-Learning | mit |
Here's the full dataset, and there are other columns. I will subselect a few of them by hand. | xvars = ['Self-reported health','Water quality','Quality of support network','GDP per capita']
X = np.array(full_country_stats[xvars])
y = np.array(full_country_stats['Life satisfaction']) | labs/lab1-soln.ipynb | wzxiong/DAVIS-Machine-Learning | mit |
I will define the following functions to expedite the LOO risk and the Empirical risk. | def loo_risk(X,y,regmod):
"""
Construct the leave-one-out square error risk for a regression model
Input: design matrix, X, response vector, y, a regression model, regmod
Output: scalar LOO risk
"""
loo = LeaveOneOut()
loo_losses = []
for train_index, test_index in loo.split(X):
... | labs/lab1-soln.ipynb | wzxiong/DAVIS-Machine-Learning | mit |
As you can see, the empirical risk is much less than the leave-one-out risk! This can happen in more dimensions.
Nearest neighbor regression
Use the method described here: http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsRegressor.html
I have already imported the necessary module, so you ju... | # knn = neighbors.KNeighborsRegressor(n_neighbors=5) | labs/lab1-soln.ipynb | wzxiong/DAVIS-Machine-Learning | mit |
Exercise 1 For each k from 1 to 30 compute the nearest neighbors empirical risk and LOO risk. Plot these as a function of k and reflect on the bias-variance tradeoff here. (Hint: use the previously defined functions) | LOOs = []
MSEs = []
K=30
Ks = range(1,K+1)
for k in Ks:
knn = neighbors.KNeighborsRegressor(n_neighbors=k)
LOOs.append(loo_risk(X,y,knn))
MSEs.append(emp_risk(X,y,knn))
plt.plot(Ks,LOOs,'r',label="LOO risk")
plt.title("Risks for kNN Regression")
plt.plot(Ks,MSEs,'b',label="Emp risk")
plt.legend()
_ = plt.x... | labs/lab1-soln.ipynb | wzxiong/DAVIS-Machine-Learning | mit |
I decided to see what the performance is for k from 1 to 30. We see that the bias does not dominate until k exceeds 17, the performance is somewhat better for k around 12. This demonstrates that you can't trust the Empirical risk, since it includes the training sample. We can compare this LOO risk to that of linear r... | X1 = np.array(full_country_stats[['Self-reported health']])
LOOs = []
MSEs = []
K=30
Ks = range(1,K+1)
for k in Ks:
knn = neighbors.KNeighborsRegressor(n_neighbors=k)
LOOs.append(loo_risk(X1,y,knn))
MSEs.append(emp_risk(X1,y,knn))
plt.plot(Ks,LOOs,'r',label="LOO risk")
plt.title("Risks for kNN Regression"... | labs/lab1-soln.ipynb | wzxiong/DAVIS-Machine-Learning | mit |
Process the English Wiktionary to generate the (default) partition probabilities.
Note: this step can take significant time for large dictionaries (~5 min). | ## Vignette 1: Build informed partition data from a dictionary,
## and store to local collection
def preprocessENwiktionary():
pa = partitioner(informed = True, dictionary = "./dictionaries/enwiktionary.txt")
pa.dumpqs(qsname="enwiktionary")
preprocessENwiktionary() | tests/partitioner_examples.ipynb | jakerylandwilliams/partitioner | apache-2.0 |
Perform a few one-off partitions. | ## Vignette 2: An informed, one-off partition of a single clause
def informedOneOffPartition(clause = "How are you doing today?"):
pa = oneoff()
print pa.partition(clause)
informedOneOffPartition()
informedOneOffPartition("Fine, thanks a bunch for asking!") | tests/partitioner_examples.ipynb | jakerylandwilliams/partitioner | apache-2.0 |
Solve for the informed stochastic expectation partition (given the informed partition probabilities). | ## Vignette 3: An informed, stochastic expectation partition of a single clause
def informedStochasticPartition(clause = "How are you doing today?"):
pa = stochastic()
print pa.partition(clause)
informedStochasticPartition() | tests/partitioner_examples.ipynb | jakerylandwilliams/partitioner | apache-2.0 |
Perform a pure random (uniform) one-off partition. | ## Vignette 4: An uniform, one-off partition of a single clause
def uniformOneOffPartition(informed = False, clause = "How are you doing today?", qunif = 0.25):
pa = oneoff(informed = informed, qunif = qunif)
print pa.partition(clause)
uniformOneOffPartition()
uniformOneOffPartition(qunif = 0.75) | tests/partitioner_examples.ipynb | jakerylandwilliams/partitioner | apache-2.0 |
Solve for the uniform stochastic expectation partition (given the uniform partition probabilities). | ## Vignette 5: An uniform, stochastic expectation partition of a single clause
def uniformStochasticPartition(informed = False, clause = "How are you doing today?", qunif = 0.25):
pa = stochastic(informed = informed, qunif = qunif)
print pa.partition(clause)
uniformStochasticPartition()
uniformStochasticPartit... | tests/partitioner_examples.ipynb | jakerylandwilliams/partitioner | apache-2.0 |
Build a rank-frequency distribution for a text and determine its Zipf/Simon (bag-of-phrase) $R^2$. | ## Vignette 6: Use the default partitioning method to partition the main partitioner.py file and compute rsq
def testPartitionTextAndFit():
pa = oneoff()
pa.partitionText(textfile = pa.home+"/../README.md")
pa.testFit()
print "R-squared: ",round(pa.rsq,2)
print
phrases = sorted(pa.counts, key = ... | tests/partitioner_examples.ipynb | jakerylandwilliams/partitioner | apache-2.0 |
Process the some other Wiktionaries to generate the partition probabilities.
Note: These dictionaries are not as well curated and potentially contain phrases from other languages (a consequence of wiktionary construction). As a result, they hold many many more phrases and will take longer to process. However, since the... | ## Vignette X1: Build informed partition data from other dictionaries,
## and store to local collection
def preprocessOtherWiktionaries():
for lang in ["ru", "pt", "pl", "nl", "it", "fr", "fi", "es", "el", "de", "en"]:
print "working on "+lang+"..."
pa = partitioner(informed = True, dic... | tests/partitioner_examples.ipynb | jakerylandwilliams/partitioner | apache-2.0 |
Test partitioner on some other languages. | from partitioner import partitioner
from partitioner.methods import *
## Vignette X2: Use the default partitioning method to partition the main partitioner.py file and compute rsq
def testFrPartitionTextAndFit():
for lang in ["ru", "pt", "pl", "nl", "it", "fr", "fi", "es", "el", "de", "en"]:
pa = oneoff(qsn... | tests/partitioner_examples.ipynb | jakerylandwilliams/partitioner | apache-2.0 |
Display Settings | # Display graph in 'retina' format for Mac with retina display. Others, use PNG or SVG format.
%config InlineBackend.figure_format = 'retina'
#%config InlineBackend.figure_format = 'PNG'
#%config InlineBackend.figure_format = 'SVG' | Equations/Dose-Response Relations/Dose-Response Relations.ipynb | ekaakurniawan/3nb | gpl-3.0 |
Housekeeping Functions
Following function plots different concentrations used to visualize dose-response relation. | def plot_concentration(c):
fig = plt.figure()
sp111 = fig.add_subplot(111)
# Display grid
sp111.grid(True, which = 'both')
# Plot concentration
len_c = len(c)
sp111.plot(np.linspace(0,len_c-1,len_c), c, color = 'gray', linewidth = 2)
# Label
sp111.set_ylabel('Concentration (nM)'... | Equations/Dose-Response Relations/Dose-Response Relations.ipynb | ekaakurniawan/3nb | gpl-3.0 |
Following function plots dose-response relation in both linear (log_flag = False) and logarithmic (log_flag = True) along X axis. | # d : Dose
# r1 : First response data
# r1_label : First response label
# r2 : Second response data
# r2_label : Second response label
# log_flag : Selection for linear or logarithmic along X axis
# - False: Plot linear (default)
# - True: Plot logarithmic
def plot_dose_respon... | Equations/Dose-Response Relations/Dose-Response Relations.ipynb | ekaakurniawan/3nb | gpl-3.0 |
Dose-Response Relations $^{[1]}$
Generally, dose-response relations can be written as follow. In which the dose is represented as concentration ($c$), while the formula returns the response ($r$).
$$r = \frac{F.c^{n_H}}{{c^{n_H} + EC_{50}^{n_H}}}$$
Other terms like $EC_{50}$ is the effective concentration achieved at 5... | c_lin = np.linspace(0,100,101) # Drug concentration in nanomolar (nM)
plot_concentration(c_lin) | Equations/Dose-Response Relations/Dose-Response Relations.ipynb | ekaakurniawan/3nb | gpl-3.0 |
Logarithmically increased concentration (c_log): | c_log = np.logspace(0,5,101) # Drug concentration in nanomolar (nM)
plot_concentration(c_log) | Equations/Dose-Response Relations/Dose-Response Relations.ipynb | ekaakurniawan/3nb | gpl-3.0 |
Agonist Only
To calculate dose-response relation in the case of agonist only, we use general dose-response relation equation described previously. The function is shown below. | # Calculate dose-response relation (DRR) for agonist only
# c : Drug concentration(s) in nanomolar (nM)
# EC_50 : 50% effective concentration in nanomolar (nM)
# F : Efficacy (unitless)
# n_H : Hill coefficients (unitless)
def calc_drr(c, EC_50 = 20, F = 1, n_H = 1):
r = (F * (c ** n_H) / ((c ** n_H) + (E... | Equations/Dose-Response Relations/Dose-Response Relations.ipynb | ekaakurniawan/3nb | gpl-3.0 |
Following result shows drug response of agonist only to the linearly increased concentrations. | c = c_lin # Drug concentration(s) in nanomolar (nM)
EC_50 = 20 # 50% effective concentration in nanomolar (nM)
F = 1 # Efficacy (unitless)
n_H = 1 # Hill coefficients (unitless)
r = calc_drr(c, EC_50, F, n_H)
plot_dose_response_relation(c, r, "Agonist") | Equations/Dose-Response Relations/Dose-Response Relations.ipynb | ekaakurniawan/3nb | gpl-3.0 |
Following result shows drug response of agonist only to the logarithmically increased concentrations. | c = c_log # Drug concentration(s) in nanomolar (nM)
EC_50 = 20 # 50% effective concentration in nanomolar (nM)
F = 1 # Efficacy (unitless)
n_H = 1 # Hill coefficients (unitless)
r = calc_drr(c, EC_50, F, n_H)
plot_dose_response_relation(c, r, "Agonist", log_flag = True) | Equations/Dose-Response Relations/Dose-Response Relations.ipynb | ekaakurniawan/3nb | gpl-3.0 |
Agonist Plus Competitive Antagonist
Compatitive antagonist, as the name sugest, competes with agonist molecules to sit in the same pocket. It makes the binding harder for agonist as well as to trigger the activation. Therefore, higher agonist concentration is required to reach both full and partial (like $EC_{50}$) act... | # Calculate dose-response relation (DRR) for agonist plus competitive antagonist
# - Agonist
# c : Drug concentration(s) in nanomolar (nM)
# EC_50 : 50% effective concentration in nanomolar (nM)
# F : Efficacy (unitless)
# n_H : Hill coefficients (unitless)
# - Antagonist
# K_i : Dissociati... | Equations/Dose-Response Relations/Dose-Response Relations.ipynb | ekaakurniawan/3nb | gpl-3.0 |
Following result shows drug response of agonist with competitive antagonist to the linearly increased concentrations. | c = c_lin # Drug concentration(s) in nanomolar (nM)
EC_50 = 20 # 50% effective concentration in nanomolar (nM)
F = 1 # Efficacy (unitless)
n_H = 1 # Hill coefficients (unitless)
r_a = calc_drr(c, EC_50, F, n_H)
K_i = 5 # Dissociation constant of inhibitor in nanomolar (nM)
c_i = 25 # Inhibitor conc... | Equations/Dose-Response Relations/Dose-Response Relations.ipynb | ekaakurniawan/3nb | gpl-3.0 |
Following result shows drug response of agonist with competitive antagonist to the logarithmically increased concentrations. | c = c_log # Drug concentration(s) in nanomolar (nM)
EC_50 = 20 # 50% effective concentration in nanomolar (nM)
F = 1 # Efficacy (unitless)
n_H = 1 # Hill coefficients (unitless)
r_a = calc_drr(c, EC_50, F, n_H)
K_i = 5 # Dissociation constant of inhibitor in nanomolar (nM)
c_i = 25 # Inhibitor conc... | Equations/Dose-Response Relations/Dose-Response Relations.ipynb | ekaakurniawan/3nb | gpl-3.0 |
Agonist Plus Noncompetitive Antagonist
Unlike competitive antagonist, noncompetitive antagonist does not compete directly to the location where agonist binds but somewhere else in the subsequent pathway. Instead of altering effective concentration (like $EC_{50}$), noncompetitive antagonist affects efficacy. New effica... | # Calculate dose-response relation (DRR) for agonist plus noncompetitive antagonist
# - Agonist
# c : Drug concentration(s) in nanomolar (nM)
# EC_50 : 50% effective concentration in nanomolar (nM)
# F : Efficacy (unitless)
# n_H : Hill coefficients (unitless)
# - Antagonist
# K_i : Dissoci... | Equations/Dose-Response Relations/Dose-Response Relations.ipynb | ekaakurniawan/3nb | gpl-3.0 |
Following result shows drug response of agonist with noncompetitive antagonist to the linearly increased concentrations. | c = c_lin # Drug concentration(s) in nanomolar (nM)
EC_50 = 20 # 50% effective concentration in nanomolar (nM)
F = 1 # Efficacy (unitless)
n_H = 1 # Hill coefficients (unitless)
r_a = calc_drr(c, EC_50, F, n_H)
K_i = 5 # Dissociation constant of inhibitor in nanomolar (nM)
c_i = 25 # Inhibitor conc... | Equations/Dose-Response Relations/Dose-Response Relations.ipynb | ekaakurniawan/3nb | gpl-3.0 |
Following result shows drug response of agonist with noncompetitive antagonist to the logarithmically increased concentrations. | c = c_log # Drug concentration(s) in nanomolar (nM)
EC_50 = 20 # 50% effective concentration in nanomolar (nM)
F = 1 # Efficacy (unitless)
n_H = 1 # Hill coefficients (unitless)
r_a = calc_drr(c, EC_50, F, n_H)
K_i = 5 # Dissociation constant of inhibitor in nanomolar (nM)
c_i = 25 # Inhibitor conc... | Equations/Dose-Response Relations/Dose-Response Relations.ipynb | ekaakurniawan/3nb | gpl-3.0 |
skip-gram | Image('diagrams/skip-gram.png') | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
```python
word1 = Input(shape=(1,), dtype='int64', name='word1')
word2 = Input(shape=(1,), dtype='int64', name='word2')
shared_embedding = Embedding(
input_dim=VOCAB_SIZE+1,
output_dim=DENSEVEC_DIM,
input_length=1,
embeddings_constraint = unit_norm(),
name='shared_embedding')
embedded_w1 = shared... | from keras.preprocessing.sequence import skipgrams
from keras.preprocessing.text import Tokenizer, text_to_word_sequence
text1 = "I love deep learning."
text2 = "Read Douglas Adams as much as possible."
tokenizer = Tokenizer()
tokenizer.fit_on_texts([text1, text2])
word2id = tokenizer.word_index
word2id.items() | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Note word id's are numbered from 1, not zero | id2word = { wordid: word for word, wordid in word2id.items()}
id2word
encoded_text = [word2id[word] for word in text_to_word_sequence(text1)]
encoded_text
[word2id[word] for word in text_to_word_sequence(text2)]
sg = skipgrams(encoded_text, vocabulary_size=len(word2id.keys()), window_size=1)
sg
for i in range(len(s... | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Model parameters | VOCAB_SIZE = len(word2id.keys())
VOCAB_SIZE
DENSEVEC_DIM = 50 | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Model build | import keras
from keras.layers.embeddings import Embedding
from keras.constraints import unit_norm
from keras.layers.merge import Dot
from keras.layers.core import Activation
from keras.layers.core import Flatten
from keras.layers import Input, Dense
from keras.models import Model | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.