Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
2,900
Given the following text description, write Python code to implement the functionality described below step by step Description: An Introduction to py-Goldsberry py-Goldsberry is a Python package that makes it easy to interface with the http Step1: py-goldsberry is designed to work in conjuntion with Pandas. Each fun...
Python Code: import goldsberry import pandas as pd goldsberry.__version__ Explanation: An Introduction to py-Goldsberry py-Goldsberry is a Python package that makes it easy to interface with the http://stats.nba.com and retrieve the data in a more analyzable format. This is the first in a series of tutorials that walk...
2,901
Given the following text description, write Python code to implement the functionality described below step by step Description: Loading data from Cloudant or CouchDB You can load data from CouchDB or a managed Cloudant instance using the Cloudant Spark connector. Prerequisites Collect your database connection informa...
Python Code: import pixiedust pixiedust.enableJobMonitor() Explanation: Loading data from Cloudant or CouchDB You can load data from CouchDB or a managed Cloudant instance using the Cloudant Spark connector. Prerequisites Collect your database connection information: the database host, user name, password and source da...
2,902
Given the following text description, write Python code to implement the functionality described below step by step Description: Decision Trees in Practice In this assignment we will explore various techniques for preventing overfitting in decision trees. We will extend the implementation of the binary decision trees ...
Python Code: import graphlab Explanation: Decision Trees in Practice In this assignment we will explore various techniques for preventing overfitting in decision trees. We will extend the implementation of the binary decision trees that we implemented in the previous assignment. You will have to use your solutions from...
2,903
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Neural Network for Image Classification Step1: 2 - Dataset You will use the same "Cat vs non-Cat" dataset as in "Logistic Regression as a Neural Network" (Assignment 2). The model you ...
Python Code: import time import numpy as np import h5py import matplotlib.pyplot as plt import scipy from PIL import Image from scipy import ndimage from dnn_app_utils import * %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt....
2,904
Given the following text description, write Python code to implement the functionality described below step by step Description: Matplotlib Exercise 3 Imports Step2: Contour plots of 2d wavefunctions The wavefunction of a 2d quantum well is Step3: The contour, contourf, pcolor and pcolormesh functions of Matplotlib ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np Explanation: Matplotlib Exercise 3 Imports End of explanation import math as math def well2d(x, y, nx, ny, L=1.0): Compute the 2d quantum well wave function. wave_funct = (2/L)*np.sin((nx*math.pi*x)/L)*np.sin((ny*math.pi*y)/L) ...
2,905
Given the following text description, write Python code to implement the functionality described below step by step Description: Precisione dei numeri floats A seguito di un paio di domande fatte a lezione, vediamo la precisione dei numeri "reali" in Python. I float in python corrispondono ai double in C e quindi son...
Python Code: 0.1+0.1+0.1-0.3 Explanation: Precisione dei numeri floats A seguito di un paio di domande fatte a lezione, vediamo la precisione dei numeri "reali" in Python. I float in python corrispondono ai double in C e quindi sono numeri in doppio precisione, e occupano in memoria 64 bits. Questo comporta un errore ...
2,906
Given the following text description, write Python code to implement the functionality described below step by step Description: Defining the Problem Here we will derive the equations of motion for the classic mass-spring-damper system under the influence of gravity. The following figure gives a pictorial description ...
Python Code: from IPython.display import SVG SVG(filename='mass_spring_damper.svg') Explanation: Defining the Problem Here we will derive the equations of motion for the classic mass-spring-damper system under the influence of gravity. The following figure gives a pictorial description of the problem. End of explanatio...
2,907
Given the following text description, write Python code to implement the functionality described below step by step Description: Finding similar documents with Word2Vec and Soft Cosine Measure Soft Cosine Measure (SCM) [1, 3] is a promising new tool in machine learning that allows us to submit a query and return the m...
Python Code: # Initialize logging. import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) Explanation: Finding similar documents with Word2Vec and Soft Cosine Measure Soft Cosine Measure (SCM) [1, 3] is a promising new tool in machine learning that allows us to submit...
2,908
Given the following text description, write Python code to implement the functionality described below step by step Description: Word2Vec Tutorial In case you missed the buzz, word2vec is a widely featured as a member of the “new wave” of machine learning algorithms based on neural networks, commonly referred to as "d...
Python Code: # import modules & set up logging import gensim, logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) sentences = [['first', 'sentence'], ['second', 'sentence']] # train word2vec on the two sentences model = gensim.models.Word2Vec(sentences, min_count=1) Expla...
2,909
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Machine Learning Model training and serving </h1> The training architecture involves collecting data from the two sources, mashing them up with Dataflow and saving the results in BigQue...
Python Code: %projects set ml-autoawesome import os PROJECT = 'ml-autoawesome' # CHANGE THIS BUCKET = 'ml-autoawesome-cmle' # CHANGE THIS REGION = 'us-central1' # CHANGE THIS os.environ['PROJECT'] = PROJECT # for bash os.environ['BUCKET'] = BUCKET # for bash os.environ['REGION'] = REGION # for bash %bash echo "proj...
2,910
Given the following text description, write Python code to implement the functionality described below step by step Description: Q3 In this question, you'll go over some of the core terms and concepts in statistics. Part A Write a function, variance, which computes the variance of a list of numbers. The function takes...
Python Code: import numpy as np np.random.seed(5987968) x = np.random.random(8491) v = x.var(ddof = 1) np.testing.assert_allclose(v, variance(x)) np.random.seed(4159) y = np.random.random(25) w = y.var(ddof = 1) np.testing.assert_allclose(w, variance(y)) Explanation: Q3 In this question, you'll go over some of the core...
2,911
Given the following text description, write Python code to implement the functionality described below step by step Description: Learn Posture use machine learning to recognize robot's posture (following the example in scikit-learn-intro.ipynb ) 1. Data collection We have colleceted data before, you need to add new da...
Python Code: %pylab inline import pickle from os import listdir, path import numpy as np from sklearn import svm, metrics ROBOT_POSE_DATA_DIR = 'robot_pose_data' classes = listdir(ROBOT_POSE_DATA_DIR) print classes def load_pose_data(i): '''load pose data from file''' data = [] target = [] # YOUR CODE H...
2,912
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting Who Will Leave and Why - Python Machine Learning In this notebook, we do a brief exploration of our HR analytics data (found on Kaggle, which you can check for more info on the da...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline Explanation: Predicting Who Will Leave and Why - Python Machine Learning In this notebook, we do a brief exploration of our HR analytics data (found on Kaggle, which you can check for more info o...
2,913
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I want to process a gray image in the form of np.array.
Problem: import numpy as np im = np.array([[1,1,1,1,1,5], [1,0,0,1,2,0], [2,1,0,0,1,0], [1,0,0,7,1,0], [1,0,0,0,0,0]]) mask = im == 0 rows = np.flatnonzero((mask).sum(axis=1)) cols = np.flatnonzero((mask).sum(axis=0)) if rows.shape[0] == 0: result = np.arr...
2,914
Given the following text description, write Python code to implement the functionality described below step by step Description: Sensitivity analysis for L-Serine In this example, the ammount of produced serine is increased in steps. The biomass production will decrease with increased accumulation of Serine. This is a...
Python Code: ser__L = model.metabolites.ser__L_c result = sensitivity_analysis(model, ser__L, is_essential=True, steps=10, biomass=model.reactions.BIOMASS_Ec_iJO1366_core_53p95M) result.data_frame result.plot(width=700, height=500) Explanation: Sensitivity analysis for L-Serine In this exa...
2,915
Given the following text description, write Python code to implement the functionality described below step by step Description: On Kepler 452 Kepler 452 is a solar-like star in the Kepler field that was recently announced to possess a planet with an orbit of 385 Earth days. Based on a stellar evolution model analysis...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt Explanation: On Kepler 452 Kepler 452 is a solar-like star in the Kepler field that was recently announced to possess a planet with an orbit of 385 Earth days. Based on a stellar evolution model analysis of the host star, the planet is f...
2,916
Given the following text description, write Python code to implement the functionality described below step by step Description: Point sources In astromodels a point source is described by its position in the sky and its spectral features. Creating a point source A simple source with a power law spectrum can be create...
Python Code: from astromodels import * # Using J2000 R.A. and Dec (ICRS), which is the default coordinate system: simple_source_icrs = PointSource('simple_source', ra=123.2, dec=-13.2, spectral_shape=powerlaw()) Explanation: Point sources In astromodels a point source is described by its position in the sky and its spe...
2,917
Given the following text description, write Python code to implement the functionality described below step by step Description: Modifying an image Basic example, rotates the image (rot_const) by 0.2 radians. Step1: Full list of modifications and defaults center Step2: Perlin noise Step3: A bunch of different confi...
Python Code: img1 = image.load_image('https://upload.wikimedia.org/wikipedia/commons/6/6a/Mona_Lisa.jpg', (220, 350)) img2 = canvas.modify_canvas(img1, {'rot_const': 0.2}) img3 = image.concatenate_images([img1, img2], margin=2) image.display(img3) Explanation: Modifying an image Basic example, rotates the image (rot_co...
2,918
Given the following text description, write Python code to implement the functionality described below step by step Description: Lectura y manipulación de datos con Pandas Autor Step1: 1. The Pandas Series Object A Pandas Series is a one-dimensional array of indexed data. It can be created from a list or array as fol...
Python Code: import numpy as np from __future__ import print_function import pandas as pd pd.__version__ Explanation: Lectura y manipulación de datos con Pandas Autor: Roberto Muñoz <br /> E-mail: &#114;&#109;&#117;&#110;&#111;&#122;&#64;&#117;&#99;&#46;&#99;&#108; This notebook shows how to create Series and Datafram...
2,919
Given the following text description, write Python code to implement the functionality described below step by step Description: Project Euler Contents Useful Functions Multiples of 3 and 5 Even Fibonacci numbers Largest prime factor Largest palindrome product Smallest multiple Sum square difference 10001st prime Larg...
Python Code: def is_prime(n): if n == 1: return False if n < 4: return True if n % 2 == 0: return False if n < 9: return True # excluded 4, 6, 8 already if n % 3 == 0: return False i = 5 while i < n**(0.5) + 1: if n % i == 0: return False if n % (i + 2) == 0: ...
2,920
Given the following text description, write Python code to implement the functionality described below step by step Description: Step4: Seminar Step5: try out snapshots Step16: MCTS Step18: Main MCTS loop With all we implemented, MCTS boils down to a trivial piece of code. Step19: Plan and execute In this section,...
Python Code: from collections import namedtuple from pickle import dumps, loads from gym.core import Wrapper # a container for get_result function below. Works just like tuple, but prettier ActionResult = namedtuple( "action_result", ("snapshot", "observation", "reward", "is_done", "info")) class WithSnapshots(Wrap...
2,921
Given the following text description, write Python code to implement the functionality described below step by step Description: Example Step1: First we build a model representing the system of equations. Step2: Generate mock data. Step3: Perform the fit. Let's pretend that for experimental reasons, we can only mea...
Python Code: from symfit import ( variables, parameters, ODEModel, D, Fit ) from symfit.core.support import key2str import numpy as np import matplotlib.pyplot as plt Explanation: Example: Multiple species Reaction Kinetics using ODEModel In this example we shall fit to a complex system of ODEs, based on that publish...
2,922
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Input To do any computation, you need to have data. Getting the data in the framework of a workflow is therefore the first step of every analysis. Nipype provides many different modules...
Python Code: from nipype import DataGrabber, Node # Create DataGrabber node dg = Node(DataGrabber(infields=['subject_id', 'ses_name', 'task_name'], outfields=['anat', 'func']), name='datagrabber') # Location of the dataset folder dg.inputs.base_directory = '/data/ds000114' # Necessary de...
2,923
Given the following text description, write Python code to implement the functionality described below step by step Description: Content and Objectives Show pulse shaping (rect and raised-cosine) for random data Spectra are determined based on the theoretical pulse shape as well as for the random signals when applying...
Python Code: # importing import numpy as np import matplotlib.pyplot as plt import matplotlib # showing figures inline %matplotlib inline # plotting options font = {'size' : 16} plt.rc('font', **font) plt.rc('text', usetex=matplotlib.checkdep_usetex(True)) matplotlib.rc('figure', figsize=(18, 8) ) Explanation: Conte...
2,924
Given the following text description, write Python code to implement the functionality described below step by step Description: Unit Tests Overview and Principles Testing is the process by which you exercise your code to determine if it performs as expected. The code you are testing is referred to as the code under t...
Python Code: import numpy as np # Code Under Test def entropy(ps): if any([(p < 0.0) or (p > 1.0) for p in ps]): raise ValueError("Bad input.") if sum(ps) > 1: raise ValueError("Bad input.") items = ps * np.log(ps) new_items = [] for item in items: if np.isnan(item): ...
2,925
Given the following text description, write Python code to implement the functionality described below step by step Description: Flowers Image Classification with TensorFlow on Cloud ML Engine TPU This notebook demonstrates how to do image classification from scratch on a flowers dataset using the Estimator API. Unlik...
Python Code: %%bash pip install apache-beam[gcp] Explanation: Flowers Image Classification with TensorFlow on Cloud ML Engine TPU This notebook demonstrates how to do image classification from scratch on a flowers dataset using the Estimator API. Unlike flowers_fromscratch.ipynb, here we do it on a TPU. Therefore, this...
2,926
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.algo - Des problèmes de graphes Découvrir les graphes avec des problèmes pas trop compliqués. Composantes connexes, plus court chemin et... Step1: Un graphe
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 1A.algo - Des problèmes de graphes Découvrir les graphes avec des problèmes pas trop compliqués. Composantes connexes, plus court chemin et... End of explanation # tutoriel_graphe noeuds = {0: 'le', 1: 'silences', 2: 'quelques', 3...
2,927
Given the following text description, write Python code to implement the functionality described below step by step Description: The Epochs data structure Step1: Step2: As we saw in the tut-events-vs-annotations tutorial, we can extract an events array from Step3: <div class="alert alert-info"><h4>Note</h4><p>We ...
Python Code: import os import mne Explanation: The Epochs data structure: discontinuous data This tutorial covers the basics of creating and working with :term:epoched &lt;epochs&gt; data. It introduces the :class:~mne.Epochs data structure in detail, including how to load, query, subselect, export, and plot data from ...
2,928
Given the following text description, write Python code to implement the functionality described below step by step Description: US energy consumption This example is based on the Sankey diagrams of US energy consumption from the Lawrence Livermore National Laboratory (thanks to John Muth for the suggestion and transc...
Python Code: from floweaver import * Explanation: US energy consumption This example is based on the Sankey diagrams of US energy consumption from the Lawrence Livermore National Laboratory (thanks to John Muth for the suggestion and transcribing the data). We jump straight to the final result – for more explanation of...
2,929
Given the following text description, write Python code to implement the functionality described below step by step Description: Photo-z Determination for SpIES High-z Candidates Notebook that actually applies the algorithms from SpIESHighzQuasarPhotoz.ipynb to the quasar candidates. Step1: Since we are running on se...
Python Code: ## Read in the Training Data and Instantiating the Photo-z Algorithm %matplotlib inline from astropy.table import Table import numpy as np import matplotlib.pyplot as plt #data = Table.read('GTR-ADM-QSO-ir-testhighz_findbw_lup_2016_starclean.fits') #JT PATH ON TRITON to training set after classification #d...
2,930
Given the following text description, write Python code to implement the functionality described below step by step Description: For ecoinvent3.4 and ecoinvent3.5, the LCIA_implmentation.xls file does not include units for emissions of the pollutants anymore. This is a requirement however, in ecopold2matrix. This note...
Python Code: import pandas as pd old_LCIA = pd.read_excel('put_the_path_to_your_old_LCIA_implementation_file.xls_here','CFs') incomplete_LCIA = pd.read_excel('put_the_path_to_your_incomplete_LCIA_implementation_file.xls_here','CFs') complete_LCIA = incomplete_LCIA.merge(old_LCIA,how='left') # drop obsolete columns comp...
2,931
Given the following text description, write Python code to implement the functionality described below step by step Description: Our test set here includes the 16 million molecules from the old ZINC clean set that could be successfully processed by the RDKit. We use the Standard InChI that comes with ChEMBL and a non-...
Python Code: %sql postgresql://localhost/inchi_split \ select count(*) from zinc_clean_nonstandard; Explanation: Our test set here includes the 16 million molecules from the old ZINC clean set that could be successfully processed by the RDKit. We use the Standard InChI that comes with ChEMBL and a non-standard InCh...
2,932
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Importar librerías Step2: Cargar base de datos Step3: Desechar imágenes no cuadradas Step4: Normalizar Step5: Balance de Clases, definir conjuntos de train, val, y...
Python Code: from google.colab import drive drive.mount('/content/drive') Explanation: <a href="https://colab.research.google.com/github/kevinracso/01Tarea/blob/master/Copia_de_Copia_de_Preprocesamiento_y_Red_test.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In C...
2,933
Given the following text description, write Python code to implement the functionality described below step by step Description: Reproducible Experiments with pynoddy All pynoddy experiments can be defined in a Python script, and if all settings are appropriate, then this script can be re-run to obtain a reproduction ...
Python Code: from IPython.core.display import HTML css_file = 'pynoddy.css' HTML(open(css_file, "r").read()) %matplotlib inline # here the usual imports. If any of the imports fails, # make sure that pynoddy is installed # properly, ideally with 'python setup.py develop' # or 'python setup.py install' import sys, os ...
2,934
Given the following text description, write Python code to implement the functionality described below step by step Description: <h2> ppm = 2.5 </h2> There weren't engouh retention-tie correlation groups here, so I should either switch to linear interpolation (not loess). So this is probably kinda meh data in real lif...
Python Code: import time import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np from sklearn import preprocessing from sklearn.ensemble import RandomForestClassifier from sklearn.cross_validation import StratifiedShuffleSplit from sklearn.cross_validation import cross_val_score #fr...
2,935
Given the following text description, write Python code to implement the functionality described below step by step Description: Classification Timothy Helton <br> <font color="red"> NOTE Step1: Exercise 1 This question should be answered using the Weekly data set. This data is similar in nature to the Smarket da...
Python Code: from k2datascience import classification from k2datascience import plotting from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" %matplotlib inline Explanation: Classification Timothy Helton <br> <font color="red"> NOTE: <br> This notebook u...
2,936
Given the following text description, write Python code to implement the functionality described below step by step Description: Using data from this FiveThirtyEight post, write code to calculate the correlation of the responses from the poll. Respond to the story in your PR. Is this a good example of data journalism?...
Python Code: import pandas as pd %matplotlib inline import statsmodels.formula.api as smf import matplotlib.pyplot as plt df = pd.read_excel("Iran_data_3.xlsx") df Explanation: Using data from this FiveThirtyEight post, write code to calculate the correlation of the responses from the poll. Respond to the story in your...
2,937
Given the following text description, write Python code to implement the functionality described below step by step Description: Source localization with MNE/dSPM/sLORETA/eLORETA The aim of this tutorial is to teach you how to compute and apply a linear minimum-norm inverse method on evoked/raw/epochs data. Step1: Pr...
Python Code: import os.path as op import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse Explanation: Source localization with MNE/dSPM/sLORETA/eLORETA The aim of this tutorial is to teach you how to compute and app...
2,938
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas objects So far, we have manipulated data which were stored in NumPy arrays. Let us consider 2D data. Step1: We could visualize it with Matplotlib. Step2: Raw data could look like th...
Python Code: import numpy as np ar = 0.5 * np.eye(3) ar[2, 1] = 1 ar Explanation: Pandas objects So far, we have manipulated data which were stored in NumPy arrays. Let us consider 2D data. End of explanation import matplotlib.pyplot as plt %matplotlib inline plt.imshow(ar, cmap=plt.cm.gray) Explanation: We could visua...
2,939
Given the following text description, write Python code to implement the functionality described below step by step Description: Checking the Equivalence of Regular Expressions In order to check whether two regular expressions $r_1$ and $r_2$ are equivalent, perform the following steps Step1: NFA-2-DFA.ipynb contain...
Python Code: %run Regexp-2-NFA.ipynb Explanation: Checking the Equivalence of Regular Expressions In order to check whether two regular expressions $r_1$ and $r_2$ are equivalent, perform the following steps: - convert $r_1$ and $r_2$ into non-deterministic <span style="font-variant:small-caps;">Fsm</span>s $F_1$ an...
2,940
Given the following text description, write Python code to implement the functionality described below step by step Description: Enter your settings here Step1: Load the data Step2: Smoothing Smoothing in the lattitudinal direction (N-S) is not affected by the projection; distances do not vary since the circles of e...
Python Code: data_folder = Path("/home/bathiany/Sebastian/datamining/edges/obsscan") data_set = DataSet([data_folder / 'ice_conc_nh_ease2-250_cdr-v2p0_remapbilt200_September.nc'], 'ice_conc') #dataset goes from 1979 - 2015 sigma_d = unit('120 km') #200 sigma_t = unit('1 year') gamma = 1e10 scaling_factor = gamma * un...
2,941
Given the following text description, write Python code to implement the functionality described below step by step Description: Now to create the needed tables we need to execute our first SQL statements. It is important to call the commit() function if you want your changes to appear in the file. It is recommended t...
Python Code: conn.execute('''CREATE TABLE FILM (ID INTEGER PRIMARY KEY, TITLE CHAR(200) NOT NULL, YEAR INTEGER NOT NULL, GENRE CHAR(50) NOT NULL, UNIQUE(TITLE, YEAR, GENRE));''') conn.execute('...
2,942
Given the following text description, write Python code to implement the functionality described below step by step Description: Données multidimensionnelles SQL - correction Correction de la séance sur l'utilisation du SQL depuis un notebook. Step1: Exercice 1 Step2: Exercice 2 Step3: Que faut-il écrire ici pour...
Python Code: %matplotlib inline import matplotlib.pyplot as plt plt.style.use('ggplot') from pyquickhelper.helpgen import NbImage from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: Données multidimensionnelles SQL - correction Correction de la séance sur l'utilisation du SQL depuis un notebook...
2,943
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Let's work through an example of single-cell data analysis using Uncurl, using many of its features. For a much briefer example using the same dataset, see examples/zeisel_subset_ex...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import scipy.io import uncurl Explanation: Tutorial Let's work through an example of single-cell data analysis using Uncurl, using many of its features. For a much briefer example using the same dataset, see examples/zeisel_subset_exampl...
2,944
Given the following text description, write Python code to implement the functionality described below step by step Description: Procrustes Analysis Step1: PCA Step2: Solving b vector $$b = \Phi^T \left(x - \bar{x}\right)$$
Python Code: import pandas df = pandas.read_csv('muct76_stasm-output.csv', header=None, usecols=np.arange(2,156), dtype=float) #df = pandas.read_csv('muct76-opencv.csv', header=0, usecols=np.arange(2,154), dtype=float) df.head() X = df.iloc[:, ::2].values Y = df.iloc[:, 1::2].values d = np.hstack((X,Y)) d.shape import ...
2,945
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Step 1 Step2: Step 2 Step3: Step 3 Step4: The CmdStan installation includes a simple example program bernoulli.stan and test data bernoulli.data.json. These are in ...
Python Code: # Load packages used in this notebook import os import json import shutil import urllib.request import pandas as pd Explanation: <a href="https://colab.research.google.com/github/probml/probml-notebooks/blob/main/notebooks/CmdStanPy_Example_Notebook.ipynb" target="_parent"><img src="https://colab.research....
2,946
Given the following text description, write Python code to implement the functionality described below step by step Description: Prepare CDL Data In this notebook, we prepare the 2016 from the USDA 2016 Crop Data Layer (CDL) for Iowa for use in the crop classification notebooks. This involves taking the CDL data for I...
Python Code: import os import pathlib from subprocess import check_output, STDOUT, CalledProcessError import tempfile import rasterio Explanation: Prepare CDL Data In this notebook, we prepare the 2016 from the USDA 2016 Crop Data Layer (CDL) for Iowa for use in the crop classification notebooks. This involves taking t...
2,947
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 1 Step1: Read the counts table This is bacterial mRNA-Seq with samples at 4 different temperatures with or without the addition of BCM. Each condition is sequenced in triplicates. A...
Python Code: def parse_barcodes(bcfile, bc_id='BC'): res = {} with open(bcfile, 'r') as fi: for line in fi: fields = line.strip().split(',') if fields[0].startswith(bc_id): res[fields[0]] = fields[1] return res def parse_exp_config(expfile, bc_dict): res =...
2,948
Given the following text description, write Python code to implement the functionality described below step by step Description: Model Evaluation How to measure a model? How to find out that the model is doing well or just predicting useless? This job is done by metrics. There are a bunch of metrics explained in sciki...
Python Code: from sklearn.model_selection import train_test_split from sklearn.datasets import load_iris X, y = load_iris(return_X_y=True) print('X.shape =', X.shape) print('y.shape =', y.shape) print() X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, shuffle=True) print('X_train.shape =', X_tra...
2,949
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Get the Data We'll work with the Ecommerce Customers csv file from the company. It has Customer info, suchas Email, Address, and their color Avatar. Then it also has nu...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> Linear Regression - Project Exercise Congratulations! You just got some contract work with an Ecommer...
2,950
Given the following text description, write Python code to implement the functionality described below step by step Description: VARMAX models This is a brief introduction notebook to VARMAX models in statsmodels. The VARMAX model is generically specified as Step1: Model specification The VARMAX class in statsmodels ...
Python Code: %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt dta = sm.datasets.webuse('lutkepohl2', 'https://www.stata-press.com/data/r12/') dta.index = dta.qtr dta.index.freq = dta.index.inferred_freq endog = dta.loc['1960-04-01':'1978-10-01', ['dl...
2,951
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Statistics in Python https Step1: Hypothesis Testing Step2: 1-sample t-test Step3: 2-sample t-test Step4: Paired tests Step5: However this doesn't account for individual...
Python Code: #import pandas and use magic function import pandas as pd %matplotlib inline # import our data using pandas read_csv() function where delimiter = ';', index_col = 0, na_values = '.' data = pd.read_csv('https://www.scipy-lectures.org/_downloads/brain_size.csv', delimiter=';', index_col=0...
2,952
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Environment Preparation Install Java 8 Run the cell on the Google Colab to install jdk 1.8. Note Step2: Install BigDL Orca You can install the latest pre-release vers...
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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
2,953
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 7 Step1: Today's lab reviews Maximum Likelihood Estimation, and introduces interctive plotting in the jupyter notebook. Part 1 Step2: Question 2 Step3: Question 3 Step4: Question 4 S...
Python Code: # Run this cell to set up the notebook. import numpy as np import pandas as pd import seaborn as sns import scipy as sci import matplotlib %matplotlib inline import matplotlib.pyplot as plt from matplotlib import patches, cm from matplotlib.ticker import LinearLocator, FormatStrFormatter from mpl_toolkits....
2,954
Given the following text description, write Python code to implement the functionality described below step by step Description: BigQuery Query Run Run query on a project. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance w...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: BigQuery Query Run Run query on a project. License Copyright 2020 Google LLC, 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 Lic...
2,955
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Form Parsing using Google Cloud Document AI This notebook shows how to use Google Cloud Document AI to parse a campaign disclosure form. It accompanies this Medium article Step2: Doc...
Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/imported/formparsing.ipynb from IPython.display import Markdown as md ### change to reflect your notebook _nb_repo = 'training-data-analyst' _nb_loc = "blogs/form_parser/formparsing.ipynb" _nb_title = "Form Parsing Using Google Cloud Document AI" ### no need to ...
2,956
Given the following text description, write Python code to implement the functionality described below step by step Description: Optimization Methods Until now, you've always used Gradient Descent to update the parameters and minimize the cost. In this notebook, you will learn more advanced optimization methods that c...
Python Code: import numpy as np import matplotlib.pyplot as plt import scipy.io import math import sklearn import sklearn.datasets from opt_utils import load_params_and_grads, initialize_parameters, forward_propagation, backward_propagation from opt_utils import compute_cost, predict, predict_dec, plot_decision_boundar...
2,957
Given the following text description, write Python code to implement the functionality described below step by step Description: Characterwise Double-Stacked LSTM as Author Step1: Defining the Model Actually, it's a single layer of GRU for now... (rather than a double-stacked LSTM) Step2: That's the underlying netw...
Python Code: import numpy import theano from theano import tensor from blocks.bricks import Tanh from blocks.bricks.recurrent import GatedRecurrent from blocks.bricks.sequence_generators import (SequenceGenerator, Readout, SoftmaxEmitter, LookupFeedback) from blocks.graph import ComputationGraph import blocks.algorithm...
2,958
Given the following text description, write Python code to implement the functionality described below step by step Description: A Decision Tree of Observable Operators Part 2 Step1: ... and emitting all of the items from all of the Observables, one Observable at a time Step2: ... by combining the items from two or ...
Python Code: reset_start_time(O.merge) l = [] def excepting_f(obs): for i in range(10): l.append(1) obs.on_next(1 / (3 - len(l))) stream1 = O.from_(('a', 'b', 'c')) stream2 = O.create(excepting_f) # merged stream stops in any case at first exception! # No guarantee of order of those immediately crea...
2,959
Given the following text description, write Python code to implement the functionality described below step by step Description: Bubble Breaker in Python / Javascript The key 'board' data structure is a numpy array, which is (for efficiency) stored on its side (with the bottom-right phone cell being the board[0,0] cel...
Python Code: import os import numpy as np import shutil, requests import pickle Explanation: Bubble Breaker in Python / Javascript The key 'board' data structure is a numpy array, which is (for efficiency) stored on its side (with the bottom-right phone cell being the board[0,0] cell): End of explanation models_dir = '...
2,960
Given the following text description, write Python code to implement the functionality described below step by step Description: Aprendizaje computacional en grandes volúmenes de texto Mario Graff (mgraffg@ieee.org, mario.graff@infotec.mx) Sabino Miranda (sabino.miranda@infotec.mx) Daniela Moctezuma (dmoctezuma@centro...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import gzip import json import numpy as np def read_data(fname): with gzip.open(fname) as fpt: d = json.loads(str(fpt.read(), encoding='utf-8')) return d %matplotlib inline plt.figure(figsize=(20, 10)) mx_pos = read_data('spanish/polari...
2,961
Given the following text description, write Python code to implement the functionality described below step by step Description: Back to the main Index Inline OMEX and COMBINE archives Tellurium provides a way to easily edit the contents of COMBINE archives in a human-readable format called inline OMEX. To create a CO...
Python Code: import tellurium as te, tempfile, os te.setDefaultPlottingEngine('matplotlib') %matplotlib inline antimony_str = ''' model myModel S1 -> S2; k1*S1 S1 = 10; S2 = 0 k1 = 1 end ''' phrasedml_str = ''' model1 = model "myModel" sim1 = simulate uniform(0, 5, 100) task1 = run sim1 on model1 plot "Fi...
2,962
Given the following text description, write Python code to implement the functionality described below step by step Description: Here we examine whether publishing volume has an impact on overall, article, or place traffic, specifically whether total, average, or median traffic is affected by increased publishing volu...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline df = pd.read_csv('All content.csv', index_col='Published',parse_dates=True) df['count']=1 df = df[(df['Page Views'] > 200)] df_resampled = df.resample('D',how ='sum') Explanation: Here we examine whether publishing vo...
2,963
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating a Simple Autoencoder By Step1: Problem 1a Step2: Problem 1b. Split the training and test set with a 66/33 split. Problem 2 Step3: Problem 3. Training This is going to be a lot of...
Python Code: !pip install astronn import torch import matplotlib.pyplot as plt import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import IsolationForest from astroNN.datasets import load_galaxy10 from astroNN.datasets.galaxy10 import galaxy10cls_lookup from sklearn.ensemble im...
2,964
Given the following text description, write Python code to implement the functionality described below step by step Description: Create new train folders with only the files from train_and_test_data_labels_safe.csv Step1: Create TFRecords
Python Code: import shutil # Read files list. Header: file, class (0: interictal, 1: preictal), safe (or not to use) files_list = np.genfromtxt('./train_and_test_data_labels_safe.csv', dtype=("|S15", np.int32, np.int32), delimiter=',', skip_header=1) # Get only files which are safe to use fi...
2,965
Given the following text description, write Python code to implement the functionality described below step by step Description: Orbital Elements Note Step1: Any components not passed automatically default to 0. REBOUND can also accept orbital elements. Reference bodies As a reminder, there is a one-to-one mapping...
Python Code: import rebound sim = rebound.Simulation() sim.add(m=1., x=1., vz = 2.) Explanation: Orbital Elements Note: All angles for orbital elements are in radians We can add particles to a simulation by specifying cartesian components: End of explanation sim.add(m=1., a=1.) sim.status() Explanation: Any components...
2,966
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have some data structured as below, trying to predict t from the features.
Problem: import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler data = load_data() scaler = StandardScaler() scaler.fit(data) scaled = scaler.transform(data) inversed = scaler.inverse_transform(scaled)
2,967
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Q-Network implementation This notebook shamelessly demands you to implement a DQN - an approximate q-learning algorithm with experience replay and target networks - and see if it works ...
Python Code: #XVFB will be launched if you run on a server import os if type(os.environ.get("DISPLAY")) is not str or len(os.environ.get("DISPLAY")) == 0: !bash ../xvfb start os.environ['DISPLAY'] = ':1' Explanation: Deep Q-Network implementation This notebook shamelessly demands you to implement a DQN - an app...
2,968
Given the following text description, write Python code to implement the functionality described below step by step Description: Morph volumetric source estimate This example demonstrates how to morph an individual subject's Step1: Setup paths Step2: Compute example data. For reference see sphx_glr_auto_examples_inv...
Python Code: # Author: Tommy Clausner <tommy.clausner@gmail.com> # # License: BSD (3-clause) import os import nibabel as nib import mne from mne.datasets import sample from mne.minimum_norm import apply_inverse, read_inverse_operator from nilearn.plotting import plot_glass_brain print(__doc__) Explanation: Morph volume...
2,969
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial In this tutorial we'll explore the two main pieces of functionality that HSMMLearn provides Step1: Decoding For this part of the tutorial we'll use an HSMM with 3 internal states a...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: Tutorial In this tutorial we'll explore the two main pieces of functionality that HSMMLearn provides: Viterbi decoding: given a sequence of observations, find the sequence of hidden states that maximizes the joint probabil...
2,970
Given the following text description, write Python code to implement the functionality described below step by step Description: MuJoCo tutorial with dm_control Python bindings <p><small><small>Copyright 2021 The dm_control Authors.</small></p> <p><small><small>Licensed under the Apache License, Version 2.0 (the "Lice...
Python Code: #@title Run to install MuJoCo and `dm_control` import distutils.util import subprocess if subprocess.run('nvidia-smi').returncode: raise RuntimeError( 'Cannot communicate with GPU. ' 'Make sure you are using a GPU Colab runtime. ' 'Go to the Runtime menu and select Choose runtime type.'...
2,971
Given the following text description, write Python code to implement the functionality described below step by step Description: Functions Making reusable blocks of code. Starting point Step1: What about for $a = 2$, $b = 8$, and $c = 1$? Step3: Functions Step5: Observe how this function works. Step7: Summarize St...
Python Code: ## Code here import math (-4 + math.sqrt(4**2 - 4*1*3))/(2*1) Explanation: Functions Making reusable blocks of code. Starting point: In this exercise, we're going to calculate one of the roots from the quadratic formula: $r_{p} = \frac{-b + \sqrt{b^{2} - 4ac}}{2a}$ Determine $r_{p}$ for $a = 1$, $b=4$, and...
2,972
Given the following text description, write Python code to implement the functionality described below step by step Description: Cppyy Tutorial (Modified from Enrico Guiraud's cppyy tutorial.) This tutorial introduces the basic concepts for using cppyy, the automatic Python-C++ generator. To install cppyy on your syst...
Python Code: import cppyy Explanation: Cppyy Tutorial (Modified from Enrico Guiraud's cppyy tutorial.) This tutorial introduces the basic concepts for using cppyy, the automatic Python-C++ generator. To install cppyy on your system, simply run (this may take a while as it will pull in and compile a custom version of LL...
2,973
Given the following text description, write Python code to implement the functionality described below step by step Description: Boosting a decision stump The goal of this notebook is to implement your own boosting module. Brace yourselves! This is going to be a fun and challenging assignment. Use SFrames to do some f...
Python Code: import graphlab import matplotlib.pyplot as plt %matplotlib inline Explanation: Boosting a decision stump The goal of this notebook is to implement your own boosting module. Brace yourselves! This is going to be a fun and challenging assignment. Use SFrames to do some feature engineering. Modify the decisi...
2,974
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating a document similarity microservice for the Reuters-21578 dataset. First download the Reuters-21578 dataset in JSON format into the local folder Step1: Create a gensim LSI document ...
Python Code: import json import codecs import os docs = [] for filename in os.listdir("reuters-21578-json/data/full"): f = open("reuters-21578-json/data/full/"+filename) js = json.load(f) for j in js: if 'topics' in j and 'body' in j: d = {} d["id"] = j['id'] d["...
2,975
Given the following text description, write Python code to implement the functionality described below step by step Description: Convolutional Autoencoder Sticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. Again, loading modules and the data. Step1: Network Archit...
Python Code: %matplotlib inline 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', validation_size=0) img = mnist.train.images[2] plt.imshow(img.reshape((28, 28)), cmap='Greys_r') Explanati...
2,976
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: Text classification with TensorFlow Lite Model Maker <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="http...
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...
2,977
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas 数据读写 API 读取 | 写入 --- | --- read_csv | to_csv read_excel | to_excel read_hdf | to_hdf read_sql | to_sql read_json | to_json read_html | to_html read_stata | to_stata read_clipboard | ...
Python Code: import numpy as np import pandas as pd csvframe=pd.read_csv('myCSV_01.csv') csvframe # 也可以通过read_table来读写数据 pd.read_table('myCSV_01.csv',sep=',') Explanation: Pandas 数据读写 API 读取 | 写入 --- | --- read_csv | to_csv read_excel | to_excel read_hdf | to_hdf read_sql | to_sql read_json | to_json read_html | to_ht...
2,978
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Mining First thing to do is to find the structure of the file. We can find a description in the "dblp.dtd" file and on the website Step1: Observation of the data Load the author-> publ...
Python Code: from importlib import reload import xml_parser reload(xml_parser) from xml_parser import Xml_parser #Xml_parser = Xml_parser().collect_data("../pmi_data") Explanation: Data Mining First thing to do is to find the structure of the file. We can find a description in the "dblp.dtd" file and on the website: Th...
2,979
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', 'cams', 'sandbox-3', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: CAMS Source ID: SANDBOX-3 Topic: Landice Sub-Topics: Glaciers, Ice. Prop...
2,980
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Text classification with preprocessed text Step2: <a id="download"></a> Download the IMDB dataset The IMDB movie reviews dataset comes packaged in tfds. It has alread...
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...
2,981
Given the following text description, write Python code to implement the functionality described below step by step Description: Diagram bifurkacyjny dla równania logistycznego $x \to a x (1-x)$ Równanie logistyczne jest niezwykle prostym równaniem iteracyjnym wykazującym zaskakująco złożone zachowanie. Jego własności...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pycuda.gpuarray as gpuarray from pycuda.curandom import rand as curand from pycuda.compiler import SourceModule import pycuda.driver as cuda try: ctx.pop() ctx.detach() except: print ("No CTX!") cuda.init() device = cu...
2,982
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing Corpus Visualizers on Yellowbrick Step1: UMAP vs T-SNE Uniform Manifold Approximation and Projection (UMAP) is a dimension reduction technique that can be used for visualisation s...
Python Code: ##### Import all the necessary Libraries from yellowbrick.text import TSNEVisualizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer from yellowbrick.text import UMAPVisualizer from yellowbrick.datasets import load_hobbies Explanation:...
2,983
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Running faster your code [Discrete signal energy](https Step2: Now, using Numpy's array multiplication and sum Step4: Another example to see that vectorization not only involves pur...
Python Code: import numpy as np def non_vectorized_dot_product(x, y): Return the sum of x[i] * y[j] for all pairs of indices i, j. Example: >>> my_dot_product(np.arange(20), np.arange(20)) result = 0 for i in range(len(x)): result += x[i] * y[i] return result signal = ...
2,984
Given the following text description, write Python code to implement the functionality described below step by step Description: $\newcommand{\xv}{\mathbf{x}} \newcommand{\Xv}{\mathbf{X}} \newcommand{\piv}{\mathbf{\pi}} \newcommand{\yv}{\mathbf{y}} \newcommand{\Yv}{\mathbf{Y}} \newcommand{\zv}{\mathbf{z}} \newcommand{...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline xs = np.linspace(-5,10,1000) mu = 5.5 plt.plot(xs, 1/np.sqrt((xs-mu)**2)) plt.ylim(0,20) plt.plot([mu, mu], [0, 20], 'r--',lw=2) plt.xlabel('$x$') plt.ylabel('$p(x)$'); Explanation: $\newcommand{\xv}{\mathbf{x}} \newcommand{\Xv}{\mathbf{...
2,985
Given the following text description, write Python code to implement the functionality described below step by step Description: 6.86x - Introduction to ML Packages (Part 2) This tutorial is designed to provide a short introduction to deep learning with PyTorch. You can start studying this tutorial as you work through...
Python Code: # Start by importing torch import torch Explanation: 6.86x - Introduction to ML Packages (Part 2) This tutorial is designed to provide a short introduction to deep learning with PyTorch. You can start studying this tutorial as you work through unit 3 of the course. For more resources, check out the PyTorch...
2,986
Given the following text description, write Python code to implement the functionality described below step by step Description: Python --> IPython --> (IPython) Notebook What, Why ? Python = language interpreter IPython = enhanced interaction, shortcuts, .. IPython notebook = html frontend + protocol Jupyter notebo...
Python Code: ## Let's have a short look at the IPython web site: from IPython.display import display, Image, HTML HTML('<iframe src=http://ipython.org width=1000 height=400> </iframe>') Explanation: Python --> IPython --> (IPython) Notebook What, Why ? Python = language interpreter IPython = enhanced interaction, shor...
2,987
Given the following text description, write Python code to implement the functionality described below step by step Description: Goal-Based Data Collection A practical approach to robot reinforcement learning is to first collect a large batch of real or simulated robot interaction data, using some data collection pol...
Python Code: from rl_coach.agents.td3_exp_agent import TD3GoalBasedAgentParameters from rl_coach.architectures.embedder_parameters import InputEmbedderParameters from rl_coach.architectures.layers import Dense, Conv2d, BatchnormActivationDropout, Flatten from rl_coach.base_parameters import EmbedderScheme from rl_coach...
2,988
Given the following text description, write Python code to implement the functionality described below step by step Description: Obtain the SELU parameters for arbitrary fixed points Author Step2: Function to obtain the parameters for the SELU with arbitrary fixed point (mean variance) Step4: Adjust the SELU functio...
Python Code: import numpy as np from scipy.special import erf,erfc from sympy import Symbol, solve, nsolve Explanation: Obtain the SELU parameters for arbitrary fixed points Author: Guenter Klambauer, 2017 tested under Python 3.5 End of explanation def getSeluParameters(fixedpointMean=0,fixedpointVar=1): Finding t...
2,989
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook Title Notebook description. Question 1 Question 1 text. Step1: Question 2 Question 2 text.
Python Code: print("Student 1 answers question 1.") print("Student 2 answers question 1.") print("Student 3 answers question 1.") Explanation: Notebook Title Notebook description. Question 1 Question 1 text. End of explanation print("Student 1 answers question 2.") print("Student 3 answers question 2.") print("Student ...
2,990
Given the following text description, write Python code to implement the functionality described below step by step Description: Step 1 Step1: So we have a general idea of what things look like. Let's convert the readings to numpy arrays. Step2: And for our purposes we have focused and non-focused. Let's pool all th...
Python Code: import json import pandas as pd import tensorflow as tf import numpy as np df = pd.read_csv("kaggle_data/eeg-data.csv") df.head() df.loc[df.label=='math1'] Explanation: Step 1: Pull in Data, preprocess it. Here I'm using example data from the BioSENSE research group at UC Berekely, collected using a Neuros...
2,991
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have the following torch tensor:
Problem: import numpy as np import pandas as pd import torch t, idx = load_data() assert type(t) == torch.Tensor assert type(idx) == np.ndarray idx = 1 - idx idxs = torch.from_numpy(idx).long().unsqueeze(1) # or torch.from_numpy(idxs).long().view(-1,1) result = t.gather(1, idxs).squeeze(1)
2,992
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook, we duplicate the neural network created in the TensorFlow example in keras. I found the model in keras to be conceptually cleaner. Step1: Set up the parameters for the mo...
Python Code: from __future__ import print_function from __future__ import division import numpy as np np.random.seed(1337) # for reproducibility from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import ...
2,993
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 4 - stripy gradients on the sphere SSRFPACK is a Fortran 77 software package that constructs a smooth interpolatory or approximating surface to data values associated with arbitraril...
Python Code: import stripy as stripy mesh = stripy.spherical_meshes.icosahedral_mesh(refinement_levels=4, include_face_points=True) print(mesh.npoints) Explanation: Example 4 - stripy gradients on the sphere SSRFPACK is a Fortran 77 software package that constructs a smooth interpolatory or approximating surface to dat...
2,994
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook explores the effect of using optimization routine and data extrapolation to zero for S(Q) We are going to load a data pattern and background Pattern of $Mg_2SiO_4$. The data is...
Python Code: %matplotlib inline import os import sys import matplotlib.pyplot as plt sys.path.insert(1, os.path.join(os.getcwd(), '../../')) from glassure.core.calc import calculate_fr, calculate_sq, optimize_sq, calculate_gr from glassure.core.utility import extrapolate_to_zero_poly, convert_density_to_atoms_per_cubic...
2,995
Given the following text description, write Python code to implement the functionality described below step by step Description: image processing Average Hash 이미지를 비교 가능한 해시 값으로 나타낸 것 해시 함수 MD5, SHA256 등을 이용해 데이터 값을 간단한 해시 값으로 변환할 수 있음 이미지가 비슷한지 등을 검출할 때는 해시함수를 사용하면 안됨. 해상도 크기 조정, 색조 보정, 압축 형식 변경 등으로 해시값이 달라짐 Step2: ...
Python Code: from PIL import Image import numpy as np def average_hash(fname, size = 16): img = Image.open(fname) img = img.convert('L') # 1을 지정하면 이진화, RGB, RGBA, CMYK 등의 모드도 지원 img = img.resize((size, size), Image.ANTIALIAS) pixel_data = img.getdata() pixels = np.array(pixel_data) pixels = pixe...
2,996
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This notebook shows how to plot and analyze a phase diagram. Written using Step1: Generating the phase diagram To generate a phase diagram, we obtain entries from the Materials...
Python Code: from pymatgen.ext.matproj import MPRester from pymatgen.analysis.phase_diagram import PhaseDiagram, PDPlotter %matplotlib inline Explanation: Introduction This notebook shows how to plot and analyze a phase diagram. Written using: - pymatgen==2021.2.8 End of explanation #This initializes the REST adaptor. ...
2,997
Given the following text description, write Python code to implement the functionality described below step by step Description: Decoding in time-frequency space data using the Common Spatial Pattern (CSP) The time-frequency decomposition is estimated by iterating over raw data that has been band-passed at different f...
Python Code: # Authors: Laura Gwilliams <laura.gwilliams@nyu.edu> # Jean-Remi King <jeanremi.king@gmail.com> # Alex Barachant <alexandre.barachant@gmail.com> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from ...
2,998
Given the following text description, write Python code to implement the functionality described below step by step Description: DKRZ CMIP6 submission form for ESGF data publication General Information (to be completed based on official CMIP6 references) Data to be submitted for ESGF data publication must follow the r...
Python Code: from dkrz_forms import form_widgets form_widgets.show_status('form-submission') Explanation: DKRZ CMIP6 submission form for ESGF data publication General Information (to be completed based on official CMIP6 references) Data to be submitted for ESGF data publication must follow the rules outlined in the CM...
2,999
Given the following text description, write Python code to implement the functionality described below step by step Description: 01 SEP 2017 Step1: Finally starting to understand this problem. So ResourceExhaustedError isn't system memory (or at least not only) but graphics memory. The card (obviously) cannot handle ...
Python Code: %matplotlib inline import importlib import os, sys; sys.path.insert(1, os.path.join('../utils')) import utils2; importlib.reload(utils2) from utils2 import * from scipy.optimize import fmin_l_bfgs_b from scipy.misc import imsave from keras import metrics from vgg16_avg import VGG16_Avg from bcolz_array_ite...