Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
14,200
Given the following text description, write Python code to implement the functionality described below step by step Description: Bidirectional LSTM on IMDB Author Step1: Build the model Step2: Load the IMDB movie review sentiment data Step3: Train and evaluate the model You can use the trained model hosted on Huggi...
Python Code: import numpy as np from tensorflow import keras from tensorflow.keras import layers max_features = 20000 # Only consider the top 20k words maxlen = 200 # Only consider the first 200 words of each movie review Explanation: Bidirectional LSTM on IMDB Author: fchollet<br> Date created: 2020/05/03<br> Last m...
14,201
Given the following text description, write Python code to implement the functionality described below step by step Description: Images Images are just arrays of data, where the data tells us the colors in the image. It will get a little more complicated than this, as we'll see below, but this is the general idea. Sin...
Python Code: import requests # from webscraping import numpy as np %matplotlib inline import matplotlib.pyplot as plt import matplotlib import cmocean import cartopy from PIL import Image # this is the pillow package from skimage import color from scipy import ndimage from io import BytesIO Explanation: Images Images...
14,202
Given the following text description, write Python code to implement the functionality described. Description: Program to find the largest and smallest ASCII valued characters in a string Function that return the largest alphabet ; Initializing max alphabet to 'a ; Find largest alphabet ; Returning largest element ; Fu...
Python Code: def largest_alphabet(a , n ) : ' max = ' A ' for i in range(n ) : if(a[i ] > max ) : max = a[i ]   return max  def smallest_alphabet(a , n ) : ' min = ' z ' ; for i in range(n - 1 ) : if(a[i ] < min ) : min = a[i ]   return min  if __name__== ' __main __' : a = "G...
14,203
Given the following text description, write Python code to implement the functionality described below step by step Description: From scratch Step1: Term frequencies Term frequency indicates how often each word appears in the document. The intuition for including term frequency in the tf-idf calculation is that the m...
Python Code: import pandas as pd import numpy as np Explanation: From scratch End of explanation from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer() term_frequencies = vectorizer.fit_transform(corpus_cleaned).toarray() term_frequencies # Visualize term_frequencies df_tf = pd...
14,204
Given the following text description, write Python code to implement the functionality described below step by step Description: GA Python Here is a simple example of using a GA in Python using PyOptSparse and my wrapper available here. Step1: Here is where we define the problem and choose an optimizer. Various opti...
Python Code: def rosen(x): f = (1 - x[0])**2 + 100*(x[1] - x[0]**2)**2 c = [] return f, c Explanation: GA Python Here is a simple example of using a GA in Python using PyOptSparse and my wrapper available here. End of explanation from pyoptsparse import NSGA2 # choose optimizer and define options optimizer ...
14,205
Given the following text description, write Python code to implement the functionality described below step by step Description: Embedded Actions in <span style="font-variant Step1: The grammar shown above has no semantic actions (with the exception of the skip action). We extend this grammar now with semantic actio...
Python Code: !cat -n Program.g4 Explanation: Embedded Actions in <span style="font-variant:small-caps;">Antlr</span> Grammars The pure grammar is stored in the file Grammar.g4. End of explanation !cat -n Calculator.g4 Explanation: The grammar shown above has no semantic actions (with the exception of the skip action). ...
14,206
Given the following text description, write Python code to implement the functionality described below step by step Description: Imports Step1: Configuration Step2: Read images and labels [WORK REQUIRED] Use fileset=tf.data.Dataset.list_files to scan the data folder Iterate through the dataset of filenames Step3: U...
Python Code: import os, sys, math import numpy as np from matplotlib import pyplot as plt if 'google.colab' in sys.modules: # Colab-only Tensorflow version selector %tensorflow_version 2.x import tensorflow as tf print("Tensorflow version " + tf.__version__) #@title "display utilities [RUN ME]" def display_9_images_f...
14,207
Given the following text description, write Python code to implement the functionality described below step by step Description: CTA AEFF interpolation There was a report of possible bugs with CTA DC-1 AEFF interpolation via email. In this notebook we have a quick look. As far as I can see, everything is as expected a...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import astropy.units as u from astropy.table import Table from gammapy.irf import EffectiveAreaTable2D Explanation: CTA AEFF interpolation There was a report of possible bugs with CTA DC-1 AEFF interpolation via email. In this notebook ...
14,208
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmos MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cas', 'fgoals-f3-l', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: CAS Source ID: FGOALS-F3-L Topic: Atmos Sub-Topics: Dynamical Core, Radiatio...
14,209
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">Authorship Attribution using Machine Learning </h1> <img src="images/title.png" height="233" width="500"> Overview and Motivation The objective of this project is to inves...
Python Code: %matplotlib inline import sys import re import os import csv import codecs import string import json import boto import pattern import pandas as pd import seaborn as sns import numpy as np import scipy as sp import nltk as nl import matplotlib as mpl import matplotlib.cm as cm import matplotlib.pyplot as p...
14,210
Given the following text description, write Python code to implement the functionality described below step by step Description: Randomization In the previous chapter, we saw how randomization eliminates selection bias. Let's explain what we mean by randomization, describe several ways we might want to randomly assign...
Python Code: import numpy as np n, p = 10, 0.5 np.random.binomial(n, p) Explanation: Randomization In the previous chapter, we saw how randomization eliminates selection bias. Let's explain what we mean by randomization, describe several ways we might want to randomly assign treatments, and discuss the components other...
14,211
Given the following text description, write Python code to implement the functionality described below step by step Description: Layerwise Sequential Unit Variance (LSUV) Getting the MNIST data and a CNN Jump_to lesson 11 video Step1: Now we're going to look at the paper All You Need is a Good Init, which introduces ...
Python Code: x_train,y_train,x_valid,y_valid = get_data() x_train,x_valid = normalize_to(x_train,x_valid) train_ds,valid_ds = Dataset(x_train, y_train),Dataset(x_valid, y_valid) nh,bs = 50,512 c = y_train.max().item()+1 loss_func = F.cross_entropy data = DataBunch(*get_dls(train_ds, valid_ds, bs), c) mnist_view = view_...
14,212
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook shows an analysis of the Falcon-9 upper stage S-band telemetry frames. It is based on r00t.cz's analysis. The frames are CCSDS Reed-Solomon frames with an interleaving depth of...
Python Code: x = np.fromfile('falcon9_frames_20210324_084608.u8', dtype = 'uint8') x = x.reshape((-1, 1195)) Explanation: This notebook shows an analysis of the Falcon-9 upper stage S-band telemetry frames. It is based on r00t.cz's analysis. The frames are CCSDS Reed-Solomon frames with an interleaving depth of 5, a (2...
14,213
Given the following text description, write Python code to implement the functionality described below step by step Description: ENV / ATM 415 Step1: Go ahead and edit the Python code cell above to do something different. To evaluate whatever is in the cell, just press shift-enter. Notice that you are free to jump ar...
Python Code: # This is an example of a Python code cell. # Note that I can include text as long as I use the # symbol (Python comment) # Results of my code will display below the input print 3+5 Explanation: ENV / ATM 415: Climate Laboratory, Spring 2016 Assignment 3 Out: Tuesday February 23, 2016 Due: Thursday Marc...
14,214
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: <img src="images/utfsm.png" alt="" width="200px" align="right"/> USM Numérica Errores en Python Objetivos Aprender a diagosticar y solucionar errores comunes en python. Aprender técni...
Python Code: IPython Notebook v4.0 para python 3.0 Librerías adicionales: IPython, pdb Contenido bajo licencia CC-BY 4.0. Código bajo licencia MIT. (c) Sebastian Flores, Christopher Cooper, Alberto Rubio, Pablo Bunout. # Configuración para recargar módulos y librerías dinámicamente %reload_ext autoreload %autoreload 2...
14,215
Given the following text description, write Python code to implement the functionality described below step by step Description: AdaptiveMD Example 4 - Custom Task objects 0. Imports Step1: Let's open our test project by its name. If you completed the first examples this should all work out of the box. Step2: Open a...
Python Code: import sys, os from adaptivemd import ( Project, Task, File, PythonTask ) Explanation: AdaptiveMD Example 4 - Custom Task objects 0. Imports End of explanation project = Project('tutorial') Explanation: Let's open our test project by its name. If you completed the first examples this should all work ou...
14,216
Given the following text description, write Python code to implement the functionality described below step by step Description: Тест. Практика проверки гипотез По данным опроса, 75% работников ресторанов утверждают, что испытывают на работе существенный стресс, оказывающий негативное влияние на их личную жизнь. Крупн...
Python Code: from __future__ import division import numpy as np import pandas as pd from scipy import stats import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" n = 100 prob = 0.75 F_H0 = stats...
14,217
Given the following text description, write Python code to implement the functionality described below step by step Description: You'll need to download some resources for NLTK (the natural language toolkit) in order to do the kind of processing we want on all the mailing list text. In particular, for this notebook yo...
Python Code: df = pd.DataFrame(columns=["MessageId","Date","From","In-Reply-To","Count"]) for row in archives[0].data.iterrows(): try: w = row[1]["Body"].replace("'", "") k = re.sub(r'[^\w]', ' ', w) k = k.lower() t = nltk.tokenize.word_tokenize(k) subdict = {} count...
14,218
Given the following text description, write Python code to implement the functionality described below step by step Description: TensorFlow Estimators Deep Dive The purporse of this tutorial is to explain the details of how to create a premade TensorFlow estimator, how trainining and evaluation work with different co...
Python Code: try: COLAB = True from google.colab import auth auth.authenticate_user() except: pass RANDOM_SEED = 19831006 import os import math import multiprocessing import pandas as pd from datetime import datetime import tensorflow as tf print "TensorFlow : {}".format(tf.__version__) tf.enable_eager_execut...
14,219
Given the following text description, write Python code to implement the functionality described below step by step Description: NOTE This notebook will make more sense (provide speed-up) once the LLVM backend is exposed in the python wrappers for SymEngine. I need to get back working on that here. In this notebook we...
Python Code: import json import numpy as np from scipy2017codegen.odesys import ODEsys from scipy2017codegen.chem import mk_rsys Explanation: NOTE This notebook will make more sense (provide speed-up) once the LLVM backend is exposed in the python wrappers for SymEngine. I need to get back working on that here. In this...
14,220
Given the following text description, write Python code to implement the functionality described below step by step Description: San Diego Burrito Analytics Step1: Load data Step3: Vitalness metric Step5: Savior metric
Python Code: %config InlineBackend.figure_format = 'retina' %matplotlib inline import numpy as np import scipy as sp import matplotlib.pyplot as plt import pandas as pd import statsmodels.api as sm import pandasql import seaborn as sns sns.set_style("white") Explanation: San Diego Burrito Analytics: Data characterizati...
14,221
Given the following text description, write Python code to implement the functionality described below step by step Description: Aprendizaje computacional en grandes volúmenes de texto Mario Graff (mgraffg@ieee.org, mario.graff@infotec.mx) Sabino Miranda (sabino.miranda@infotec.mx) Daniela Moctezuma (dmoctezuma@centro...
Python Code: from microtc.textmodel import norm_chars text = "Autoridades de la Ciudad de México aclaran que el equipo del cineasta mexicano no fue asaltado, pero sí una riña ahhh." Explanation: Aprendizaje computacional en grandes volúmenes de texto Mario Graff (mgraffg@ieee.org, mario.graff@infotec.mx) Sabino Miranda...
14,222
Given the following text description, write Python code to implement the functionality described below step by step Description: Departamento de Física - Faculdade de Ciências e Tecnologia da Universidade de Coimbra Física Computacional - Ficha 6 - Diagonalização de Matrizes Rafael Isaque Santos - 2012144694 - Licenci...
Python Code: import numpy as np import numpy.linalg as linalg import matplotlib.pyplot as pl %matplotlib inline def npower(matrix, k): # método da potência n-ésima para um x = np.array([1, 0, 0]) print(0, x, x.transpose() @ matrix @ x) for i in range(k): x = matrix @ x x_norm = lina...
14,223
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to visualizing data in the eeghdf files Getting started The EEG is stored in hierachical data format (HDF5). This format is widely used, open, and supported in many languages, e...
Python Code: # import libraries from __future__ import print_function, division, unicode_literals %matplotlib inline # %matplotlib notebook import matplotlib import matplotlib.pyplot as plt import pandas as pd import numpy as np import h5py from pprint import pprint import stacklineplot # local copy # matplotlib.rcPara...
14,224
Given the following text description, write Python code to implement the functionality described below step by step Description: Overview Kunci utama dari Efisiensi pengiriman adalah customer harus terassign ke kitchen yang terdekat dulu. Kami melakukannya dengan menSort customer dari jarak yang paling jauh dari titik...
Python Code: # Find center point of customer, buat nyari # long long_centroid = sum(customer['long'])/len(customer) # lat lat_centroid = sum(customer['lat'])/len(customer) # Find distance from customer point to central customer point customer['distSort'] = np.sqrt( (customer.long-long_centroid)**2 + (customer.lat-lat_c...
14,225
Given the following text description, write Python code to implement the functionality described below step by step Description: 通用範例/範例二 Step1: 測試資料: * iris為一個dict型別資料。 | 顯示 | 說明 | | -- | -- | | ('target_names', (3L,))| 共有三種鳶尾花 setosa, versicolor, virginica | | ('data', (150L, 4L)) | 有150筆資料,共四種特徵 | | ('target', (15...
Python Code: from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.grid_search import GridSearchCV from sklearn.svm import SVC from sklearn.datasets import load_iris from sklearn.decomposition import PCA from sklearn.feature_selection import SelectKBest iris = load_iris() X, y = iris.data, iris.target Explan...
14,226
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t...
14,227
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Convolutional Neural Networks Welcome to the first week of the first deep learning certificate! We're going to use convolutional neural networks (CNNs) to allow our computer to see - s...
Python Code: %matplotlib inline Explanation: Using Convolutional Neural Networks Welcome to the first week of the first deep learning certificate! We're going to use convolutional neural networks (CNNs) to allow our computer to see - something that is only possible thanks to deep learning. Introduction to this week's t...
14,228
Given the following text description, write Python code to implement the functionality described below step by step Description: A Recursive Parser for Arithmetic Expressions In this notebook we implement a simple recursive descend parser for arithmetic expressions. This parser will implement the following grammar Ste...
Python Code: import re Explanation: A Recursive Parser for Arithmetic Expressions In this notebook we implement a simple recursive descend parser for arithmetic expressions. This parser will implement the following grammar: $$ \begin{eqnarray} \mathrm{expr} & \rightarrow & \mathrm{product}\;\;\mathrm{exprRes...
14,229
Given the following text description, write Python code to implement the functionality described below step by step Description: Imbalanced Weighted Binary Classification Step1: Get data Step2: Create model Step3: Train unweighted loss model Step4: Now train weighted loss model Step5: Grid search Step6: Plot res...
Python Code: import shutil import numpy as np import pandas as pd import tensorflow as tf print(tf.__version__) Explanation: Imbalanced Weighted Binary Classification End of explanation df = pd.read_csv(filepath_or_buffer = "UCI_Credit_Card.csv") df.head() df.describe() FEATURE_NAMES = list(df.columns) NUMERIC_FEATURE_...
14,230
Given the following text description, write Python code to implement the functionality described below step by step Description: CSCS530 Winter 2015 Complex Systems 530 - Computer Modeling of Complex Systems (Winter 2015) Course ID Step1: Random number generation and seeds Basic reading on random number generation St...
Python Code: %matplotlib inline # Imports import numpy import numpy.random import matplotlib.pyplot as plt Explanation: CSCS530 Winter 2015 Complex Systems 530 - Computer Modeling of Complex Systems (Winter 2015) Course ID: CMPLXSYS 530 Course Title: Computer Modeling of Complex Systems Term: Winter 2015 Schedule: Wedn...
14,231
Given the following text description, write Python code to implement the functionality described below step by step Description: Examples Importing libraries Step1: datacleaning The datacleaning module is used to clean and organize the data into 51 CSV files corresponding to the 50 states of the US and the District o...
Python Code: from ceo import data_cleaning from ceo import missing_data from ceo import svr_prediction from ceo import ridge_prediction Explanation: Examples Importing libraries End of explanation data_cleaning.clean_all_data() Explanation: datacleaning The datacleaning module is used to clean and organize the data int...
14,232
Given the following text description, write Python code to implement the functionality described below step by step Description: Suggestions for lab exercises. Variables and assignment Exercise 1 Remember that $n! = n \times (n - 1) \times \dots \times 2 \times 1$. Compute $15!$, assigning the result to a sensible var...
Python Code: fifteen_factorial = 15*14*13*12*11*10*9*8*7*6*5*4*3*2*1 print(fifteen_factorial) Explanation: Suggestions for lab exercises. Variables and assignment Exercise 1 Remember that $n! = n \times (n - 1) \times \dots \times 2 \times 1$. Compute $15!$, assigning the result to a sensible variable name. Solution En...
14,233
Given the following text description, write Python code to implement the functionality described below step by step Description: Projeto Hillary x Trump Nesse projeto vamos utilizar tweets relacionados a última eleição presidencial dos Estados Unidos, onde Hillary Clinton e Donald Trump dispuram o pleito final. A prop...
Python Code: import pandas as pd import nltk df = pd.read_csv("https://www.data2learning.com/machinelearning/datasets/tweets.csv") dataset = df[['text','handle']] dict_ = dataset.T.to_dict("list") Explanation: Projeto Hillary x Trump Nesse projeto vamos utilizar tweets relacionados a última eleição presidencial dos Est...
14,234
Given the following text description, write Python code to implement the functionality described below step by step Description: Run full timeseries simulations In this section, we will learn how to Step1: Get timeseries inputs Step2: Prepare PV array parameters Step3: Run single timestep with PVEngine and inspect ...
Python Code: # Import external libraries import os import numpy as np import matplotlib.pyplot as plt from datetime import datetime import pandas as pd import warnings # Settings %matplotlib inline np.set_printoptions(precision=3, linewidth=300) warnings.filterwarnings('ignore') # Paths LOCAL_DIR = os.getcwd() DATA_DIR...
14,235
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create A Dictionary Step2: Convert Dictionary To Feature Matrix Step3: View Feature Names
Python Code: from sklearn.feature_extraction import DictVectorizer Explanation: Title: Loading Features From Dictionaries Slug: loading_features_from_dictionaries Summary: Loading Features From Dictionaries Date: 2016-11-01 12:00 Category: Machine Learning Tags: Preprocessing Structured Data Authors: Chris Albon Pr...
14,236
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1 toc-item"><a href="#Imports" data-toc-modified-id="Imports-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Imports</a></div><div class="lev1 toc-item"...
Python Code: from __future__ import print_function from __future__ import division import copy import json import re import string import matplotlib import matplotlib.pyplot as plt import pandas as pd import seaborn # To improve the chart styling. import wordtree from IPython.display import display from IPython.displa...
14,237
Given the following text description, write Python code to implement the functionality described below step by step Description: Programming Assignment Step1: Составление корпуса Step2: Наша коллекция небольшая, и целиком помещается в оперативную память. Gensim может работать с такими данными и не требует их сохране...
Python Code: import json with open("recipes.json") as f: recipes = json.load(f) print recipes[0] Explanation: Programming Assignment: Готовим LDA по рецептам Как вы уже знаете, в тематическом моделировании делается предположение о том, что для определения тематики порядок слов в документе не важен; об этом гласит г...
14,238
Given the following text description, write Python code to implement the functionality described below step by step Description: What's new in PyKE 3? Developed since 2012, PyKE offers a user-friendly way to inspect and analyze the pixels and lightcurves obtained by NASA's Kepler and K2. The latest version of PyKE, v3...
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline from matplotlib import rcParams rcParams["figure.figsize"] = (14, 5) Explanation: What's new in PyKE 3? Developed since 2012, PyKE offers a user-friendly way to inspect and analyze the pixels and lightcurves obtained by NASA's Kepler and K2. The latest ...
14,239
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="images/logo.jpg" style="display Step2: <p style="text-align Step3: <p style="text-align Step4: <p style="text-align Step5: <p style="text-align Step6: <p style="text-align Ste...
Python Code: import os import zipfile Explanation: <img src="images/logo.jpg" style="display: block; margin-left: auto; margin-right: auto;" alt="לוגו של מיזם לימוד הפייתון. נחש מצויר בצבעי צהוב וכחול, הנע בין האותיות של שם הקורס: לומדים פייתון. הסלוגן המופיע מעל לשם הקורס הוא מיזם חינמי ללימוד תכנות בעברית."> <span st...
14,240
Given the following text description, write Python code to implement the functionality described below step by step Description: Create the reference solar abundance file Here we join the Asplund+ (2009) data with other sources of information to create our output solar_abundances.fits file. Step1: Read in the Asplund...
Python Code: output_file = 'solarabundances.fits' import matplotlib.pyplot as plt import numpy as np from astropy.io import fits from astropy.table import Table,Column,join Explanation: Create the reference solar abundance file Here we join the Asplund+ (2009) data with other sources of information to create our output...
14,241
Given the following text description, write Python code to implement the functionality described below step by step Description: Postar uma foto Step1: Postar uma foto em um Album Step2: Recuperar os álbuns existentes na minha conta Step3: Exercício 1 – Crie um álbum de fotos chamado Cursos. Depois adicione as 4 im...
Python Code: import facebook access_token = 'EAACUzLmOZC7kBAPfCPMRBG23rGoY3iQWKJMIO7ESZCp0LPZCwQQv0AoQeEtBm9IyNDi5yP2RHMGzCzjquLb4ZCWUHLZA6vY1Pp6x8oFXZA7IMissQbporZAwUoIZCuZBoOBrWQDxi8PUUZCb96uWmSwB2ZBqEIwnvZCRZBnqJjGZBQJVhl1gZDZD' api = facebook.GraphAPI(access_token) api.version foto = open("fia.jpg", "rb") api.put_...
14,242
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualize GAR Global Flood Hazard Map with Python Flooding is one of the most damaging natural hazards, accounting for 31% of all economic losses worldwide resulting from natural hazards(Eur...
Python Code: import numpy as np import numpy.ma as ma from osgeo import gdal import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap %matplotlib inline Explanation: Visualize GAR Global Flood Hazard Map with Python Flooding is one of the most damaging natural hazards, accounting for 31% of all economic...
14,243
Given the following text description, write Python code to implement the functionality described below step by step Description: Diagonalizing operators Step1: Periodic A Step2: $v_k = \omega^{jk}, j \in {0,1,\ldots,N-1}$ Step3: To see eigenvalues, divide the product $Av$ by $v$
Python Code: import scipy.linalg as LA # Example from Strang, 1999 A0 = LA.circulant([2,-1,0,-1]) print(A0) # LA.LU Lam, V = LA.eig(A0) print(Lam) print(V) print(V[:, 0]) LA.norm(V, axis=1) LA.norm(V[:, 0]) 1/np.sqrt(2) Explanation: Diagonalizing operators: End of explanation N = A0.shape[0] omega = np.exp(1j*2*np.pi /...
14,244
Given the following text description, write Python code to implement the functionality described below step by step Description: Watson Visual Recognition Training with Spectrogram Images from SETI Signal Data https Step1: <br/> Init the Watson Visual Recognition Python Library you may need to install the SDK first S...
Python Code: #!pip install --user --upgrade watson-developer-cloud #Making a local folder to put my data. #NOTE: YOU MUST do something like this on a Spark Enterprise cluster at the hackathon so that #you can put your data into a separate local file space. Otherwise, you'll likely collide with #your fellow participant...
14,245
Given the following text description, write Python code to implement the functionality described below step by step Description: A Gentle Introduction to HARK This notebook provides a simple, hands-on tutorial for first time HARK users -- and potentially first time Python users. It does not go "into the weeds" - we h...
Python Code: # This cell has a bit of initial setup. You can click the triangle to the left to expand it. # Click the "Run" button immediately above the notebook in order to execute the contents of any cell # WARNING: Each cell in the notebook relies upon results generated by previous cells # The most common problem ...
14,246
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute envelope correlations in source space Compute envelope correlations of orthogonalized activity Step1: Here we do some things in the name of speed, such as crop (which will hurt SNR)...
Python Code: # Authors: Eric Larson <larson.eric.d@gmail.com> # Sheraz Khan <sheraz@khansheraz.com> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import os.path as op import numpy as np import matplotlib.pyplot as plt import mne from mne.connectivity import envelope_correlati...
14,247
Given the following text description, write Python code to implement the functionality described below step by step Description: Create a new (initially empty) viewer. This starts a webserver in a background thread, which serves a copy of the Neuroglancer client, and which also can serve local volume data and handles...
Python Code: viewer = neuroglancer.Viewer() Explanation: Create a new (initially empty) viewer. This starts a webserver in a background thread, which serves a copy of the Neuroglancer client, and which also can serve local volume data and handles sending and receiving Neuroglancer state updates. End of explanation vie...
14,248
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Hidden Treasure This ebook contains few lesser known Python gems. As usual, I will try to keep them updated and will continue to expand. If you wish to add any new, send them to me at...
Python Code: a = 10 b = "TEST" a, b = b, a print(a, b) Explanation: Python Hidden Treasure This ebook contains few lesser known Python gems. As usual, I will try to keep them updated and will continue to expand. If you wish to add any new, send them to me at (funmayank @ yahoo . co . in). Variables In-place value swapp...
14,249
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2017 Google LLC. Step1: # TensorFlow 编程概念 学习目标: * 学习 TensorFlow 编程模型的基础知识,重点了解以下概念: * 张量 * 指令 * 图 * 会话 * 构建一个简单的 TensorFlow 程序,使用该程序绘制一个默认图并创建一个运行该图的会话 注意:请仔细阅...
Python Code: # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribute...
14,250
Given the following text description, write Python code to implement the functionality described below step by step Description: 340-Plotting and Fitting Data This is the same set of data and fitting function as in the "Intro to Matlab" document. Data and error bars Step1: Fitting function to the data For physical re...
Python Code: %pylab inline # mathematical routines are expecting 'array' x = array([-10, -9, -8, -7, -6, -5, -4, -3, 0]); y = array([2.65, 2.10, 1.90, 1.40, 1.00, 0.80, 0.60, 0.30, 0.00]); ey = array([0.1, 0.1, 0.1, 0.1, 0.05, 0.05, 0.05, 0.05, 0.2]); # Plot the data with error bars errorbar(x,y,ey,linestyle = '',mar...
14,251
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploration of Prudential Life Insurance Data Data retrieved from Step1: Define categorical data types Step2: Importing life insurance data set The following variables are all categorical ...
Python Code: # Importing libraries %pylab inline %matplotlib inline import pandas as pd import matplotlib.pyplot as plt from matplotlib.colors import LogNorm from sklearn import preprocessing import numpy as np # Convert variable data into categorical, continuous, discrete, # and dummy variable lists the following in...
14,252
Given the following text description, write Python code to implement the functionality described below step by step Description: L'objectif des "compare" est d'évaluer la qualité des calages effectués. Ils comparent les dépenses ou quantités agrégées de Budget des Familles après calage, avec celles de la comptabilité ...
Python Code: from __future__ import division import pkg_resources import os import pandas as pd from pandas import concat import seaborn Explanation: L'objectif des "compare" est d'évaluer la qualité des calages effectués. Ils comparent les dépenses ou quantités agrégées de Budget des Familles après calage, avec celles...
14,253
Given the following text description, write Python code to implement the functionality described below step by step Description: Outline Glossary 2. Mathmatical Groundwork Previous Step1: Import section specific modules Step5: 2.11 Least-squares Minimization<a id='groundwork Step6: The three functions defined abo...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS Explanation: Outline Glossary 2. Mathmatical Groundwork Previous: 2.10 Linear Algrebra Next: 2.12 Solid Angle Import standard modules: End of explanation ...
14,254
Given the following text description, write Python code to implement the functionality described below step by step Description: Load the airport and flight data from Cloudant Step1: Build the vertices and edges dataframe from the data Step2: Install GraphFrames package using PixieDust packageManager The GraphFrames...
Python Code: cloudantHost='dtaieb.cloudant.com' cloudantUserName='weenesserliffircedinvers' cloudantPassword='72a5c4f939a9e2578698029d2bb041d775d088b5' airports = sqlContext.read.format("com.cloudant.spark").option("cloudant.host",cloudantHost)\ .option("cloudant.username",cloudantUserName).option("cloudant.passwor...
14,255
Given the following text description, write Python code to implement the functionality described below step by step Description: An early result in the study of human dynamic systems is the claim that response times to email follow a power law distribution (http Step1: We will look at messages in our archive that are...
Python Code: from bigbang.archive import Archive import pandas as pd arx = Archive("ipython-dev",archive_dir="../archives") print arx.data.shape arx.data.drop_duplicates(subset=('From','Date'),inplace=True) Explanation: An early result in the study of human dynamic systems is the claim that response times to email foll...
14,256
Given the following text description, write Python code to implement the functionality described below step by step Description: Clase 4 Step1: 1. Uso de Pandas para descargar datos de precios de cierre Ahora, en forma de función Step2: Una vez cargados los paquetes, es necesario definir los tickers de las acciones ...
Python Code: #importar los paquetes que se van a usar import pandas as pd import pandas_datareader.data as web import numpy as np from sklearn.cluster import KMeans import datetime from datetime import datetime import scipy.stats as stats import scipy as sp import scipy.optimize as optimize import scipy.cluster.hierarc...
14,257
Given the following text description, write Python code to implement the functionality described below step by step Description: <div class="alert alert-block alert-info" style="margin-top Step1: Set the random seed Step2: create a linear regression object, as our input and output will be two we set the parameters ...
Python Code: from torch import nn import torch Set the random seed: torch.manual_seed(1) Explanation: <div class="alert alert-block alert-info" style="margin-top: 20px"> <a href="http://cocl.us/pytorch_link_top"><img src = "http://cocl.us/Pytorch_top" width = 950, align = "center"></a> <img src = "https://ibm.box.com/...
14,258
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction You all know word clouds Step1: We see that <tt>wordcloud</tt> just did some text preprocessing (like removing the "!") and rendered the texts. That's it! Advanced example The ...
Python Code: from wordcloud import WordCloud WordCloud().generate("Hello reader!").to_image() Explanation: Introduction You all know word clouds: They give you a quick overview of the top topics of your blog, book, source code &ndash; or presentation. The latter was the one that got me thinking: How cool would it be...
14,259
Given the following text description, write Python code to implement the functionality described below step by step Description: CEOS Data Cube - Water Analysis Notebook Description Step1: First, we must connect to our data cube. We can then query the contents of the data cube we have connected to, including both the...
Python Code: %matplotlib inline from datetime import datetime import numpy as np import datacube from dc_water_classifier import wofs_classify from dc_utilities import perform_timeseries_analysis import dc_au_colormaps from dc_notebook_utilities import * Explanation: CEOS Data Cube - Water Analysis Notebook Description...
14,260
Given the following text description, write Python code to implement the functionality described below step by step Description: High-level Plotting with Pandas and Seaborn In 2016, there are more options for generating plots in Python than ever before Step1: Notice that by default a line plot is drawn, and light bac...
Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt normals = pd.Series(np.random.normal(size=10)) normals.plot() Explanation: High-level Plotting with Pandas and Seaborn In 2016, there are more options for generating plots in Python than ever before: matplotlib Pandas...
14,261
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Postprocessing This notebook visualizes the output of the deep neural network and plots the associated ROC curve. Step2: A 5-layer neural network was trained to separate $B \rightarr...
Python Code: import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd def output_probs(network_output, y): # Break network output down into signal and background components labels = np.argmax(y, 1) sig_indices = np.where(labels == 1) bkg_indices = np.where(labels == 0...
14,262
Given the following text description, write Python code to implement the functionality described below step by step Description: If you have not already read it, you may want to start with the first tutorial Step1: The data for our two surveys are stored in two separate CSV files included with the documentation. We w...
Python Code: import astropy.table as at import astropy.units as u from astropy.visualization.units import quantity_support import matplotlib.pyplot as plt import numpy as np %matplotlib inline import corner import pymc3 as pm import pymc3_ext as pmx import exoplanet as xo import exoplanet.units as xu import arviz as az...
14,263
Given the following text description, write Python code to implement the functionality described below step by step Description: <div class="alert alert-block alert-info" style="margin-top Step1: <code>plot_channels</code> Step2: <code>show_data</code> Step4: Create some toy data Step5: <code>plot_activation</code...
Python Code: import torch import torch.nn as nn import torchvision.transforms as transforms import torchvision.datasets as dsets import matplotlib.pylab as plt import numpy as np import pandas as pd torch.manual_seed(4) Explanation: <div class="alert alert-block alert-info" style="margin-top: 20px"> <a href="http://c...
14,264
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Toplevel MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specif...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-lr', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: EC-EARTH-CONSORTIUM Source ID: EC-EARTH3-LR Sub-Topic...
14,265
Given the following text description, write Python code to implement the functionality described below step by step Description: Income Inequality between high earners and low earners A critique of http Step1: Getting the data Before going into the purely visual aspects and how effective they are at conveying a story...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import seaborn as sns sns.set(palette = sns.dark_palette("skyblue", 8, reverse=True)) Explanation: Income Inequality between high earners and low earners A critique of http://www.informationisbeautiful.net/visualizations/what-are-wallst...
14,266
Given the following text description, write Python code to implement the functionality described below step by step Description: More on SQLalchemy filter and operators Step1: Let's start from a simple query and see how we can use different operators to refine it. Step2: equals ( == ) Step3: not equals ( != )...
Python Code: ! module use /g/data3/hh5/public/modules ! module load conda/analysis27 from ARCCSSive import CMIP5 from ARCCSSive.CMIP5.Model import Instance from ARCCSSive.CMIP5.other_functions import unique db=CMIP5.connect() Explanation: More on SQLalchemy filter and operators End of explanation results=db.outputs(ens...
14,267
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Athena Modelling the Effect of Relative Humidity on Surface Temperature In this short tutorial, we'll use Athena to build an equation that models the relationship between hou...
Python Code: import pandas as pd from dateutil.parser import parse from athena.equations import * from athena.framework import Framework from athena.dataset import Dataset from athena.model import AdditiveModel from athena.helpers import * Explanation: Introduction to Athena Modelling the Effect of Relative Humidity o...
14,268
Given the following text description, write Python code to implement the functionality described below step by step Description: Hello world (press space) This is how you do slides with ipython notebooks! Formatting is simple, with markdown ...your python love will help you... Step1: How cool to have live code insid...
Python Code: a = "Hello" b = "World" print a,b + "!" Explanation: Hello world (press space) This is how you do slides with ipython notebooks! Formatting is simple, with markdown ...your python love will help you... End of explanation # Please consider also that you can re-use # variables defined in older slides ;) pri...
14,269
Given the following text description, write Python code to implement the functionality described. Description: Count numbers less than N containing digits from the given set : Digit DP Python3 implementation to find the count of numbers possible less than N , such that every digit is from the given set of digits ; Func...
Python Code: import numpy as np ; dp = np . ones(( 15 , 2 ) ) * - 1 ; def convertToString(num ) : return str(num ) ;  def calculate(pos , tight , D , sz , num ) : if(pos == len(num ) ) : return 1 ;  if(dp[pos ][tight ] != - 1 ) : return dp[pos ][tight ] ;  val = 0 ; if(tight == 0 ) : for i...
14,270
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: 高斯分布 高斯分布,也称为正态分布,广泛应用于连续型随机变量分布的模型中。 对于一元变量x的情形,高斯分布可以写成如下的形式: $$\mathcal{N}(x|\mu,\sigma^2)=\frac{1}{(2\pi\sigma^2)^{1/2}}exp{-\frac{1}{2\sigma^2}(x-\mu)^2}$$ 其中$\mu$是均值,$\sigma^2$是...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy.stats import uniform from scipy.stats import binom from scipy.stats import norm as norm_dist def uniform_central_limit(n, length): @param: n:计算rv的n次平均值, length:平均随机变量的样本数 @return: rv_mean: 长度为length的数组,它是平...
14,271
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create Word Tokens Step2: Load Stop Words Step3: Remove Stop Words
Python Code: # Load library from nltk.corpus import stopwords # You will have to download the set of stop words the first time import nltk nltk.download('stopwords') Explanation: Title: Remove Stop Words Slug: remove_stop_words Summary: How to remove stop words from unstructured text data for machine learning in Python...
14,272
Given the following text description, write Python code to implement the functionality described below step by step Description: expression.thompson Generate the Thompson automaton from an expression. Caveats Step1: You may, however, use a labelset which does not feature a "one", in which case the context of the auto...
Python Code: import vcsn from IPython.display import display vcsn.context('lan_char, b').expression('a[bc]d').thompson() vcsn.context('law_char, b').expression("'aa'[bc]'dd'").thompson() Explanation: expression.thompson Generate the Thompson automaton from an expression. Caveats: - it is not guaranteed that Result.is_v...
14,273
Given the following text description, write Python code to implement the functionality described below step by step Description: TFRecord and tf.Example Learning Objectives Understand the TFRecord format for storing data Understand the tf.Example message type Read and Write a TFRecord file Introduction In this noteboo...
Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst !pip install -q tf-nightly import IPython.display as display import numpy as np import tensorflow as tf print("TensorFlow version: ", tf.version.VERSION) Explanation: TFRecord and tf.Example Learning Objectives Understand the TFRecord forma...
14,274
Given the following text description, write Python code to implement the functionality described below step by step Description: Groupwise Correlation Toy Example Step1: ## The main helper function splits input arrays into groups Step2: The parse_replicates function requires two arrays Step3: The main wrapper funct...
Python Code: import sys, getopt, math import itertools as itt from scipy.stats.stats import pearsonr x2reps = ['xa1', 'xa2', 'xb1', 'xb2', 'xc1', 'xc2', 'xd1', 'xd2'] y2reps = ['ya1', 'ya2', 'yb1', 'yb2', 'yc1', 'yc2', 'yd1', 'yd2'] x3reps = ['xa1', 'xa2', 'xa3', 'xb1', 'xb2', 'xb3', 'xc1', 'xc2', 'xc3', 'xd1', 'xd2',...
14,275
Given the following text description, write Python code to implement the functionality described below step by step Description: Validating Configuration Settings with Batfish Network engineers routinely need to validate configuration settings of various devices in their network. In a multi-vendor network, this valida...
Python Code: # Import packages %run startup.py bf = Session(host="localhost") # Initialize a network and snapshot NETWORK_NAME = "example_network" SNAPSHOT_NAME = "example_snapshot" SNAPSHOT_PATH = "networks/example" bf.set_network(NETWORK_NAME) bf.init_snapshot(SNAPSHOT_PATH, name=SNAPSHOT_NAME, overwrite=True) Explan...
14,276
Given the following text description, write Python code to implement the functionality described below step by step Description: How to create a Deployment In this notebook, we show you how to create a Deployment with 3 ReplicaSets. These ReplicaSets are owned by the Deployment and are managed by the Deployment contro...
Python Code: from kubernetes import client, config Explanation: How to create a Deployment In this notebook, we show you how to create a Deployment with 3 ReplicaSets. These ReplicaSets are owned by the Deployment and are managed by the Deployment controller. We would also learn how to carry out RollingUpdate and RollB...
14,277
Given the following text description, write Python code to implement the functionality described below step by step Description: Pythonを使って顔ランドマークで遊んでみよう 今回はPythonを使ったプログラミングをやってみます。ただの数値計算では面白くないので WebCAMを使って自分の顔をキャプチャ 顔検出 顔ランドマーク検出 ランドマークを使って何かやる という流れです。 使うパッケージ この例では OpenCV Step1: これでdlibとcv2が使えるようになりました。dlib.あるい...
Python Code: import dlib import cv2 Explanation: Pythonを使って顔ランドマークで遊んでみよう 今回はPythonを使ったプログラミングをやってみます。ただの数値計算では面白くないので WebCAMを使って自分の顔をキャプチャ 顔検出 顔ランドマーク検出 ランドマークを使って何かやる という流れです。 使うパッケージ この例では OpenCV: 画像処理ライブラリ(cv2) dlib: 機械学習ライブラリ を使います。 1. WebCAMを使って自分の顔をキャプチャ まず,OpenCV(cv2)とdlibを使う宣言をします。C言語の#includeみたいなもんです。 セルが緑色の状...
14,278
Given the following text description, write Python code to implement the functionality described below step by step Description: Theano, Lasagne and why they matter got no lasagne? Install the bleeding edge version from here Step1: theano teaser Doing the very same thing Step2: How does it work? 1 You define inputs ...
Python Code: import numpy as np def sum_squares(N): return <student.Implement_me()> %%time sum_squares(10**8) Explanation: Theano, Lasagne and why they matter got no lasagne? Install the bleeding edge version from here: http://lasagne.readthedocs.org/en/latest/user/installation.html Warming up Implement a function ...
14,279
Given the following text description, write Python code to implement the functionality described below step by step Description: Making prettier (and more impactful) plots Making prettier plots is part matter-of-taste, part an appreciation for optical perception. These days, there are a number of things you can do to ...
Python Code: # we'll use the pythonic pyplot interface import matplotlib.pyplot as plt # necessary for the notebook to render the plots inline %matplotlib inline import numpy as np np.random.seed(42) x = np.linspace(0, 40, 1000) y = np.sin(np.linspace(0, 10*np.pi, 1000)) y += np.random.randn(len(x...
14,280
Given the following text description, write Python code to implement the functionality described below step by step Description: Snow drift potential Step1: Accessing netcdf file via thredds The wind speeds in ...metcoop_default... are post-processed and based on FX (highest 10 min avergae within the hour). FX is in ...
Python Code: %matplotlib inline import netCDF4 import numpy as np import pylab as plt plt.rcParams['figure.figsize'] = (14, 5) Explanation: Snow drift potential End of explanation ncdata = netCDF4.Dataset('http://thredds.met.no/thredds/dodsC/arome25/arome_metcoop_default2_5km_latest.nc') x_wind_v = ncdata.variables['x_...
14,281
Given the following text description, write Python code to implement the functionality described below step by step Description: Get Facebook statuses from Python Download status updates and comments from Facebook pages and Facebook groups. Uses the Facebook GraphAPI. Facebook access token To use the Facebook GraphAPI...
Python Code: accesstoken = "XXX" Explanation: Get Facebook statuses from Python Download status updates and comments from Facebook pages and Facebook groups. Uses the Facebook GraphAPI. Facebook access token To use the Facebook GraphAPI, you need an access token. It's basically a key that unlocks the service. How to g...
14,282
Given the following text description, write Python code to implement the functionality described below step by step Description: Analyis of global temperature In this example we show some analysis of global surface temperature fields. The data which is used is the NCEP reanalysis data which we first download. Step1: ...
Python Code: %matplotlib inline import os from pycmbs.data import Data from pycmbs.mapping import map_plot # we download some NCEP data if not os.path.exists('air.mon.mean.nc'): !wget --ftp-user=anonymous --ftp-password=nothing ftp://ftp.cdc.noaa.gov/Datasets/ncep.reanalysis.derived/surface/air.mon.mean.nc ncep = D...
14,283
Given the following text description, write Python code to implement the functionality described below step by step Description: 100 pandas puzzles Inspired by 100 Numpy exerises, here are 100* short puzzles for testing your knowledge of pandas' power. Since pandas is a large library with many different specialist fea...
Python Code: import pandas as pd Explanation: 100 pandas puzzles Inspired by 100 Numpy exerises, here are 100* short puzzles for testing your knowledge of pandas' power. Since pandas is a large library with many different specialist features and functions, these excercises focus mainly on the fundamentals of manipulati...
14,284
Given the following text description, write Python code to implement the functionality described below step by step Description: Project Euler, first problem Step1: Let's create a predicate that returns True if a number is a multiple of 3 or 5 and False otherwise. Step2: Given the predicate function P a suitable pro...
Python Code: from notebook_preamble import J, V, define Explanation: Project Euler, first problem: "Multiples of 3 and 5" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. End of expla...
14,285
Given the following text description, write Python code to implement the functionality described below step by step Description: 04-notebook-rough-draft for final project I am working on the Kaggle Grupo Bimbo competition dataset for this project. Link to Grupo Bimbo Kaggle competition Step1: Part 1. Identify the Pr...
Python Code: import numpy as np import pandas as pd from sklearn import cross_validation from sklearn import metrics from sklearn import linear_model from sklearn import ensemble #QUESTION - what is diff bw random forest classifier and rf regressor? #import seaborn as sns import matplotlib.pyplot as plt #sns.set(style=...
14,286
Given the following text description, write Python code to implement the functionality described below step by step Description: In-Class Coding Lab Step1: Reading from the file Let's start with some code to read the lines of text from CCL-mbox-tiny.txt this code reads the contents of the file one line at a time and ...
Python Code: ! curl https://raw.githubusercontent.com/mafudge/datasets/master/ist256/07-Files/mbox-tiny.txt -o mbox-tiny.txt ! curl https://raw.githubusercontent.com/mafudge/datasets/master/ist256/07-Files/mbox-short.txt -o mbox-short.txt Explanation: In-Class Coding Lab: Files The goals of this lab are to help you to ...
14,287
Given the following text description, write Python code to implement the functionality described below step by step Description: Non-uniform random distributions In the previous section we learned how to generate random deviates with a uniform probability distribution in an interval $[a,b]$. This distributioon is norm...
Python Code: %matplotlib inline import numpy as np from matplotlib import pyplot N = 10000 r = np.random.random(N) xlambda = 0.1 x = -np.log(r)/xlambda binwidth=xlambda*5 pyplot.hist(x,bins=np.arange(0.,100., binwidth),density=True); pyplot.plot(np.arange(0.,100.,binwidth),xlambda*np.exp(-xlambda*np.arange(0.,100.,binw...
14,288
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Astro 283 Homework 6</h1> Bijan Pourhamzeh Step1: <h3> Problem 1 </h3> To estimate the values of $(\alpha,\beta)$, we maximize the posterior function $p(\alpha,\beta\mid{D})$ with respe...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy.special import iv from scipy.optimize import fmin from csv import reader from astropy.io import fits from __future__ import print_function Explanation: <h1>Astro 283 Homework 6</h1> Bijan Pourhamzeh End of explanation #Read in...
14,289
Given the following text description, write Python code to implement the functionality described below step by step Description: Adding Trends R.A. Collenteur (University of Graz), O.N. Ebbens (Artesia) In this notebook it is explained how to use linear and step trend models to improve the simulation of groundwater le...
Python Code: import pandas as pd import pastas as ps ps.set_log_level("ERROR") ps.show_versions() Explanation: Adding Trends R.A. Collenteur (University of Graz), O.N. Ebbens (Artesia) In this notebook it is explained how to use linear and step trend models to improve the simulation of groundwater levels. End of explan...
14,290
Given the following text description, write Python code to implement the functionality described below step by step Description: GA4GH 1000 Genome Variant Service Example This example illustrates how to access the different variant calls implemented within the variant service. Initialize the client In this step we cre...
Python Code: import ga4gh_client.client as client c = client.HttpClient("http://1kgenomes.ga4gh.org") Explanation: GA4GH 1000 Genome Variant Service Example This example illustrates how to access the different variant calls implemented within the variant service. Initialize the client In this step we create a client ob...
14,291
Given the following text description, write Python code to implement the functionality described below step by step Description: Contract a Grid Circuit Shallow circuits on a planar grid with low-weight observables permit easy contraction. Note Step1: Make an example circuit topology We'll use entangling gates accord...
Python Code: import numpy as np import networkx as nx import cirq import quimb import quimb.tensor as qtn from cirq.contrib.svg import SVGCircuit import cirq.contrib.quimb as ccq %matplotlib inline from matplotlib import pyplot as plt import seaborn as sns sns.set_style('ticks') plt.rc('axes', labelsize=16, titlesize=1...
14,292
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Research Module Usage We start with some useful imports and constant definitions Step1: Reducing Extra Dataset Loads Running Research Sequentially In previous tutorial we learned h...
Python Code: import sys import os import shutil import warnings warnings.filterwarnings('ignore') from tensorflow import logging logging.set_verbosity(logging.ERROR) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import matplotlib %matplotlib inline sys.path.append('../../..') from batchflow import Pipeline, B, C, V, D, L fr...
14,293
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Network Structure Learning in Pomegranate author Step1: The structure attribute returns a tuple of tuples, where each inner tuple corresponds to that node in the graph (and the col...
Python Code: %pylab inline %load_ext memory_profiler from pomegranate import BayesianNetwork import seaborn, time seaborn.set_style('whitegrid') X = numpy.random.randint(2, size=(2000, 7)) X[:,3] = X[:,1] X[:,6] = X[:,1] X[:,0] = X[:,2] X[:,4] = X[:,5] model = BayesianNetwork.from_samples(X, algorithm='exact') print mo...
14,294
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook a Q learner with dyna and a custom predictor will be trained and evaluated. The Q learner recommends when to buy or sell shares of one particular stock, and in which quantit...
Python Code: # Basic imports import os import pandas as pd import matplotlib.pyplot as plt import numpy as np import datetime as dt import scipy.optimize as spo import sys from time import time from sklearn.metrics import r2_score, median_absolute_error from multiprocessing import Pool import pickle %matplotlib inline ...
14,295
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualization 1 Step1: Scatter plots Learn how to use Matplotlib's plt.scatter function to make a 2d scatter plot. Generate random data using np.random.randn. Style the markers (color, size...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np Explanation: Visualization 1: Matplotlib Basics Exercises End of explanation y=np.random.randn(30) x=np.random.randn(30) plt.scatter(x,y, color="r",s=50, marker='x',alpha=.9) plt.xlabel('Random Values for X') plt.ylabel('Randome Values f...
14,296
Given the following text description, write Python code to implement the functionality described below step by step Description: We have 2 banners promoting a new sport club. The first banner is aggressive Step1: To decide which banner is better we run experiment. We show both banners to random clients and make the c...
Python Code: crossfitters_ratio = .48 aggressive = {"crossfitters": .68, "runners": .04} neutral = {"crossfitters": .28, "runners": .4} def test_banner(banner, shows): runners_dist = stats.bernoulli(banner["runners"]) crossfitters_dist = stats.bernoulli(banner["crossfitters"]) crossfitters_cnt = stats.berno...
14,297
Given the following text description, write Python code to implement the functionality described below step by step Description: Exceptions An exception is an event which occurs during the execution of a program and that disrupts the normal flow of the program's instructions. When a Python code generates an exception,...
Python Code: # Note: You must interrupt the kernel (see the menu) in order to simulate <ctrl>+c. try: text = input('Please, enter something (or stop the kernel): ') except: print('Sorry, something wrong happened :-(') # This command never should be executed if you didn't provide an input print('You entered...
14,298
Given the following text description, write Python code to implement the functionality described below step by step Description: Figure Step1: values from Okanoya paper below (KOUMURA_OKANOYA_NOTE_ERROR_RATES) are taken from this table
Python Code: TRAIN_DUR_IND_MAP = { k:v for k, v in zip( sorted(curve_df['train_set_dur'].unique()), sorted(curve_df['train_set_dur_ind'].unique()) ) } Explanation: Figure End of explanation SAVE_FIG = True sns.set("paper") KOUMURA_OKANOYA_NOTE_ERROR_RATES = { 120. : 0.84, 480. : 0.46, }...
14,299
Given the following text description, write Python code to implement the functionality described below step by step Description: Time Series Exercise - Follow along with the instructions in bold. Watch the solutions video if you get stuck! The Data Source Step1: Use pandas to read the csv of the monthly-milk-product...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline Explanation: Time Series Exercise - Follow along with the instructions in bold. Watch the solutions video if you get stuck! The Data Source: https://datamarket.com/data/set/22ox/monthly-milk-production-pounds-per-cow...