Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
11,900
Given the following text description, write Python code to implement the functionality described below step by step Description: CLIXO Ontology Tree Generator This is a notebook to generate tree data file from original table and annotations. This is the final version of the script creating an Cytoscape.js file with g...
Python Code: # Load data sets import pandas as pd treeSourceUrl = './data/preds_yeastnet_no_gi_0.04_0.5.txt.propagate.small_parent_tree' geneCountFile = './data/preds_yeastnet_no_gi_0.04_0.5.txt.propagate.term_sizes' alignmentFile = './data/alignments_FDR_0.1_t_0.1' geneAssignment = './data/preds_yeastnet_no_gi_0.04_0....
11,901
Given the following text description, write Python code to implement the functionality described below step by step Description: 贝叶斯分类器含义 贝叶斯分类器是一种基于贝叶斯概率的模型,属于生成式分类器算法,用来处理分类问题.最常见的是朴素贝叶斯分类器和高斯贝叶斯分类器,"朴素"是因为它假设各个预测变量之间相互独立,"高斯"是因为它假设每类数据的每个预测变量都服从参数独立的高斯分布,也就是正态分布. 贝叶斯公式 贝叶斯分类器来源于贝叶斯公式,也就是条件概率公式,以离散情况为例便是$P(Y|X)=\fra...
Python Code: import requests import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import classification_report Explanation: 贝叶斯分类器含义 贝叶斯分类器是一种基于贝叶斯概率的模型,属于生成式分类器算法,用来处理分类问题.最常见的是朴素贝叶斯分类器...
11,902
Given the following text description, write Python code to implement the functionality described below step by step Description: (Run the last cell first in order to enable custom formatting) Learning Pandas AMCDawes Dec 2015 Some parts of our CCDimage code would be much improved by the use of pandas. In particular, s...
Python Code: # standard imports: import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib # use inline plots: %matplotlib inline # use ggplot style: matplotlib.style.use('ggplot') Explanation: (Run the last cell first in order to enable custom formatting) Learning Pandas AMCDawes Dec 201...
11,903
Given the following text description, write Python code to implement the functionality described below step by step Description: Battleship! A variation on the classic game. A ship of random length will be placed on a board whose size is determined by you, the player. You may also select the number of turns you woul...
Python Code: from random import randint from ipythonblocks import BlockGrid from IPython.display import clear_output def place_ship(boardsize): ''' Place a ship randomly on the board of size boardsize x boardsize. Randomly decide whether it is vertical or horizontal, what length ship, the pla...
11,904
Given the following text description, write Python code to implement the functionality described below step by step Description: Write a function Step1: V- 1 - used numpy to sum soon realized numpy does not work on codality. I have usually required more time working on solutions when solving something espically with ...
Python Code: Ax = [-1, 3, -4, 5, 1, -6, 2, 1] Explanation: Write a function: def solution(A) that, given a zero-indexed array A consisting of N integers, returns any of its equilibrium indices. The function should return −1 if no equilibrium index exists. For example, given array A shown above, the function may return ...
11,905
Given the following text description, write Python code to implement the functionality described below step by step Description: Online Learning DavisSML Step1: Loss Step6: Exercise 8.2 Look at LROnline.py and determine what the decay argument is doing. Play with the arguments and see when you achieve convergence a...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt ## open wine data wine = pd.read_csv('../../data/winequality-red.csv',delimiter=';') Y = wine.values[:,-1] X = wine.values[:,:-1] n,p = X.shape X = n**0.5 * (X - X.mean(axis=0)) / X.std(axis=0) ## Look at LROnline.py from LROnline impor...
11,906
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Introduction and Foundations Project Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the shi...
Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd from IPython.display import display # Allows the use of display() for DataFrames # Import supplementary visualizations code visuals.py import visuals as vs # Pretty display for notebooks %matplotlib inline # Load the datas...
11,907
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 11 Step1: Load time series data Step2: There are a few supported file formats. AT2 files can be loaded as follows Step3: Create site profile This is about the simplest profile th...
Python Code: import matplotlib.pyplot as plt import numpy as np import pysra %matplotlib inline # Increased figure sizes plt.rcParams["figure.dpi"] = 120 Explanation: Example 11 : Time series SRA using FDM Time series analysis to acceleration transfer functions and spectral ratios. End of explanation fname = "data/NIS0...
11,908
Given the following text description, write Python code to implement the functionality described below step by step Description: Raykar(RGZ) Step1: It seems that higher values of $\alpha$ are correlated with lower values of $\beta$, and vice versa. This seems to make some intuitive sense. Raykar-estimated $\vec \alph...
Python Code: from pprint import pprint import crowdastro.crowd.util from crowdastro.crowd.raykar import RaykarClassifier import crowdastro.experiment.experiment_rgz_raykar as rgzr from crowdastro.experiment.results import Results import crowdastro.plot import h5py import matplotlib.pyplot as plt import numpy import skl...
11,909
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">TensorFlow Neural Network Lab</h1> <img src="image/notmnist.png"> In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl...
Python Code: import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfile import ZipFile p...
11,910
Given the following text description, write Python code to implement the functionality described below step by step Description: Analýza volatilních pohybů v Pythonu a Pandas 1 V následujícím grafu jsou pro příklad zvýrazněny volatilní pohyby Step1: Každý řádek představuje cenu pro daný den a to nejvyšší (High), nejn...
Python Code: import pandas as pd import pandas_datareader.data as web import datetime start = datetime.datetime(2015, 1, 1) end = datetime.datetime(2018, 8, 31) spy_data = web.DataReader('SPY', 'yahoo', start, end) spy_data = spy_data.drop(['Volume', 'Adj Close'], axis=1) # sloupce 'Volume' a 'Adj Close' nebudu potřebo...
11,911
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Crash Course Exercises This is an optional exercise to test your understanding of Python Basics. The questions tend to have a financial theme to them, but don't look to deeply into th...
Python Code: price = 300 import math math.sqrt( price ) import math math.sqrt( price ) Explanation: Python Crash Course Exercises This is an optional exercise to test your understanding of Python Basics. The questions tend to have a financial theme to them, but don't look to deeply into these tasks themselves, many of ...
11,912
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Datasets We introduce several datasets used as running examples in TSA. Step2: Dataset 1 This dataset is derived from a time series of daily GBP/USD exchange rates, $(S_t){t=0,1,\l...
Python Code: # Copyright (c) Thalesians Ltd, 2019. All rights reserved # Copyright (c) Paul Alexander Bilokon, 2019. All rights reserved # Author: Paul Alexander Bilokon <paul@thalesians.com> # Version: 1.0 (2019.04.23) # Email: education@thalesians.com # Platform: Tested on Windows 10 with Python 3.6 Explanation: End...
11,913
Given the following text description, write Python code to implement the functionality described below step by step Description: AI Platform Step1: Step 1 Step2: Inspect what the data looks like by looking at the first couple of rows Step8: Step 2 Step11: The second file, called model.py, defines the input functio...
Python Code: import os Explanation: AI Platform: Qwik Start This lab gives you an introductory, end-to-end experience of training and prediction on AI Platform. The lab will use a census dataset to: Create a TensorFlow 2.x training application and validate it locally. Run your training job on a single worker instance i...
11,914
Given the following text description, write Python code to implement the functionality described below step by step Description: <H1>Covariance and correlation</H1> Step1: <H2>Covariance</H2> <P>Measures how two variables vary in tandem from their means. To measure the covariance we take a variable that consist of a ...
Python Code: %pylab inline Explanation: <H1>Covariance and correlation</H1> End of explanation # generate two random variables x = np.random.normal(3.0, 1.0, 1000) y = np.random.normal(50.0, 10.0, 1000) # calculate variance vectors x_var = [i - x.mean() for i in x] y_var = [i - y.mean() for i in y] # compute dot produc...
11,915
Given the following text description, write Python code to implement the functionality described below step by step Description: jQAssistant Demos Neo4j-Server starten mvn jqassistant Step1: Klasse mit den meisten Methoden auflisten Step2: Statische, geschriebene Variablen Step3: Aggregation von Messergebnissen übe...
Python Code: %load_ext cypher Explanation: jQAssistant Demos Neo4j-Server starten mvn jqassistant:server Browser öffnen http://localhost:7474/browser/ Drawer öffnen Labels durchklicken Commit Class :DECLARES jQAssistant Dokumentation: http://buschmais.github.io/jqassistant/doc/1.3.0/#_java_plugin Beispiel-Queries Setup...
11,916
Given the following text description, write Python code to implement the functionality described below step by step Description: FD_1D_DX4_DT2_fast 1-D acoustic Finite-Difference modelling GNU General Public License v3.0 Author Step1: Input Parameter Step2: Preparation Step3: Create space and time vector Step4: So...
Python Code: %matplotlib inline import numpy as np import time as tm import matplotlib.pyplot as plt Explanation: FD_1D_DX4_DT2_fast 1-D acoustic Finite-Difference modelling GNU General Public License v3.0 Author: Florian Wittkamp Finite-Difference acoustic seismic wave simulation Discretization of the first-order acou...
11,917
Given the following text description, write Python code to implement the functionality described below step by step Description: Big-graph generation In this demo, we will verify that our big-graph generation code is functioning properly on a small portion of a real DWI dataset that we can manually verify very easily....
Python Code: import ndmg import ndmg.utils as mgu # run small demo for experiments print(mgu.execute_cmd('ndmg_demo-dwi', verb=True)[0]) Explanation: Big-graph generation In this demo, we will verify that our big-graph generation code is functioning properly on a small portion of a real DWI dataset that we can manually...
11,918
Given the following text description, write Python code to implement the functionality described below step by step Description: Case Study - Text classification for SMS spam detection We first load the text data from the dataset directory that should be located in your notebooks directory, which we created by running...
Python Code: import os with open(os.path.join("datasets", "smsspam", "SMSSpamCollection")) as f: lines = [line.strip().split("\t") for line in f.readlines()] text = [x[1] for x in lines] y = [int(x[0] == "spam") for x in lines] text[:10] y[:10] print('Number of ham and spam messages:', np.bincount(y)) type(text) ty...
11,919
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating Models with TensorFlow and PyTorch In the tutorials so far, we have used standard models provided by DeepChem. This is fine for many applications, but sooner or later you will want...
Python Code: !pip install --pre deepchem Explanation: Creating Models with TensorFlow and PyTorch In the tutorials so far, we have used standard models provided by DeepChem. This is fine for many applications, but sooner or later you will want to create an entirely new model with an architecture you define yourself. ...
11,920
Given the following text description, write Python code to implement the functionality described below step by step Description: IPython IPython (Interactive Python) is an enhanced Python shell which provides a more robust and productive development environment for users. There are several key features that set it apa...
Python Code: import numpy as np np.sin(4)**2 _1 _i1 _1 / 4. Explanation: IPython IPython (Interactive Python) is an enhanced Python shell which provides a more robust and productive development environment for users. There are several key features that set it apart from the standard Python shell. Interactive data analy...
11,921
Given the following text description, write Python code to implement the functionality described below step by step Description: NGC ... (UGC ...) Step1: <h2 id="tocheading">Оглавление</h2> <div id="toc"></div> Статьи Разное Step2: Кинематические данные по звездам Кривая вращения Step3: Дисперсии Для большой оси St...
Python Code: from IPython.display import HTML from IPython.display import Image import os %pylab %matplotlib inline %run ../../utils/load_notebook.py from photometry import * from instabilities import * name = '...' gtype = '...' incl = None scale = None #kpc/arcsec data_path = None # sin_i, cos_i = np.sin(incl*np.pi/1...
11,922
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Numpy Techniques <img src="assets/numpylogo.png" alt="http Step1: Bandwidth-limited ops Have to pull in more cache lines for the pointers Poor locality causes pipeline stalls Step2...
Python Code: import numpy as np import time import gc import sys assert sys.maxsize > 2 ** 32, "get a new computer!" # Allocation-sensitive timing needs to be done more carefully # Compares runtimes of f1, f2 def compare_times(f1, f2, setup1=None, setup2=None, runs=5): print(' format: mean seconds (standard erro...
11,923
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ipsl', 'sandbox-2', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: IPSL Source ID: SANDBOX-2 Topic: Ocnbgchem Sub-Topics: Tracers. Prop...
11,924
Given the following text description, write Python code to implement the functionality described below step by step Description: xkcd 1313 Step1: We can see that there are multiple names that are both winners and losers Step2: Clinton? He won both his elections, didn't he? Yes, Bill Clinton did, but George Clinton (...
Python Code: from __future__ import division, print_function import re import itertools def words(text): return set(text.split()) winners = words('''washington adams jefferson jefferson madison madison monroe monroe adams jackson jackson van-buren harrison polk taylor pierce buchanan lincoln lincoln grant gra...
11,925
Given the following text description, write Python code to implement the functionality described below step by step Description: The following source code defines a convolutional neural network architecture called LeNet. LeNet is a popular network known to work well on digit classification tasks. We will use a slightl...
Python Code: data = mx.sym.var('data') # first conv layer conv1 = mx.sym.Convolution(data=data, kernel=(5,5), num_filter=20) tanh1 = mx.sym.Activation(data=conv1, act_type="tanh") pool1 = mx.sym.Pooling(data=tanh1, pool_type="max", kernel=(2,2), stride=(2,2)) # second conv layer conv2 = mx.sym.Convolution(data=pool1, k...
11,926
Given the following text description, write Python code to implement the functionality described below step by step Description: Let's do a quick inspection of the data by plotting the distribution of the different types of cuisines in the dataset. Step1: Italian and mexican categories dominate the recipes dataset. W...
Python Code: train = pd.read_json("train.json") matplotlib.style.use('ggplot') cuisine_group = train.groupby('cuisine') cuisine_group.size().sort_values(ascending=True).plot.barh() plt.show() Explanation: Let's do a quick inspection of the data by plotting the distribution of the different types of cuisines in the data...
11,927
Given the following text description, write Python code to implement the functionality described below step by step Description: To create a new database, we first import sqlite3 and then instantiate a new database object with the sqlite3.connect() method. Step2: Next, we connect to the database with the sqlite3.conn...
Python Code: import sqlite3 db = sqlite3.connect("name_database.db") Explanation: To create a new database, we first import sqlite3 and then instantiate a new database object with the sqlite3.connect() method. End of explanation # create a database called name_database.db # add one table to the database called names_ta...
11,928
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Load and inspect the data Step1: 2. Let the toolkit choose the model Step2: 3. The simple thresholding model Step3: 4. The moving Z-score model Step4: 5. The Bayesian changepoint mode...
Python Code: import graphlab as gl okla_daily = gl.load_timeseries('working_data/ok_daily_stats.ts') print "Number of rows:", len(okla_daily) print "Start:", okla_daily.min_time print "End:", okla_daily.max_time okla_daily.print_rows(3) import matplotlib.pyplot as plt %matplotlib notebook plt.style.use('ggplot') fig, a...
11,929
Given the following text description, write Python code to implement the functionality described below step by step Description: KinMS galaxy fitting tutorial This tutorial aims at getting you up and running with galaxy kinematic modelling using KinMS! To start you will need to download the KinMSpy code and have it in...
Python Code: from kinms import KinMS import numpy as np from astropy.io import fits from kinms.utils.KinMS_figures import KinMS_plotter Explanation: KinMS galaxy fitting tutorial This tutorial aims at getting you up and running with galaxy kinematic modelling using KinMS! To start you will need to download the KinMSpy ...
11,930
Given the following text description, write Python code to implement the functionality described below step by step Description: This is the IOHMM model with the parameters learned in a supervised way. This is corresponding to the counting frequency process as in the supervised HMM. See notes in http Step1: Load spee...
Python Code: from __future__ import division import json import warnings import numpy as np import pandas as pd from IOHMM import SupervisedIOHMM from IOHMM import OLS, CrossEntropyMNL warnings.simplefilter("ignore") Explanation: This is the IOHMM model with the parameters learned in a supervised way. This is correspo...
11,931
Given the following text description, write Python code to implement the functionality described below step by step Description: Sebastian Raschka, 2015 Python Machine Learning Essentials Compressing Data via Dimensionality Reduction Note that the optional watermark extension is a small IPython notebook plugin that I ...
Python Code: %load_ext watermark %watermark -a 'Sebastian Raschka' -u -d -v -p numpy,scipy,matplotlib,scikit-learn # to install watermark just uncomment the following line: #%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py Explanation: Sebastian Raschka, 2015 Python Machine Learning Es...
11,932
Given the following text description, write Python code to implement the functionality described below step by step Description: Energy Lancaster publication miner This workbook parses all of the publications listed on Energy Lancaster's Lancaster University Research Portal page and extracts keywoprds an topical data ...
Python Code: #python dom extension functions to get class and other attributes def getAttr(dom,cl,attr='class',el='div'): toreturn=[] divs=dom.getElementsByTagName(el) for div in divs: clarray=div.getAttribute(attr).split(' ') for cli in clarray: if cli==cl: toreturn.append(div) ...
11,933
Given the following text description, write Python code to implement the functionality described. Description: Construct two N Function to generate two arrays satisfying the given conditions ; Declare the two arrays A and B ; Iterate from range [ 1 , 2 * n ] ; Assign consecutive numbers to same indices of the two array...
Python Code: def printArrays(n ) : A , B =[] ,[] ; for i in range(1 , 2 * n + 1 ) : if(i % 2 == 0 ) : A . append(i ) ;  else : B . append(i ) ;   print("{ ▁ ", end = "") ; for i in range(n ) : print(A[i ] , end = "") ; if(i != n - 1 ) : print(", ▁ ", end = "") ;   print("} ") ; prin...
11,934
Given the following text description, write Python code to implement the functionality described below step by step Description: COSC Learning Lab 03_interface_startup.py Related Scripts Step1: Implementation Step2: Execution Step3: HTTP
Python Code: help('learning_lab.03_interface_startup') Explanation: COSC Learning Lab 03_interface_startup.py Related Scripts: * 03_interface_shutdown.py * 03_interface_configuration.py Table of Contents Table of Contents Documentation Implementation Execution HTTP Documentation End of explanation from importlib import...
11,935
Given the following text description, write Python code to implement the functionality described below step by step Description: GEM-PRO - SBML Model This notebook gives an example of how to run the GEM-PRO pipeline with a SBML model, in this case iNJ661, the metabolic model of M. tuberculosis. <div class="alert alert...
Python Code: import sys import logging # Import the GEM-PRO class from ssbio.pipeline.gempro import GEMPRO # Printing multiple outputs per cell from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" Explanation: GEM-PRO - SBML Model This notebook gives an example of h...
11,936
Given the following text description, write Python code to implement the functionality described below step by step Description: Beaming and Boosting Due to concerns about accuracy, support for Beaming & Boosting has been disabled as of the 2.2 release of PHOEBE (although we hope to bring it back in a future release)....
Python Code: #!pip install -I "phoebe>=2.3,<2.4" Explanation: Beaming and Boosting Due to concerns about accuracy, support for Beaming & Boosting has been disabled as of the 2.2 release of PHOEBE (although we hope to bring it back in a future release). It may come as surprise that support for Doppler boosting has been ...
11,937
Given the following text description, write Python code to implement the functionality described below step by step Description: Upvote data Step1: In the Yelp Question in HW1, please normalize the data so that it has the same L2 norm. We will grade it either way, but please state clearly what you did to treat the ye...
Python Code: # Load a text file of integers: y = np.loadtxt("yelp_data/upvote_labels.txt", dtype=np.int) # Load a text file with strings identifying the 1000 features: featureNames = open("yelp_data/upvote_features.txt").read().splitlines() featureNames = np.array(featureNames) # Load a csv of floats, which are the val...
11,938
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">TensorFlow Neural Network Lab</h1> <img src="image/notmnist.png"> In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl...
Python Code: import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfile import ZipFile p...
11,939
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="img/nao.jpg" align="right" width=200> Sensor de so (micròfon) El micròfon del robot detecta el soroll ambiental. No sap reconèixer paraules, però si pot reaccionar a una palmada, o...
Python Code: from functions import connect, sound, forward, stop connect() Explanation: <img src="img/nao.jpg" align="right" width=200> Sensor de so (micròfon) El micròfon del robot detecta el soroll ambiental. No sap reconèixer paraules, però si pot reaccionar a una palmada, o un crit. Altres robots més sofisticats co...
11,940
Given the following text description, write Python code to implement the functionality described below step by step Description: Initial Overview First we want to have a look at the data. Step1: Ok, so we're getting a pretty simple input format Step2: According to my knowledge with quora, this is indeed a full text ...
Python Code: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np %matplotlib inline df = pd.read_csv('../data/raw/train.csv') df.head() Explanation: Initial Overview First we want to have a look at the data. End of explanation questions = pd.concat([df['question1'], df['question...
11,941
Given the following text description, write Python code to implement the functionality described below step by step Description: Using ctools from Python In this notebook you will learn how to use the ctools and cscripts from Python instead of typing the commands in the console. ctools provides two Python modules that...
Python Code: import gammalib import ctools import cscripts Explanation: Using ctools from Python In this notebook you will learn how to use the ctools and cscripts from Python instead of typing the commands in the console. ctools provides two Python modules that allow using all tools and scripts as Python classes. To u...
11,942
Given the following text description, write Python code to implement the functionality described below step by step Description: Exemplo de CRUD no MongoDB Exemplo de CRUD completo em MongoDB Autor Step1: Definindo um documento para ser inserido Step2: Inserindo o documento na base Step3: Recuperando documentos Ste...
Python Code: from pymongo import MongoClient cli = MongoClient() db = cli['treinamento'] col = db['cadastro'] Explanation: Exemplo de CRUD no MongoDB Exemplo de CRUD completo em MongoDB Autor: Christiano Anderson Propus Data Science Estabelecendo a conexão com o banco End of explanation cad = { 'nome': 'Christiano ...
11,943
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing Stock Indices by Magnus Erik Hvass Pedersen / GitHub / Videos on YouTube Introduction When comparing the historical returns on stock indices, it is a common mistake to only conside...
Python Code: %matplotlib inline # Imports from Python packages. import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter import pandas as pd import numpy as np import os # Imports from FinanceOps. from data_keys import * from data import load_index_data, load_usa_cpi from data import load_usa_gov_bon...
11,944
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple Sounding Use MetPy as straightforward as possible to make a Skew-T LogP plot. Step1: We will pull the data out of the example dataset into individual variables and assign units.
Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd import metpy.calc as mpcalc from metpy.cbook import get_test_data from metpy.plots import add_metpy_logo, SkewT from metpy.units import units # Change default to be better for skew-T plt.rcParams['figure.figsize'] = (9, 9) # Upper air d...
11,945
Given the following text description, write Python code to implement the functionality described below step by step Description: Here we want to place n events of transition between an ancestral lifestyle and a convergent lifestyle in a phylogeny. We want these n events to be independent, not nested. We return them in...
Python Code: from ete3 import Tree import string import scipy.stats as stats import numpy as np tl = Tree() # We create a random tree topology numTips = 20 candidateNames = list(string.ascii_lowercase) tipNames = candidateNames[0:20] tl.populate(numTips, names_library=tipNames) print (tl) #Alternatively we could read a...
11,946
Given the following text description, write Python code to implement the functionality described below step by step Description: Data deduplication Introduction This example shows how to find records in datasets belonging to the same entity. In our case,we try to deduplicate a dataset with records of persons. We will ...
Python Code: import recordlinkage from recordlinkage.datasets import load_febrl1 Explanation: Data deduplication Introduction This example shows how to find records in datasets belonging to the same entity. In our case,we try to deduplicate a dataset with records of persons. We will try to link within the dataset based...
11,947
Given the following text description, write Python code to implement the functionality described below step by step Description: Image classification with EANet (External Attention Transformer) Author Step1: Prepare the data Step2: Configure the hyperparameters Step3: Use data augmentation Step4: Implement the pat...
Python Code: import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import tensorflow_addons as tfa import matplotlib.pyplot as plt Explanation: Image classification with EANet (External Attention Transformer) Author: ZhiYong Chang<br> Date created: 2021/10/19<br> La...
11,948
Given the following text description, write Python code to implement the functionality described below step by step Description: La función Esta ecuación por Glass y Pasternack (1978) sirve para modelar redes neuronales y de interacción génica. $$x_{t+1}=\frac{\alpha x_{t}}{1+\beta x_{t}}$$ Donde $\alpha$ y $\beta$ so...
Python Code: def g(x, alpha, beta): assert alpha >= 0 and beta >= 0 return (alpha*x)/(1 + (beta * x)) def plot_cobg(x, alpha, beta): y = np.linspace(x[0],x[1],300) g_y = g(y, alpha, beta) cobweb(lambda x: g(x, alpha, beta), y, g_y) # configura gráfica interactiva interact(plot_cobg, x=wid...
11,949
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Landice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cccma', 'sandbox-3', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: CCCMA Source ID: SANDBOX-3 Topic: Landice Sub-Topics: Glaciers, Ice. Pr...
11,950
Given the following text description, write Python code to implement the functionality described below step by step Description: How to run the /home/test/indras_net/models/flocking model. First we import all necessary files. Step1: We then initialize global variables. Step2: Next we call the set_up function to set ...
Python Code: from models.flocking import set_up Explanation: How to run the /home/test/indras_net/models/flocking model. First we import all necessary files. End of explanation from indra.agent import Agent, X, Y from indra.composite import Composite from indra.display_methods import BLUE, TREE from indra.env import En...
11,951
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The Cirq Developers Step1: Rabi oscillation experiment <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: In this experiment,...
Python Code: # @title 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 # dis...
11,952
Given the following text description, write Python code to implement the functionality described below step by step Description: sell-short-in-may-and-go-away see Step1: Some global data Step2: Define Strategy Class Step3: Run Strategy Step4: Run Benchmark, Retrieve benchmark logs, and Generate benchmark stats Ste...
Python Code: import datetime import matplotlib.pyplot as plt import pandas as pd import pinkfish as pf # Format price data pd.options.display.float_format = '{:0.2f}'.format %matplotlib inline # Set size of inline plots '''note: rcParams can't be in same cell as import matplotlib or %matplotlib inline %matplo...
11,953
Given the following text description, write Python code to implement the functionality described below step by step Description: 2. Acquire the Data Finding Data Sources There are three place to get onion price and quantity information by market. Agmarket - This is the website run by the Directorate of Marketing & In...
Python Code: # Import the library we need, which is Pandas import pandas as pd # Read all the tables from the html document AllTables = pd.read_html('MonthWiseMarketArrivalsJan2016.html') # Let us find out how many tables has it found? len(AllTables) Explanation: 2. Acquire the Data Finding Data Sources There are thre...
11,954
Given the following text description, write Python code to implement the functionality described below step by step Description: 분산 분석 기반의 카테고리 분석 회귀 분석 대상이 되는 독립 변수가 카테고리 값을 가지는 변수인 경우에는 카테고리 값에 의해 연속 변수인 y값이 달라진다. 이러한 경우, 분산 분석(ANOVA)을 사용하면 카테고리 값의 영향을 정량적으로 분석할 수 있다. 또한 이는 카테고리 값에 의해 회귀 모형이 달라지는 것으로도 볼 수 있기 때문에 모형 ...
Python Code: from sklearn.preprocessing import OneHotEncoder encoder = OneHotEncoder() x0 = np.random.choice(3, 10) x0 encoder.fit(x0[:, np.newaxis]) X = encoder.transform(x0[:, np.newaxis]).toarray() X dfX = pd.DataFrame(X, columns=encoder.active_features_) dfX Explanation: 분산 분석 기반의 카테고리 분석 회귀 분석 대상이 되는 독립 변수가 카테고리 값...
11,955
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This IPython notebook illustrates how to perform matching using the rule-based matcher. First, we need to import py_entitymatching package and other libraries as follows Step1: ...
Python Code: # Import py_entitymatching package import py_entitymatching as em import os import pandas as pd Explanation: Introduction This IPython notebook illustrates how to perform matching using the rule-based matcher. First, we need to import py_entitymatching package and other libraries as follows: End of explana...
11,956
Given the following text description, write Python code to implement the functionality described below step by step Description: https Step1: Step 0 - hyperparams Step2: Step 1 - collect data (and/or generate them) Step3: Step 2 - Build model Step4: Step 3 training the network Step5: TODO Co integration https
Python Code: from __future__ import division import tensorflow as tf from os import path import numpy as np import pandas as pd import csv from sklearn.model_selection import StratifiedShuffleSplit from time import time from matplotlib import pyplot as plt import seaborn as sns from mylibs.jupyter_notebook_helper impor...
11,957
Given the following text description, write Python code to implement the functionality described below step by step Description: Using the template below, make a widget view that displays text, possibly 'Hello World'. Step1: Using the template below, make a color picker widget. This can be done in a few steps
Python Code: %%javascript delete requirejs.s.contexts._.defined.CustomViewModule; define('CustomViewModule', ['jquery', 'widgets/js/widget'], function($, widget) { var CustomView = widget.DOMWidgetView.extend({ }); return {CustomView: CustomView}; }); from IPython.html.widgets import DOMWidget from IPython....
11,958
Given the following text description, write Python code to implement the functionality described below step by step Description: minimask mosaic example Construct a mosaic of squares over the sky Step1: Specify the location of the mask file to write Step2: Construct a mask using a tile pattern with centers specified...
Python Code: %matplotlib notebook import os import numpy as np import tempfile import matplotlib.pyplot as pyplot import logging logging.basicConfig(level=logging.INFO) import minimask.mask as mask import minimask.healpix_projection as hp import minimask.io.mosaic as mosaic Explanation: minimask mosaic example Construc...
11,959
Given the following text description, write Python code to implement the functionality described below step by step Description: DAT210x - Programming with Python for DS Module4- Lab1 Step1: Every 100 samples in the dataset, we save 1. If things run too slow, try increasing this number. If things run too fast, try de...
Python Code: import pandas as pd import matplotlib.pyplot as plt import matplotlib from mpl_toolkits.mplot3d import Axes3D from plyfile import PlyData, PlyElement # Look pretty... # matplotlib.style.use('ggplot') plt.style.use('ggplot') Explanation: DAT210x - Programming with Python for DS Module4- Lab1 End of explanat...
11,960
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Feature Engineering </h1> In this notebook, you will learn how to incorporate feature engineering into your pipeline. <ul> <li> Working with feature columns </li> <li> Adding feature cr...
Python Code: %%bash source activate py2env conda install -y pytz pip uninstall -y google-cloud-dataflow pip install --upgrade apache-beam[gcp]==2.9.0 Explanation: <h1> Feature Engineering </h1> In this notebook, you will learn how to incorporate feature engineering into your pipeline. <ul> <li> Working with feature col...
11,961
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="#A-short-study-of-Rényi-entropy" data-toc-modified-id="A-short-study-of-Rényi-entropy-1"><span class="toc-item-num">1&nbsp;&nbsp;</sp...
Python Code: !pip install watermark matplotlib numpy %load_ext watermark %watermark -v -m -a "Lilian Besson" -g -p matplotlib,numpy import numpy as np import matplotlib.pyplot as plt Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#A-short-study-of-Rényi-entropy" data-toc-modified-id="A-short-stud...
11,962
Given the following text description, write Python code to implement the functionality described below step by step Description: Combining and Merging Streams Step1: Combining Streams with Binary Operators For streams x, y, and a binary operator, op Step2: Examples of zip_stream and zip_map zip_stream is similar to ...
Python Code: import sys sys.path.append("../") from IoTPy.core.stream import Stream, run from IoTPy.agent_types.op import map_element from IoTPy.helper_functions.recent_values import recent_values Explanation: Combining and Merging Streams End of explanation w = Stream('w') x = Stream('x') y = Stream('y') z = (x+y)*w #...
11,963
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Exercises This notebook is for programming exercises in python using Step1: Python Statistics Step2: Some simpler exercises based on common python function Question Step3: Questio...
Python Code: import math import numpy as np import pandas as pd import re from operator import itemgetter, attrgetter Explanation: Python Exercises This notebook is for programming exercises in python using : Statistics Inbuilt Functions and Libraries Pandas Numpy End of explanation def median(dataPoints): "comp...
11,964
Given the following text description, write Python code to implement the functionality described below step by step Description: Image Processing This ipython (sorry, Jupyter) notebook contains the examples that I'll be covering in the 1-dimensional part of my image processing session. There are no external data file...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline # A nice alternative to inline (which allows interaction with the plots, but can be confusing) is # %matplotlib notebook Explanation: Image Processing This ipython (sorry, Jupyter) notebook contains the examples that I'll be covering in ...
11,965
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep CNN Models Constructing and training your own ConvNet from scratch can be Hard and a long task. A common trick used in Deep Learning is to use a pre-trained model and finetune it to the...
Python Code: from keras.applications import VGG16 from keras.applications.imagenet_utils import preprocess_input, decode_predictions import os # -- Jupyter/IPython way to see documentation # please focus on parameters (e.g. include top) VGG16?? vgg16 = VGG16(include_top=True, weights='imagenet') Explanation: Deep CNN M...
11,966
Given the following text description, write Python code to implement the functionality described below step by step Description: 자료 안내 Step1: 주의 위 모듈을 임포트하면 아래 모듈 또한 자동으로 임포트 된다. GongSu21_Statistics_Averages.py 주요 내용 상관분석 공분산 상관관계와 인과관계 주요 예제 21장에서 다룬 미국의 51개 주에서 거래되는 담배(식물)의 도매가격 데이터를 보다 상세히 분석한다. 특히, 캘리포니아 주에서 거래된...
Python Code: from GongSu22_Statistics_Population_Variance import * Explanation: 자료 안내: 여기서 다루는 내용은 아래 사이트의 내용을 참고하여 생성되었음. https://github.com/rouseguy/intro2stats 상관분석 안내사항 지난 시간에 다룬 21장과 22장 내용을 활용하고자 한다. 따라서 아래와 같이 21장과 22장 내용을 모듈로 담고 있는 파이썬 파일을 임포트 해야 한다. 주의: 아래 두 개의 파일이 동일한 디렉토리에 위치해야 한다. * GongSu21_Statistics_Aver...
11,967
Given the following text description, write Python code to implement the functionality described below step by step Description: Notes from David Beazley's Python3 Metaprogramming tutorial (2013) "ported" to Python 2.7, unless noted otherwise A Debugging Decorator Step1: Decorators with arguments Calling convention p...
Python Code: from functools import wraps def debug(func): msg = func.__name__ # wraps is used to keep the metadata of the original function @wraps(func) def wrapper(*args, **kwargs): print(msg) return func(*args, **kwargs) return wrapper @debug def add(x,y): return x+y add(2,3) d...
11,968
Given the following text description, write Python code to implement the functionality described below step by step Description: Geospatial data models Resources Step1: In startup pannel set GIS Data Directory to path to datasets, for example on MS Windows, C Step2: The -p flag for g.region is used to print the regi...
Python Code: # Obtain sample data and set new Grass mapset import urllib from zipfile import ZipFile import os.path zip_path = "/home/jovyan/work/tmp/nc_spm_08_grass7.zip" mapset_path = "/home/jovyan/grassdata" if not os.path.exists(zip_path): urllib.urlretrieve("https://grass.osgeo.org/sampledata/north_carolina/nc...
11,969
Given the following text description, write Python code to implement the functionality described below step by step Description: Performing Linear Regression in TensorFlow I gathered this data for current real estate listing prices in North Bergen from Zillow. Let's see if we can use it to develop a model for housing ...
Python Code: %matplotlib inline #Typical imports import matplotlib import matplotlib.pyplot as plt import numpy as np import tensorflow as tf import pandas as pd # plots on fleek matplotlib.style.use('ggplot') # Read the housing data from the csv file into a pandas dataframe # the names keyword allows us to name the co...
11,970
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Linear Regression Learning Objectives Analyze a Pandas Dataframe Create Seaborn plots for Exporatory Data Analysis Train a Linear Regression Model using Scikit-Learn Introdu...
Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns # Seaborn is a Python data visualization library based on matplotlib. %matplotlib inline Explanation: Introduction to Linear Regression ...
11,971
Given the following text description, write Python code to implement the functionality described below step by step Description: pandasのデータフレーム Step1: 2次元の array を DataFrame に変換する例です。 Step2: columns オプションで、各列の column 名を指定します。 Step3: Series オブジェクトから DataFrame を作成する例です。 Step4: 各列の column 名と対応する Series オブジェクトのディクショナリ...
Python Code: import numpy as np import matplotlib.pyplot as plt import pandas as pd from pandas import Series, DataFrame Explanation: pandasのデータフレーム End of explanation from numpy.random import randint dices = randint(1,7,(5,2)) dices Explanation: 2次元の array を DataFrame に変換する例です。 End of explanation diceroll = DataFrame(...
11,972
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: NumPy has many built-in functions and capabilities. We won't cover them all but instead we will focus on some of the most important aspects of NumPy Step2: Built-in Me...
Python Code: import numpy as np Explanation: <a href='http://www.pieriandata.com'><img src='../Pierian_Data_Logo.png'/></a> <center><em>Copyright Pierian Data</em></center> <center><em>For more information, visit us at <a href='http://www.pieriandata.com'>www.pieriandata.com</a></em></center> NumPy NumPy is a powerful ...
11,973
Given the following text description, write Python code to implement the functionality described below step by step Description: Generative Adversarial Network In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d...
Python Code: %matplotlib inline import pickle as pkl import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data') Explanation: Generative Adversarial Network In this notebook, we'll be building a gen...
11,974
Given the following text description, write Python code to implement the functionality described below step by step Description: Input Data Step1: Test Frame Nodes Table nodes (file nodes.csv) provides the $x$-$y$ coordinates of each node. Other columns, such as the $z$- coordinate are optional, and ignored if give...
Python Code: from salib import extend, NBImporter from Tables import Table, DataSource from Nodes import Node from Members import Member from LoadSets import LoadSet, LoadCombination from NodeLoads import makeNodeLoad from MemberLoads import makeMemberLoad from collections import OrderedDict, defaultdict import numpy a...
11,975
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Keras <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: tf.keras ではKerasと互換性のあるコードを実行できますが、注意...
Python Code: #@title 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 # dist...
11,976
Given the following text description, write Python code to implement the functionality described below step by step Description: The Two Envelope Paradox - Simulated Introduction Bayesian statistics can most naively be described as the art of thinking conditionally. Conditional probability leads often to unexpected ou...
Python Code: import matplotlib import matplotlib.pyplot as plt import numpy as np import pymc as pm from numpy.random import choice %matplotlib inline matplotlib.style.use('ggplot') matplotlib.rc_params_from_file("../styles/matplotlibrc" ).update() Explanation: The Two Envelope Paradox - Simulated Introduction Bayesian...
11,977
Given the following text description, write Python code to implement the functionality described below step by step Description: Dimensionality Reduction with the Shogun Machine Learning Toolbox By Sergey Lisitsyn (lisitsyn) and Fernando J. Iglesias Garcia (iglesias). This notebook illustrates <a href="http Step1: Th...
Python Code: import numpy import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') def generate_data(curve_type, num_points=1000): if curve_type=='swissroll': tt = numpy.array((3*numpy.pi/2)*(1+2*numpy.random.rand(num_points))) height = numpy.array((numpy.random.rand(num_points)-0.5)) X = numpy.ar...
11,978
Given the following text description, write Python code to implement the functionality described below step by step Description: Generative Adversarial Network In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d...
Python Code: %matplotlib inline import pickle as pkl import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data') Explanation: Generative Adversarial Network In this notebook, we'll be building a gen...
11,979
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: MNIST on TPU (Tensor Processing Unit)<br>or GPU using tf.Keras and tf.data.Dataset <table><tr><td><img valign="middle" src="https Step2: (you can double-ckick on collapsed cells to v...
Python Code: import os, re, time, json import PIL.Image, PIL.ImageFont, PIL.ImageDraw import numpy as np import tensorflow as tf from matplotlib import pyplot as plt AUTOTUNE = tf.data.AUTOTUNE print("Tensorflow version " + tf.__version__) #@title visualization utilities [RUN ME] This cell contains helper functions use...
11,980
Given the following text description, write Python code to implement the functionality described below step by step Description: Load necessary packages Step1: Define functions for filtering, moving averages, and normalizing data Step2: Read bandwidth and rain/temperature data and normalize them Step3: Smoothing da...
Python Code: %matplotlib inline from scipy import interpolate from scipy import special from scipy.signal import butter, lfilter, filtfilt import matplotlib.pyplot as plt import numpy as np from numpy import genfromtxt from nitime import algorithms as alg from nitime import utils from scipy.stats import t import pandas...
11,981
Given the following text description, write Python code to implement the functionality described below step by step Description: Практическое задание к уроку 1 (2 неделя). Линейная регрессия Step1: Мы будем работать с датасетом "bikes_rent.csv", в котором по дням записаны календарная информация и погодные условия, ха...
Python Code: import pandas as pd import numpy as np from matplotlib import pyplot as plt %matplotlib inline Explanation: Практическое задание к уроку 1 (2 неделя). Линейная регрессия: переобучение и регуляризация В этом задании мы на примерах увидим, как переобучаются линейные модели, разберем, почему так происходит, и...
11,982
Given the following text description, write Python code to implement the functionality described below step by step Description: Assembly of system with multiple domains, variables and numerics This tutorial has the dual purpose of illustrating parameter assigment in PorePy, and also showing how to set up problems in...
Python Code: import numpy as np import scipy.sparse as sps import porepy as pp Explanation: Assembly of system with multiple domains, variables and numerics This tutorial has the dual purpose of illustrating parameter assigment in PorePy, and also showing how to set up problems in (mixed-dimensional) geometries. It co...
11,983
Given the following text description, write Python code to implement the functionality described below step by step Description: Classifying dogs vs cats with Alex Net In this notebook, we try to implement a (somehow simplified) version of Alex Net to solve the Cats vs Dogs problem from Kaggle. Following indications f...
Python Code: from __future__ import division, print_function from matplotlib import pyplot as plt %matplotlib inline import os, errno import numpy as np from tqdm import tqdm from shutil import copy import numpy as np import pandas as pd import cv2 import bcolz IMAGE_WIDTH = 227 IMAGE_HEIGHT = 227 Explanation: Classify...
11,984
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex client library Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Once you've installed the Vertex client library and Google clo...
Python Code: import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG Explanation: Vertex client library: AutoML image segmentation model for online prediction <table a...
11,985
Given the following text description, write Python code to implement the functionality described below step by step Description: Contents and Objectives Implementation of the water-filling algorithm Interactive illustration of the water-filling principle Step1: Specify total power p_tot as well as the noise levels of...
Python Code: import numpy as np import matplotlib.pyplot as plt import matplotlib from ipywidgets import interactive import ipywidgets as widgets %matplotlib inline # plotting options font = {'size' : 30} plt.rc('font', **font) plt.rc('text', usetex=matplotlib.checkdep_usetex(True)) matplotlib.rc('figure', figsize=(...
11,986
Given the following text description, write Python code to implement the functionality described below step by step Description: Near-duplicate image search Author Step1: Load the dataset and create a training set of 1,000 images To keep the run time of the example short, we will be using a subset of 1,000 images fro...
Python Code: import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import time import tensorflow_datasets as tfds tfds.disable_progress_bar() Explanation: Near-duplicate image search Author: Sayak Paul<br> Date created: 2021/09/10<br> Last modified: 2021/09/10<br> Description: Building a near-dupli...
11,987
Given the following text description, write Python code to implement the functionality described below step by step Description: Overlapping Mixtures of Gaussian Processses Valentine Svensson 2015 <br> (with small edits by James Hensman November 2015) This illustrates use of the OMGP model described in Overlapping Mix...
Python Code: %matplotlib inline import GPy from GPclust import OMGP import matplotlib matplotlib.rcParams['figure.figsize'] = (12,6) from matplotlib import pyplot as plt Explanation: Overlapping Mixtures of Gaussian Processses Valentine Svensson 2015 <br> (with small edits by James Hensman November 2015) This illustrat...
11,988
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Step1: Modern X-ray CCDs are technologically similar to the CCDs used in optical astronomy Step2: Both files are in FITS image format, which we can read in using astropy.io.fits (...
Python Code: exec(open('tbc.py').read()) # define TBC and TBC_above import astropy.io.fits as pyfits import numpy as np import matplotlib.pyplot as plt %matplotlib inline from astropy.visualization import LogStretch logstretch = LogStretch() import scipy.stats as st Explanation: Tutorial: X-ray Image Data This notebook...
11,989
Given the following text description, write Python code to implement the functionality described below step by step Description: Encontro 02, Parte 2 Step1: A seguir, vamos configurar as propriedades visuais Step2: Por fim, vamos carregar e visualizar um grafo Step3: Caminhos de comprimento mínimo Seja $\langle n_0...
Python Code: import sys sys.path.append('..') import socnet as sn Explanation: Encontro 02, Parte 2: Revisão de Busca em Largura Este guia foi escrito para ajudar você a atingir os seguintes objetivos: implementar o algoritmo de busca em largura; usar funcionalidades avançadas da biblioteca da disciplina. Primeiramente...
11,990
Given the following text description, write Python code to implement the functionality described below step by step Description: Posterior Predictive Checks PPCs are a great way to validate a model. The idea is to generate data sets from the model using parameter settings from draws from the posterior. Elaborating sl...
Python Code: %matplotlib inline import numpy as np import pymc3 as pm import seaborn as sns import matplotlib.pyplot as plt from collections import defaultdict Explanation: Posterior Predictive Checks PPCs are a great way to validate a model. The idea is to generate data sets from the model using parameter settings fro...
11,991
Given the following text description, write Python code to implement the functionality described below step by step Description: Simulation API A merchant wants to offer products and maximize profits. Just like on a real online marketplace, he can look at all existing offers, add some own, restock or reprice. First, i...
Python Code: import sys sys.path.append('../') Explanation: Simulation API A merchant wants to offer products and maximize profits. Just like on a real online marketplace, he can look at all existing offers, add some own, restock or reprice. First, it has to order products from the producer, which comes with costs. All...
11,992
Given the following text description, write Python code to implement the functionality described below step by step Description: <!-- Some HTML for ncie picture --> <p> <a href="https Step1: A. The semantic connections Step2: A. Web of Science - Recursion 1. Search details Date Step3: Keyword analysis Step4: J...
Python Code: maketimeseries() # Load this function from bottom of notebook to print. Explanation: <!-- Some HTML for ncie picture --> <p> <a href="https://commons.wikimedia.org/wiki/File:Open_Science_-_Prinzipien.png#/media/File:Open_Science_-_Prinzipien.png"><img src="https://upload.wikimedia.org/wikipedia/commons...
11,993
Given the following text description, write Python code to implement the functionality described. Description: Queries for rotation and Kth character of the given string in constant time Python3 implementation of the approach ; Function to perform the required queries on the given string ; Pointer pointing to the curre...
Python Code: size = 2 def performQueries(string , n , queries , q ) : ptr = 0 ; for i in range(q ) : if(queries[i ][0 ] == 1 ) : ptr =(ptr + queries[i ][1 ] ) % n ;  else : k = queries[i ][1 ] ; index =(ptr + k - 1 ) % n ; print(string[index ] ) ;    if __name__== "__main __": string = "a...
11,994
Given the following text description, write Python code to implement the functionality described below step by step Description: FAI1 Practical Deep Learning I | 11 May 2017 | Wayne Nixalo In this notebook I'll be building a simple linear model in Keras using Sequential() Tutorial on Linear Model for MNIST Step1: Tha...
Python Code: # Import relevant libraries from keras.models import Sequential from keras.layers import Dense from keras.optimizers import SGD, RMSprop from keras.preprocessing import image import numpy as np import os # Data functions ~ mostly from utils.py or vgg16.py def get_batches(dirname, gen=image.ImageDataGenerat...
11,995
Given the following text description, write Python code to implement the functionality described below step by step Description: <font size="8">Energy Meter Examples</font> <br> <font size="5">BayLibre's ACME Cape and IIOCapture</font> <br> <hr> Import Required Modules Step1: Target Configuration Step2: Workload Exe...
Python Code: import logging reload(logging) logging.basicConfig( format='%(asctime)-9s %(levelname)-8s: %(message)s', datefmt='%I:%M:%S') # Enable logging at INFO level logging.getLogger().setLevel(logging.INFO) # Generate plots inline %matplotlib inline import os # Support to access the remote target import de...
11,996
Given the following text description, write Python code to implement the functionality described below step by step Description: Multi-bootstrap for evaluating pretrained LMs This notebook shows an example of a paired multi-bootstrap analysis. This type of analysis is applicable for any kind of intervention that is ap...
Python Code: #@title Import libraries and multibootstrap code import re import os import numpy as np import pandas as pd import sklearn.metrics import scipy.stats from tqdm.notebook import tqdm # for progress indicator import multibootstrap scratch_dir = "/tmp/multiberts_mnli" if not os.path.isdir(scratch_dir): o...
11,997
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 6.1.2 - Using word embeddings Embedding layer with Keras Step1: The layers transforms a 2D input tensor of integer of shape (number_of samples, sequence_length) into a 3D floating p...
Python Code: import keras keras.__version__ from keras.layers import Embedding # Number of maximum tokens is equal of maximum word index + 1 max_number_of_tokens = 1000 embedding_dimentionality = 64 embedding_layer = Embedding(max_number_of_tokens, embedding_dimentionality) Explanation: Chapter 6.1.2 - Using word embed...
11,998
Given the following text description, write Python code to implement the functionality described below step by step Description: Starting the Analysis Cluster NEXUS utilizes Apache Spark running on Apache Mesos for its analytical functions. Now that the infrastructure has been started, we can start up the analysis clu...
Python Code: # TODO Run this cell to see the status of the Mesos slaves. You should see 3 slaves connected. import requests import json response = requests.get('http://mesos-master:5050/state.json') print(json.dumps(response.json()['slaves'], indent=2)) Explanation: Starting the Analysis Cluster NEXUS utilizes Apache S...
11,999
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Model10 Step2: Feature functions(private) Step3: Feature function(public) Step4: Utility functions Step5: GMM Classifying questions features Step7: B. Modeling Select model Step8...
Python Code: import gzip import pickle from os import path from collections import defaultdict from numpy import sign Load buzz data as a dictionary. You can give parameter for data so that you will get what you need only. def load_buzz(root='../data', data=['train', 'test', 'questions'], format='pklz'): buzz_data ...