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 |
|---|---|---|---|---|---|
---Brute force some features | def feat_amount_sold(groupby):
return groupby["order"].sum()
def feat_value(groupby):
return groupby["salesPrice"].sum()
def amount_of_transactions():
return groupby.size()
func_feats_past_time = {
"quantidade_vend_sum_{}": feat_amount_sold,
"valor_vend_sum_{}": feat_value,
}
# These are featu... | _____no_output_____ | MIT | santana/EDA/new_featuresBruno.ipynb | joaopedromattos/DMC2020 |
Train model | full_train = X_full_val_feats.query("group_backwards > 1")
train = X_full_val_feats.query("group_backwards > 2")
val = X_full_val_feats.query("group_backwards == 2")
sub = X_full_val_feats.query("group_backwards == 1")
drop_cols = ["order", "salesPrice"]
x_full_train = full_train.drop(columns=drop_cols)
x_train = trai... | _____no_output_____ | MIT | santana/EDA/new_featuresBruno.ipynb | joaopedromattos/DMC2020 |
from sklearn.metrics import mean_squared_error as mse
def evaluate(prediction, target, simulationPrice):
return np.sum((prediction - np.maximum(prediction - target, 0) * 1.6) * simulationPrice) | _____no_output_____ | MIT | santana/EDA/new_featuresBruno.ipynb | joaopedromattos/DMC2020 | |
- First normal xgb | import xgboost as xgb
xgb.__version__
# custom objective
def gradient(prediction, dtrain):
y = dtrain.get_label()
# prediction.astype(int)
# prediction = np.minimum(prediction.astype(int), 1)
return -2 * (prediction - np.maximum(prediction - y, 0) * 1.6) * (1 - (prediction > y) * 1.6)
def hessian(pred... | _____no_output_____ | MIT | santana/EDA/new_featuresBruno.ipynb | joaopedromattos/DMC2020 |
Plots the pmfs of binomial distributions with varying probability of success parameter | try:
import jax
except:
%pip install jax jaxlib
import jax
import jax.numpy as jnp
try:
import matplotlib.pyplot as plt
except:
%pip install matplotlib
import matplotlib.pyplot as plt
try:
import seaborn as sns
except:
%pip install seaborn
import seaborn as sns
try:
from scipy... | WARNING:absl:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.)
| MIT | notebooks/book1/binom_dist_plot.ipynb | peterchang0414/pyprobml |
DemoYou can see different examples of binomial distributions by changing the theta in the following demo. | from ipywidgets import interact
@interact(theta=(0.1, 0.9))
def generate_random(theta):
n = 10
data = {"x": jnp.arange(0, n + 1), "n": n, "theta": theta}
make_graph(data) | _____no_output_____ | MIT | notebooks/book1/binom_dist_plot.ipynb | peterchang0414/pyprobml |
1 - Step**1.** Looking for missing values. | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#%matplotlib inline
%matplotlib notebook
df = pd.read_csv('./winequality-red.csv')
df_missig_values = df[df.isna() == True].value_counts()
print("Checking if contains missing values: {}".format(len(df_missig_values)))
print("Size: {} rows and ... | _____no_output_____ | FTL | wine-qualty.ipynb | FernandoNici/Write-a-data-science-blog-post |
Dataframe info- Dataframe have 1599 records- Data columns: total 12 columns- There is no missing values- There is no categorical feature 2 - Step**2.** Correlation between the features | import seaborn as sns
%matplotlib inline
plt.subplots(figsize=(10, 8))
sns.heatmap(df.corr(), annot=True, fmt=".3f", linewidths=.5);
# Normalize the dataframe to return proportions rather than frequencies
def normalize_data(dataframe, column, ascending):
'''
Parameters
----------
dataframe: DataFr... | _____no_output_____ | FTL | wine-qualty.ipynb | FernandoNici/Write-a-data-science-blog-post |
3 - Step**3.** Transform into percentage values | def convert_value_into_percentage(fraction_number):
'''
Parameters
----------
fraction_number: float
Number in decimal form
Returns
-------
float
the percentage calculated
'''
return fraction_number * 100
quality_count = normalize_data(df, 'qualit... | _____no_output_____ | FTL | wine-qualty.ipynb | FernandoNici/Write-a-data-science-blog-post |
4 - Step**4.** Looking on alcohol features distribution using box plot | f, ax = plt.subplots(1, 1, figsize=(12, 6))
sns.despine(left=True)
sns.boxplot(x=df['alcohol'])
#sns.boxplot(x=df['citric acid'], ax=ax[1])
#sns.boxplot(x=df['sulphates'], ax=ax[2])
plt.show() | _____no_output_____ | FTL | wine-qualty.ipynb | FernandoNici/Write-a-data-science-blog-post |
5 - Step**5.** Looking the alcohol features distribution bases on quality | sns.catplot(x="quality", y="alcohol", data=df)
plt.show() | _____no_output_____ | FTL | wine-qualty.ipynb | FernandoNici/Write-a-data-science-blog-post |
Diabetes Data AnalysisAll information regarding the features and dataset can be found in this research arcticle:Impact of HbA1c Measurement on Hospital Readmission Rates: Analysis of 70,000 Clinical Database Patient RecordsIn this project we want to know how different features affect diabetes in general.For this kernel... | #import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
# read the file and create a pandas dataframe
data = pd.read_csv('dataset/diabetic_data.csv')
# check the dimensions of the data
data.shape
# first 5 rows of data
data.head() | _____no_output_____ | MIT | Diabetes-Data-Analysis-main/Diabetes Data Analysis.ipynb | Lilasrinivasreddy/NLP_Speech_recog |
we get discriptive statistics of numerical variable | #discribtion of numerical data
data[['time_in_hospital','num_lab_procedures','num_procedures','num_medications',
'number_outpatient','number_emergency','number_inpatient',
'number_diagnoses']].describe()
#no of unique patient
len(np.unique(data['patient_nbr'])) | _____no_output_____ | MIT | Diabetes-Data-Analysis-main/Diabetes Data Analysis.ipynb | Lilasrinivasreddy/NLP_Speech_recog |
+ Remove duplicate recod based on patient_nbr column | #remove duplicate patient recods
data = data.drop_duplicates(subset = 'patient_nbr', keep = 'first') | _____no_output_____ | MIT | Diabetes-Data-Analysis-main/Diabetes Data Analysis.ipynb | Lilasrinivasreddy/NLP_Speech_recog |
+ Plot some column data | # the response variable 'readmitted' in the original dataset contains three categories.
# 11% of patients were readmitted within 30 days (<30)
# 35% of patients were readmitted after 30 days (>30)
# 54% of patients were never readmitted (NO)
data.groupby('readmitted').size().plot(kind='bar')
plt.ylabel('Count')
plt.tit... | _____no_output_____ | MIT | Diabetes-Data-Analysis-main/Diabetes Data Analysis.ipynb | Lilasrinivasreddy/NLP_Speech_recog |
+ Drop unnecessary column from data | # remove irrelevant features
data.drop(['encounter_id','patient_nbr', 'weight', 'payer_code','max_glu_serum','A1Cresult'], axis=1, inplace=True)
# remove rows that have NA in 'race', 'diag_1', 'diag_2', or 'diag_3' and 'gender'
# remove rows that have invalid values in 'gender'
data = data[data['race'] != '?']
data = d... | _____no_output_____ | MIT | Diabetes-Data-Analysis-main/Diabetes Data Analysis.ipynb | Lilasrinivasreddy/NLP_Speech_recog |
> from above graph we see that 60 to 100 age group data is large so we make single group for this | # Recategorize 'age' so that the population is more evenly distributed
data['age'] = pd.Series(['[20-60)' if val in ['[20-30)', '[30-40)', '[40-50)', '[50-60)'] else val
for val in data['age']], index=data.index)
data['age'] = pd.Series(['[60-100)' if val in ['[60-70)','[70-80)','[80-90)', '[9... | _____no_output_____ | MIT | Diabetes-Data-Analysis-main/Diabetes Data Analysis.ipynb | Lilasrinivasreddy/NLP_Speech_recog |
Find Top Features in data | # split X and y into cross-validation (75%) and testing (25%) data sets
from sklearn.model_selection import train_test_split
X_cv, X_test, y_cv, y_test = train_test_split(X, y, test_size=0.25)
# fit Random Forest model to the cross-validation data
from sklearn.ensemble import RandomForestClassifier
forest = RandomFores... | Top 10 features are:
num_lab_procedures
diag_3
diag_2
num_medications
diag_1
comorbidity
time_in_hospital
emergency_visits
acuity_of_admission
medical_specialty
| MIT | Diabetes-Data-Analysis-main/Diabetes Data Analysis.ipynb | Lilasrinivasreddy/NLP_Speech_recog |
Use over sampling method for handle imbalanace data | from imblearn.over_sampling import SMOTE
from sklearn import metrics
from collections import Counter
oversample = SMOTE()
X, y = oversample.fit_resample(X, y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .3) | _____no_output_____ | MIT | Diabetes-Data-Analysis-main/Diabetes Data Analysis.ipynb | Lilasrinivasreddy/NLP_Speech_recog |
Logistic Regession | from sklearn.linear_model import LogisticRegression
clf=LogisticRegression(solver='saga')
clf.fit(X_train, y_train)
print(clf.score(X_test, y_test))
from sklearn.metrics import cohen_kappa_score
y_pred=clf.predict(X_test)
cohen_kappa_score(y_test, y_pred)
#Classification Score
from sklearn.metrics import classification... | precision recall f1-score support
0 0.68 0.71 0.69 7304
1 0.69 0.66 0.67 7238
accuracy 0.68 14542
macro avg 0.68 0.68 0.68 14542
weighted avg 0.68 0.68 0.68 ... | MIT | Diabetes-Data-Analysis-main/Diabetes Data Analysis.ipynb | Lilasrinivasreddy/NLP_Speech_recog |
Random Forest | rf = RandomForestClassifier()
rf.fit(X_train, y_train)
print(rf.score(X_test, y_test))
# cohen kappa score
from sklearn.metrics import cohen_kappa_score
y_pred=rf.predict(X_test)
cohen_kappa_score(y_test, y_pred)
#Classification Score
from sklearn.metrics import classification_report
print(classification_report(y_test... | precision recall f1-score support
0 0.90 0.98 0.94 7304
1 0.97 0.90 0.93 7238
accuracy 0.94 14542
macro avg 0.94 0.94 0.94 14542
weighted avg 0.94 0.94 0.94 ... | MIT | Diabetes-Data-Analysis-main/Diabetes Data Analysis.ipynb | Lilasrinivasreddy/NLP_Speech_recog |
Object Tracking Class | class Tracker:
def __init__(self, maxLost = 30): # maxLost: maximum object lost counted when the object is being tracked
self.nextObjectID = 0 # ID of next object
self.objects = OrderedDict() # stores ID:Locations
self.lost = OrderedDict() ... | _____no_output_____ | MIT | tracking-tensorflow-ssd_mobilenet_v2_coco_2018_03_29.ipynb | chaitanya9807/GuidedVision |
Loading Object Detector Model Tensorflow model for Object Detection and TrackingHere, the SSD Object Detection Model is used.For more details about single shot detection (SSD), refer the following: - **Liu, W., Anguelov, D., Erhan, D., Szegedy, C., Reed, S., Fu, C. Y., & Berg, A. C. (2016, October). Ssd: Single shot ... | model_info = {"config_path":"./tensorflow_model_dir/ssd_mobilenet_v2_coco_2018_03_29.pbtxt",
"model_weights_path":"./tensorflow_model_dir/ssd_mobilenet_v2_coco_2018_03_29/frozen_inference_graph.pb",
"object_names": {0: 'background',
1: 'person', 2: 'bicycle', 3: 'ca... | _____no_output_____ | MIT | tracking-tensorflow-ssd_mobilenet_v2_coco_2018_03_29.ipynb | chaitanya9807/GuidedVision |
Instantiate the Tracker Class | maxLost = 5 # maximum number of object losts counted when the object is being tracked
tracker = Tracker(maxLost = maxLost) | _____no_output_____ | MIT | tracking-tensorflow-ssd_mobilenet_v2_coco_2018_03_29.ipynb | chaitanya9807/GuidedVision |
Initiate opencv video capture objectThe `video_src` can take two values:1. If `video_src=0`: OpenCV accesses the camera connected through USB2. If `video_src='video_file_path'`: OpenCV will access the video file at the given path (can be MP4, AVI, etc format) | video_src = "./data/video_test5.mp4"#0
cap = cv.VideoCapture(video_src) | _____no_output_____ | MIT | tracking-tensorflow-ssd_mobilenet_v2_coco_2018_03_29.ipynb | chaitanya9807/GuidedVision |
Start object detection and tracking | (H, W) = (None, None) # input image height and width for the network
writer = None
while(True):
ok, image = cap.read()
if not ok:
print("Cannot read the video feed.")
break
if W is None or H is None: (H, W) = image.shape[:2]
blob = cv.dnn.blobFromImage(image, size=(3... | Cannot read the video feed.
| MIT | tracking-tensorflow-ssd_mobilenet_v2_coco_2018_03_29.ipynb | chaitanya9807/GuidedVision |
Simulative approach to calculate SIR curves | # set some basic parameters
# beta/gamma is denoted as 'basic reproduction number'
def simulate_SIR(country='Germany'):
N0=1000000 #max susceptible population
beta=0.4 # infection spread dynamics
gamma=0.1 # recovery rate
# condition I0+S0+R0=N0
I0=df_analyse[country][35]
S0=N0-I0
R0=0... | _____no_output_____ | MIT | notebooks/Back_up/SIR_modeling_Working_nested.ipynb | VikasRajashekar/DataScienceProject |
Fitting the parameters of SIR model | # ensure re-initialization
def dynamic_beda_SIR(country='Germany'):
def SIR_model_t(SIR,t,beta,gamma):
''' Simple SIR model
S: susceptible population
t: time step, mandatory for integral.odeint
I: infected people
R: recovered people
beta:
... | /home/vikas/anaconda3/envs/ds/lib/python3.6/site-packages/scipy/integrate/odepack.py:247: ODEintWarning: Excess work done on this call (perhaps wrong Dfun type). Run with full_output = 1 to get quantitative information.
warnings.warn(warning_msg, ODEintWarning)
| MIT | notebooks/Back_up/SIR_modeling_Working_nested.ipynb | VikasRajashekar/DataScienceProject |
Dynamic beta in SIR (infection rate) | def dynamic_beta_SIR(country='Germany'):
t_initial=28
t_intro_measures=14
t_hold=21
t_relax=21
ydata = np.array(df_analyse[country][35:])
I0=ydata[0]
N0=1000000
S0=N0-I0
R0=0
beta_max=0.4
beta_min=0.11
gamma=0.1
pd_beta=np.concatenate((np.array(t_initial*[beta_max])... | _____no_output_____ | MIT | notebooks/Back_up/SIR_modeling_Working_nested.ipynb | VikasRajashekar/DataScienceProject |
Step 2: Create Job Submission ScriptThe next step is to create our job submission script. In the cell below, you will need to complete the job submission script and run the cell to generate the file using the magic `%%writefile` command. Your main task is to complete the following items of the script:* Create a variab... | %%writefile queue_job.sh
#!/bin/bash
exec 1>/output/stdout.log 2>/output/stderr.log
model=args.model
device=args.device
video_file=args.video
max_people=args.max_people
threshold=args.threshold
output_path=args.output_path
# TODO: Create MODEL variable
MODEL=$2
# TODO: Create DEVICE variable
... | _____no_output_____ | MIT | Create_Job_Submission_Script.ipynb | aboussetta/deploy-ai-edge-iot-smart-queuing-system-app |
Import model, training function | def plot_learning_curve_points(sizes, errors, label='None', linestyle='-', color='k', marker='.', linewidth=2):
'''
Plots the learning curve.
Inputs:
sizes : list, int
List of traning dataset sizes
errors : list, float
List of final errors for some metric
... | _____no_output_____ | BSD-3-Clause | examples/source-interdiction/results-notebooks/Learning-Curves.ipynb | arfc/annsa |
All models Full | plt.figure(figsize=(10,5))
matplotlib.rcParams.update({'font.size': 22})
dataset_modes = ['test', 'train']
models = [
'dnn',
'cnn',
'caednn',
'daednn',
]
model_modes = ['full']
train_sizes = [
'50',
'100',
'500',
'1000',
'5000',
'10000',
'15000',
'20000',
]
errors_al... | test_dnn 0.74
train_dnn 0.76
test_cnn 0.88
train_cnn 0.93
test_caednn 0.89
train_caednn 0.94
test_daednn 0.74
train_daednn 0.76
| BSD-3-Clause | examples/source-interdiction/results-notebooks/Learning-Curves.ipynb | arfc/annsa |
All models Easy | plt.figure(figsize=(10,5))
dataset_modes = ['test', 'train']
models = [
'dnn',
'cnn',
'caednn',
'daednn',
]
model_modes = ['easy']
train_sizes = [
'50',
'100',
'500',
'1000',
'5000',
'10000',
'15000',
'20000',
]
for model, model_mode, dataset_mode in product (model... | test_dnn 0.88
train_dnn 0.87
test_cnn 0.98
train_cnn 0.98
test_caednn 0.97
train_caednn 0.98
test_daednn 0.82
train_daednn 0.81
| BSD-3-Clause | examples/source-interdiction/results-notebooks/Learning-Curves.ipynb | arfc/annsa |
Exercises 9. Adjust the learning rate. Try a value of 0.02. Does it make a difference?** Solution **This is the simplest exercise and you have do that before. Find the line: optimize = tf.train.AdamOptimizer(learning_rate=0.001).minimize(mean_loss) And change the learning_rate to 0.02.While Adam adapts to the p... | import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# TensorFLow includes a data provider for MNIST that we'll use.
# This function automatically downloads the MNIST dataset to the chosen directory.
# The dataset is already split into training, validation, and test su... | Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
| MIT | course_2/course_material/Part_7_Deep_Learning/S54_L390/9. TensorFlow_MNIST_Learning_rate_Part_2_Solution.ipynb | Alexander-Meldrum/learning-data-science |
Outline the modelThe whole code is in one cell, so you can simply rerun this cell (instead of the whole notebook) and train a new model.The tf.reset_default_graph() function takes care of clearing the old parameters. From there on, a completely new training starts. | input_size = 784
output_size = 10
# Use same hidden layer size for both hidden layers. Not a necessity.
hidden_layer_size = 50
# Reset any variables left in memory from previous runs.
tf.reset_default_graph()
# As in the previous example - declare placeholders where the data will be fed into.
inputs = tf.placeholder(... | Epoch 1. Mean loss: 0.284. Validation loss: 0.213. Validation accuracy: 94.28%
Epoch 2. Mean loss: 0.195. Validation loss: 0.182. Validation accuracy: 95.14%
Epoch 3. Mean loss: 0.169. Validation loss: 0.167. Validation accuracy: 95.64%
Epoch 4. Mean loss: 0.161. Validation loss: 0.166. Validation accuracy: 95.88%
Epoc... | MIT | course_2/course_material/Part_7_Deep_Learning/S54_L390/9. TensorFlow_MNIST_Learning_rate_Part_2_Solution.ipynb | Alexander-Meldrum/learning-data-science |
Test the modelAs we discussed in the lectures, after training on the training and validation sets, we test the final prediction power of our model by running it on the test dataset that the algorithm has not seen before.It is very important to realize that fiddling with the hyperparameters overfits the validation data... | input_batch, target_batch = mnist.test.next_batch(mnist.test._num_examples)
test_accuracy = sess.run([accuracy],
feed_dict={inputs: input_batch, targets: target_batch})
# Test accuracy is a list with 1 value, so we want to extract the value from it, using x[0]
# Uncomment the print to see how it looks before the ... | Test accuracy: 95.68%
| MIT | course_2/course_material/Part_7_Deep_Learning/S54_L390/9. TensorFlow_MNIST_Learning_rate_Part_2_Solution.ipynb | Alexander-Meldrum/learning-data-science |
The Core Language of Python: Part 3 For Loops and List Comprehensions A `for` loop can **iterate** over a list or tuple, performing calculations for each item in the sequence. Like `if` statements, `for` loops require a **colon** to terminate the first line and consistent **indentation** (typically four spaces) belo... | my_list = [0, 1, 2, 3, 4, 5]
# print the square of each item in my_list
# - colon and indentation are important!
for i in my_list:
print(i**2) | 0
1
4
9
16
25
| CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
Be careful what name you give the iterator variable, since its value will be overwritten again and again with the items in the sequence. If the variable had a value before the `for` loop, it will be lost, which may not be what you intended. | i = 'abc'
print(f'i at the start = {i}')
for i in my_list:
print(i**2)
print(f'i at the end = {i}') | i at the start = abc
0
1
4
9
16
25
i at the end = 5
| CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
If you wanted to store a result from each step of the `for` loop in another list, one way you could do it is1. Initialize another variable as an empty list (`another_list = []`), and then2. Append a result to the new list in each step (`another_list.append`).For example: | another_list = []
for i in my_list:
another_list.append(i**2)
another_list | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
If the calculation of the result (in this example, squaring `i`) is fairly simple, you can perform the same work using a more concise notation called **list comprehension**. The simplest version of list comprehension takes the form `[f(i) for i in my_list]`, where `f(i)` is some function or transformation of the list i... | # basic list comprehension
# - this means "square the item for each item in my_list"
another_list = [i**2 for i in my_list]
another_list | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
All of the work is completed in a single line of code. Elegant!List comprehensions can be more complex than this. Suppose we modified the `for` loop to append a result only if the list item is an even number (`i % 2 == 0` means that `i` divided by 2 must have a remainder of 0): | another_list = []
for i in my_list:
if i % 2 == 0:
# append only if i is even
another_list.append(i**2)
# the squares of 0, 2, 4
another_list | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
To do this with list comprehension, just add `if i % 2 == 0` to the end: | # list comprehension with conditional
# - this means "square the item for each item in my_list if it is even (otherwise skip it)"
another_list = [i**2 for i in my_list if i % 2 == 0]
another_list | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
Suppose we modify the `for` loop further to perform a different calculation if the list item is an odd number: | another_list = []
for i in my_list:
if i % 2 == 0:
# square if i is even
another_list.append(i**2)
else:
# add 100 if i is odd
another_list.append(i+100)
another_list | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
This can be done with list comprehension by moving the `if i % 2 == 0` to an earlier position, just after `i**2`, and adding `else i+100`: | # list comprehension with complex conditional
# - this means "square the item if it is even, otherwise add 100 to it, for each item in my_list"
another_list = [i**2 if i%2==0 else i+100 for i in my_list]
another_list | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
The results stored in `another_list` could be something other than a calculation using `i`. For example, strings: | # this means "store the string 'less than 2' if the item is less than 2, otherwise store '2 or greater', for each item in my_list"
another_list = ['less than 2' if i < 2 else '2 or greater' for i in my_list]
another_list | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
While Loops A `while` loop is another way to repeatedly perform calculations. Whereas `for` loops execute code for each item in a sequence, `while` loops execute code for as long as a condition is true. For example: | x = 0
while x < 5:
print(x)
x = x + 1
print(f'final value of x = {x}') | 0
1
2
3
4
final value of x = 5
| CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
Generally, this means that the code within the `while` loop should take steps toward making the condition no longer true, even if it is unknown ahead of time how many steps that may require. In the simple example above, `x` was incremented each step until `x` was no longer less than 5. A more practical example would be... | # this will run forever until interrupted!
x = 0
while x < 5:
pass # do nothing | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
Dictionaries Dictionaries are another important data type in Python. Dictionaries store **key-value pairs**, where each piece of data (the **value**) is assigned a name (the **key**) for easy access.Dictionaries are created using curly braces (`{}`). (This is different from the use of curly braces in f-strings!) Insid... | # create a new dictionary using curly braces {}
my_dict = {'genus': 'Aplysia', 'species': 'californica', 'mass': 150}
my_dict | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
The syntax for extracting a piece of data from a dictionary is similar to indexing into lists. It uses square brackets after the dictionary name (not curly braces like you might guess), but instead of a number indicating position, a key should be provided. | # select items by key
my_dict['species'] | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
Like changing the value of an item in a list via its index, the value of an item in a dictionary can be changed via its key: | # change values by key
my_dict['mass'] = 300
my_dict | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
New key-value pairs can be added to a dictionary the same way. In fact, you can start with an empty dictionary and build it up one key-value pair at a time: | my_dict2 = {}
my_dict2['genus'] = 'Aplysia'
my_dict2['species'] = 'californica'
my_dict2['mass'] = 300
my_dict2 | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
Values can have any data type. Most basic data types are valid for keys too, but an important exception is lists: **lists are not allowed to be dictionary keys**. Tuples, on the other hand, are allowed to be keys. This is because keys must be immutable (uneditable), which is a property that tuples have but lists do not... | # lists cannot be keys, so this is NOT allowed
# - the error "unhashable type" is a consequence of the fact that lists are not immutable (they can be changed)
my_dict2[['x', 'y', 'z']] = [1, 2, 3]
# tuples can be keys, so this IS allowed
my_dict2[('x', 'y', 'z')] = [1, 2, 3]
my_dict2 | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
You can delete a key-value pair from a dictionary using the `del` keyword: | del my_dict2['species']
my_dict2 | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
As a matter of fact, **`del` is how you unset any variable**: | del my_dict2
# now my_dict2 is not defined
my_dict2 | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
Just like lists and tuples, `for` loops can iterate over a dictionary. In its simplest form, this actually iterates over the dictionary's keys. In the example below, we choose to use the name `k`, rather than `i`, for the temporary variable to reflect this. To access the value associated with key `k`, we must use `my_d... | # iterate over keys
for k in my_dict:
print(f'key: {k} --> value: {my_dict[k]}') | key: genus --> value: Aplysia
key: species --> value: californica
key: mass --> value: 300
| CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
The dictionary method `items()` returns a (special type of) list of tuples, where each tuple is a key-value pair: | # using list() here to simplify how the list of tuples is displayed
list(my_dict.items()) | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
When using a `for` loop to iterate over any list of tuples (or a list of lists, or a tuple of lists, or a tuple of tuples...) such as this, you can assign a temporary variable name to each item in the inner tuple/list. This is an example of what is called **unpacking**. For example: | list_of_tuples = [
('a', 1),
('b', 2),
('c', 3),
]
for (letter, number) in list_of_tuples:
print(letter, number) | a 1
b 2
c 3
| CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
In the example above, the parentheses around the iterator variables `(letter, number)` are actually optional, so the loop could be written without them: | for letter, number in list_of_tuples:
print(letter, number) | a 1
b 2
c 3
| CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
Using the list of tuples produced by `my_dict.items()` and unpacking each key-value tuple into `k,v`, we can write the `for` loop this way: | # iterate over key-value pairs
for k,v in my_dict.items():
print(f'key: {k} --> value: {v}') | key: genus --> value: Aplysia
key: species --> value: californica
key: mass --> value: 300
| CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
Notice this does exactly the same thing as```pythonfor k in my_dict: print(f'key: {k} --> value: {my_dict[k]}')```seen earlier, except the version using `for k,v in my_dict.items()` conveniently assigns the name `v` to the value of each key-value pair, so that `my_dict[k]` does not need to be typed out.Like list com... | my_list = [0, 1, 2, 3, 4, 5]
squares = {}
for i in my_list:
# store keys as strings and values as integers
squares[str(i)] = i**2
squares | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
Here is a dictionary comprehension that does the same thing. Note it is enclosed with curly braces because it produces a dictionary, and a colon separates a key and its value. | # basic dictionary comprehension
# - this means "pair a string version of the item with its square for each item in my_list"
squares = {str(i): i**2 for i in my_list}
squares | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
Like list comprehension, conditionals are allowed for the values: | # dictionary comprehension with complex conditional
# - this means "pair a string version of the item with its square if it is even, otherwise with the item plus 100, for each item in my_list"
squares = {str(i): i**2 if i%2==0 else i+100 for i in my_list}
squares | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
A Practical Example for Dictionaries and Comprehensions So how are dictionaries useful? There are countless ways, but let's look at one example. Previously we saw in the section titled "Lists vs. Tuples" that a list of tuples with consistent structure is useful because pieces of data have predictable indices. For exam... | species_data = [
# genus, species, date named, common name
('Aplysia', 'californica', 1863, 'California sea hare'),
('Macrocystis', 'pyrifera', 1820, 'Giant kelp'),
('Pagurus', 'samuelis', 1857, 'Blueband hermit crab'),
]
# print every genus
for sp in species_data:
print(sp[0]) | Aplysia
Macrocystis
Pagurus
| CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
However, this approach requires that we memorize the meaning of each index (0 = genus, 1 = species, etc.). If we use dictionaries instead of tuples, we can access data by name, rather than arbitrary indices. To do this, we could convert every tuple into a dictionary, so that the whole data set is a list of dictionaries... | species_dicts = [
{'genus': 'Aplysia', 'species': 'californica', 'year': 1863, 'common': 'California sea hare'},
{'genus': 'Macrocystis', 'species': 'pyrifera', 'year': 1820, 'common': 'Giant kelp'},
{'genus': 'Pagurus', 'species': 'samuelis', 'year': 1857, 'common': 'Blueband hermit crab'},
] | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
However, if the `species_data` list already existed and was much longer than it is here, this would be a lot of extra work!Instead, we could use what we have learned to programmatically construct the list of dictionaries from the existing list of tuples using a `for` loop. Here's one way to do that which uses tuple unp... | # create a new empty list
species_dicts = []
# for each tuple, unpack the 4 pieces of data into 4 temporary variables
for genus, species, year, common in species_data:
# build a new dictionary for this species
d = {'genus': genus, 'species': species, 'year': year, 'common': common}
# append the dictionar... | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
Now the genus of every entry can be accessed using the key `'genus'` rather than index 0: | # print every genus
for sp in species_dicts:
print(sp['genus']) | Aplysia
Macrocystis
Pagurus
| CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
If we want to be *really* clever, we can do the entire conversion in a single step by *constructing a dictionary inside a list comprehension*. For this, we need to first introduce another built-in function.The `zip()` function takes two or more sequences (e.g., lists or tuples) as inputs and groups the elements from ea... | list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
# using list() here to simplify how the result is displayed
list(zip(list1, list2)) | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
How can we use `zip()` to help us convert our list of tuples into a list of dictionaries? First, define a variable containing the dictionary keys: | keys = ('genus', 'species', 'year', 'common') | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
With this, it is possible to pair the values from one of the tuples with these keys. For example, if we just look at the first tuple: | values = species_data[0]
list(zip(keys, values)) | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
Here we have a list of tuples, where each tuple is a key-value pair. This is just like what the `items()` function returns for a dictionary. From this, we could construct a dictionary from this first tuple using dictionary comprehension: | {k:v for k,v in zip(keys, values)} | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
Equivalently, because there is no extra manipulation of `k` or `v` here, we could use the built-in function `dict()` to convert the list of key-value pairs directly into a dictionary: | dict(zip(keys, values)) | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
All we have to do now is generalize this to all tuples in `species_data`. We can use a list comprehension for this, which gives us the final expression that does the entire conversion in one step, from a list of tuples to a list of dictionaries: | keys = ('genus', 'species', 'year', 'common')
species_dicts = [dict(zip(keys, values)) for values in species_data]
species_dicts | _____no_output_____ | CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
This is much more elegant than writing out the list of dictionaries by hand!As a final proof of success, we can once again access the genus of every entry using a key: | # print every genus
for sp in species_dicts:
print(sp['genus']) | Aplysia
Macrocystis
Pagurus
| CC-BY-4.0 | notebooks/02.3-The-Core-Language-of-Python.ipynb | jpgill86/python-for-neuroscientists |
A glimpse into the inner working of a 2 layer Neural network | %load_ext autoreload
%autoreload 2
import numpy as np
from numpy import random as nprand
from cs771 import plotData as pd, utils, genSyntheticData as gsd
from keras.models import Sequential
from keras.layers import Dense as dense
from keras import optimizers
d = 2
n = 20
r = 2
tmp1 = gsd.genSphericalData( d, n, [-5, ... | [array([[ 8.140034 , 6.2257695],
[-8.022345 , -6.2070103]], dtype=float32), array([ 7.6521316, -6.4985967], dtype=float32)]
[array([[ 7.7717934],
[-8.765444 ]], dtype=float32), array([-3.4945343], dtype=float32)]
| MIT | lecture_code/20_Deep Learning.ipynb | alokranjan1802/ml19-20w |
Prepared by Abuzer Yakaryilmaz and Maksim Dimitrijev Özlem Salehi | December 4, 2019 (updated) This cell contains some macros. If there is a problem with displaying mathematical formulas, please run this cell to load these macros. $ \newcommand{\bra}[1]{\langle 1|} $... | # draw the circuit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
qreg1 = QuantumRegister(2)
creg1 = ClassicalRegister(2)
mycircuit1 = QuantumCircuit(qreg1,creg1)
mycircuit1.cx(qreg1[1],qreg1[0])
job = execute(mycircuit1,Aer.get_backend('unitary_simulator'))
u=job.result().get... | 1.0 0.0 0.0 0.0
0.0 1.0 0.0 0.0
0.0 0.0 0.0 1.0
0.0 0.0 1.0 0.0
| MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
Now, let's apply CNOT to the states $ \ket{00}, \ket{01}, \ket{10}, \ket{11} $ iteratively where qreg[1] is the control and qreg[0] is the target. | # import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_inputs=['00','01','10','11']
for input in all_inputs:
qreg2 = QuantumRegister(2) # quantum register with 2 qubits
creg2 = ClassicalRegister(2) # classical re... | our input is 00 : 00 is observed 100 times
our input is 01 : 01 is observed 100 times
our input is 10 : 11 is observed 100 times
our input is 11 : 10 is observed 100 times
| MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
Task 1Our task is to learn the behavior of the following quantum circuit by doing experiments.Our circuit has two qubits. Apply Hadamard to both qubits. Apply CNOT(qreg[1] is the control,qreg[0] is the target). Apply Hadamard to both qubits. Measure the circuit.Iteratively initialize the qubits to $ \... | # import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
#
# your code is here
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_inputs=['00','01','10','11']
for input in all_inputs:
q... | our input is 00 : 00 is observed 100 times
our input is 01 : 11 is observed 100 times
our input is 10 : 10 is observed 100 times
our input is 11 : 01 is observed 100 times
| MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
click for our solution Task 2Our task is to learn the behavior of the following quantum circuit by doing experiments.Our circuit has two qubits. Apply CNOT(qreg[1] is the control, qreg[0] is the target). Apply CNOT(qreg[0] is the control, qreg[1] is the target). Apply CNOT(qreg[0] is the control, qreg[1] i... | # import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
#
# your code is here
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_inputs=['00','01','10','11']
for input in all_inputs:
q... | our input is 00 : 00 is observed 100 times
our input is 01 : 01 is observed 100 times
our input is 10 : 11 is observed 100 times
our input is 11 : 10 is observed 100 times
| MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
click for our solution Task 3 [Extra] Create a quantum curcuit with $ n=5 $ qubits.Set each qubit to $ \ket{1} $.Repeat 4 times: Randomly pick a pair of qubits, and apply cx-gate (CNOT operator) on the pair.Draw your circuit, and execute your program 100 times.Verify your measurement results by checking the diagram... | # import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# import randrange for random choices
from random import randrange
#
# your code is here
#
| _____no_output_____ | MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
click for our solution Task 4 In this task, our aim is to create an operator which will apply the NOT operator to the target qubit qreg[0] when the control qubit qreg[1] is in state $\ket{0}$. In other words, we want to obtain the following operator:$\mymatrix{cccc}{0 & 1 & 0 & 0 \\ 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0... | def c0x(mycircuit,qreg):
#
# Your code here
#
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
qreg4 = QuantumRegister(2)
creg4 = ClassicalRegister(2)
mycircuit4 = QuantumCircuit(qreg4,creg4)
#We apply the operator c0x by calling the function
c0x(mycircuit4,qreg4)
job = execute(... | _____no_output_____ | MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
click for our solution CCNOTNow we will discuss CNOT gate controlled by two qubits (also called the Toffoli gate). The idea behind this gate is simple - NOT operator is applied to the target qubit when both control qubits are in state $\ket{1}$. Below you can see its matrix representation:$\mymatrix{cccccccc}{1 & 0 & 0... | # import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_inputs=['000','001','010','011','100','101','110','111']
for input in all_inputs:
qreg3 = QuantumRegister(3) # quantum register with 3 qubits
creg3 = Classic... | our input is 000 : 000 is observed 100 times
our input is 001 : 001 is observed 100 times
our input is 010 : 010 is observed 100 times
our input is 011 : 011 is observed 100 times
our input is 100 : 100 is observed 100 times
our input is 101 : 101 is observed 100 times
our input is 110 : 111 is observed 100 time... | MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
Recall Task 4. Similarly, we can create an operator which applies NOT operator to a target qubit, controlled by two qubits which are in states different than 1. For example, the following implementation allows to apply NOT operator to the target qubit if both control qubits are in state $\ket{0}$. The matrix form of th... | def cc0x(mycircuit,qreg):
mycircuit.x(qreg[2])
mycircuit.x(qreg[1])
mycircuit.ccx(qreg[2],qreg[1],qreg[0])
# Returning control qubits to the initial state
mycircuit.x(qreg[1])
mycircuit.x(qreg[2])
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
qreg4 = Qu... | 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0
1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0 0... | MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
Task 5You have a circuit with three qubits. Apply NOT operator to qreg[1] if qreg[0] is in state 0 and qreg[2] is in state 1. Check its efffect on different inputs. | from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_inputs=['000','001','010','011','100','101','110','111']
for input in all_inputs:
qreg5 = QuantumRegister(3) # quantum register with 3 qubits
creg5 = ClassicalRegister(3) # classical register with 3 bits
mycircuit5 = ... | our input is 000 : 000 is observed 100 times
our input is 001 : 001 is observed 100 times
our input is 010 : 010 is observed 100 times
our input is 011 : 011 is observed 100 times
our input is 100 : 110 is observed 100 times
our input is 101 : 101 is observed 100 times
our input is 110 : 100 is observed 100 time... | MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
click for our solution More controlsSuppose that you are given ccx operator which applies a not operator controlled by two qubits. You can use additional qubits to implement a not operator controlled by more than two qubits.The following code implements a NOT operator controlled by the three qubits qreg[1], qreg[2] and... | def cccx(mycircuit,qreg):
#qreg[4] is set to 1 if qreg[1] and qreg[2] are 1
mycircuit.ccx(qreg[1],qreg[2],qreg[4])
#NOT operator is applied to qreg[0] if all three qubits are 1
mycircuit5.ccx(qreg[3],qreg[4],qreg[0])
#We set back qreg[4] back to its initial value
mycircuit5.ccx(qreg[1... | our input is 0000 : 00000 is observed 100 times
our input is 0001 : 00001 is observed 100 times
our input is 0010 : 00010 is observed 100 times
our input is 0011 : 00011 is observed 100 times
our input is 0100 : 00100 is observed 100 times
our input is 0101 : 00101 is observed 100 times
our input is 0110 : 00110... | MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
Task 6Implement the NOT operator controlled by 4 qubits where qreg[0] is the target and apply it iteratively to all possible states. Note that you will need additional qubits. | def ccccx(mycircuit,qreg):
#
#Your code here
mycircuit.ccx(qreg[4],qreg[3],qreg[5])
mycircuit.ccx(qreg[2],qreg[1],qreg[6])
mycircuit.ccx(qreg[5],qreg[6],qreg[0])
# Returning additional qubits to the initial state
mycircuit.ccx(qreg[2],qreg[1],qreg[6])
mycircuit.ccx(qreg[4],qreg[3]... | our input is 00000 : 0000000 is observed 10000 times
our input is 00001 : 0000001 is observed 10000 times
our input is 00010 : 0000010 is observed 10000 times
our input is 00011 : 0000011 is observed 10000 times
our input is 00100 : 0000100 is observed 10000 times
our input is 00101 : 0000101 is observed 10000 ti... | MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
click for our solution Task 7Implement the following control: the NOT operator is applied to the target qubit qreg[0] if 5 control qubits qreg[5] to qreg[1] are initially in the state $\ket{10101}$. Check your operator by trying different initial states. You may define a function or write your code directly. | # import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
#Try different initial states
all_inputs=['101010','101011','100000','111111']
for input in all_inputs:
qreg7 = QuantumRegister(9) # quantum register with 9 qubits
... | _____no_output_____ | MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
click for our solution Task 8 (Optional)Implement the parametrized controlled NOT operator with 4 control qubits, where parameter will be the state of control qubits for which NOT operator will be applied to the target qubit.As a result you need to define the following function: control(circuit,quantum_reg,number), whe... | #state - the state of control qubits, between 0 and 15.
def control(circuit,quantum_reg,state):
#
# your code is here
# | _____no_output_____ | MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
You can try different inputs to see that your function is implementing the mentioned control operation. | #Try different initial states
all_inputs=['01010','01011','10000','11111']
for input in all_inputs:
qreg8 = QuantumRegister(7) # quantum register with 7 qubits
creg8 = ClassicalRegister(7) # classical register with 7 bits
mycircuit8 = QuantumCircuit(qreg8,creg8) # quantum circuit with quantum and classica... | _____no_output_____ | MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
click for our solution Multi-controlled Not Gate In Qiskit there is a multi-controlled not gate, known as the multi controlled Toffoli gate. It is represented by mct. circuit.mct(control_list,target_qubit,ancilla_list) x-gate (NOT operator) is applied to the target qubit CONTROLLED by the list of control qubits us... | # import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_inputs=['11110','11111']
for input in all_inputs:
qreg = QuantumRegister(7) # quantum register with 7 qubits
creg = ClassicalRegister(7) # classical register... | our input is 11110 : 0011111 is observed 100 times
our input is 11111 : 0011110 is observed 100 times
| MIT | bronze/B39_Controlled_Operations.ipynb | HasanIjaz-HB/Quantum-Computing |
Neuromatch Academy: Week 3, Day 2, Tutorial 1 Neuronal Network Dynamics: Neural Rate Models BackgroundThe brain is a complex system, not because it is composed of a large number of diverse types of neurons, but mainly because of how neurons are connected to each other. The brain is a very large network of densely in... | # Imports
import matplotlib.pyplot as plt # import matplotlib
import numpy as np # import numpy
import scipy.optimize as opt # import root-finding algorithm
import ipywidgets as widgets # interactive display
#@title Figure Settings
%matplotlib inline
fig_w, fig_h = 6, 4
my_fontsize = 16
... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/course-content |
Neuronal network dynamics | #@title Video: Dynamic networks
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="ZSsAaeaG9ZM", 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=ZSsAaeaG9ZM
| CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/course-content |
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 different network parameter... | #@title Default parameters for a single excitatory population model
def default_parsE( **kwargs):
pars = {}
### Excitatory parameters ###
pars['tau_E'] = 1. # Timescale of the E population [ms]
pars['a_E'] = 1.2 # Gain of the E population
pars['theta_E'] = 2.8 # Threshold of the E population
... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/course-content |
You can use:- `pars = default_parsE()` to get all the parameters, and then you can execute `print(pars)` to check these parameters. - `pars = default_parsE(T=T_sim, dt=time_step)` to set new simulation time and time step- After `pars = default_parsE()`, use `pars['New_para'] = value` to add an new parameter with its va... | # Excercise 1
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
"""
#########################... | findfont: Font family ['xkcd', 'xkcd Script', 'Humor Sans', 'Comic Neue', 'Comic Sans MS'] not found. Falling back to DejaVu Sans.
| CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/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 F-I curve Explorer
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 range of input
x = np.arange(0,10,.1)
plt.figure()
... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/course-content |
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 using the Eul... | #@title E population simulator: `simulate_E`
def simulate_E(pars):
"""
Simulate an excitatory population of neurons
Args:
pars : Parameter dictionary
Returns:
E : Activity of excitatory population (array)
"""
# Set parameters
tau_E, a_E, theta_E = pars['tau_E'], pars['a_E'], pars... | Help on function simulate_E in module __main__:
simulate_E(pars)
Simulate an excitatory population of neurons
Args:
pars : Parameter dictionary
Returns:
E : Activity of excitatory population (array)
None
| CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/course-content |
Interactive Demo: Parameter Exploration of single population dynamicsNote that $w_{EE}=0$, as in the default setting, means no recurrent input to the excitatory population in Equation (1). Hence, the dynamics is entirely determined by the external input $I_{E}^{\text{ext}}$. Try to explore how $E_{sim}(t)$ changes wit... | #@title Mean-field model Explorer
# get default parameters
pars = default_parsE(T=20.)
def Myplot_E_diffI_difftau(I_ext, tau_E):
# set external input and time constant
pars['I_ext_E'] = I_ext
pars['tau_E'] = tau_E
# simulation
E = simulate_E(pars)
# Analytical Solution
E_ana = pars['E_init'] + (F(I_... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/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, $E(t)$ either decays to zero or reaches a fixed non-zero value.- Why doesn't the solution of the system "e... | #@title Video: Fixed point
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="B31fX6V0PZ4", 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=B31fX6V0PZ4
| CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/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
def my_fpE(pars, E_init):
# get the parameters
a_E, theta_E = pars['a_E'], pars['theta_E']
wEE = pars['wEE']
I_ext_E = pars['I_ext_E']
# define the right hand of E dynamics
def my_WCr(x):
E = x[0]
dEdt=(-E + F(wEE*E+I_ext_E,a_E,theta_E))
y = np... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/course-content |
Exercise 2: Visualization of the fixed pointWhen no analytical solution of Equation $3$ can be found, it is often useful to plot $\displaystyle{\frac{dE}{dt}=0}$ as a function of $E$. The values of E for which the plotted function crosses zero on the y axis correspond to fixed points. Here, let us, for example, set $w... | # Exercise 2
pars = default_parsE() # get default parameters
# set your external input and wEE
pars['I_ext_E'] = 0.5
pars['wEE'] = 5.0
E_grid = np.linspace(0, 1., 1000)# give E_grid
#figure, line (E, dEdt)
###############################
## TODO for students: #
## Calculate dEdt = -E + F(.) #
## Then plot th... | findfont: Font family ['xkcd', 'xkcd Script', 'Humor Sans', 'Comic Neue', 'Comic Sans MS'] not found. Falling back to DejaVu Sans.
| CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/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_{\text{EE}}$ and the external input $I_E^{\text{ext}}$ take different values. | #@title Fixed point Explorer
def plot_intersection_E(wEE, I_ext_E):
#set your parameters
pars['wEE'] = wEE
pars['I_ext_E'] = I_ext_E
#note that wEE !=0
if wEE>0:
# find fixed point
x_fp_1 = my_fpE(pars, 0.)
x_fp_2 = my_fpE(pars, 0.4)
x_fp_3 = my_fpE(pars, 0.9)
plt.figure()
E_grid = ... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/course-content |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.