Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
7,400
Given the following text description, write Python code to implement the functionality described below step by step Description: PyNNDescent with different metrics In the initial tutorial we looked at how to get PyNNDescent running on your data, and how to query the indexes it builds. Implicit in all of that was the m...
Python Code: import pynndescent import numpy as np import h5py from urllib.request import urlretrieve import os def get_ann_benchmark_data(dataset_name): if not os.path.exists(f"{dataset_name}.hdf5"): print(f"Dataset {dataset_name} is not cached; downloading now ...") urlretrieve(f"http://ann-benchm...
7,401
Given the following text description, write Python code to implement the functionality described below step by step Description: Study of Correlation Between Building Demolition and Associated Features Capstone Project for Data Science at Scale on Coursera Repo is located here Chen Yang yangcnju@gmail.com Step1: Obje...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt from IPython.display import Image %matplotlib inline Explanation: Study of Correlation Between Building Demolition and Associated Features Capstone Project for Data Science at Scale on Coursera Repo is located here Chen Yang yangcnju@gm...
7,402
Given the following text description, write Python code to implement the functionality described below step by step Description: First BigQuery ML models for Taxifare Prediction Learning Objectives * Choose the correct BigQuery ML model type and specify options * Evaluate the performance of your ML model * Impro...
Python Code: PROJECT = !gcloud config get-value project PROJECT = PROJECT[0] BUCKET = PROJECT REGION = "us-central1" %env PROJECT=$PROJECT %env BUCKET=$BUCKET %env REGION=$REGION Explanation: First BigQuery ML models for Taxifare Prediction Learning Objectives * Choose the correct BigQuery ML model type and specify o...
7,403
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] Explanation: TV Script Generation In this project, you'll generate your own Simpsons TV script...
7,404
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="http Step1: Example 2
Python Code: import numpy as np import matplotlib.pyplot as plt from landlab import RasterModelGrid from landlab.components import SimpleSubmarineDiffuser grid = RasterModelGrid((3, 51)) # grid has just one row of core nodes # Close top and bottom boundaries grid.set_closed_boundaries_at_grid_edges(False, True, False,...
7,405
Given the following text description, write Python code to implement the functionality described below step by step Description: Import Step1: Reading initial data Step2: Define label label = signB * signVtx > 0 * same sign of B and vtx -> label = 1 * opposite sign of B and vtx -> label = 0 Step3: Define B-like eve...
Python Code: import pandas import numpy from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import roc_curve, roc_auc_score from rep.metaml import FoldingClassifier from rep.data import LabeledDataStorage from rep.report import ClassificationReport from rep.report.metrics import RocAuc from utils i...
7,406
Given the following text description, write Python code to implement the functionality described below step by step Description: 01 - Data Analysis and Preparation This notebook covers the following tasks Step1: Setup Google Cloud project Step2: Set configurations Step3: 1. Explore the data in BigQuery Step4: 2. C...
Python Code: import os import pandas as pd import tensorflow as tf import tensorflow_data_validation as tfdv from google.cloud import bigquery import matplotlib.pyplot as plt from google.cloud import aiplatform as vertex_ai Explanation: 01 - Data Analysis and Preparation This notebook covers the following tasks: Perfor...
7,407
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploring the Lorenz System of Differential Equations In this Notebook we explore the Lorenz system of differential equations Step2: Computing the trajectories and plotting the result We de...
Python Code: %matplotlib inline from ipywidgets import interact, interactive from IPython.display import clear_output, display, HTML import numpy as np from scipy import integrate from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.colors import cnames from matplotlib import ani...
7,408
Given the following text description, write Python code to implement the functionality described below step by step Description: Sigma to Pressure Interpolation By using metpy.calc.log_interp, data with sigma as the vertical coordinate can be interpolated to isobaric coordinates. Step1: Data The data for this example...
Python Code: import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt from netCDF4 import Dataset, num2date import metpy.calc as mpcalc from metpy.cbook import get_test_data from metpy.plots import add_metpy_logo, add_timestamp from metpy.units import units Explanation: Sigma to Pre...
7,409
Given the following text description, write Python code to implement the functionality described below step by step Description: Index - Back - Next Widget List Complete list For a complete list of the widgets available to you, you can list the classes in the widget namespace (as seen below). Widget and DOMWidget, no...
Python Code: from IPython.html import widgets [n for n in dir(widgets) if not n.endswith('Widget') and n[0] == n[0].upper() and not n[0] == '_'] Explanation: Index - Back - Next Widget List Complete list For a complete list of the widgets available to you, you can list the classes in the widget namespace (as seen below...
7,410
Given the following text description, write Python code to implement the functionality described below step by step Description: <div style="width Step1: Next we create an instance of the RadarServer object to point at one of these collections. This downloads some top level metadata and sets things up so we can easil...
Python Code: from siphon.catalog import TDSCatalog cat = TDSCatalog('http://thredds.ucar.edu/thredds/radarServer/catalog.xml') list(cat.catalog_refs) Explanation: <div style="width:1000 px"> <div style="float:right; width:98 px; height:98px;"> <img src="https://raw.githubusercontent.com/Unidata/MetPy/master/metpy/plots...
7,411
Given the following text description, write Python code to implement the functionality described below step by step Description: Project 2 Step1: Now, can you find out the following facts about the dataset? - Total number of students - Number of students who passed - Number of students who failed - Graduation rate of...
Python Code: # Import libraries import numpy as np import pandas as pd # Read student data student_data = pd.read_csv("student-data.csv") print "Student data read successfully!" # Note: The last column 'passed' is the target/label, all other are feature columns student_data.head() Explanation: Project 2: Supervised Lea...
7,412
Given the following text description, write Python code to implement the functionality described below step by step Description: Motor Controller Sizing There are a lot of things that go into sizing a motor controller. This will look at the torque needed to climb an incline. From that, and some data found on the inter...
Python Code: from __future__ import division from __future__ import print_function %matplotlib inline import matplotlib.pyplot as plt import numpy as np from math import sin, pi, tan Explanation: Motor Controller Sizing There are a lot of things that go into sizing a motor controller. This will look at the torque neede...
7,413
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> 2c. Loading large datasets progressively with the tf.data.Dataset </h1> In this notebook, we continue reading the same small dataset, but refactor our ML pipeline in two small, but sign...
Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.5 from google.cloud import bigquery import tensorflow as tf import numpy as np import shutil print(tf.__version__) Explanation: <h1> 2c. Loading large d...
7,414
Given the following text description, write Python code to implement the functionality described below step by step Description: Setup data directory Step1: Download database files Step2: download a small test dataset ATT
Python Code: cd /usr/local/notebooks mkdir -p ./data cd ./data Explanation: Setup data directory End of explanation !wget https://s3.amazonaws.com/ssusearchdb/SSUsearch_db.tgz !tar -xzvf SSUsearch_db.tgz Explanation: Download database files End of explanation !wget https://s3.amazonaws.com/ssusearchdb/test.tgz !tar -xz...
7,415
Given the following text description, write Python code to implement the functionality described below step by step Description: Scientific Computing with Python This is a course about applying computer programming to problems of modeling physical systems and analysing data related to those systems. We'll be using a p...
Python Code: # # When the cursor is in this cell hit "shift enter" to execute the python code here # x=3 # x is assigned an integer value of 3 y=2.4 # y is assigned a floating point value of 2.4 print("x and y are:", x, 'and',y) Explanation: Scientific Computing with Python This is a course about applying compute...
7,416
Given the following text description, write Python code to implement the functionality described below step by step Description: Color palette with python Germain Salvato Vallverdu germain.vallverdu@univ-pau.fr This notebook aims to present several ways to manage color palette with python, mainly for plot purpose. Imp...
Python Code: import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from IPython.display import HTML # intégration notebook %matplotlib inline Explanation: Color palette with python Germain Salvato Vallverdu germain.vallverdu@univ-pau.fr This notebook aims to present several ways to manage color pa...
7,417
Given the following text description, write Python code to implement the functionality described below step by step Description: Ch 07 Step1: Instead of feeding all the training data to the training op, we will feed data in small batches Step2: Define the autoencoder class Step3: The Iris dataset is often used as a...
Python Code: import tensorflow as tf import numpy as np Explanation: Ch 07: Concept 01 Autoencoder All we'll need is TensorFlow and NumPy: End of explanation def get_batch(X, size): a = np.random.choice(len(X), size, replace=False) return X[a] Explanation: Instead of feeding all the training data to the trainin...
7,418
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1 toc-item"><a href="#Building-an-ANN" data-toc-modified-id="Building-an-ANN-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Building an ANN</a></div><d...
Python Code: # Installing Theano # pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git # Installing Tensorflow # pip install tensorflow # Installing Keras # pip install --upgrade keras Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#Building-an-ANN" data-toc-modified-id="Buildi...
7,419
Given the following text description, write Python code to implement the functionality described below step by step Description: RTA workload The RTA or RTApp workload represents a type of workload obtained using the rt-app test application. More details on the test application can be found at https Step1: Test envir...
Python Code: import logging from conf import LisaLogging LisaLogging.setup() # Generate plots inline %pylab inline import json import os # Support to initialise and configure your test environment import devlib from env import TestEnv # Support to configure and run RTApp based workloads from wlgen import RTA, Periodic,...
7,420
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 1 Step1: To download data, we need to identify the relevant tables containing the variables of interest to us. One way to do this would be to refer to the ACS documentation, in part...
Python Code: import pandas as pd import censusdata pd.set_option('display.expand_frame_repr', False) pd.set_option('display.precision', 2) Explanation: Example 1: Downloading Block Group Data and Exporting to CSV As a first example, let's suppose we're interested in unemployment and high school dropout rates for block ...
7,421
Given the following text description, write Python code to implement the functionality described below step by step Description: Example data Step1: VectorAssembler To fit a ML model in pyspark, we need to combine all feature columns into one single column of vectors Step2: Assemble feature columns into one single f...
Python Code: import pandas as pd pdf = pd.DataFrame({ 'x1': ['a','a','b','b', 'b', 'c'], 'x2': ['apple', 'orange', 'orange','orange', 'peach', 'peach'], 'x3': [1, 1, 2, 2, 2, 4], 'x4': [2.4, 2.5, 3.5, 1.4, 2.1,1.5], 'y1': [1, 0, 1, 0, 0, 1], 'y2': ['yes', 'no', 'no', 'yes...
7,422
Given the following text description, write Python code to implement the functionality described below step by step Description: Passband Luminosity Setup Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab). Step1: And w...
Python Code: #!pip install -I "phoebe>=2.3,<2.4" import phoebe from phoebe import u # units import numpy as np logger = phoebe.logger() b = phoebe.default_binary() Explanation: Passband Luminosity Setup Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online...
7,423
Given the following text description, write Python code to implement the functionality described below step by step Description: <header class="w3-container w3-teal"> <img src="images/utfsm.png" alt="" height="100px" align="left"/> <img src="images/mat.png" alt="" height="100px" align="right"/> </header> <br/><br/><br...
Python Code: # Configuracion para recargar módulos y librerías %reload_ext autoreload %autoreload 2 %matplotlib inline from IPython.display import Image as ShowImage from IPython.core.display import HTML HTML(open("style/mat281.css", "r").read()) from mat281_code.lab import greetings alumno_1 = ("Sebastian Flores", "2...
7,424
Given the following text description, write Python code to implement the functionality described below step by step Description: Running Tune experiments with HEBOSearch In this tutorial we introduce HEBO, while running a simple Ray Tune experiment. Tune’s Search Algorithms integrate with ZOOpt and, as a result, allow...
Python Code: # !pip install ray[tune] !pip install HEBO==0.3.2 Explanation: Running Tune experiments with HEBOSearch In this tutorial we introduce HEBO, while running a simple Ray Tune experiment. Tune’s Search Algorithms integrate with ZOOpt and, as a result, allow you to seamlessly scale up a HEBO optimization proces...
7,425
Given the following text description, write Python code to implement the functionality described below step by step Description: Dual CRISPR Screen Analysis Count Combination Amanda Birmingham, CCBB, UCSD (abirmingham@ucsd.edu) Instructions To run this notebook reproducibly, follow these steps Step1: CCBB Library Imp...
Python Code: g_timestamp = "" g_dataset_name = "20160510_A549" g_count_alg_name = "19mer_1mm_py" g_fastq_counts_dir = '/Users/Birmingham/Repositories/ccbb_tickets/20160210_mali_crispr/data/interim/20160510_D00611_0278_BHK55CBCXX_A549' g_fastq_counts_run_prefix = "19mer_1mm_py_20160615223822" g_collapsed_counts_dir = "/...
7,426
Given the following text description, write Python code to implement the functionality described below step by step Description: Train an Agent using Generative Adversarial Imitation Learning The idea of generative adversarial imitation learning is to train a discriminator network to distinguish between expert traject...
Python Code: from stable_baselines3 import PPO from stable_baselines3.ppo import MlpPolicy import gym import seals env = gym.make("seals/CartPole-v0") expert = PPO( policy=MlpPolicy, env=env, seed=0, batch_size=64, ent_coef=0.0, learning_rate=0.0003, n_epochs=10, n_steps=64, ) expert.lea...
7,427
Given the following text description, write Python code to implement the functionality described below step by step Description: Sympy is a Python package used for solving equations using symbolic math. Let's solve the following problem with SymPy. Given Step1: We need to define six different symbols Step2: Next w...
Python Code: from sympy import symbols, nonlinsolve Explanation: Sympy is a Python package used for solving equations using symbolic math. Let's solve the following problem with SymPy. Given: The density of two different polymer samples $\rho_1$ and $\rho_2$ are measured. $$ \rho_1 = 0.904 \ g/cm^3 $$ $$ \rho_2 = 0....
7,428
Given the following text description, write Python code to implement the functionality described below step by step Description: 新增刪修格式 GET - 查詢 (Retrieve) ``` r = requests.get(url, params=API_KEY) query by record ID Step1: 查詢單筆資料 Step2: 新增資料 Step3: 刪除資料 Step4: 修改資料
Python Code: query_string = {'api_key':'keyshdNC8CZdj1xgo', 'maxRecords':'100', 'pageSize':'2', 'filterByFormula':'{屬種} = "new type"'} #pageSize:一個頁面顯示(取回)幾筆資料 r = requests.get(url, params=query_string) r.status_code r.text Explanation: 新增刪修格式 GET - 查詢 (Retrieve) ``` r = requests.get(url, params=API_KEY...
7,429
Given the following text description, write Python code to implement the functionality described below step by step Description: 局部异常因子方法发现异常点 局部异常因子(Local Outlier Factor,LOF)也是一种异常检测算法,它对数据实例的局部密度和邻居进行比较,判断这个数据是否属于相似的密度的区域,它适合从那些簇个数未知,簇的密度和大小各不相同的数据中筛选出异常点。 从k近邻算法启发来 Step1: 局部异常因子计算出每个点的局部密度,通过它与K最近邻的点的距离来评估点的局部密度...
Python Code: from collections import defaultdict import numpy as np import matplotlib.pyplot as plt instance = np.matrix([[0,0],[0,1],[1,1],[1,0],[5,0]]) x = np.squeeze(np.asarray(instance[:,0])) y = np.squeeze(np.asarray(instance[:,1])) plt.cla() plt.figure(1) plt.scatter(x,y) plt.show() Explanation: 局部异常因子方法发现异常点 局部异...
7,430
Given the following text description, write Python code to implement the functionality described below step by step Description: Why EP-ABC can produce too narrow posteriors When you use EP-ABC for inference you may notice that your posterior distributions appear suspiciously narrow, i.e., you may not belief the certa...
Python Code: def plot_mean_with_std(mean, std, std_mult=2, xvals=None, ax=None): if xvals is None: xvals = np.arange(mean.shape[0]) if ax is None: ax = plt.axes() ax.plot(mean, 'k', lw=3) ax.fill_between(xvals, mean + std_mult*std, mean - std_mult*std, edgec...
7,431
Given the following text description, write Python code to implement the functionality described below step by step Description: Examples of propagating uncertainties in mocsy <hr> James Orr - 11 November 2018<br> <img align="left" width="60%" src="http Step1: 1.2 Import standard python libraries Step2: 1.3 Import m...
Python Code: %%bash pwd mkdir code cd code git clone https://github.com/jamesorr/mocsy.git cd mocsy make pwd Explanation: Examples of propagating uncertainties in mocsy <hr> James Orr - 11 November 2018<br> <img align="left" width="60%" src="http://www.lsce.ipsl.fr/Css/img/banniere_LSCE_75.png" ><br><br> LSCE/IPSL, CEA...
7,432
Given the following text description, write Python code to implement the functionality described below step by step Description: ATM 623 Step1: Contents A single layer atmosphere Introducing the two-layer grey gas model Tuning the grey gas model to observations Level of emission Radiative forcing in the 2-layer grey ...
Python Code: # Ensure compatibility with Python 2 and 3 from __future__ import print_function, division Explanation: ATM 623: Climate Modeling Brian E. J. Rose, University at Albany Lecture 7: Elementary greenhouse models Warning: content out of date and not maintained You really should be looking at The Climate Labor...
7,433
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev2 toc-item"><a href="#start" data-toc-modified-id="start-01"><span class="toc-item-num">0.1&nbsp;&nbsp;</span>start</a></div><div class="lev2 toc-item"><a...
Python Code: # which *sites % ll ../*sites Explanation: Table of Contents <p><div class="lev2 toc-item"><a href="#start" data-toc-modified-id="start-01"><span class="toc-item-num">0.1&nbsp;&nbsp;</span>start</a></div><div class="lev2 toc-item"><a href="#Bootstrap-regions-file" data-toc-modified-id="Bootstrap-regions-fi...
7,434
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1 toc-item"><a href="#Summary" data-toc-modified-id="Summary-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Summary</a></div><div class="lev1 toc-item"...
Python Code: %run ../../code/version_check.py Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#Summary" data-toc-modified-id="Summary-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Summary</a></div><div class="lev1 toc-item"><a href="#Version-Control" data-toc-modified-id="Version-Control-2"><s...
7,435
Given the following text description, write Python code to implement the functionality described below step by step Description: This IPython notebook illustrates how to down sample two large tables that are loaded in the memory Step1: Down sampling is typically done when the input tables are large (e.g. each contain...
Python Code: import py_entitymatching as em Explanation: This IPython notebook illustrates how to down sample two large tables that are loaded in the memory End of explanation # Read the CSV files A = em.read_csv_metadata('./citeseer.csv',low_memory=False) # setting the parameter low_memory to False to speed up loadin...
7,436
Given the following text description, write Python code to implement the functionality described below step by step Description: FashionMNIST classification with Multilayer perceptrons https Step1: Preparing the dataset Download and convert to float Step2: IMPORTANT Step3: Understanding the sizes of the data Make s...
Python Code: import matplotlib.pyplot as plt import seaborn as sns import numpy as np from torchvision import datasets import torch import torch.nn as nn import torch.optim as optim Explanation: FashionMNIST classification with Multilayer perceptrons https://github.com/zalandoresearch/fashion-mnist Exercises Try changi...
7,437
Given the following text description, write Python code to implement the functionality described below step by step Description: PyTimeSeries Test for pytimeseries package Importamos la librería Step1: Preparación de los datos pytimeseries recibe una serie de pandas para analizar. A continuación se muestra la prepara...
Python Code: import pytimeseries import pandas import matplotlib Explanation: PyTimeSeries Test for pytimeseries package Importamos la librería End of explanation tserie = pandas.read_csv('champagne.csv', index_col='Month') print(tserie) Explanation: Preparación de los datos pytimeseries recibe una serie de pandas para...
7,438
Given the following text description, write Python code to implement the functionality described below step by step Description: Hackathon de Nanterre 17 octobre 2015 Coder la ville... ... en Python Step1: Lecture des données relatives aux acteurs du numérique (www.datea.pe) Step2: Lecture des données relatives aux ...
Python Code: import pandas as pnd import matplotlib.pylab as plt import matplotlib.patches as mpatches from IPython.display import HTML %matplotlib inline img = plt.imread("rueildigital.jpg") plt.axis('off') plt.imshow(img); Explanation: Hackathon de Nanterre 17 octobre 2015 Coder la ville... ... en Python End of expla...
7,439
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Fully-Connected Neural Nets In the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since t...
Python Code: # As usual, a bit of setup import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplot...
7,440
Given the following text description, write Python code to implement the functionality described below step by step Description: If you don't care about the confidence interval of parameter Step1: If you want the confidence intervals
Python Code: from lmfit.models import GaussianModel # initialize the gaussian model gm = GaussianModel() # take a look at the parameter names print gm.param_names # I get RuntimeError since my numpy version is a little old # guess parameters par_guess = gm.guess(n,x=xpos) # fit data result = gm.fit(n, par_guess, x=xpos...
7,441
Given the following text description, write Python code to implement the functionality described below step by step Description: The Step1: Here for convenience we read the evoked dataset from a file. Step2: Notice that the reader function returned a list of evoked instances. This is because you can store multiple ...
Python Code: import os.path as op import mne Explanation: The :class:Evoked &lt;mne.Evoked&gt; data structure: evoked/averaged data The :class:Evoked &lt;mne.Evoked&gt; data structure is mainly used for storing averaged data over trials. In MNE the evoked objects are usually created by averaging epochs data with :func:...
7,442
Given the following text description, write Python code to implement the functionality described below step by step Description: Label and feature engineering Learning objectives Step1: Create time-series features and determine label based on market movement Summary of base tables Step2: Label engineering Ultimately...
Python Code: PROJECT = !(gcloud config get-value core/project) PROJECT = PROJECT[0] import pandas as pd from google.cloud import bigquery from IPython import get_ipython from IPython.core.magic import register_cell_magic bq = bigquery.Client(project=PROJECT) # Allow you to easily have Python variables in SQL query. @re...
7,443
Given the following text description, write Python code to implement the functionality described below step by step Description: Old version that was developed here (now probably out of sync with official version in PISA...) Step1: Testing out a container class but that
Python Code: print hash_obj([0, 1, 2]) bits = 64*2 n_elements = 200 np.log10(2*2**bits/(n_elements*(n_elements-1))) Explanation: Old version that was developed here (now probably out of sync with official version in PISA...): python def hash_obj(obj): hash_val, = struct.unpack('&lt;q', hashlib.md5( pick...
7,444
Given the following text description, write Python code to implement the functionality described below step by step Description: Galaxies that are missing from Simard+2011 Summary * A total of 44 galaxies are not in galfit sample * 31/44 are not in the SDSS catalog, so these would not have been targeted by Simard+2011...
Python Code: %run ~/Dropbox/pythonCode/LCSanalyzeblue.py t = s.galfitflag & s.lirflag & s.sizeflag & ~s.agnflag & s.sbflag galfitnogim = t & ~s.gim2dflag sum(galfitnogim) Explanation: Galaxies that are missing from Simard+2011 Summary * A total of 44 galaxies are not in galfit sample * 31/44 are not in the SDSS catalog...
7,445
Given the following text description, write Python code to implement the functionality described below step by step Description: 1.9 查找两字典的相同点 怎样在两字典中寻找相同点(相同的key or 相同的 value) Step1: 为寻找两字典的相同点 可通过简单的在两字典keys() or items() method 中Return 结果 进行set 操作 Step2: 以上操作亦可用于修改or过滤dict element <br> if you want 以现有dict 来构造一个...
Python Code: a = { 'x':1, 'y':2, 'z':3 } b = { 'w':10, 'x':11, 'y':2 } # In a ::: x : 1 ,y : 2 # In b ::: x : 11,y : 2 Explanation: 1.9 查找两字典的相同点 怎样在两字典中寻找相同点(相同的key or 相同的 value) End of explanation # Find keys in common kc = a.keys() & b.keys() print('a 和 b 共有的键',kc) # Find keys in a that are n...
7,446
Given the following text description, write Python code to implement the functionality described below step by step Description: Purchase frequency In this notebook we create a table grouping transaction information by customers’ purchase frequency. This is done with functions from the pandas librairie such as df.grou...
Python Code: import pandas as pd import contiamo Explanation: Purchase frequency In this notebook we create a table grouping transaction information by customers’ purchase frequency. This is done with functions from the pandas librairie such as df.groupby() and df.cut(). End of explanation transactions = %contiamo quer...
7,447
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: CMU Mocap Database Motion capture data from the CMU motion capture data base (CMU Motion Capture Lab, 2003). You can download any subject and motion from the data set....
Python Code: import matplotlib.pyplot as plt plt.style.use("seaborn-pastel") %%capture %pip install --upgrade git+https://github.com/lawrennd/ods %pip install --upgrade git+https://github.com/SheffieldML/GPy.git import GPy, pods import numpy as np np.random.seed(42) Explanation: <a href="https://colab.research.google.c...
7,448
Given the following text description, write Python code to implement the functionality described below step by step Description: Cookbook Step1: Import Python libraries The call to %matplotlib inline here enables support for plotting directly inside the notebook. Step2: Quick guide (tldr;) The following cell shows t...
Python Code: ## conda install ipyrad -c ipyrad ## conda install -c conda-forge scikit-allel Explanation: Cookbook: PCA analyses As part of the ipyrad.analysis toolkit we've created convenience functions for easily performing exploratory principal component analysis (PCA) on your data. PCA is a very standard dimension-r...
7,449
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 7 - Refining a triangulation We have seen how the standard meshes can be uniformly refined to finer resolution. The routines used for this task are available to the stripy user for n...
Python Code: import stripy as stripy import numpy as np Explanation: Example 7 - Refining a triangulation We have seen how the standard meshes can be uniformly refined to finer resolution. The routines used for this task are available to the stripy user for non-uniform refinement as well. Notebook contents Uniform mes...
7,450
Given the following text description, write Python code to implement the functionality described below step by step Description: Rulefit Boston Housing Demo Rulefit algorithm aims for a compromise between interpretability and complexity of the resulting model. While simpler ML algorithms usually miss interaction effec...
Python Code: import h2o from h2o.estimators.random_forest import H2ORandomForestEstimator h2o.init() train = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/gbm_test/BostonHousing.csv") x = train.columns y = "medv" x.remove(y) x.remove("b") train['medv'].hist() train.head() Explanation: Rulefit...
7,451
Given the following text description, write Python code to implement the functionality described below step by step Description: 3 Step1: Answer Step2: 4 Step3: Answer Step4: 5 Step5: 6 Step6: 7 Step7: 10
Python Code: import math Explanation: 3: The math module Instructions Use the sqrt() function within the math module to assign the square root of 16.0 to a. Use the ceil() function within the math module to assign the ceiling of 111.3 to b. Use the floor() function within the math module to assign the floor of 89.9 to ...
7,452
Given the following text description, write Python code to implement the functionality described. Description: You'll be given a string of words, and your task is to count the number of boredoms. A boredom is a sentence that starts with the word "I". Sentences are delimited by '.', '?' or '!'. For e...
Python Code: def is_bored(S): import re sentences = re.split(r'[.?!]\s*', S) return sum(sentence[0:2] == 'I ' for sentence in sentences)
7,453
Given the following text description, write Python code to implement the functionality described below step by step Description: Text Using Markdown If you double click on this cell, you will see the text change so that all of the formatting is removed. This allows you to edit this block of text. This block of text is...
Python Code: # Hit shift + enter or use the run button to run this cell and see the results print('hello world') # The last line of every code cell will be displayed by default, # even if you don't print it. Run this cell to see how this works. 2 + 2 # The result of this line will not be displayed 3 + 3 # The result o...
7,454
Given the following text description, write Python code to implement the functionality described below step by step Description: External data Helper functions to download the fastai datasets To download any of the datasets or pretrained weights, simply run untar_data by passing any dataset name mentioned above like s...
Python Code: #|export @lru_cache(maxsize=None) def fastai_cfg() -> Config: # Config that contains default download paths for `data`, `model`, `storage` and `archive` "`Config` object for fastai's `config.ini`" return Config(Path(os.getenv('FASTAI_HOME', '~/.fastai')), 'config.ini', create=dict( data = '...
7,455
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align = 'center'> Neural Networks Demystified </h1> <h2 align = 'center'> Part 7 Step1: Last time, we trained our Neural Network, and it made suspiciously good predictions of your test ...
Python Code: from IPython.display import YouTubeVideo YouTubeVideo('S4ZUwgesjS8') Explanation: <h1 align = 'center'> Neural Networks Demystified </h1> <h2 align = 'center'> Part 7: Overfitting, Testing, and Regularization </h2> <h4 align = 'center' > @stephencwelch </h4> End of explanation %pylab inline from partSix im...
7,456
Given the following text description, write Python code to implement the functionality described below step by step Description: Does RFT FDR control the nominal FDR value? In this notebook, I made a small simulation, to verify that the RFT peak FDR procedure does not control the overall FDR but the conditional FDR (f...
Python Code: % matplotlib inline import os import numpy as np import nibabel as nib from nipy.labs.utils.simul_multisubject_fmri_dataset import surrogate_3d_dataset import nipy.algorithms.statistics.rft as rft from __future__ import print_function, division import math import matplotlib.pyplot as plt import palettable....
7,457
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Root Finding and Optimization GOAL Step3: Fixed Point Iteration How do we go about solving this? Could try to solve at least partially for $r$ Step4: Guess at $r_0$ and check to see...
Python Code: def total_value(P, m, r, n): Total value of portfolio given parameters Based on following formula: A = \frac{P}{(r / m)} \left[ \left(1 + \frac{r}{m} \right)^{m \cdot n} - 1 \right ] :Input: - *P* (float) - Payment amount per compounding period - *m...
7,458
Given the following text description, write Python code to implement the functionality described below step by step Description: Use Case 3 Step1: Open MODIS/Aqua files with chlorophyll in the North Sea and fetch data Step2: Plot chlorophyll-a maps in swath projection Step3: Colocate data. Reproject both images ont...
Python Code: # download sample files !wget -P data -nc ftp://ftp.nersc.no/nansat/test_data/obpg_l2/A2015121113500.L2_LAC.NorthNorwegianSeas.hdf !wget -P data -nc ftp://ftp.nersc.no/nansat/test_data/obpg_l2/A2015122122000.L2_LAC.NorthNorwegianSeas.hdf import numpy as np import matplotlib.pyplot as plt from IPython.displ...
7,459
Given the following text description, write Python code to implement the functionality described below step by step Description: Cloud Data Center Step1: Data Center IP Traffic
Python Code: import matplotlib.pyplot as plt import csv a = [] b = [] with open('data/dc_hyperscale.csv','r') as csvfile: plots = csv.reader(csvfile, delimiter=';') for row in plots: a.append(int(row[0])) b.append(int(row[1])) plt.bar(a,b, label='Hyperscale Data Centers') plt.xlabel('A...
7,460
Given the following text description, write Python code to implement the functionality described below step by step Description: Hybrid integrations with MERCURIUS REBOUND comes with several integrators, each of which has its own advantages and disadvantages. MERCURIUS is a hybrid integrastor that is very similar to t...
Python Code: import math import rebound, rebound.data %matplotlib inline sim = rebound.Simulation() rebound.data.add_outer_solar_system(sim) # add some particles for testing for i in range(1,sim.N): sim.particles[i].m *= 50. sim.integrator = "WHFast" # This will end badly! sim.dt = sim.particles[1].P * 0.002 # Time...
7,461
Given the following text description, write Python code to implement the functionality described below step by step Description: Traverse a Square - Part 1 - Simply Does It In this notebook and the next, you will explore various strategies for programming a robot to traverse a regular two dimensional shape, such as a ...
Python Code: %run 'Set-up.ipynb' %run 'Loading scenes.ipynb' %run 'vrep_models/PioneerP3DX.ipynb' Explanation: Traverse a Square - Part 1 - Simply Does It In this notebook and the next, you will explore various strategies for programming a robot to traverse a regular two dimensional shape, such as a square. These strat...
7,462
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Here is my code:
Problem: import numpy as np import pandas as pd from sklearn.feature_extraction.text import CountVectorizer words = load_data() count = CountVectorizer(lowercase=False, token_pattern='[a-zA-Z0-9$&+:;=@#|<>^*()%-]+') vocabulary = count.fit_transform([words]) feature_names = count.get_feature_names_out()
7,463
Given the following text description, write Python code to implement the functionality described below step by step Description: Importing data Getting data from kaggle first Step1: Baseline model Step2: Deep Forest By Hand Step3: This is not very handy, not at all. We already see a lot of code duplication, and on...
Python Code: import pkg_resources raw_data = pd.read_csv(pkg_resources.resource_stream('deepforest', 'data/train.csv')) clean_data = raw_data.drop(["Cabin", "Name", "PassengerId", "Ticket"], axis=1) clean_data = pd.get_dummies(clean_data).fillna(-1) train, test = train_test_split(clean_data) def split_x_y(dataframe, ta...
7,464
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Basic Stellar Photometry Measuring Flux in 1D Version 0.1 In this notebook we will introduce some basic concepts related to measuring the flux of a point source. As this is a...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib notebook Explanation: Introduction to Basic Stellar Photometry Measuring Flux in 1D Version 0.1 In this notebook we will introduce some basic concepts related to measuring the flux of a point source. As this is an introduction, several challeng...
7,465
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Compare CoNLL files against themselves We're now using the official CoNLL scorer to compare each MAZ176 coreference annotated document against itself. All comparisons should result in...
Python Code: import sys def has_valid_annotation(mmax_file, scorer_path, metric, verbose=False): Parameters ---------- metric : str muc, bcub, ceafm, ceafe, blanc verbose : bool or str True, False or 'very' scorer = sh.Command(scorer_path) mdg = MMAXDocumentGraph(mmax_f...
7,466
Given the following text description, write Python code to implement the functionality described below step by step Description: Exponential Weighted Moving Average (EWMA) Pro jednoduchost výpočtu patří exponenciální vážený klouzavý průměr (EWMA) k hojně využívaným nástrojům pro analýzu dat, machine learning, atd. Nar...
Python Code: import datetime start = datetime.datetime(2018, 1, 1) end = datetime.datetime(2019, 1, 1) spy_data = pdr.data.DataReader('SPY', 'yahoo', start, end) spy_data.drop(['High', 'Low', 'Open', 'Close', 'Volume'], axis=1, inplace=True) # these columns are not needed spy_data.head(5) Explanation: Exponential Weigh...
7,467
Given the following text description, write Python code to implement the functionality described below step by step Description: Doppler shifts Exploring doppler shift on precision and quality. Specifically in the K-band Step1: Applying doppler shifts of $+/- 200$ km/s only produce changes of $< \pm0.1$ m/s for condi...
Python Code: import matplotlib.pyplot as plt import numpy as np from tqdm import tqdm import PyAstronomy.pyasl as pyasl from astropy import constants as const from eniric import config import eniric # config.cache["location"] = None # Disable caching for these tests config.cache["location"] = ".joblib" # Enable cachi...
7,468
Given the following text description, write Python code to implement the functionality described below step by step Description: Initialize set up Amplifyer is fet -15V and = +85V Calibrate strain gauge to zero with the kinesis software Pull fiber back Set nicard to -3.75 Step1: Move close with fiber
Python Code: mynicard._write_cavity_ao(np.array([0.0],dtype=float), start=True) Explanation: Initialize set up Amplifyer is fet -15V and = +85V Calibrate strain gauge to zero with the kinesis software Pull fiber back Set nicard to -3.75 End of explanation first_resonances = cavitylogic.get_nth_full_sweep(sweep_number=...
7,469
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Polyglot has polarity lexicons for 136 languages. The scale of the words' polarity consisted of three degrees Step1: Polarity To inquiry the polarity of a word, we can just call i...
Python Code: from polyglot.downloader import downloader print(downloader.supported_languages_table("sentiment2", 3)) from polyglot.text import Text Explanation: Sentiment Polyglot has polarity lexicons for 136 languages. The scale of the words' polarity consisted of three degrees: +1 for positive words, and -1 for nega...
7,470
Given the following text description, write Python code to implement the functionality described below step by step Description: Для удобного получения твитов пользователей будем использовать библиотеку tweepy. Step1: Вводим данные разработчика. Step2: Получаем доступ к Twitter API. Step3: Теперь считаем твиты кажд...
Python Code: import warnings warnings.filterwarnings('ignore') import tweepy Explanation: Для удобного получения твитов пользователей будем использовать библиотеку tweepy. End of explanation access_token = "" access_token_secret = "" consumer_key = "" consumer_secret = "" # Чтобы получить данные разработчика, нужно зар...
7,471
Given the following text description, write Python code to implement the functionality described below step by step Description: Parcel loading Given a set of parcels (assumes GDB format) from the parcel provider, this notebook will load individual features (from the parcel provider -- currently each feature-type is a...
Python Code: import psycopg2 as pg import pandas as pd import os conn = pg.connect('service=parcels') conn_str = os.environ.get('PARCELS_CONNECTION') Explanation: Parcel loading Given a set of parcels (assumes GDB format) from the parcel provider, this notebook will load individual features (from the parcel provider --...
7,472
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple Rotations Author Step1: Use the Q8 class that places these 4 numbers in 8 slots like so Step3: If you are unfamiliar with this notation, the $I^2 = -1,\, i^3=-i,\, j^3=-j,\, k^3=-k$...
Python Code: %%capture from Q_tool_devo import Q8; U=Q8([1,2,-3,4]) V=Q8([4,-2,3,1]) R=Q8([5,6,7,-8]) Explanation: Simple Rotations Author: Doug &#115;&#119;&#101;&#101;&#116;&#115;&#101;&#114;&#64;&#97;&#108;&#117;&#109;&#46;&#109;&#105;&#116;&#46;&#101;&#100;&#117; A deep leason from special relativity is that all me...
7,473
Given the following text description, write Python code to implement the functionality described below step by step Description: Spectral clustering for image segmentation In this example, an image with connected circles is generated and spectral clustering is used to separate the circles. In these settings, the Step...
Python Code: print(__doc__) # Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org> # Gael Varoquaux <gael.varoquaux@normalesup.org> # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.feature_extraction import image from sklearn.cluster import spectral_clust...
7,474
Given the following text description, write Python code to implement the functionality described below step by step Description: SPINSpy Tutorial (2D) Step1: If we want to use our shiny python scripts, we'll need to import them too. Step2: If we want a quick man-page style summary, we can call help(spy). We can also...
Python Code: %matplotlib inline # Tells the system to plot in-line, only necessary for iPython notebooks, # not regular command-line python import numpy as np import os import sys import matplotlib.pyplot as plt import time # Now that we have our packages, we need data. The file 'make_2d_data.py' will # generate a sam...
7,475
Given the following text description, write Python code to implement the functionality described below step by step Description: Beaming and Boosting Due to concerns about accuracy, support for Beaming & Boosting has been disabled in the 2.2 release of PHOEBE. It may come as surprise that support for Doppler boosting ...
Python Code: import phoebe import numpy as np import matplotlib.pyplot as plt from astropy.io import fits Explanation: Beaming and Boosting Due to concerns about accuracy, support for Beaming & Boosting has been disabled in the 2.2 release of PHOEBE. It may come as surprise that support for Doppler boosting has been dr...
7,476
Given the following text description, write Python code to implement the functionality described below step by step Description: DBSCAN (Density-Based Spatial Clustering of Applications with Noise) Find core samples of high density and expand clusters from them. The minimum number of samples in a neighborhood for a po...
Python Code: import pandas as pd df1=pd.read_csv('team_out_1.csv') df2=pd.read_csv('team_out_a2.csv') df=df1.append(df2) df.dropna(inplace=True) df.reset_index(inplace=True,drop=True) df=df[df.Total_Expenses>0] df=df[df.Program_Exp<=1] df Explanation: DBSCAN (Density-Based Spatial Clustering of Applications with Noise)...
7,477
Given the following text description, write Python code to implement the functionality described below step by step Description: Non-parametric 1 sample cluster statistic on single trial power This script shows how to estimate significant clusters in time-frequency power estimates. It uses a non-parametric statistical...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD-3-Clause import numpy as np import matplotlib.pyplot as plt import mne from mne.time_frequency import tfr_morlet from mne.stats import permutation_cluster_1samp_test from mne.datasets import sample print(__doc__) Explanation: Non-...
7,478
Given the following text description, write Python code to implement the functionality described below step by step Description: Quickstart Step1: DataFrame Creation A PySpark DataFrame can be created via pyspark.sql.SparkSession.createDataFrame typically by passing a list of lists, tuples, dictionaries and pyspark.s...
Python Code: from pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() Explanation: Quickstart: DataFrame This is a short introduction and quickstart for the PySpark DataFrame API. PySpark DataFrames are lazily evaluated. They are implemented on top of RDDs. When Spark transforms data, it does not...
7,479
Given the following text description, write Python code to implement the functionality described below step by step Description: Importing data from LOBO-Buoy server Objectives Step1: NOTE Step2: Exploring the data Lets see what is in "data"... Step3: Now lets disect "data" a bit... lets find the title (or "keys") ...
Python Code: # URL quering the LOBO server for data (in this case, temperature data) URL = 'http://lobo.satlantic.com/cgi-data/nph-data.cgi?min_date=20090610&max_date=20090706&y=temperature' Explanation: Importing data from LOBO-Buoy server Objectives: * Download data from LOBO server * (if needed) transform data into ...
7,480
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to on road lane detection program Programm has image processing pipeline that support both RGB images and BGR video input. RGB image processing consists of next steps Step1: Next cl...
Python Code: import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 import pandas import os def getPathFor(file_path): current_directory = %pwd path = os.path.join(current_directory, file_path) print("About to open file: {}\n".format(path)) return path Explan...
7,481
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: write a program to train a machine learning model using support vector machines algorithm and print the predictions
Python Code:: from sklearn import svm model = svm.SVC() model.fit(X_train, y_train) pred = model.predict(X_test) print(pred)
7,482
Given the following text description, write Python code to implement the functionality described below step by step Description: Indico.io sentiment score analysis Step1: Compute average sentiment score per week make it 0.5 if no news that week. Step2: read bitcoin price data Step3: add news volume data Step4: Alc...
Python Code: score_data = pd.read_csv("../data/indico_nyt_bitcoin.csv", index_col='time', parse_dates=[0], date_parser=lambda x: datetime.datetime.strptime(x, time_format)) score_data.head() Explanation: Indico.io sentiment score analysis End of explanation weekly_score = score_data.resample('w', how...
7,483
Given the following text description, write Python code to implement the functionality described below step by step Description: Twitter Bots A workshop by Dillon Niederhut and Juan Shishido. Interacting with <a href="https Step1: What you see Step2: What you get Step3: You have access to more than just the text. J...
Python Code: import json with open('data/first_tweet.json','r') as f: a_tweet = json.loads(f.read()) Explanation: Twitter Bots A workshop by Dillon Niederhut and Juan Shishido. Interacting with <a href="https://twitter.com/tob_pohskrow" target="_blank">tob_pohskrow</a>. Bots The W's: What, why, and probably even ho...
7,484
Given the following text description, write Python code to implement the functionality described below step by step Description: Showing some of the dstoolbox features The purpose of this notebook is to demonstrate some of the features of dstoolbox using a toy dataset that contains different categories of features. Im...
Python Code: from functools import partial import operator import random import numpy as np import pandas as pd from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_squared_error from sklearn.preprocessing import FunctionTransformer from sklearn.preprocessing import PolynomialFeatures fro...
7,485
Given the following text description, write Python code to implement the functionality described below step by step Description: This tutorial will show you how to find the suitable habitat range for Bristlecone pine using GeoPySpark This tutorial will focus on GeoPySpark functionality, but you can find more resources...
Python Code: import geopyspark as gps from pyspark import SparkContext Explanation: This tutorial will show you how to find the suitable habitat range for Bristlecone pine using GeoPySpark This tutorial will focus on GeoPySpark functionality, but you can find more resources and tutorials about GeoNotebooks here. Suitab...
7,486
Given the following text description, write Python code to implement the functionality described below step by step Description: Continuous training with TFX and Google Cloud AI Platform Learning Objectives Use the TFX CLI to build a TFX pipeline. Deploy a TFX pipeline version without tuning to a hosted AI Platform Pi...
Python Code: import yaml # Set `PATH` to include the directory containing TFX CLI and skaffold. PATH=%env PATH %env PATH=/home/jupyter/.local/bin:{PATH} Explanation: Continuous training with TFX and Google Cloud AI Platform Learning Objectives Use the TFX CLI to build a TFX pipeline. Deploy a TFX pipeline version witho...
7,487
Given the following text description, write Python code to implement the functionality described below step by step Description: Wasserstein Discriminant Analysis This example illustrate the use of WDA as proposed in [11]. [11] Flamary, R., Cuturi, M., Courty, N., & Rakotomamonjy, A. (2016). Wasserstein Discriminant A...
Python Code: # Author: Remi Flamary <remi.flamary@unice.fr> # # License: MIT License import numpy as np import matplotlib.pylab as pl from ot.dr import wda, fda Explanation: Wasserstein Discriminant Analysis This example illustrate the use of WDA as proposed in [11]. [11] Flamary, R., Cuturi, M., Courty, N., & Rakotoma...
7,488
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing different movie rating systems In this notebook, I use simple statistical metrics (mean, median, standard deviation and some quantiles) to analyze different movie rating systems. I...
Python Code: import pandas as pd import numpy as np import scipy.stats as sps import matplotlib.pyplot as plt %matplotlib inline movies = pd.read_csv('fandango_score_comparison.csv') movies.describe() movies.info() # Check the movie data structure movies.head() Explanation: Comparing different movie rating systems In t...
7,489
Given the following text description, write Python code to implement the functionality described below step by step Description: Drawdown caused by groundwater extraction Developed by R.A. Collenteur & M. Bakker In this example notebook it is shown how to simulate the effect of a pumping well on the groundwater levels...
Python Code: import pandas as pd import pastas as ps import matplotlib.pyplot as plt %matplotlib inline Explanation: Drawdown caused by groundwater extraction Developed by R.A. Collenteur & M. Bakker In this example notebook it is shown how to simulate the effect of a pumping well on the groundwater levels. We will fir...
7,490
Given the following text description, write Python code to implement the functionality described below step by step Description: 2A.ml - Clustering Ce notebook utilise les données des vélos de Chicago Divvy Data. Il s'inspire du challenge créée pour découvrir les habitudes des habitantes de la ville City Bike. L'idée ...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() %matplotlib inline Explanation: 2A.ml - Clustering Ce notebook utilise les données des vélos de Chicago Divvy Data. Il s'inspire du challenge créée pour découvrir les habitudes des habitantes de la ville City Bike. L'idée est d'explorer plusie...
7,491
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating MNE objects from data arrays In this simple example, the creation of MNE objects from numpy arrays is demonstrated. In the last example case, a NEO file format is used as a source f...
Python Code: # Author: Jaakko Leppakangas <jaeilepp@student.jyu.fi> # # License: BSD (3-clause) import numpy as np import neo import mne print(__doc__) Explanation: Creating MNE objects from data arrays In this simple example, the creation of MNE objects from numpy arrays is demonstrated. In the last example case, a NE...
7,492
Given the following text description, write Python code to implement the functionality described below step by step Description: View in Colaboratory Classifying Handwritting using Convolutional Neural Networks In this example we are going to use PyTorch, a commonly used Deep Learning Framework to classify Handwritten...
Python Code: !pip3 install http://download.pytorch.org/whl/cu80/torch-0.3.0.post4-cp36-cp36m-linux_x86_64.whl !pip3 install torchvision !pip3 install numpy !pip3 install matplotlib !pip3 install seaborn Explanation: View in Colaboratory Classifying Handwritting using Convolutional Neural Networks In this example we are...
7,493
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 1 - Overfitting Sample Data Here, we will use a simple model to overfit a set of randomly generated data points. First, we import Numpy to hold the data, and we import Learny McLearn...
Python Code: import numpy as np import LearnyMcLearnface as lml Explanation: Example 1 - Overfitting Sample Data Here, we will use a simple model to overfit a set of randomly generated data points. First, we import Numpy to hold the data, and we import Learny McLearnface. End of explanation test_data = np.random.randn(...
7,494
Given the following text description, write Python code to implement the functionality described. Description: Divide given numeric string into at most two increasing subsequences which form an increasing string upon concatenation Function to check for valid subsequences ; Stores which element belongs to which subseque...
Python Code: def findSubsequence(str ) : n = len(str ) res =['0' for i in range(n ) ] for pos in range(10 ) : lst1 = '0' flag = 1 lst2 = chr(pos + 48 ) for i in range(n ) : if(lst2 <= str[i ] ) : res[i ] = '2' lst2 = str[i ]  elif(lst1 <= str[i ] ) : res[i ] = '1' lst1 = str[i ]  else...
7,495
Given the following text description, write Python code to implement the functionality described below step by step Description: Assignment 6 Step1: Importing data Unfortunately, the USGS does not have any data from this year available from the Feather River or its tributaries. (For this river, it only makes data ava...
Python Code: # Import numerical tools import numpy as np #Import pandas for reading in and managing data import pandas as pd # Import pyplot for plotting import matplotlib.pyplot as plt #Import seaborn (useful for plotting) import seaborn as sns # Magic function to make matplotlib inline; other style specs must come AF...
7,496
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Bracket Indexing and Selection The simplest way to pick one or some elements of an array looks very similar to python lists Step2: Broadcasting Numpy arrays differ fro...
Python Code: import numpy as np #Creating sample array arr = np.arange(0,11) #Show arr Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> NumPy Indexing and Selection In this lecture we will discuss how to select elements or groups of elements from an array. End of explanation...
7,497
Given the following text description, write Python code to implement the functionality described below step by step Description: Corpora and Vector Spaces Demonstrates transforming text into a vector space representation. Also introduces corpus streaming and persistence to disk in various formats. Step1: First, let’s...
Python Code: import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) Explanation: Corpora and Vector Spaces Demonstrates transforming text into a vector space representation. Also introduces corpus streaming and persistence to disk in various formats. End of explanatio...
7,498
Given the following text description, write Python code to implement the functionality described below step by step Description: Risk Sharing and Moral Hazard Step1: Risk-sharing review A simple employment contract Employer hires worker to perform a task that has a stochastic outcome. Project can either Step2: Mora...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from ipywidgets import interact, fixed Explanation: Risk Sharing and Moral Hazard End of explanation alpha = 0.25 def u(c, alpha=alpha): return (1/alpha)*c**alpha def E(x,p): return p*x[1] + (1-p)*x[0] def EU(c, p): return p*...
7,499
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TensorFlow Authors. Step1: TFX Python function component tutorial Note Step2: Upgrade Pip To avoid upgrading Pip in a system when running locally, check to make sure tha...
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...