markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
**Error**: This error happens because Python sees that there is an assignment statement for `dosa` in the `getDosa` function 1 and therefore considers `dosa` to be local. But because `print("dosa=",dosa)` is executed before `dosa` is assigned anything, the local variable `dosa` doesn’t exist. Python will not fall back ... | def divideBy(n):
return 4/n
print(divideBy(4))
print(divideBy(1))
print(divideBy(0)) | 1.0
4.0
| MIT | day-1/session-2.ipynb | vchrombie/da-python |
**Note**: The division by zero is not possible, so it raised error. Instead of stopping the program abruptly, we can handle the error (using `try-except`) such that an error message is displayed and the program finished the execution without any interruption. | def divideBy(n):
try:
return 4/n
except ZeroDivisionError:
print("Invalid argument.")
print(divideBy(4))
print(divideBy(1))
print(divideBy(0))
def divideBy(n):
return 4/n
try:
print(divideBy(4))
print(divideBy(1))
print(divideBy(0))
except ZeroDivisionError:
print("... | 1.0
4.0
Invalid argument.
| MIT | day-1/session-2.ipynb | vchrombie/da-python |
Setup | import numpy as np
DATA_PERCENT = 100 | _____no_output_____ | Apache-2.0 | DR_colab.ipynb | tradman1/pytorch-pretrained-BERT |
Download data | !git clone https://gist.github.com/60c2bdb54d156a41194446737ce03e2e.git
!mv 60c2bdb54d156a41194446737ce03e2e/download_glue_data.py .
!rm -rf 60c2bdb54d156a41194446737ce03e2e
%cd /content
%run download_glue_data.py --data_dir glue_data --tasks SST
task = "SST-2"
with open(f"/content/glue_data/{task}/train.tsv") as trai... | _____no_output_____ | Apache-2.0 | DR_colab.ipynb | tradman1/pytorch-pretrained-BERT |
Install Pytorch BERT | #!git clone https://github.com/huggingface/pytorch-pretrained-BERT.git
from google.colab import drive
drive.mount('/content/drive')
# %cp -r /content/drive/My\ Drive/dr/pytorch-pretrained-BERT /content
!git clone https://github.com/tradman1/pytorch-pretrained-BERT.git
%cd /content/pytorch-pretrained-BERT
!python se... | running install
running bdist_egg
running egg_info
creating pytorch_pretrained_bert.egg-info
writing pytorch_pretrained_bert.egg-info/PKG-INFO
writing dependency_links to pytorch_pretrained_bert.egg-info/dependency_links.txt
writing entry points to pytorch_pretrained_bert.egg-info/entry_points.txt
writing requirements ... | Apache-2.0 | DR_colab.ipynb | tradman1/pytorch-pretrained-BERT |
Run train | # without intermediate pretraining
%run examples/run_classifier.py \
--task_name SST-2 \
--do_train \
--do_eval \
--do_lower_case \
--data_dir /content/glue_data/SST-2 \
--bert_model bert-base-uncased \
--max_seq_length 128 \
--train_batch_size 32 \
--learning_rate 2e-5 \
--num_train_epochs 3.0 \
... | _____no_output_____ | Apache-2.0 | DR_colab.ipynb | tradman1/pytorch-pretrained-BERT |
Google form analysis visualizations Table of Contents['Google form analysis' functions checks](funcchecks)['Google form analysis' functions tinkering](functinkering) | %run "../Functions/1. Google form analysis.ipynb" | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
'Google form analysis' functions checks 'Google form analysis' functions tinkering | binarizedAnswers = plotBasicStats(getSurveysOfBiologists(gform), 'non biologists', includeUndefined = True)
gform.loc[:, [localplayerguidkey, 'Temporality']].groupby('Temporality').count()
#sample = gform.copy()
samples = [
[gform.copy(), 'complete set'],
[gform[gform['Language'] == 'en'], 'Engl... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
abandoned algorithms | #totalPerQuestion = np.dot(np.ones(sciBinarized.shape[0]), sciBinarized)
#totalPerQuestion.shape
totalPerQuestionSci = np.dot(np.ones(sciBinarized.shape[0]), sciBinarized)
totalPerQuestionAll = np.dot(np.ones(allBinarized.shape[0]), allBinarized)
totalPerQuestionDFAll = pd.DataFrame(data=np.dot(np.ones(allBinarized.sha... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
sample getters tinkering | ##### getRMAfter / Before tinkering
#def getRMAfters(sample):
afters = sample[sample['Temporality'] == 'after']
#def getRMBefores(sample):
befores = sample[sample['Temporality'] == 'before']
QPlayed1 = 'Have you ever played an older version of Hero.Coli before?'
QPlayed2 = 'Have you played the current version of Hero.C... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
set operators | # equality tests
#(sample1.columns == sample2.columns).all()
#sample1.columns.duplicated().any() or sample2.columns.duplicated().any()
#pd.concat([sample1, sample2], axis=1).columns.duplicated().any() | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getUnionQuestionnaires tinkering | sample1 = befores
sample2 = afters
#def getUnionQuestionnaires(sample1, sample2):
if (not (sample1.columns == sample2.columns).all()):
print("warning: parameter columns are not the same")
result = pd.concat([sample1, sample2]).drop_duplicates() | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getIntersectionQuestionnaires tinkering | sample1 = befores[:15]
sample2 = befores[10:]
#def getIntersectionQuestionnaires(sample1, sample2):
if (not (sample1.columns == sample2.columns).all()):
print("warning: parameter columns are not the same")
result = pd.merge(sample1, sample2, how = 'inner').drop_duplicates() | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getIntersectionUsersSurveys tinkering | sample1 = befores
sample2 = afters
# get sample1 and sample2 rows where users are common to sample1 and sample2
#def getIntersectionUsersSurveys(sample1, sample2):
result1 = sample1[sample1[localplayerguidkey].isin(sample2[localplayerguidkey])]
result2 = sample2[sample2[localplayerguidkey].isin(sample1[localplayerguid... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getGFormBefores tinkering | sample = gform
# returns users who declared that they have never played the game, whatever platform
# previousPlayPositives is defined in '../Static data/English localization.ipynb'
#def getGFormBefores(sample):
befores = sample[
~sample[QPlayed1].isin(previousPlayPositives)
& ~sample[QPlayed2].isin(previo... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getGFormAfters tinkering | sample = gform
# returns users who declared that they have already played the game, whatever platform
# previousPlayPositives is defined in '../Static data/English localization.ipynb'
#def getGFormAfters(sample):
afters = sample[
sample[QPlayed1].isin(previousPlayPositives)
| sample[QPlayed2].isin(previousP... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getGFormTemporality tinkering | _GFUserId = getSurveysOfBiologists(gform)[localplayerguidkey].iloc[3]
_gformRow = gform[gform[localplayerguidkey] == _GFUserId].iloc[0]
sample = gform
answerTemporalities[1]
#while result != 'after':
_GFUserId = getRandomGFormGUID()
_gformRow = gform[gform[localplayerguidkey] == _GFUserId].iloc[0]
# returns an element... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getSurveysOfUsersWhoAnsweredBoth tinkering | sample = gform
gfMode = True
rmMode = False
#def getSurveysOfUsersWhoAnsweredBoth(sample, gfMode = True, rmMode = False):
befores = sample
afters = sample
if gfMode:
befores = getGFormBefores(befores)
afters = getGFormAfters(afters)
if rmMode:
befores = getRMBefores(befores)
afters = getRMAfters(aft... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getSurveysThatAnswered tinkering | sample = gform
#_GFUserId = getSurveysOfBiologists(gform)[localplayerguidkey].iloc[1]
#sample = gform[gform[localplayerguidkey] == _GFUserId]
hardPolicy = True
questionsAndPositiveAnswers = [[Q6BioEdu, biologyStudyPositives],
[Q8SynBio, yesNoIdontknowPositives],
... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getSurveysOfBiologists tinkering | sample = gform
hardPolicy = True
#def getSurveysOfBiologists(sample, hardPolicy = True):
Q6BioEdu = 'How long have you studied biology?' #biologyStudyPositives
#irrelevant QInterest 'Are you interested in biology?' #biologyInterestPositives
Q8SynBio = 'Before playing Hero.Coli, had you ever heard about synthetic biolo... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getSurveysOfGamers tinkering | sample = gform
hardPolicy = True
#def getSurveysOfGamers(sample, hardPolicy = True):
Q2Interest = 'Are you interested in video games?' #interestPositives
Q3Play = 'Do you play video games?' #frequencyPositives
questionsAndPositiveAnswers = [[Q2Interest, interestPositives], [Q3Play, frequencyPositives]]
result = getS... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getSurveysWithMatchingAnswers tinkering | _GFUserId = getSurveysOfBiologists(gform)[localplayerguidkey].iloc[2]
_gformRow = gform[gform[localplayerguidkey] == _GFUserId].iloc[0]
sample = gform
sample = gform
_gformRow = gform[gform[localplayerguidkey] == _GFUserId].iloc[0]
hardPolicy = False
Q4 = 'How old are you?'
Q5 = 'What is your gender?'
Q2Interest = 'Are... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getMatchingDemographics tinkering | sample = gform
_gformRow = gform[gform[localplayerguidkey] == _GFUserId].iloc[0]
hardPolicy = True
#def getMatchingDemographics(sample, _gformRow, hardPolicy = False):
# age and gender
Q4 = 'How old are you?'
Q5 = 'What is your gender?'
# interests, hobbies, and knowledge - evaluation may vary after playing
Q2Interes... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getGFormRowCorrection tinkering | _gformRow = gform[gform[localplayerguidkey] == _GFUserId].iloc[0]
_source = correctAnswers
#def getGFormRowCorrection( _gformRow, _source = correctAnswers):
result = _gformRow.copy()
if(len(_gformRow) == 0):
print("this gform row is empty")
else:
result = pd.Series(index = _gformRow.index, data = np.full(len... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getGFormRowScore tinkering | _gformRow = gform[gform[localplayerguidkey] == _GFUserId].iloc[0]
_source = correctAnswers
#def getGFormRowScore( _gformRow, _source = correctAnswers):
correction = getGFormRowCorrection( _gformRow, _source = _source)
_counts = correction.value_counts()
_thisScore = 0
if(True in _counts):
_thisScore = _counts[Tru... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
getGFormDataPreview tinkering | _GFUserId = getSurveysOfBiologists(gform)[localplayerguidkey].iloc[2]
sample = gform
# for per-gform, manual analysis
#def getGFormDataPreview(_GFUserId, sample):
gforms = gform[gform[localplayerguidkey] == _GFUserId]
result = {}
for _ilocIndex in range(0, len(gforms)):
gformsIndex = gforms.index[_ilocIndex]
... | _____no_output_____ | CC0-1.0 | v1.52/Tests/1.3 Google form analysis visualizations.ipynb | CyberCRI/herocoli-metrics-redwire |
save this xml | save_filename = os.path.join(source_folder, f"generated_dave_H{hyb_start}-{hyb_start+num_rounds-1}.txt")
with open(save_filename, 'w') as _output_handle:
print(save_filename)
_output_handle.write(final_str)
| D:\Pu\20220102-CTP11-1000_CTP12-DNA_from_1229\generated_dave_H51-64.txt
| MIT | jupyter/Generate_dave_xml_DNA_IDEX.ipynb | shiwei23/STORM6 |
Neuromatch Academy: Week 3, Day 2, Tutorial 1 Neuronal Network Dynamics: Neural Rate Models__Content creators:__ Qinglong Gu, Songtin Li, Arvind Kumar, John Murray, Julijana Gjorgjieva __Content reviewers:__ Spiros Chavlis, Lorenzo Fontolan, Richard Gao, Maryam Vaziri-Pashkam,Michael Waskom --- Tutorial ObjectivesThe... | # Imports
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt # root-finding algorithm
# @title Figure Settings
import ipywidgets as widgets # interactive display
%config InlineBackend.figure_format = 'retina'
plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/cou... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Section 1: Neuronal network dynamics | # @title Video 1: Dynamic networks
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="p848349hPyw", width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | Video available at https://youtube.com/watch?v=p848349hPyw
| CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Section 1.1: Dynamics of a single excitatory populationIndividual neurons respond by spiking. When we average the spikes of neurons in a population, we can define the average firing activity of the population. In this model, we are interested in how the population-averaged firing varies as a function of time and netwo... | # @title Default parameters for a single excitatory population model
def default_pars_single(**kwargs):
pars = {}
# Excitatory parameters
pars['tau'] = 1. # Timescale of the E population [ms]
pars['a'] = 1.2 # Gain of the E population
pars['theta'] = 2.8 # Threshold of the E population
# Conne... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
You can use:- `pars = default_pars_single()` to get all the parameters, and then you can execute `print(pars)` to check these parameters. - `pars = default_pars_single(T=T_sim, dt=time_step)` to set new simulation time and time step- After `pars = default_pars_single()`, use `pars['New_para'] = value` to add an new par... | def F(x, a, theta):
"""
Population activation function.
Args:
x (float): the population input
a (float): the gain of the function
theta (float): the threshold of the function
Returns:
float: the population activation response F(x) for input x
"""
###########################################... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Interactive Demo: Parameter exploration of F-I curveHere's an interactive demo that shows how the F-I curve is changing for different values of the gain and threshold parameters.**Remember to enable the demo by running the cell.** | # @title
# @markdown Make sure you execute this cell to enable the widget!
def interactive_plot_FI(a, theta):
"""
Population activation function.
Expecxts:
a : the gain of the function
theta : the threshold of the function
Returns:
plot the F-I curve with give parameters
"""
# set the ... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Section 1.3: Simulation scheme of E dynamicsBecause $F(\cdot)$ is a nonlinear function, the exact solution of Equation $1$ can not be determined via analytical methods. Therefore, numerical methods must be used to find the solution. In practice, the derivative on the left-hand side of Equation $1$ can be approximated ... | # @title Single population rate model simulator: `simulate_single`
def simulate_single(pars):
"""
Simulate an excitatory population of neurons
Args:
pars : Parameter dictionary
Returns:
rE : Activity of excitatory population (array)
Example:
pars = default_pars_single()
r = simulate... | Help on function simulate_single in module __main__:
simulate_single(pars)
Simulate an excitatory population of neurons
Args:
pars : Parameter dictionary
Returns:
rE : Activity of excitatory population (array)
Example:
pars = default_pars_single()
r = simula... | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Interactive Demo: Parameter Exploration of single population dynamicsNote that $w=0$, as in the default setting, means no recurrent input to the neuron population in Equation (1). Hence, the dynamics is entirely determined by the external input $I_{\text{ext}}$. Try to explore how $r_{\text{sim}}(t)$ changes with diff... | # @title
# @markdown Make sure you execute this cell to enable the widget!
# get default parameters
pars = default_pars_single(T=20.)
def Myplot_E_diffI_difftau(I_ext, tau):
# set external input and time constant
pars['I_ext'] = I_ext
pars['tau'] = tau
# simulation
r = simulate_single(pars)
# Analytic... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Think!Above, we have numerically solved a system driven by a positive input and that, if $w_{EE} \neq 0$, receives an excitatory recurrent input (**try changing the value of $w_{EE}$ to a positive number**). Yet, $r_E(t)$ either decays to zero or reaches a fixed non-zero value.- Why doesn't the solution of the system ... | # @title Video 2: Fixed point
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="Ox3ELd1UFyo", width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | Video available at https://youtube.com/watch?v=Ox3ELd1UFyo
| CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
As you varied the two parameters in the last Interactive Demo, you noticed that, while at first the system output quickly changes, with time, it reaches its maximum/minimum value and does not change anymore. The value eventually reached by the system is called the **steady state** of the system, or the **fixed point**.... | # @title Function of calculating the fixed point
# @markdown Make sure you execute this cell to enable the function!
def my_fp_single(pars, r_init):
"""
Calculate the fixed point through drE/dt=0
Args:
pars : Parameter dictionary
r_init : Initial value used for scipy.optimize function
Returns:
... | Help on function my_fp_single in module __main__:
my_fp_single(pars, r_init)
Calculate the fixed point through drE/dt=0
Args:
pars : Parameter dictionary
r_init : Initial value used for scipy.optimize function
Returns:
x_fp : value of fixed point
None
Help on function ch... | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Exercise 2: Visualization of the fixed pointWhen it is not possible to find the solution for Equation (3) analytically, a graphical approach can be taken. To that end, it is useful to plot $\displaystyle{\frac{dr}{dt}=0}$ as a function of $r$. The values of $r$ for which the plotted function crosses zero on the y axis... | pars = default_pars_single() # get default parameters
# set your external input and wEE
pars['I_ext'] = 0.5
pars['w'] = 5.0
r = np.linspace(0, 1, 1000) # give the values of r
# Calculate drEdt
# drdt = ...
# Uncomment this to plot the drdt across r
# plot_dr_r(r, drdt)
###########################################... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Interactive Demo: fixed points as a function of recurrent and external inputs.You can now explore how the previous plot changes when the recurrent coupling $w$ and the external input $I_{\text{ext}}$ take different values. | # @title
# @markdown Make sure you execute this cell to enable the widget!
def plot_intersection_single(w, I_ext):
# set your parameters
pars['w'] = w
pars['I_ext'] = I_ext
# note that wEE!=0
if w > 0:
# find fixed point
x_fp_1 = my_fp_single(pars, 0.)
x_fp_2 = my_fp_single(pars, 0.4)
x_fp... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
--- SummaryIn this tutorial, we have investigated the dynamics of a rate-based single population of neurons.We learned about:- The effect of the input parameters and the time constant of the network on the dynamics of the population.- How to find the fixed point(s) of the system.Next, we have two Bonus, but important c... | # @title Video 3: Stability of fixed points
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="KKMlWWU83Jg", width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | Video available at https://youtube.com/watch?v=KKMlWWU83Jg
| CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Initial values and trajectoriesHere, let us first set $w=5.0$ and $I_{\text{ext}}=0.5$, and investigate the dynamics of $r(t)$ starting with different initial values $r(0) \equiv r_{\text{init}}$. We will plot the trajectories of $r(t)$ with $r_{\text{init}} = 0.0, 0.1, 0.2,..., 0.9$. | # @title Initial values
# @markdown Make sure you execute this cell to see the trajectories!
pars = default_pars_single()
pars['w'] = 5.0
pars['I_ext'] = 0.5
plt.figure(figsize=(8, 5))
for ie in range(10):
pars['r_init'] = 0.1 * ie # set the initial value
r = simulate_single(pars) # run the simulation
# plo... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Interactive Demo: dynamics as a function of the initial valueLet's now set $r_{\rm init}$ to a value of your choice in this demo. How does the solution change? What do you observe? | # @title
# @markdown Make sure you execute this cell to enable the widget!
pars = default_pars_single()
pars['w'] = 5.0
pars['I_ext'] = 0.5
def plot_single_diffEinit(r_init):
pars['r_init'] = r_init
r = simulate_single(pars)
plt.figure()
plt.plot(pars['range_t'], r, 'b', zorder=1)
plt.plot(0, r[0], 'bo',... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Stability analysis via linearization of the dynamicsJust like Equation $1$ in the case ($w=0$) discussed above, a generic linear system $$\frac{dx}{dt} = \lambda (x - b),$$ has a fixed point for $x=b$. The analytical solution of such a system can be found to be:$$x(t) = b + \big{(} x(0) - b \big{)} \text{e}^{\lambda t... | def dF(x, a, theta):
"""
Population activation function.
Args:
x : the population input
a : the gain of the function
theta : the threshold of the function
Returns:
dFdx : the population activation response F(x) for input x
"""
#################################################
#... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Exercise 4: Compute eigenvaluesAs discussed above, for the case with $w=5.0$ and $I_{\text{ext}}=0.5$, the system displays **three** fixed points. However, when we simulated the dynamics and varied the initial conditions $r_{\rm init}$, we could only obtain **two** steady states. In this exercise, we will now check th... | def eig_single(pars, fp):
"""
Args:
pars : Parameter dictionary
fp : fixed point r_fp
Returns:
eig : eigevalue of the linearized system
"""
# get the parameters
tau, a, theta = pars['tau'], pars['a'], pars['theta']
w, I_ext = pars['w'], pars['I_ext']
print(tau, a, theta, w, I_ext)
###... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
**SAMPLE OUTPUT**```Fixed point1 at 0.042 with Eigenvalue=-0.583Fixed point2 at 0.447 with Eigenvalue=0.498Fixed point3 at 0.900 with Eigenvalue=-0.626``` | # to_remove solution
def eig_single(pars, fp):
"""
Args:
pars : Parameter dictionary
fp : fixed point r_fp
Returns:
eig : eigevalue of the linearized system
"""
# get the parameters
tau, a, theta = pars['tau'], pars['a'], pars['theta']
w, I_ext = pars['w'], pars['I_ext']
print(tau, a, th... | 1.0 1.2 2.8 5.0 0.5
Fixed point1 at 0.042 with Eigenvalue=-0.583
1.0 1.2 2.8 5.0 0.5
Fixed point2 at 0.447 with Eigenvalue=0.498
1.0 1.2 2.8 5.0 0.5
Fixed point3 at 0.900 with Eigenvalue=-0.626
| CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Think! Throughout the tutorial, we have assumed $w> 0 $, i.e., we considered a single population of **excitatory** neurons. What do you think will be the behavior of a population of inhibitory neurons, i.e., where $w> 0$ is replaced by $w< 0$? --- Bonus 2: Noisy input drives the transition between two stable states ... | # @title OU process `my_OU(pars, sig, myseed=False)`
# @markdown Make sure you execute this cell to visualize the noise!
def my_OU(pars, sig, myseed=False):
"""
A functions that generates Ornstein-Uhlenback process
Args:
pars : parameter dictionary
sig : noise amplitute
myseed : r... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Example: Up-Down transitionIn the presence of two or more fixed points, noisy inputs can drive a transition between the fixed points! Here, we stimulate an E population for 1,000 ms applying OU inputs. | # @title Simulation of an E population with OU inputs
# @markdown Make sure you execute this cell to spot the Up-Down states!
pars = default_pars_single(T=1000)
pars['w'] = 5.0
sig_ou = 0.7
pars['tau_ou'] = 1. # [ms]
pars['I_ext'] = 0.56 + my_OU(pars, sig=sig_ou, myseed=2020)
r = simulate_single(pars)
plt.figure(f... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | NinelK/course-content |
Charger le modèle que nous venons de créer | model = Word2Vec.load("../tpfinal/bulletins.model") | _____no_output_____ | MIT | tpfinal/s5_model_explorer.ipynb | oussamagh97/tac |
Comment est représenté le mot "rue" ? | model["hospices"] | _____no_output_____ | MIT | tpfinal/s5_model_explorer.ipynb | oussamagh97/tac |
Et fleuriste ? | model['medicaux'] | _____no_output_____ | MIT | tpfinal/s5_model_explorer.ipynb | oussamagh97/tac |
Quel est leur similarité ? | model.wv.similarity("budget", "lois")
model.wv.similarity("services", "revenus")
model.wv.similarity("ville","politique")
model.wv.similarity("hospices","travaux") | _____no_output_____ | MIT | tpfinal/s5_model_explorer.ipynb | oussamagh97/tac |
Quel mot est le plus proche de rue ? | model.wv.most_similar("hospices", topn=30) | _____no_output_____ | MIT | tpfinal/s5_model_explorer.ipynb | oussamagh97/tac |
Et de Bruxelles ? | model.wv.most_similar("hopitaux")
model.wv.most_similar("medicaux")
model.wv.most_similar("medical")
model.wv.most_similar("malade")
model.wv.most_similar("politique") | _____no_output_____ | MIT | tpfinal/s5_model_explorer.ipynb | oussamagh97/tac |
Comment obtenir une ville de France grâce à notre modèle ? | model.wv.most_similar(positive=['bruxelles', 'france'], negative=['belgique'], topn=1)
model.wv.most_similar(positive=['bruxelles', 'liege', 'france'], negative=['belgique'], topn=1) | _____no_output_____ | MIT | tpfinal/s5_model_explorer.ipynb | oussamagh97/tac |
`sourmash tax` submodule for integrating taxonomic information The sourmash tax (alias `taxonomy`) commands integrate taxonomic information into the results of sourmash gather. tax commands require a properly formatted taxonomy csv file that corresponds to the database used for gather. For supported databases (e.g. G... | %%bash
mkdir -p lineages
curl -L https://osf.io/p6z3w/download -o lineages/gtdb-rs202.taxonomy.csv
%%bash
head lineages/gtdb-rs202.taxonomy.csv | ident,superkingdom,phylum,class,order,family,genus,species
GCF_014075335.1,d__Bacteria,p__Proteobacteria,c__Gammaproteobacteria,o__Enterobacterales,f__Enterobacteriaceae,g__Escherichia,s__Escherichia flexneri
GCF_002310555.1,d__Bacteria,p__Proteobacteria,c__Gammaproteobacteria,o__Enterobacterales,f__Enterobacteriaceae,... | BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
download NCBI lineage filesNow let's go ahead and grab the Genbank taxonomy files as well. | %%bash
curl -L https://osf.io/cbhgd/download -o lineages/bacteria_genbank_lineages.csv
curl -L https://osf.io/urtfx/download -o lineages/protozoa_genbank_lineages.csv | % Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 459 100 459 0 0 1267 0 --:--:-- --:--:-- --:--:-- 1267
100 83.1M 100 83.1M 0 0 16.5M 0 0:00:05 0:00:05 --:--:-- 20.6M
% ... | BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
If you do a `head` on these files, you'll notice they have an extra `taxid` column, but otherwise follow the same format. | %%bash
head lineages/protozoa_genbank_lineages.csv | accession,taxid,superkingdom,phylum,class,order,family,genus,species,strain
GCA_004431415,2762,Eukaryota,,Glaucocystophyceae,,Cyanophoraceae,Cyanophora,Cyanophora paradoxa,
GCA_000150955,556484,Eukaryota,Bacillariophyta,Bacillariophyceae,Naviculales,Phaeodactylaceae,Phaeodactylum,Phaeodactylum tricornutum,Phaeodactylum... | BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
Combining taxonomies with `sourmash tax prepare` All sourmash tax commands must be given one or more taxonomy files as parameters to the `--taxonomy` argument.`sourmash tax prepare` is a utility function that can ingest and validate multiple CSV files or sqlite3databases, and output a CSV file or a sqlite3 database. I... | # to see the arguments, run the `--help` like so:
! sourmash tax prepare --help
%%bash
sourmash tax prepare --taxonomy lineages/bacteria_genbank_lineages.csv \
lineages/protozoa_genbank_lineages.csv \
lineages/gtdb-rs202.taxonomy.csv \
... | [K
== This is sourmash version 4.2.1. ==
[K== Please cite Brown and Irber (2016), doi:10.21105/joss.00027. ==
[Kloading taxonomies...
[K...loaded 882562 entries.
[Ksaving to 'lineages/gtdb-rs202_genbank.taxonomy.db', format sql...
[Kdone!
| BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
> Note that the **order is important if the databases contain overlappingaccession identifiers**. In this case, GTDB contains only a subset of all identifiersin the NCBI taxonomy. Putting GTDB last here will allow the GTDB lineage informationto override the lineage information provided in the NCBI file, thus utilizing ... | %%bash
ls -lsrht lineages/ | total 566776
73856 -rw-r--r-- 1 tessa staff 35M Aug 2 15:16 gtdb-rs202.taxonomy.csv
196736 -rw-r--r-- 1 tessa staff 83M Aug 2 15:16 bacteria_genbank_lineages.csv
256 -rw-r--r-- 1 tessa staff 107K Aug 2 15:16 protozoa_genbank_lineages.csv
295928 -rw-r--r-- 1 tessa staff 139M Aug 2 15:17 gtdb-rs... | BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
We'll use this prepared database in each of the commands below. `sourmash tax metagenome` | # to see the arguments, run the `--help` like so:
! sourmash tax metagenome --help | [K
== This is sourmash version 4.2.1. ==
[K== Please cite Brown and Irber (2016), doi:10.21105/joss.00027. ==
usage:
sourmash tax metagenome --gather-csv <gather_csv> [ ... ] --taxonomy-csv <taxonomy-csv> [ ... ]
The 'tax metagenome' command reads in metagenome gather result CSVs and
summarizes by taxonomic l... | BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
Download a small demo `sourmash gather` output file from metagenome `HSMA33MX`.This `gather` was run at a DNA ksize of 31 against both GTDB and our legacy Genbank database. | %%bash
mkdir -p gather
curl -L https://osf.io/xb8jg/download -o gather/HSMA33MX_gather_x_gtdbrs202_genbank_k31.csv | % Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 459 100 459 0 0 1201 0 --:--:-- --:--:-- --:--:-- 1201
100 2662 100 2662 0 0 1928 0 0:00:01 0:00:01 --:--:-- 0
| BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
Take a look at this gather file: | %%bash
head gather/HSMA33MX_gather_x_gtdbrs202_genbank_k31.csv | intersect_bp,f_orig_query,f_match,f_unique_to_query,f_unique_weighted,average_abund,median_abund,std_abund,name,filename,md5,f_match_orig,unique_intersect_bp,gather_result_rank,remaining_bp,query_filename,query_name,query_md5,query_bp
442000,0.08815317112086159,0.08438335242458954,0.08815317112086159,0.0581527936145952... | BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
summarize this metagenome and produce `krona` output at the `species` level: | %%bash
sourmash tax metagenome --gather-csv gather/HSMA33MX_gather_x_gtdbrs202_genbank_k31.csv \
--taxonomy lineages/gtdb-rs202_genbank.taxonomy.db \
--output-format csv_summary krona --rank species \
--output-base HSMA33MX.gather-tax
# build kron... | Writing text.krona.html...
| BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
This will produce both `csv_summary` and `krona` output files, with the basename `HSMA33MX.gather-tax`: | %%bash
ls HSMA33MX.gather-tax*
%%bash
head HSMA33MX.gather-tax.summarized.csv
%%bash
head HSMA33MX.gather-tax.krona.tsv
# generate krona html
!ktImportText HSMA33MX.gather-tax.krona.tsv | Writing text.krona.html...
| BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
comparing metagenomes with `sourmash tax metagenome`:We can also download a second metagenome `gather` csv and use `metagenome` to generate a`lineage_summary` output to compare these samples.> The lineage summary format is most useful when comparing across metagenome queries.> Each row is a lineage at the desired repo... | %%bash
curl -L https://osf.io/nqtgs/download -o gather/PSM7J4EF_gather_x_gtdbrs202_genbank_k31.csv
%%bash
sourmash tax metagenome --gather-csv gather/HSMA33MX_gather_x_gtdbrs202_genbank_k31.csv \
gather/PSM7J4EF_gather_x_gtdbrs202_genbank_k31.csv \
--taxonom... | lineage HSMA33MX PSM7J4EF
Eukaryota;Apicomplexa;Aconoidasida;Haemosporida;Plasmodiidae;Plasmodium;Plasmodium vivax 0.041084962106102914 0.004553734061930784
Eukaryota;Apicomplexa;Conoidasida;Eucoccidiorida;Sarcocystidae;Toxoplasma;Toxoplasma gondii 0.010370961308336658 0.0011275912915257177
d__Bacteria;p__Bacteroidota;... | BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
Note, these are mini gather results, so your unclassified fraction will hopefully be much smaller! Classifying genomes with `sourmash tax genome` To illustrate the utility of genome, let’s consider a signature consisting of two differentShewanella strains, Shewanella baltica OS185 strain=OS185 and Shewanella baltica O... | %%bash
curl -L https://osf.io/pgsc2/download -o gather/Sb47+63_x_gtdb-rs202.gather.csv
%%bash
head gather/Sb47+63_x_gtdb-rs202.gather.csv | intersect_bp,f_orig_query,f_match,f_unique_to_query,f_unique_weighted,average_abund,median_abund,std_abund,name,filename,md5,f_match_orig,unique_intersect_bp,gather_result_rank,remaining_bp,query_filename,query_name,query_md5,query_bp
5238000,0.6642150646715699,1.0,0.6642150646715699,0.6642150646715699,,,,"GCF_00002166... | BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
Now, let's run `tax genome` classification: | %%bash
# to see the arguments, run the `--help` like so:
sourmash tax genome --help
%%bash
sourmash tax genome --gather-csv gather/Sb47+63_x_gtdb-rs202.gather.csv \
--taxonomy lineages/gtdb-rs202_genbank.taxonomy.db \
--output-base Sb47+63.gather-tax | [K
== This is sourmash version 4.2.1. ==
[K== Please cite Brown and Irber (2016), doi:10.21105/joss.00027. ==
[Kloaded 2 gather results.
[Kof 2, missed 0 lineage assignments.
[Kloaded results from 1 gather CSVs
[Ksaving `classification` output to Sb47+63.gather-tax.classifications.csv.
| BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
The default output format is `csv_summary`.This outputs a csv with taxonomic classification for each query genome. This output currently consists of six columns:`query_name`,`rank`,`fraction`,`lineage`,`query_md5`,`query_filename`, where `fraction` is the fraction of the query matched tothe reported rank and lineage. T... | !ls Sb47+63.gather-tax*
!head Sb47+63.gather-tax.classifications.csv | query_name,status,rank,fraction,lineage,query_md5,query_filename,f_weighted_at_rank,bp_match_at_rank
Sb47+63,match,species,1.0,d__Bacteria;p__Proteobacteria;c__Gammaproteobacteria;o__Enterobacterales;f__Shewanellaceae;g__Shewanella;s__Shewanella baltica,491c0a81,,1.0,7886000.0
| BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
> Here, we see that the match percentages to both strains have been aggregated, and we have 100% species-level> Shewanella baltica annotation (fraction = 1.0). `sourmash tax annotate` `sourmash tax annotate` adds a column with taxonomic lineage information for each database match to gather output.It does not do any LC... | %%bash
sourmash tax annotate --gather-csv gather/Sb47+63_x_gtdb-rs202.gather.csv \
--taxonomy lineages/gtdb-rs202_genbank.taxonomy.db
!head Sb47+63_x_gtdb-rs202.gather.with-lineages.csv | intersect_bp,f_orig_query,f_match,f_unique_to_query,f_unique_weighted,average_abund,median_abund,std_abund,name,filename,md5,f_match_orig,unique_intersect_bp,gather_result_rank,remaining_bp,query_filename,query_name,query_md5,query_bp,lineage
5238000,0.6642150646715699,1.0,0.6642150646715699,0.6642150646715699,,,,"GCF_... | BSD-3-Clause | binder/sourmash-tax.ipynb | sourmash-bio/sourmash-recipes |
1. DES | def shift_left(s, n):
for i in range(n):
s = s[1:] + s[0]
return s
def permute(s, key):
ans = []
for i in key:
ans.append(s[i - 1])
return ''.join(ans)
def create_keys(key_with_parity_bits):
parity_bit_drop_table = [57, 49, 41, 33, 25, 17, 9,
1, 58, 50,... | 1100000010110111101010001101000001011111001110101000001010011100
| MIT | cryptography_and_network_security/lab_assignment_5/lab_assignment_5_q1_and_q2_complete.ipynb | piyushmoolchandani/Lab_codes |
2. AES : 10 Round, 128 bit input, 128 bit key | def hex_to_bits(a):
x = bin(int(a, 16))[2:]
x = '0' * (8 - len(x)) + x
return x
def left_shift(s):
return s[1:] + s[0]
def sub_word(s):
subbytes_table = [['0x63', '0x7c', '0x77', '0x7b', '0xf2', '0x6b', '0x6f', '0xc5', '0x30', '0x1', '0x67', '0x2b', '0xfe', '0xd7', '0xab', '0x76'],
... | ['0x29', '0x57', '0x40', '0x1a']
['0xc3', '0x14', '0x22', '0x2']
['0x50', '0x20', '0x99', '0xd7']
['0x5f', '0xf6', '0xb3', '0x3a']
00101001110000110101000001011111010101110001010000100000111101100100000000100010100110011011001100011010000000101101011100111010
| MIT | cryptography_and_network_security/lab_assignment_5/lab_assignment_5_q1_and_q2_complete.ipynb | piyushmoolchandani/Lab_codes |
Deck> Deck of playing cards. | from nbdev import *
from binary_classifier.card import Card
# export
class Deck:
"""Represents a deck of cards.
Attributes:
cards: list of Card objects.
"""
def __init__(self):
"""Initializes the Deck with 52 cards.
"""
self.cards = []
for suit in range(4):
... | _____no_output_____ | Apache-2.0 | 00_deck.ipynb | fnauman/binary_classifier |
A deck of cards | deck = Deck()
assert isinstance(deck.pop_card(), Card)
show_doc(Deck.move_cards) | _____no_output_____ | Apache-2.0 | 00_deck.ipynb | fnauman/binary_classifier |
Import Libraries | import sys
import pandas as pd
import numpy as np
from sklearn import preprocessing
from sklearn.decomposition import PCA
from sklearn import random_projection
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import fbeta_score, roc_curve, auc
from sklearn import svm
import pprint
sys.path.inser... | Using TensorFlow backend.
| MIT | machine_learning/notebooks/accuracy_report.ipynb | cyberj0g/verification-classifier |
Data preparation | features = ['dimension',
'size',
'temporal_dct-mean',
'temporal_gaussian_mse-mean',
'temporal_gaussian_difference-mean',
'temporal_threshold_gaussian_difference-mean'
]
path = '../../machine_learning/cloud_functions/data-large.csv'
metric_proce... | Shape of train: (18014, 6)
Shape of test: (4504, 6)
Shape of attacks: (111778, 6)
| MIT | machine_learning/notebooks/accuracy_report.ipynb | cyberj0g/verification-classifier |
The train and test are **only** composed by legit assets | # Scaling the data
ss = StandardScaler()
x_train = ss.fit_transform(X_train)
x_test = ss.transform(X_test)
x_attacks = ss.transform(X_attacks) | _____no_output_____ | MIT | machine_learning/notebooks/accuracy_report.ipynb | cyberj0g/verification-classifier |
One Class SVM | # Train the model
OCSVM = svm.OneClassSVM(kernel='rbf',gamma='auto', nu=0.01, cache_size=5000)
OCSVM.fit(x_train)
fb, area, tnr, tpr_train, tpr_test = evaluation.unsupervised_evaluation(OCSVM, x_train, x_test, x_attacks)
# Show global results of classification
print('TNR: {}\nTPR_test: {}\nTPR_train: {}\n'.format(tnr, ... | _____no_output_____ | MIT | machine_learning/notebooks/accuracy_report.ipynb | cyberj0g/verification-classifier |
Report | # Zoom in in the mean distances of the test set to the decision function by resolution. Percentiles, standard
# deviation, min and max values are shown too.
display(df_test[['dist_to_dec_funct', 'dimension']].groupby('dimension').describe())
# Zoom in in the mean distances of the attack set to the decision function by... | {144: {'black_and_white': 0.9661604050093259,
'flip_vertical': 1.0,
'vignette': 0.9992006394884093,
'watermark': 0.7503330668798295,
'watermark-345x114': 0.2269209508015478,
'watermark-856x856': 0.9845218352681039},
240: {'black_and_white': 0.9757527311484147,
'flip_vertical':... | MIT | machine_learning/notebooks/accuracy_report.ipynb | cyberj0g/verification-classifier |
AMPL Model Colaboratory Template[](https://github.com/ampl/amplcolab/blob/master/template/colab.ipynb) [](https://colab.research.google.com/github/ampl/amplcolab/blob/m... | # Install dependencies
!pip install -q amplpy ampltools
# Google Colab & Kaggle interagration
MODULES=['ampl', 'coin']
from ampltools import cloud_platform_name, ampl_notebook
from amplpy import AMPL, register_magics
if cloud_platform_name() is None:
ampl = AMPL() # Use local installation of AMPL
else:
ampl = a... | _____no_output_____ | MIT | template/colab.ipynb | ampl/amplcolab |
Use `%%ampl_eval` to evaluate AMPL commands | %%ampl_eval
option version; | _____no_output_____ | MIT | template/colab.ipynb | ampl/amplcolab |
Use %%writeifile to create files | %%writefile cut2.mod
problem Cutting_Opt;
# ----------------------------------------
param nPAT integer >= 0, default 0;
param roll_width;
set PATTERNS = 1..nPAT;
set WIDTHS;
param orders {WIDTHS} > 0;
param nbr {WIDTHS,PATTERNS} integer >= 0;
check {j in PATTERNS}: sum {i in WIDTHS} i * nbr[i,j] <= roll_widt... | _____no_output_____ | MIT | template/colab.ipynb | ampl/amplcolab |
Use `%%ampl_eval` to run the script cut2.run | %%ampl_eval
commands cut2.run; | _____no_output_____ | MIT | template/colab.ipynb | ampl/amplcolab |
WARNING:"fitting_parameters.h5" need to be in the directory you are working onor there will be an error for importing mr_forecast in the next cell.If you don't want the file in this directory,change the mr_forecast.py line 16hyper_file = 'fitting_parameters.h5' ->hyper_file = [directory of fitting parameter file]+'fitt... | import numpy as np
import mr_forecast as mr
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | MIT | .ipynb_checkpoints/demo-checkpoint.ipynb | esandford/forecaster |
================================predict the mean and std of radius given those of the mass | Rmedian, Rplus, Rminus = mr.Mstat2R(mean=1.0, std=0.1, unit='Earth', sample_size=100, classify='Yes')
print 'R = %.2f (+ %.2f - %.2f) REarth' % (Rmedian, Rplus, Rminus) | R = 1.00 (+ 0.12 - 0.10) REarth
| MIT | .ipynb_checkpoints/demo-checkpoint.ipynb | esandford/forecaster |
================================predict a vector of radius given a vector of mass | M1 = np.loadtxt('demo_mass.dat')
R1 = mr.Mpost2R(M1, unit='Earth', classify='Yes')
plt.plot(np.log10(M1), np.log10(R1), 'bx')
plt.xlabel(r'$log_{10}\ M/M_{\oplus}$')
plt.ylabel(r'$log_{10}\ R/R_{\oplus}$')
plt.show() | _____no_output_____ | MIT | .ipynb_checkpoints/demo-checkpoint.ipynb | esandford/forecaster |
================================predict the mean and std of mass given those of the radius | Mmedian, Mplus, Mminus = mr.Rstat2M(mean=0.1, std=0.01, unit='Jupiter', sample_size=100, grid_size=1e3, classify='Yes')
print 'M = %.3f (+ %.3f - %.3f) MEarth' % (Mmedian, Mplus, Mminus) | M = 0.005 (+ 0.004 - 0.002) MEarth
| MIT | .ipynb_checkpoints/demo-checkpoint.ipynb | esandford/forecaster |
================================predict a vector of mass given a vector of radius | R2 = np.loadtxt('demo_radius.dat')
M2 = mr.Rpost2M(R2, unit='Earth', grid_size=1e3, classify='Yes')
plt.hist(np.log10(M2))
plt.xlabel(r'$log_{10}\ M/M_{\odot}$')
plt.show() | _____no_output_____ | MIT | .ipynb_checkpoints/demo-checkpoint.ipynb | esandford/forecaster |
TV Script GenerationIn this project, you'll generate your own [Simpsons](https://en.wikipedia.org/wiki/The_Simpsons) TV scripts using RNNs. You'll be using part of the [Simpsons dataset](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data) of scripts from 27 seasons. The Neural Network you'll build will gener... | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:] | _____no_output_____ | Apache-2.0 | project-3-tv-script-generation/dlnd_tv_script_generation.ipynb | vwiart/deeplearning-udacity |
Explore the DataPlay around with `view_sentence_range` to view different parts of the data. | view_sentence_range = (20, 30)
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
print('Dataset Stats')
print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))
scenes = text.split('\n\n')
print('Number of scenes: {}'.format(len(scenes)))
sentence_count_scene = [s... | Dataset Stats
Roughly the number of unique words: 11492
Number of scenes: 262
Average number of sentences in each scene: 15.251908396946565
Number of lines: 4258
Average number of words in each line: 11.50164396430249
The sentences 20 to 30:
Moe_Szyslak: Looks like this is the end.
Barney_Gumble: That's all right. I... | Apache-2.0 | project-3-tv-script-generation/dlnd_tv_script_generation.ipynb | vwiart/deeplearning-udacity |
Implement Preprocessing FunctionsThe first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below:- Lookup Table- Tokenize Punctuation Lookup TableTo create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:- Dictiona... | import numpy as np
import problem_unittests as tests
def create_lookup_tables(text):
"""
Create lookup tables for vocabulary
:param text: The text of tv scripts split into words
:return: A tuple of dicts (vocab_to_int, int_to_vocab)
"""
filtered_out = ['']
tokenized_text = set([t.lower() f... | Tests Passed
| Apache-2.0 | project-3-tv-script-generation/dlnd_tv_script_generation.ipynb | vwiart/deeplearning-udacity |
Tokenize PunctuationWe'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!".Implement the function `token_lookup` to return a dict that will be used to toke... | def token_lookup():
"""
Generate a dict to turn punctuation into a token.
:return: Tokenize dictionary where the key is the punctuation and the value is the token
"""
return {
'.': '||period||',
',': '||comma||',
'"': '||quotation_mark||',
';': '||semicolon||',
... | Tests Passed
| Apache-2.0 | project-3-tv-script-generation/dlnd_tv_script_generation.ipynb | vwiart/deeplearning-udacity |
Preprocess all the data and save itRunning the code cell below will preprocess all the data and save it to file. | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
# Preprocess Training, Validation, and Testing Data
helper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables) | _____no_output_____ | Apache-2.0 | project-3-tv-script-generation/dlnd_tv_script_generation.ipynb | vwiart/deeplearning-udacity |
Check PointThis is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk. | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
import numpy as np
import problem_unittests as tests
int_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess() | _____no_output_____ | Apache-2.0 | project-3-tv-script-generation/dlnd_tv_script_generation.ipynb | vwiart/deeplearning-udacity |
Build the Neural NetworkYou'll build the components necessary to build a RNN by implementing the following functions below:- get_inputs- get_init_cell- get_embed- build_rnn- build_nn- get_batches Check the Version of TensorFlow and Access to GPU | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
from distutils.version import LooseVersion
import warnings
import tensorflow as tf
# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer'
print('TensorFlow Version: {}'.format(tf.__version__))
# Che... | TensorFlow Version: 1.0.0
Default GPU Device: /gpu:0
| Apache-2.0 | project-3-tv-script-generation/dlnd_tv_script_generation.ipynb | vwiart/deeplearning-udacity |
InputImplement the `get_inputs()` function to create TF Placeholders for the Neural Network. It should create the following placeholders:- Input text placeholder named "input" using the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder) `name` parameter.- Targets placeholder- Learning Rate pl... | def get_inputs():
"""
Create TF Placeholders for input, targets, and learning rate.
:return: Tuple (input, targets, learning rate)
"""
inputs = tf.placeholder(tf.int32,
shape=[None, None],
name="input")
targets = tf.placeholder(tf.int32,
... | Tests Passed
| Apache-2.0 | project-3-tv-script-generation/dlnd_tv_script_generation.ipynb | vwiart/deeplearning-udacity |
Build RNN Cell and InitializeStack one or more [`BasicLSTMCells`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/BasicLSTMCell) in a [`MultiRNNCell`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/MultiRNNCell).- The Rnn size should be set using `rnn_size`- Initalize Cell State using the MultiRNN... | keep_prob = 0.8
lstm_layers = 16
def get_init_cell(batch_size, rnn_size):
"""
Create an RNN Cell and initialize it.
:param batch_size: Size of batches
:param rnn_size: Size of RNNs
:return: Tuple (cell, initialize state)
"""
lstm = tf.contrib.rnn.BasicLSTMCell(rnn_size)
drop = tf.contri... | Tests Passed
| Apache-2.0 | project-3-tv-script-generation/dlnd_tv_script_generation.ipynb | vwiart/deeplearning-udacity |
Word EmbeddingApply embedding to `input_data` using TensorFlow. Return the embedded sequence. | def get_embed(input_data, vocab_size, embed_dim):
"""
Create embedding for <input_data>.
:param input_data: TF placeholder for text input.
:param vocab_size: Number of words in vocabulary.
:param embed_dim: Number of embedding dimensions
:return: Embedded input.
"""
embedding = tf.Variab... | Tests Passed
| Apache-2.0 | project-3-tv-script-generation/dlnd_tv_script_generation.ipynb | vwiart/deeplearning-udacity |
Build RNNYou created a RNN Cell in the `get_init_cell()` function. Time to use the cell to create a RNN.- Build the RNN using the [`tf.nn.dynamic_rnn()`](https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn) - Apply the name "final_state" to the final state using [`tf.identity()`](https://www.tensorflow.org/a... | def build_rnn(cell, inputs):
"""
Create a RNN using a RNN Cell
:param cell: RNN Cell
:param inputs: Input text data
:return: Tuple (Outputs, Final State)
"""
outputs, final_state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32)
final_state = tf.identity(final_state, "final_state")
... | Tests Passed
| Apache-2.0 | project-3-tv-script-generation/dlnd_tv_script_generation.ipynb | vwiart/deeplearning-udacity |
Build the Neural NetworkApply the functions you implemented above to:- Apply embedding to `input_data` using your `get_embed(input_data, vocab_size, embed_dim)` function.- Build RNN using `cell` and your `build_rnn(cell, inputs)` function.- Apply a fully connected layer with a linear activation and `vocab_size` as the... | def build_nn(cell, rnn_size, input_data, vocab_size):
"""
Build part of the neural network
:param cell: RNN cell
:param rnn_size: Size of rnns
:param input_data: Input data
:param vocab_size: Vocabulary size
:return: Tuple (Logits, FinalState)
"""
embeds = get_embed(input_data, vocab... | Tests Passed
| Apache-2.0 | project-3-tv-script-generation/dlnd_tv_script_generation.ipynb | vwiart/deeplearning-udacity |
BatchesImplement `get_batches` to create batches of input and targets using `int_text`. The batches should be a Numpy array with the shape `(number of batches, 2, batch size, sequence length)`. Each batch contains two elements:- The first element is a single batch of **input** with the shape `[batch size, sequence le... | def shuffle(arr, seq_length, n_batches):
reshape = arr.reshape(-1, seq_length)
splits = [[] for _ in range(n_batches)]
for i, a in enumerate(reshape):
splits[i % n_batches].append(a)
return splits
def get_batches(int_text, batch_size, seq_length):
"""
Return batches of input and target
... | Tests Passed
| Apache-2.0 | project-3-tv-script-generation/dlnd_tv_script_generation.ipynb | vwiart/deeplearning-udacity |
Neural Network Training HyperparametersTune the following parameters:- Set `num_epochs` to the number of epochs.- Set `batch_size` to the batch size.- Set `rnn_size` to the size of the RNNs.- Set `seq_length` to the length of sequence.- Set `learning_rate` to the learning rate.- Set `show_every_n_batches` to the numbe... | # Number of Epochs
num_epochs = 200
# Batch Size
batch_size = 64
# RNN Size
rnn_size = 256
# Sequence Length
seq_length = 256
# Learning Rate
learning_rate = 0.01
# Show stats for every n number of batches
show_every_n_batches = 10
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
save_dir = './save' | _____no_output_____ | Apache-2.0 | project-3-tv-script-generation/dlnd_tv_script_generation.ipynb | vwiart/deeplearning-udacity |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.