Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
11,400
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Tutorial Numpy is a computational library for Python that is optimized for operations on multi-dimensional arrays. In this notebook we will use numpy to work with 1-d arrays (often cal...
Python Code: import numpy as np # importing this way allows us to refer to numpy as np Explanation: Numpy Tutorial Numpy is a computational library for Python that is optimized for operations on multi-dimensional arrays. In this notebook we will use numpy to work with 1-d arrays (often called vectors) and 2-d arrays (o...
11,401
Given the following text description, write Python code to implement the functionality described below step by step Description: Response functions This notebook provides an overview of the response functions that are available in Pastas. Response functions describe the response of the dependent variable (e.g., ground...
Python Code: import numpy as np import pandas as pd import pastas as ps import matplotlib.pyplot as plt ps.show_versions() Explanation: Response functions This notebook provides an overview of the response functions that are available in Pastas. Response functions describe the response of the dependent variable (e.g., ...
11,402
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction à l'I/O Asynchrone Le Socket de Berkeley Il est difficile d'imaginer le nombre d'instanciations d'objets de type Socket depuis leur introduction en 1983 à l'université Berkeley....
Python Code: from IPython.display import Image from IPython.display import display import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("etsmtl.ca" , 80)) Explanation: Introduction à l'I/O Asynchrone Le Socket de Berkeley Il est difficile d'imaginer le nombre d'instanciations d'objets de...
11,403
Given the following text description, write Python code to implement the functionality described below step by step Description: 14 - Advanced topics - Cement Pavers albedo example This journal creates a paver underneath the single-axis trackers, and evaluates the improvement for one day -- June 17th with and without ...
Python Code: import os from pathlib import Path import pandas as pd testfolder = str(Path().resolve().parent.parent / 'bifacial_radiance' / 'TEMP' / 'Tutorial_14') if not os.path.exists(testfolder): os.makedirs(testfolder) print ("Your simulation will be stored in %s" % testfolder) from bifacial_radiance impor...
11,404
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Convolutional Neural Network in TensorFlow In this notebook, we convert our LeNet-5-inspired, MNIST-classifying, deep convolutional network from Keras to TensorFlow (compare them side b...
Python Code: import numpy as np np.random.seed(42) import tensorflow as tf tf.set_random_seed(42) Explanation: Deep Convolutional Neural Network in TensorFlow In this notebook, we convert our LeNet-5-inspired, MNIST-classifying, deep convolutional network from Keras to TensorFlow (compare them side by side) following A...
11,405
Given the following text description, write Python code to implement the functionality described below step by step Description: Non-Linear Time History Analysis (NLTHA) for Single Degree of Freedom (SDOF) Oscillators In this method, a single degree of freedom (SDOF) model of each structure is subjected to non-linear ...
Python Code: import NLTHA_on_SDOF from rmtk.vulnerability.common import utils %matplotlib inline Explanation: Non-Linear Time History Analysis (NLTHA) for Single Degree of Freedom (SDOF) Oscillators In this method, a single degree of freedom (SDOF) model of each structure is subjected to non-linear time history analysi...
11,406
Given the following text description, write Python code to implement the functionality described below step by step Description: AutoML for Text Classification Learning Objectives Learn how to create a text classification dataset for AutoML using BigQuery Learn how to train AutoML to build a text classification model ...
Python Code: import os from google.cloud import bigquery import pandas as pd %load_ext google.cloud.bigquery Explanation: AutoML for Text Classification Learning Objectives Learn how to create a text classification dataset for AutoML using BigQuery Learn how to train AutoML to build a text classification model Learn ho...
11,407
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 1 Step1: Load house sales data Dataset is from house sales in King County, the region where the city of Seattle, WA is located. Step2: Split data into training and testing ...
Python Code: import graphlab Explanation: Regression Week 1: Simple Linear Regression In this notebook we will use data on house sales in King County to predict house prices using simple (one input) linear regression. You will: * Use graphlab SArray and SFrame functions to compute important summary statistics * Write a...
11,408
Given the following text description, write Python code to implement the functionality described below step by step Description: Birthday problem simulated Let's say we can't figure out how to formally calculate the probability that 2 people out of N have the same birthday (ignoring leap years). Not to worry Step1: T...
Python Code: import random from collections import defaultdict def num_people_same_birthday(n): bdays = defaultdict(int) for i in range(n): bdays[random.randrange(0, 365)] += 1 return len([k for (k, v) in bdays.items() if v > 1]) num_people_same_birthday(60) Explanation: Birthday problem simulat...
11,409
Given the following text description, write Python code to implement the functionality described below step by step Description: Python中常用的高级特性 三目运算符 例如Javascript或者php等大部分编程语言中都会提供三目运算符以达到快捷的判断赋值功能. 但是在Python开发者认为不符合Python简洁, 简单的特点, 所以其实Python中没有常见的? Step1: 列表生成式 列表生成式是一种生成规律数组的简写形式. Step2: 字典生成式 字典生成式和列表生成式语法类型. 也是...
Python Code: # 给一个变量赋值, 取得给定整形变量的绝对值 number1 = -11 value1 = number1 if value1 < 0: value1 = -value1 print(value1) # 我们这边可以使用Python中特殊的三目运算符形式 number2 = -22 value2 = number2 if number2 > 0 else -number2 print(value2) Explanation: Python中常用的高级特性 三目运算符 例如Javascript或者php等大部分编程语言中都会提供三目运算符以达到快捷的判断赋值功能. 但是在Python开发者认为不符合...
11,410
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Preprocessing using Dataflow </h1> This notebook illustrates Step1: Run the command again if you are getting oauth2client error. Note Step2: You may receive a UserWarning about the Ap...
Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst pip install --user apache-beam[gcp]==2.16.0 Explanation: <h1> Preprocessing using Dataflow </h1> This notebook illustrates: <ol> <li> Creating datasets for Machine Learning using Dataflow </ol> <p> While Pandas is fine for experimenting, fo...
11,411
Given the following text description, write Python code to implement the functionality described below step by step Description: 3/ Exercises solutions Step1: RREF exercises E3.1 Step2: Verify the solution geometrically Step3: E3.2 Step4: E3.3 Step5: Matrix equations Matrix product E3.5 Compute the following matr...
Python Code: # helper code needed for running in colab if 'google.colab' in str(get_ipython()): print('Downloading plot_helpers.py to util/ (only neded for colab') !mkdir util; wget https://raw.githubusercontent.com/minireference/noBSLAnotebooks/master/util/plot_helpers.py -P util from sympy import * init_print...
11,412
Given the following text description, write Python code to implement the functionality described below step by step Description: Predict Concentrations of Metabolites The objective is to see whether continuous vector embedding can help in the prediction of concentrations of metabolites. Step1: Load Standards Data Ste...
Python Code: %matplotlib inline %load_ext autoreload %autoreload 2 import matplotlib import numpy as np import matplotlib.pyplot as plt from IPython.display import display, HTML from scipy import stats from sklearn import linear_model from sklearn.linear_model import LinearRegression from sklearn.gaussian_process impor...
11,413
Given the following text description, write Python code to implement the functionality described below step by step Description: Biblioteca Shapely e Objetos geométricos Fonte Step1: Vamos ver como a variável do tipo Point é mostrada no jupyter Step2: Também podemos imprimir os pontos para ver a sua definição Step3:...
Python Code: # Import necessary geometric objects from shapely module from shapely.geometry import Point, LineString, Polygon # Create Point geometric object(s) with coordinates point1 = Point(2.2, 4.2) point2 = Point(7.2, -25.1) point3 = Point(9.26, -2.456) point3D = Point(9.26, -2.456, 0.57) Explanation: Biblioteca S...
11,414
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Analyse If you want to do your own analyse of the data on db.sqlite3 and are going to use Python you can take advantage of some Django code. This Jupyter Notebook will help you to enabl...
Python Code: import lowfat.models as models Explanation: Data Analyse If you want to do your own analyse of the data on db.sqlite3 and are going to use Python you can take advantage of some Django code. This Jupyter Notebook will help you to enable the Django code. Setup and run To setup your environment to run this Ju...
11,415
Given the following text description, write Python code to implement the functionality described below step by step Description: <table align="left"> <td> <a href="https Step1: Restart the Kernel Once you've installed the {packages}, you need to restart the notebook kernel so it can find the packages. Step2: B...
Python Code: %pip install -U missing_or_updating_package --user Explanation: <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/ai-platform-samples/blob/main/notebooks/templates/ai_platform_notebooks_template_hybrid.ipynb""> <img src="https://cloud.google.com/ml-...
11,416
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: TensorFlow Addons 优化器:ConditionalGradient <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: 构建模型 S...
Python Code: #@title Licensed under the Apache License, Version 2.0 # 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 # distributed under the...
11,417
Given the following text description, write Python code to implement the functionality described below step by step Description: STA 208 Step1: Load the following medical dataset with 750 patients. The response variable is survival dates (Y), the predictors are 104 measurements measured at a specific time (numerical ...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import Ridge, RidgeCV, Lasso, LassoCV, lars_path, LogisticRegression from sklearn.preprocessing import scale from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt plt.style.use('ggplot') ...
11,418
Given the following text description, write Python code to implement the functionality described below step by step Description: Examples of Stacking BOSS Spectra using Speclite Examples of using the speclite package to perform basic operations on spectral data accessed with the bossdata package. To keep the examples...
Python Code: %pylab inline import speclite print(speclite.version.version) import bossdata print(bossdata.__version__) finder = bossdata.path.Finder() mirror = bossdata.remote.Manager() Explanation: Examples of Stacking BOSS Spectra using Speclite Examples of using the speclite package to perform basic operations on sp...
11,419
Given the following text description, write Python code to implement the functionality described below step by step Description: Clase 5 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...
11,420
Given the following text description, write Python code to implement the functionality described below step by step Description: Chem 30324, Spring 2019, Homework 5 Due Febrary 25, 2020 Real-world particle-in-a-box. A one-dimensional particle-in-a-box is a simple but plausible model for the π electrons of a conjugated...
Python Code: import numpy as np import matplotlib.pyplot as plt E = [] l = 1.4e-10 #m hbar = 1.05457e-34 #J*s m = 9.109e-31 #kg N = [1,3,5,7,9] #N = number of C-C bonds for n in range (1,7): for i in N: e = (n**2*np.pi**2*hbar**2*6.2415e18)/(2*m*(i*l)**2) E.append(e) plt.scatter(N,E[0:5], label = "n=1") plt....
11,421
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial 2 of 3 Step1: Let's generate a cubic network again, but with a different connectivity Step2: This Network has pores distributed in a cubic lattice, but connected to diagonal neigh...
Python Code: import numpy as np import scipy as sp import openpnm as op np.random.seed(10) ws = op.Workspace() ws.settings["loglevel"] = 40 Explanation: Tutorial 2 of 3: Digging Deeper into OpenPNM This tutorial will follow the same outline as Getting Started, but will dig a little bit deeper at each step to reveal the...
11,422
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Sentiment analysis model using deep learning
Python Code:: import tensorflow as tf model = tf.keras.model.Sequential() model.add(tf.keras.layers.Embedding(n_most_words,n_dim,input_length = X_train.shape[1])) model.add(tf.keras.layers.Dropout(0.25)) model.add(tf.keras.layers.Conv1D(64, 3, padding = 'same', activation = 'relu')) model.add(tf.keras.layers.LSTM(64,dr...
11,423
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 DeepMind Technologies Limited. 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 ...
Python Code: !pip install dm-acme !pip install dm-acme[reverb] !pip install dm-acme[tf] !pip install dm-sonnet !git clone https://github.com/deepmind/deepmind-research.git %cd deepmind-research Explanation: Copyright 2020 DeepMind Technologies Limited. Licensed under the Apache License, Version 2.0 (the "License"); you...
11,424
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 2 Step1: Load in house sales data Dataset is from house sales in King County, the region where the city of Seattle, WA is located. Step2: Split data into training and testi...
Python Code: import graphlab graphlab.product_key.set_product_key("C0C2-04B4-D94B-70F6-8771-86F9-C6E1-E122") Explanation: Regression Week 2: Multiple Regression (Interpretation) The goal of this first notebook is to explore multiple regression and feature engineering with existing graphlab functions. In this notebook y...
11,425
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have two input arrays x and y of the same shape. I need to run each of their elements with matching indices through a function, then store the result at those indices in a third a...
Problem: import numpy as np x = [[2, 2, 2], [2, 2, 2], [2, 2, 2]] y = [[3, 3, 3], [3, 3, 3], [3, 3, 1]] x_new = np.array(x) y_new = np.array(y) z = x_new + y_new
11,426
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean 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', 'fio-ronm', 'sandbox-3', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: FIO-RONM Source ID: SANDBOX-3 Topic: Ocean Sub-Topics: Timestepping Frame...
11,427
Given the following text description, write Python code to implement the functionality described below step by step Description: Summary scikit-learn API X Step1: Model complexity, overfitting, underfitting Pipelines Step2: Scoring metrics Step3: Data Wrangling
Python Code: from sklearn.datasets import load_digits from sklearn.linear_model import LogisticRegression from sklearn.cross_validation import cross_val_score digits = load_digits() X, y = digits.data / 16., digits.target cross_val_score(LogisticRegression(), X, y, cv=5) from sklearn.grid_search import GridSearchCV fro...
11,428
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmoschem 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', 'mri', 'sandbox-1', 'atmoschem') Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: MRI Source ID: SANDBOX-1 Topic: Atmoschem Sub-Topics: Transport, Emiss...
11,429
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Network Traffic Forecasting (using time series data) In telco, accurate forecast of KPIs (e.g. network traffic, utilizations, user experience, etc.) for communication networks ( 2G/3G...
Python Code: def plot_predict_actual_values(date, y_pred, y_test, ylabel): plot the predicted values and actual values (for the test data) fig, axs = plt.subplots(figsize=(16,6)) axs.plot(date, y_pred, color='red', label='predicted values') axs.plot(date, y_test, color='blue', label='actual va...
11,430
Given the following text description, write Python code to implement the functionality described below step by step Description: How rider usage varies with temperature when binning months Setting up the data Step1: Getting the data into groupby objects and getting a correlation table Step2: Comments on above As we ...
Python Code: import numpy as np import pandas as pd import datetime from pandas import Series, DataFrame stations = pd.read_table('stations.tsv') usage = pd.read_table('usage_2012.tsv') weather = pd.read_table('daily_weather.tsv') def change_seasons(): weather.loc[weather["season_code"] == 1, "season_desc"] = 'Wint...
11,431
Given the following text description, write Python code to implement the functionality described below step by step Description: Probabilistic Programming in Python using PyMC Authors Step1: Here is what the simulated data look like. We use the pylab module from the plotting library matplotlib. Step2: Model Specific...
Python Code: import numpy as np import matplotlib.pyplot as plt # Initialize random number generator np.random.seed(123) # True parameter values alpha, sigma = 1, 1 beta = [1, 2.5] # Size of dataset size = 100 # Predictor variable X1 = np.random.randn(size) X2 = np.random.randn(size) * 0.2 # Simulate outcome variable Y...
11,432
Given the following text description, write Python code to implement the functionality described below step by step Description: <h2> Plot a horizontal map of gridded radar data</h2> <h4>This script loads in a binary file of gridded tail Doppler radar from the NOAA P-3 produced by the windsyn program (NOAA NSSL) - a s...
Python Code: # Load the needed packages from glob import glob import os import matplotlib.pyplot as plt from awot.io import read_p3_radar from awot.graph.common import create_basemap from awot.graph import RadarHorizontalPlot from awot.graph import FlightLevel %matplotlib inline Explanation: <h2> Plot a horizontal map ...
11,433
Given the following text description, write Python code to implement the functionality described below step by step Description: Loss Functions Custom fastai loss functions Step1: Wrapping a general loss function inside of BaseLoss provides extra functionalities to your loss functions Step3: Focal Loss is the same a...
Python Code: #|export class BaseLoss(): "Same as `loss_cls`, but flattens input and target." activation=decodes=noops def __init__(self, loss_cls, # Uninitialized PyTorch-compatible loss *args, axis:int=-1, # Class axis flatten:bool=True, # Flatten `inp` and `targ` before ca...
11,434
Given the following text description, write Python code to implement the functionality described below step by step Description: ApJdataFrames McClure Title Step1: Table 1 - Target Information for Ophiuchus Sources Step2: Table 2 - Spectral Type Information for the Entire Sample Step3: Merge the two catalogs Step4:...
Python Code: import warnings warnings.filterwarnings("ignore") from astropy.io import ascii import pandas as pd Explanation: ApJdataFrames McClure Title: THE EVOLUTIONARY STATE OF THE PRE-MAIN SEQUENCE POPULATION IN OPHIUCHUS: A LARGE INFRARED SPECTROGRAPH SURVEY Authors: McClure et al. Data is from this paper: http://...
11,435
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 01 Import Step2: Interact basics Write a print_sum function that prints the sum of its arguments a and b. Step3: Use the interact function to interact with the print_sum ...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display Explanation: Interact Exercise 01 Import End of explanation def print_sum(a, b): Print the sum of the arguments a and b. retur...
11,436
Given the following text description, write Python code to implement the functionality described below step by step Description: CH82 Model The following tries to reproduce Fig 8 from Hawkes, Jalali, Colquhoun (1992). First we create the $Q$-matrix for this particular model. Please note that the units are different fr...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from dcprogs.likelihood import QMatrix tau = 1e-4 qmatrix = QMatrix([[ -3050, 50, 3000, 0, 0 ], [ 2./3., -1502./3., 0, 500, 0 ], [ 15, 0, -2065, 50, 2000 ]...
11,437
Given the following text description, write Python code to implement the functionality described below step by step Description: Spam detection The main aim of this project is to build a machine learning classifier that is able to automatically detect spammy articles, based on their content. Step1: Modeling We tried...
Python Code: ! sh bootstrap.sh from sklearn.cluster import KMeans import numpy as np import pandas as pd import matplotlib.pyplot as plt import random from sklearn.utils import shuffle from sklearn.metrics import f1_score from sklearn.cross_validation import KFold from sklearn.metrics import recall_score from sklearn.e...
11,438
Given the following text description, write Python code to implement the functionality described below step by step Description: Missionaries and Infidels We illustrate the notion of a search problem with the following example, which is also known as the <a href="https Step1: $\texttt{no_problem}(m, i)$ is true if th...
Python Code: problem = lambda m, i: 0 < m < i Explanation: Missionaries and Infidels We illustrate the notion of a search problem with the following example, which is also known as the <a href="https://en.wikipedia.org/wiki/Missionaries_and_cannibals_problem">missionaries and cannibals problem</a>: Three missionaries a...
11,439
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic Optimization In this example, we'll be performing a simple optimization of single-objective functions using the global-best optimizer in pyswarms.single.GBestPSO and the local-best opt...
Python Code: # Import modules import numpy as np # Import PySwarms import pyswarms as ps from pyswarms.utils.functions import single_obj as fx # Some more magic so that the notebook will reload external python modules; # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython %load_ext autoreloa...
11,440
Given the following text description, write Python code to implement the functionality described below step by step Description: L'objectif de ce script est d'illustrer graphiquement l'évolution du taux implicite de la TICPE depuis 1993. On étudie ce taux pour le diesel, et pour les carburants sans plombs. Import de m...
Python Code: from pandas import concat %matplotlib inline Explanation: L'objectif de ce script est d'illustrer graphiquement l'évolution du taux implicite de la TICPE depuis 1993. On étudie ce taux pour le diesel, et pour les carburants sans plombs. Import de modules généraux End of explanation from openfisca_france_in...
11,441
Given the following text description, write Python code to implement the functionality described below step by step Description: Recommender Systems In this project, we build a movie recommender system. We read a dataset of movie ratings by users, then we select other movies that a specific user would be interesting i...
Python Code: import numpy as np import pandas as pd Explanation: Recommender Systems In this project, we build a movie recommender system. We read a dataset of movie ratings by users, then we select other movies that a specific user would be interesting in based on his previous choice. End of explanation column_names =...
11,442
Given the following text description, write Python code to implement the functionality described below step by step Description: Clustering the subsampled 1.3 M cells The data consists in 20K Neurons, downsampled from 1.3 Million Brain Cells from E18 Mice and is freely available from 10x Genomics (here). Step1: Run s...
Python Code: import numpy as np import pandas as pd import scanpy.api as sc sc.settings.verbosity = 3 # verbosity: errors (0), warnings (1), info (2), hints (3) sc.settings.set_figure_params(dpi=70) # dots (pixels) per inch determine size of inline figures sc.logging.print_versions() adata = sc.read_10x_h5('./data/1M...
11,443
Given the following text description, write Python code to implement the functionality described below step by step Description: Minimos Cuadrados Por Step1: 2- Aplique paso a paso el método de mínimos cuadrados de tal forma que le permita obtener la mejor curva lineal de ajuste de los datos anteriores, y determine l...
Python Code: ######################################################## ## Librerias para el trabajo ######################################################## import matplotlib.pyplot as plt import numpy as np %matplotlib inline data1= np.loadtxt('datos.csv',delimiter=',') #datos para regresion lineal X1=data1[:,0] Y1=dat...
11,444
Given the following text description, write Python code to implement the functionality described below step by step Description: Ordinal Regression Step1: Loading a stata data file from the UCLA website.This notebook is inspired by https Step2: This dataset is about the probability for undergraduate students to appl...
Python Code: import numpy as np import pandas as pd import scipy.stats as stats from statsmodels.miscmodels.ordinal_model import OrderedModel Explanation: Ordinal Regression End of explanation url = "https://stats.idre.ucla.edu/stat/data/ologit.dta" data_student = pd.read_stata(url) data_student.head(5) data_student.dt...
11,445
Given the following text description, write Python code to implement the functionality described below step by step Description: Think Bayes This notebook presents example code and exercise solutions for Think Bayes. Copyright 2018 Allen B. Downey MIT License Step1: The dinner party Suppose you are having a dinner pa...
Python Code: # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import classes from thinkbayes2 from thinkbayes2 import Hist, Pmf, Suite, Beta import thinkp...
11,446
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 1 Step1: This dataset is a debug dump from a Lustre filesystem. Typically these events occur due to code bugs (LBUG), heavy load, hardware problems, or misbehaving user application...
Python Code: from pyspark import SparkConf, SparkContext import re Explanation: Example 1: Parallel Log Parsing with Map and Filter Step 1: Data ingest and parsing End of explanation sc partitions = 18 parlog = sc.textFile("/lustre/janus_scratch/dami9546/lustre_debug.out", partitions) Explanation: This dataset is a deb...
11,447
Given the following text description, write Python code to implement the functionality described below step by step Description: Q1. Let's practice the seq2seq framework with a simple example. In this example, we will take the last state of the encoder as the initial state of the decoder. Complete the code. Step1: Q2...
Python Code: # Inputs and outputs: ten digits x = tf.placeholder(tf.int32, shape=(32, 10)) y = tf.placeholder(tf.int32, shape=(32, 10)) # One-hot encoding enc_inputs = tf.one_hot(x, 10) dec_inputs = tf.concat((tf.zeros_like(y[:, :1]), y[:, :-1]), -1) dec_inputs = tf.one_hot(dec_inputs, 10) # encoder encoder_cell = tf.c...
11,448
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 5 Imports Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell. Step2: Interact with SVG display SVG is a simple way of drawing vec...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.html import widgets from IPython.display import SVG Explanation: Interact Exercise 5 Imports Put the standard imports for Matplotlib, Numpy and the IPython widget...
11,449
Given the following text description, write Python code to implement the functionality described below step by step Description: Eaton & Ree (2013) single-end RAD data set Here we demonstrate a denovo assembly for an empirical RAD data set using the ipyrad Python API. This example was run on a workstation with 20 core...
Python Code: ## conda install ipyrad -c ipyrad ## conda install toytree -c eaton-lab ## conda install sra-tools -c bioconda ## conda install entrez-direct -c bioconda ## imports import ipyrad as ip import ipyrad.analysis as ipa import ipyparallel as ipp Explanation: Eaton & Ree (2013) single-end RAD data set Here we de...
11,450
Given the following text description, write Python code to implement the functionality described below step by step Description: Assigning particles unique IDs and removing particles from the simulation For some applications, it is useful to keep track of which particle is which, and this can get jumbled up when parti...
Python Code: import rebound import numpy as np def setupSimulation(Nplanets): sim = rebound.Simulation() sim.integrator = "ias15" # IAS15 is the default integrator, so we don't need this line sim.add(m=1.,id=0) for i in range(1,Nbodies): sim.add(m=1e-5,x=i,vy=i**(-0.5),id=i) sim.move_to_com(...
11,451
Given the following text description, write Python code to implement the functionality described below step by step Description: Function ptrans Synopse Perform periodic translation in 1-D, 2-D or 3-D space. g = ptrans(f, t) OUTPUT g Step1: Examples Step2: Example 1 Numeric examples in 2D and 3D. Step3: Example 2 I...
Python Code: def ptrans(f,t): import numpy as np g = np.empty_like(f) if f.ndim == 1: W = f.shape[0] col = np.arange(W) g = f[(col-t)%W] elif f.ndim == 2: H,W = f.shape rr,cc = t row,col = np.indices(f.shape) g = f[(row-rr)%H, (col-cc)%W] elif f.ndim == 3: ...
11,452
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Morphological Transformations Morphological Transformations are some simple operation based on the image shape. Morphological Transformations are normally performed on binary image...
Python Code:: import cv2 %matplotlib notebook %matplotlib inline from matplotlib import pyplot as plt img = cv2.imread("hsv_ball.jpg",cv2.IMREAD_GRAYSCALE) _,mask = cv2.threshold(img, 220,255,cv2.THRESH_BINARY_INV) titles = ['images',"mask"] images = [img,mask] for i in range(2): plt.subplot(1,2,i+1) plt.imshow...
11,453
Given the following text description, write Python code to implement the functionality described below step by step Description: Ported to Python (by Ilan Fridman Rojas) from original R implementation by Rasmus Bååth Step2: The standard bootstrap method Step5: The Bayesian bootstrap (with a Dirichlet prior) (See Ste...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.style.use('ggplot') %matplotlib inline data = pd.read_csv('american_presidents.csv', header=0, index_col=None) data data.describe() data.plot(x='order',y='height_cm', color='blue') data.plot('order', kind='hist', color='blue') impor...
11,454
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol 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', 'mri', 'sandbox-3', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: MRI Source ID: SANDBOX-3 Topic: Aerosol Sub-Topics: Transport, Emissions, ...
11,455
Given the following text description, write Python code to implement the functionality described below step by step Description: Example of how to find peaks in a synthetic image Create a set of 2D Gaussians Find the center of the Guassian to integer accuracy Optimize the position using Gaussian fitting for each peak ...
Python Code: %matplotlib notebook import numpy as np import matplotlib.pyplot as plt # Import these from ncempy.algo from ncempy.algo import gaussND from ncempy.algo import peakFind Explanation: Example of how to find peaks in a synthetic image Create a set of 2D Gaussians Find the center of the Guassian to integer acc...
11,456
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol 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', 'snu', 'sandbox-1', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: SNU Source ID: SANDBOX-1 Topic: Aerosol Sub-Topics: Transport, Emissions, ...
11,457
Given the following text description, write Python code to implement the functionality described below step by step Description: Steady-state simulation of organic light emitting cell This is an example of steady-state simulation of the light emitting electrochemical cell. It attempts to reproduce reference. Exact agr...
Python Code: from oedes.fvm import mesh1d from oedes import progressbar, testing, init_notebook, models, context init_notebook() %matplotlib inline import matplotlib.pylab as plt import numpy as np Explanation: Steady-state simulation of organic light emitting cell This is an example of steady-state simulation of the l...
11,458
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Exercise 3 Imports Step2: Geometric Brownian motion Here is a function that produces standard Brownian motion using NumPy. This is also known as a Wiener Process. Step3: Call the bro...
Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import antipackage import github.ellisonbg.misc.vizarray as va Explanation: Numpy Exercise 3 Imports End of explanation def brownian(maxt, n): Return one realization of a Brownian (Wiener) process with n steps a...
11,459
Given the following text description, write Python code to implement the functionality described below step by step Description: Note Step1: Suppose we want to get from A to B. Where can we go from the start state, A? Step2: We see that from A we can get to any of the three cities ['Z', 'T', 'S']. Which should we ch...
Python Code: romania = { 'A': ['Z', 'T', 'S'], 'B': ['F', 'P', 'G', 'U'], 'C': ['D', 'R', 'P'], 'D': ['M', 'C'], 'E': ['H'], 'F': ['S', 'B'], 'G': ['B'], 'H': ['U', 'E'], 'I': ['N', 'V'], 'L': ['T', 'M'], 'M': ['L', 'D'], 'N': ['I'], 'O': ['Z', 'S'], 'P': ['R', 'C', 'B'], 'R': ['S', 'C', 'P'], 'S': ['A'...
11,460
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> <a href="http Step1: 2.2 Données "Titanic" Les données sur le naufrage du Titanic sont décrites dans le calepin consacré à la librairie pandas. Reconstruire la table des données en...
Python Code: # Importations import matplotlib.pyplot as plt from sklearn import datasets %matplotlib inline # les données digits = datasets.load_digits() # Contenu et mode d'obtention print(digits) images_and_labels = list(zip(digits.images, digits.target)) for index, (image, label) in enumerate(images_and_labels...
11,461
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: 5T_데이터 분석을 위한 SQL 실습 (4) - SQL Advanced 특정 카테고리에 포함된 영화들의 렌탈 횟수 rental, inventory, film, film_category, category "Comedy", "Sports", "Family" 카테고리에 포함되는 영화들의 렌탈 횟수 Step3: Store 1의 등급...
Python Code: import pymysql db = pymysql.connect( "db.fastcamp.us", "root", "dkstncks", "sakila", charset='utf8', ) rental_df = pd.read_sql("SELECT * FROM rental;", db) inventory_df = pd.read_sql("SELECT * FROM inventory;", db) film_df = pd.read_sql("SELECT * FROM film;", db) film_category_df = pd.r...
11,462
Given the following text description, write Python code to implement the functionality described below step by step Description: Multi-Class Classifier on Particle Track Data Step1: Get angle values and cast to boolean Step2: Create our simple classification target Step3: Create an image generator from this datafra...
Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import os import sys import numpy as np import math Explanation: Multi-Class Classifier on Particle Track Data End of explanation track_params = pd.read_csv('../TRAIN/track_parms.csv') track_params.tail() Explanation: Get angle values a...
11,463
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: Create an Estimator from a Keras model <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Crea...
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,464
Given the following text description, write Python code to implement the functionality described below step by step Description: 练习 1:仿照求$ \sum_{i=1}^mi + \sum_{i=1}^ni + \sum_{i=1}^ki$的完整代码,写程序,可求m!+n!+k! Step1: 练习 2:写函数可返回1 - 1/3 + 1/5 - 1/7...的前n项的和。在主程序中,分别令n=1000及100000,打印4倍该函数的和。 Step2: 练习 3:将task3中的练习1及练习4改写...
Python Code: def compute_multi(end): i = 0 multi = 1 while i < end: i = i + 1 multi = multi * i return multi n = int(input('请输入第1个整数,以回车结束。')) m = int(input('请输入第2个整数,以回车结束。')) k = int(input('请输入第3个整数,以回车结束。')) print('最终的和是:', compute_multi(m) + compute_multi(n) + compute_multi(k)) Expla...
11,465
Given the following text description, write Python code to implement the functionality described below step by step Description: Keypoint Detection with Transfer Learning Author Step1: Data collection The StanfordExtra dataset contains 12,000 images of dogs together with keypoints and segmentation maps. It is develop...
Python Code: !pip install -q -U imgaug Explanation: Keypoint Detection with Transfer Learning Author: Sayak Paul<br> Date created: 2021/05/02<br> Last modified: 2021/05/02<br> Description: Training a keypoint detector with data augmentation and transfer learning. Keypoint detection consists of locating key object parts...
11,466
Given the following text description, write Python code to implement the functionality described below step by step Description: Census Data Correlation Correlate another table with US Census data. Expands a data set dimensions by finding population segments that correlate with the master table. License Copyright 202...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: Census Data Correlation Correlate another table with US Census data. Expands a data set dimensions by finding population segments that correlate with the master table. License Copyright 2020 Google LLC, Licensed under the Apache License, ...
11,467
Given the following text description, write Python code to implement the functionality described below step by step Description: tsam - 1. Example Example usage of the time series aggregation module (tsam) Date Step1: Input data Read in time series from testdata.csv with pandas Step2: Show a slice of the dataset Ste...
Python Code: %load_ext autoreload %autoreload 2 import copy import os import pandas as pd import matplotlib.pyplot as plt import tsam.timeseriesaggregation as tsam %matplotlib inline Explanation: tsam - 1. Example Example usage of the time series aggregation module (tsam) Date: 08.05.2017 Author: Leander Kotzur Import ...
11,468
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: JFreeChart Versions - Diving into Differences and Similarities This notebook reports code and results of the analysis conducted on the two versions of the JfreeChart software system i...
Python Code: # %load preamble_directives.py Some imports and path settings to make notebook code running smoothly. # Author: Valerio Maggio <valeriomaggio@gmail.com> # Copyright (c) 2015 Valerio Maggio <valeriomaggio@gmail.com> # License: BSD 3 clause import sys, os # Extending PYTHONPATH to allow relative import! sys....
11,469
Given the following text description, write Python code to implement the functionality described below step by step Description: XGBoost-Ray with Dask This notebook includes an example workflow using XGBoost-Ray and Dask for distributed model training, hyperparameter optimization, and prediction. Cluster Setup First, ...
Python Code: import argparse import time import dask import dask.dataframe as dd from xgboost_ray import RayDMatrix, RayParams, train, predict import ray from ray import tune from ray.util.dask import ray_dask_get Explanation: XGBoost-Ray with Dask This notebook includes an example workflow using XGBoost-Ray and Dask f...
11,470
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Preprocessing Joeri R. Hermans Departement of Data Science & Knowledge Engineering Maastricht University, The Netherlands In this notebook we mainly...
Python Code: %matplotlib inline import numpy as np import os from pyspark import SparkContext from pyspark import SparkConf from pyspark.storagelevel import StorageLevel from pyspark.sql import Row from pyspark.sql.types import * import matplotlib.mlab as mlab import matplotlib.pyplot as plt # Use the DataBricks AVRO r...
11,471
Given the following text description, write Python code to implement the functionality described below step by step Description: Excercises Electric Machinery Fundamentals Chapter 9 Problem 9-1 Step1: Description A 120-V 1/4-hp 60-Hz four-pole split-phase induction motor has the following impedances Step2: If the sl...
Python Code: %pylab notebook %precision %.4g Explanation: Excercises Electric Machinery Fundamentals Chapter 9 Problem 9-1 End of explanation V = 120 # [V] p = 4 R1 = 2.0 # [Ohm] R2 = 2.8 # [Ohm] X1 = 2.56 # [Ohm] X2 = 2.56 # [Ohm] Xm = 60.5 # [Ohm] s = 0.05 Prot = 51 # [W] Explanation: Descript...
11,472
Given the following text description, write Python code to implement the functionality described below step by step Description: Example Usage for Drop-in List Replacements Step1: BList The underlying data structure can be any drop-in replacement for list, in this example blist is used. Step2: All the standard funct...
Python Code: # remove comment to use latest development version import sys; sys.path.insert(0, '../') # import libraries import raccoon as rc Explanation: Example Usage for Drop-in List Replacements End of explanation from blist import blist # Construct with blist df_blist = rc.DataFrame({'a': [1, 2, 3]}, index=[5, 6, ...
11,473
Given the following text description, write Python code to implement the functionality described below step by step Description: Step5: tsfresh returns a great number of features. Depending on the dynamics of the inspected time series, some of them maybe highly correlated. A common technique to deal with such highly ...
Python Code: from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler import pandas as pd class PCAForPandas(PCA): This class is just a small wrapper around the PCA estimator of sklearn including normalization to make it compatible with pandas DataFrames. def __init__(sel...
11,474
Given the following text description, write Python code to implement the functionality described below step by step Description: Posterior Predictive Checks in PyMC3 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. PyMC3 ...
Python Code: %load_ext autoreload %autoreload 2 %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 in PyMC3 PPCs are a great way to validate a model. The idea is to generate data sets...
11,475
Given the following text description, write Python code to implement the functionality described below step by step Description: Сценарий Step1: Группируем по миллисекундам и усредняем Step2: Интересные нам всплески потребления кончаются где-то на 10000-ной миллисекунде. Step3: Синхронизируемся по 3-му всплеску, ка...
Python Code: df = pd.DataFrame(np.fromfile( "./browser_download_lte_wf.bin", dtype=np.uint16).astype(np.float32) * (3300 / 2**12)) Explanation: Сценарий: - заранее выдвигаем шторку с фонариком и запускаем браузер - включаем мониторинг - мигаем фонариком пять раз - задвигаем шторку, ждем чуть больше мину...
11,476
Given the following text description, write Python code to implement the functionality described below step by step Description: &larr; Back to Index Exercise Step1: Load 120 seconds of an audio file Step2: Plot the time-domain waveform of the audio signal Step3: Play the audio file Step4: Step 2 Step5: We transp...
Python Code: filename_brahms = 'brahms_hungarian_dance_5.mp3' url = "http://audio.musicinformationretrieval.com/" + filename_brahms if not os.path.exists(filename_brahms): urllib.urlretrieve(url, filename=filename_brahms) Explanation: &larr; Back to Index Exercise: Genre Recognition Goals Extract features from an a...
11,477
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Biology with Python By Fatih Enes Kemal Ergin In this small tutorial I will talk about biological concepts with theory and implementation in Python Before we go into the implementatio...
Python Code: # Here is the genetic code of the amino acids defined as dictionaries STANDARD_GENETIC_CODE = {'UUU':'Phe', 'UUC':'Phe', 'UCU':'Ser', 'UCC':'Ser', 'UAU':'Tyr', 'UAC':'Tyr', 'UGU':'Cys', 'UGC':'Cys', 'UUA':'Leu', 'UCA':'Ser', 'UAA':None, 'UGA':None, ...
11,478
Given the following text description, write Python code to implement the functionality described below step by step Description: new_data['residuals1'] = results.resid Step1: Subseting the data Three different methods for subsetting the data. 1. Using a systematic selection by index modulus 2. Using a random uniform ...
Python Code: #new_data = prepareDataFrame("/RawDataCSV/idiv_share/plotsClimateData_11092017.csv") ## En Hec #new_data = prepareDataFrame("/home/hpc/28/escamill/csv_data/idiv/plotsClimateData_11092017.csv") ## New "official" dataset new_data = prepareDataFrame("/RawDataCSV/idiv_share/FIA_Plots_Biomass_11092017.csv") #IN...
11,479
Given the following text description, write Python code to implement the functionality described below step by step Description: Adding a discharge point source to a LEM (Greg Tucker, CSDMS / CU Boulder, fall 2020) This notebook shows how to add one or more discharge point sources to a Landlab-built landscape evolutio...
Python Code: from landlab import RasterModelGrid, imshow_grid from landlab.components import FlowAccumulator import numpy as np Explanation: Adding a discharge point source to a LEM (Greg Tucker, CSDMS / CU Boulder, fall 2020) This notebook shows how to add one or more discharge point sources to a Landlab-built landsca...
11,480
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', 'cas', 'sandbox-2', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: CAS Source ID: SANDBOX-2 Sub-Topics: Radiative Forcings. Properties: 85...
11,481
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 по рецептам Как вы уже знаете, в тематическом моделировании делается предположение о том, что для определения тематики порядок слов в документе не важен; об этом гласит ...
11,482
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Crear una serie Se pueden crear series desde listas, arreglos de numpy y diccionarios Step2: Usando listas Step3: Arreglos Numpy Step4: Diccionarios Step5: Informac...
Python Code: # librerias import numpy as np import pandas as pd Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> Series El primer tipo de dato que vamos a aprender en pandas es Series Una series es muy similar a un arreglo de Numpy, la diferencia es que una serie tiene etiqu...
11,483
Given the following text description, write Python code to implement the functionality described below step by step Description: Assembling detector data into images The X-ray detectors at XFEL are made up of a number of small pieces. To get an image from the data, or analyse it spatially, we need to know where each p...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import h5py from karabo_data import RunDirectory, stack_detector_data from karabo_data.geometry2 import LPD_1MGeometry run = RunDirectory('/gpfs/exfel/exp/FXE/201830/p900020/proc/r0221/') run.info() # Find a train with some data in empty...
11,484
Given the following text description, write Python code to implement the functionality described below step by step Description: Linear regresion - part 2 Many variables Step1: For many variables we will use vectorized implementation $$X=\left[\begin{array}{cc} 1 & (\vec x^{(1)})^T \ 1 & (\vec x^{(2)})^T \ \vdots & \...
Python Code: # imports import pandas as pd import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import seaborn as sns from IPython.display import ( display, Math, Latex ) %matplotlib inline Explanation: Linear regresion - part 2 Many variables End of explanation df = ...
11,485
Given the following text description, write Python code to implement the functionality described below step by step Description: The problem with perfect phylogenies Previously, I wrote a blog post, exploring the Gusfield algorithm for building phylogenetic trees from binary traits. While the algorithm works well if y...
Python Code: from mgraph import MGraph Explanation: The problem with perfect phylogenies Previously, I wrote a blog post, exploring the Gusfield algorithm for building phylogenetic trees from binary traits. While the algorithm works well if you have a clean matrix that just-so happes to form a perfect phylogeny, if you...
11,486
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook, we mainly utilize extreme gradient boost to improve the prediction model originially proposed in TLE 2016 November machine learning tuotrial. Extreme gradient boost can be ...
Python Code: %matplotlib inline import pandas as pd from pandas.tools.plotting import scatter_matrix import matplotlib.pyplot as plt import matplotlib as mpl import seaborn as sns import matplotlib.colors as colors import xgboost as xgb import numpy as np from sklearn.metrics import confusion_matrix, f1_score, accuracy...
11,487
Given the following text description, write Python code to implement the functionality described below step by step Description: Generate a left cerebellum volume source space Generate a volume source space of the left cerebellum and plot its vertices relative to the left cortical surface source space and the freesurf...
Python Code: # Author: Alan Leggitt <alan.leggitt@ucsf.edu> # # License: BSD (3-clause) import numpy as np from scipy.spatial import ConvexHull from mayavi import mlab from mne import setup_source_space, setup_volume_source_space from mne.datasets import sample print(__doc__) data_path = sample.data_path() subjects_dir...
11,488
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2017 Google LLC. Step1: Creating and Manipulating Tensors Learning Objectives Step2: Vector Addition You can perform many typical mathematical operations on tensors (TF API). The...
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...
11,489
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 3 Step1: Note Step2: Now, let's start with the ANTs normalization workflow! Imports (ANTs) First, we need to import all the modules we later want to use. Step3: Experiment paramet...
Python Code: %%bash datalad get -J 4 -d /data/ds000114 /data/ds000114/derivatives/fmriprep/sub-0[2345789]/anat/*h5 Explanation: Example 3: Normalize data to MNI template This example covers the normalization of data. Some people prefer to normalize the data during the preprocessing, just before smoothing. I prefer to d...
11,490
Given the following text description, write Python code to implement the functionality described below step by step Description: Outline Glossary 5. Imaging Previous Step1: Import section specific modules Step2: 5.3 Gridding and Degridding for using the FFT <a id='imaging Step3: Figure Step4: Figure Step5: Figure...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML from IPython.display import Image, display, clear_output from ipywidgets import HBox, Label, FloatSlider, Layout HTML('../style/course.css') #apply general CSS Explanation: Outline Glossary 5. Imaging Pr...
11,491
Given the following text description, write Python code to implement the functionality described below step by step Description: Original Voce-Chaboche Model Fitting Example 1 An example of fitting the original Voce-Chaboche model to a set of test data is provided. Documentation for all the functions used in this exam...
Python Code: import RESSPyLab as rpl import numpy as np Explanation: Original Voce-Chaboche Model Fitting Example 1 An example of fitting the original Voce-Chaboche model to a set of test data is provided. Documentation for all the functions used in this example can be found by either looking at docstrings for any of t...
11,492
Given the following text description, write Python code to implement the functionality described below step by step Description: Global Ocean Waves Analysis As a part of the continuous Marine Data support, this time Planet OS Team releases a Meteo France Global Ocean Waves Analysis and and Meteo France WAve Model (MF...
Python Code: import os from dh_py_access import package_api import dh_py_access.lib.datahub as datahub import xarray as xr from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np import imageio import shutil import datetime import matplotlib as mpl mpl.rcParams['font.family'] = 'Aven...
11,493
Given the following text description, write Python code to implement the functionality described below step by step Description: Face verification Goals train a network for face similarity using triplet loss work data augmentation, generators and hard negative mining Dataset We will be using Labeled Faces in the Wild ...
Python Code: import tensorflow as tf # If you have a GPU, execute the following lines to restrict the amount of VRAM used: gpus = tf.config.experimental.list_physical_devices('GPU') if len(gpus) > 1: print("Using GPU {}".format(gpus[0])) tf.config.experimental.set_visible_devices(gpus[0], 'GPU') else: print...
11,494
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>2b. Machine Learning using tf.estimator </h1> In this notebook, we will create a machine learning model using tf.estimator and evaluate its performance. The dataset is rather small (770...
Python Code: import tensorflow as tf import pandas as pd import numpy as np import shutil print(tf.__version__) Explanation: <h1>2b. Machine Learning using tf.estimator </h1> In this notebook, we will create a machine learning model using tf.estimator and evaluate its performance. The dataset is rather small (7700 sam...
11,495
Given the following text description, write Python code to implement the functionality described below step by step Description: IPython Widgets IPython widgets are tools that give us interactivity within our analysis. This is most useful when looking at a complication plot and trying to figure out how it depends on a...
Python Code: import IPython.html.widgets as widg import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint %matplotlib inline Explanation: IPython Widgets IPython widgets are tools that give us interactivity within our analysis. This is most useful when looking at a complication plot and try...
11,496
Given the following text description, write Python code to implement the functionality described below step by step Description: The Fibonacci Numbers The Fibonacci numbers $F_n$ are defined by induction for all $n\in\mathbb{N}$ Step1: It seems that the Fibonacci numbers grow pretty fast. Let us plot these numbers to...
Python Code: def fibonacci(n): if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2) [ (n,fibonacci(n)) for n in range(19) ] Explanation: The Fibonacci Numbers The Fibonacci numbers $F_n$ are defined by induction for all $n\in\mathbb{N}$: - $F_0 := 0$, - $F_1 := 1$, - $F_{n+2} = F_{n+1} + F_...
11,497
Given the following text description, write Python code to implement the functionality described below step by step Description: The big reset So I went ahead and cleared the memory. Step1: The mystery section remains the same. Step2: All the blocks are empty. Step3: The 'PresetStyle' settings are empty, too. Step4...
Python Code: import sys sys.path.append('..') import collections import mido from commons import dgxdump from commons.dumpdata import messages, songdata, regdata, regvalues old_syx_messages = mido.read_syx_file('../data/syxout5.syx') clear_syx_messages = mido.read_syx_file('../data/clear_bulk.txt') o_dump = dgxdump.Dgx...
11,498
Given the following text description, write Python code to implement the functionality described below step by step Description: GEE nested covariance structure simulation study This notebook is a simulation study that illustrates and evaluates the performance of the GEE nested covariance structure. A nested covarianc...
Python Code: import numpy as np import pandas as pd import statsmodels.api as sm Explanation: GEE nested covariance structure simulation study This notebook is a simulation study that illustrates and evaluates the performance of the GEE nested covariance structure. A nested covariance structure is based on a nested seq...
11,499
Given the following text description, write Python code to implement the functionality described below step by step Description: Fast Sign Adversary Generation Example This notebook demos find adversary example by using symbolic API and integration with Numpy Reference Step1: Build Network note Step2: Prepare useful...
Python Code: %matplotlib inline import mxnet as mx import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from mxnet.test_utils import get_mnist_iterator Explanation: Fast Sign Adversary Generation Example This notebook demos find adversary example by using symbolic API and integration with Numpy...