Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
1,200
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright (c) 2015, 2016 Sebastian Raschka https Step1: The use of watermark is optional. You can install this IPython extension via "pip install watermark". For more information, please se...
Python Code: %load_ext watermark %watermark -a 'Sebastian Raschka' -u -d -v -p numpy,pandas,matplotlib,sklearn,nltk Explanation: Copyright (c) 2015, 2016 Sebastian Raschka https://github.com/rasbt/python-machine-learning-book MIT License Python Machine Learning - Code Examples Chapter 8 - Applying Machine Learning To S...
1,201
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression with scikit-learn and statmodels This notebook demonstrates how to conduct a valid regression analysis using a combination of Sklearn and statmodels libraries. While sklearn is po...
Python Code: import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns Explanation: Regression with scikit-learn and statmodels This notebook demonstrates how to conduct a valid regression analysis using a combination of Sklearn and statmodels libraries. While sklearn is popular and p...
1,202
Given the following text description, write Python code to implement the functionality described below step by step Description: DATASCI W261 Step1: Data Visualiazation Step2: MrJob class code The solution of linear model $$ \textbf{Y} = \textbf{X}\theta $$ is Step3: Driver Step4: Gradient descent - doesn't work
Python Code: %matplotlib inline import numpy as np import pylab size = 1000 x = np.random.uniform(-40, 40, size) y = x * 1.0 - 4 + np.random.normal(0,5,size) data = zip(range(size),y,x) #data = np.concatenate((y, x), axis=1) np.savetxt('LinearRegression.csv',data,'%i,%f,%f') data[:10] Explanation: DATASCI W261: Machin...
1,203
Given the following text description, write Python code to implement the functionality described below step by step Description: Run from bootstrap paths Now we will use the initial trajectories we obtained from bootstrapping to run an MSTIS simulation. This will show both how objects can be regenerated from storage a...
Python Code: %matplotlib inline import openpathsampling as paths import numpy as np import math # the openpathsampling OpenMM engine import openpathsampling.engines.openmm as eng Explanation: Run from bootstrap paths Now we will use the initial trajectories we obtained from bootstrapping to run an MSTIS simulation. Thi...
1,204
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This notebook demonstrates how to perform diffusivity and ionic conductivity analyses starting from a series of VASP AIMD simulations using Python Materials Genomics (pymatgen) ...
Python Code: from IPython.display import Image %matplotlib inline import matplotlib.pyplot as plt import json import collections from pymatgen.core import Structure from pymatgen.analysis.diffusion_analyzer import DiffusionAnalyzer, \ get_arrhenius_plot, get_extrapolated_conductivity from pymatgen.analysis.diffusio...
1,205
Given the following text description, write Python code to implement the functionality described below step by step Description: The Lasso Modified from the github repo Step1: Hitters dataset Let's load the dataset from the previous lab. Step2: Exercise Compare the previous methods to the Lasso on this dataset. Tun...
Python Code: # %load ../standard_import.txt import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import scale from sklearn.model_selection import LeaveOneOut from sklearn.linear_model import LinearRegression, lars_path, Lasso, LassoCV %matplotlib inline n=100 p=1000 X = np....
1,206
Given the following text description, write Python code to implement the functionality described below step by step Description: Keras Backend In this notebook we will be using the Keras backend module, which provides an abstraction over both Theano and Tensorflow. Let's try to re-implement the Logistic Regression Mod...
Python Code: import keras.backend as K import numpy as np import matplotlib.pyplot as plt %matplotlib inline from kaggle_data import load_data, preprocess_data, preprocess_labels X_train, labels = load_data('../data/kaggle_ottogroup/train.csv', train=True) X_train, scaler = preprocess_data(X_train) Y_train, encoder = p...
1,207
Given the following text description, write Python code to implement the functionality described below step by step Description: Feedback or issues? For any feedback or questions, please open an issue. Vertex SDK for Python Step1: Enter your project and GCS bucket Enter your Project Id in the cell below. Then run the...
Python Code: !pip3 uninstall -y google-cloud-aiplatform !pip3 install --upgrade google-cloud-kms !pip3 install google-cloud-aiplatform import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) Explanation: Feedback or issues? For any feedback or questions, please open an issue. Vertex SDK for Pyt...
1,208
Given the following text description, write Python code to implement the functionality described below step by step Description: User guide and example for the Landlab SPACE component This notebook provides a brief introduction and user's guide for the Stream Power And Alluvial Conservation Equation (SPACE) component ...
Python Code: ## Import Numpy and Matplotlib packages import numpy as np import matplotlib.pyplot as plt # For plotting results; optional ## Import Landlab components # Pit filling; optional from landlab.components import DepressionFinderAndRouter # Flow routing from landlab.components import FlowAccumulator # SPACE mo...
1,209
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Threaded Serial Port reader</h1> <hr style="border Step1: <span> We first create the queue where we want the serial port thread will be pushing the readings. </span> Step2: <span> It i...
Python Code: import sys #sys.path.insert(0, '/home/asanso/workspace/att-spyder/att/src/python/') sys.path.insert(0, 'i:/dev/workspaces/python/att-workspace/att/src/python/') Explanation: <h1>Threaded Serial Port reader</h1> <hr style="border: 1px solid #000;"> <span> <h2>Serial Port reader in an execution thread.<br> P...
1,210
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Naive-Bayes" data-toc-modified-id="Naive-Bayes-1"><span class="toc-item-num"...
Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', '..', 'notebook_format')) from formats import load_style load_style(plot_style = False) os.chdir(path) # 1. magic for inline plot # 2. magic to...
1,211
Given the following text description, write Python code to implement the functionality described below step by step Description: Constraints 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: What are Cons...
Python Code: #!pip install -I "phoebe>=2.3,<2.4" import phoebe from phoebe import u # units import numpy as np import matplotlib.pyplot as plt logger = phoebe.logger() b = phoebe.default_binary() Explanation: Constraints Setup Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line...
1,212
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cnrm-cerfacs', 'cnrm-cm6-1-hr', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: CNRM-CERFACS Source ID: CNRM-CM6-1-HR Topic: Ocean Sub-Topics: Ti...
1,213
Given the following text description, write Python code to implement the functionality described below step by step Description: Dogs versus Cats Redux Competition on Kaggle Setup Step1: Prepare Data Note Step2: Create validation and test sets Step3: Checkpoint - Extract Features Step4: Checkpoint - Transfer Learn...
Python Code: #reset python environment %reset -f from pathlib import Path import numpy as np import tensorflow as tf import time import os current_dir = os.getcwd() home_directory = Path(os.getcwd()) dataset_directory = home_directory / "datasets" / "dogs-vs-cats-redux-kernels-edition" training_dataset_dir = dataset_di...
1,214
Given the following text description, write Python code to implement the functionality described below step by step Description: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 7</font> Download Step1: Missão 2 Step2: Teste da Solução
Python Code: # Versão da Linguagem Python from platform import python_version print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version()) Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 7</font> Download: http://github.com/dsacademybr End of explanation class...
1,215
Given the following text description, write Python code to implement the functionality described below step by step Description: Load data from http Step1: Load sales time-series data Step2: Following Aarshay Jain over at Analytics Vidhya (see here) we implement a Rolling Mean, Standard Deviation + Dickey-Fuller tes...
Python Code: # code written in py_3.0 import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import seaborn as sns Explanation: Load data from http://media.wiley.com/product_ancillary/6X/11186614/DOWNLOAD/ch08.zip, SwordForecasting.xlsx End of explanation # find path to...
1,216
Given the following text description, write Python code to implement the functionality described below step by step Description: <div style='background-image Step1: 1. Chebyshev derivative method Exercise Define a python function call "get_cheby_matrix(nx)" that initializes the Chebyshev derivative matrix $D_{ij}$, c...
Python Code: # This is a configuration step for the exercise. Please run it before calculating the derivative! import numpy as np import matplotlib.pyplot as plt from ricker import ricker # Show the plots in the Notebook. plt.switch_backend("nbagg") Explanation: <div style='background-image: url("../../share/images/he...
1,217
Given the following text description, write Python code to implement the functionality described below step by step Description: Fundamentals of text processing Content in this section is adapted from Ramalho (2015) and Lutz (2013). The most basic characters in a string are the ASCII characters. The string library in ...
Python Code: string.ascii_letters Explanation: Fundamentals of text processing Content in this section is adapted from Ramalho (2015) and Lutz (2013). The most basic characters in a string are the ASCII characters. The string library in Python, helpfully has these all listed out. End of explanation string.punctuation s...
1,218
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Step1: 1. Data We should now have all the data loaded, named as it was before. As a reminder, these are the NGC numbers of the galaxies in the data set Step2: 2. Independent fits ...
Python Code: exec(open('tbc.py').read()) # define TBC and TBC_above import dill # may need to change the load path TBC() # dill.load_session('../ignore/cepheids_one.db') exec(open('tbc.py').read()) # (re-)define TBC and TBC_above Explanation: Tutorial: The Cepheid Period-Luminosity Relation for Multiple Galaxies So far...
1,219
Given the following text description, write Python code to implement the functionality described below step by step Description: CS446/546 - Class Session 19 - Correlation network In this class session we are going to analyze gene expression data from a human bladder cancer cohort, using python. We will load a data ma...
Python Code: import pandas import scipy.stats import matplotlib import pylab import numpy import statsmodels.sandbox.stats.multicomp import igraph import math Explanation: CS446/546 - Class Session 19 - Correlation network In this class session we are going to analyze gene expression data from a human bladder cancer co...
1,220
Given the following text description, write Python code to implement the functionality described below step by step Description: Intro to TensorFlow What is a Computation Graph? Everything in TensorFlow comes down to building a computation graph. What is a computation graph? Its just a series of math operations that o...
Python Code: a = tf.placeholder(tf.float32) b = tf.placeholder(tf.float32) c = tf.add(a, b) d = tf.subtract(b, 1) e = tf.multiply(c, d) Explanation: Intro to TensorFlow What is a Computation Graph? Everything in TensorFlow comes down to building a computation graph. What is a computation graph? Its just a series of mat...
1,221
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic 1D non-linear regression with Keras TODO Step1: Make the dataset Step2: Make the regressor
Python Code: import tensorflow as tf tf.__version__ import keras keras.__version__ import h5py h5py.__version__ import pydot pydot.__version__ Explanation: Basic 1D non-linear regression with Keras TODO: see https://stackoverflow.com/questions/44998910/keras-model-to-fit-polynomial Install Keras https://keras.io/#insta...
1,222
Given the following text description, write Python code to implement the functionality described below step by step Description: Model Fitting One of the most common things in scientific computing is model fitting. Numerical Recipes devotes a number of chapters to this. scipy "curve_fit" astropy.modeling lmfit (emcee)...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import math Explanation: Model Fitting One of the most common things in scientific computing is model fitting. Numerical Recipes devotes a number of chapters to this. scipy "curve_fit" astropy.modeling lmfit (emcee) - Levenberg-Marquardt...
1,223
Given the following text description, write Python code to implement the functionality described below step by step Description: Define simple printing functions Step1: Constructing and allocating dictionaries The syntax for dictionaries is that {} indicates an empty dictionary Step2: There are multiple ways to cons...
Python Code: from __future__ import print_function import json def print_dict(dd): print(json.dumps(dd, indent=2)) Explanation: Define simple printing functions End of explanation d1 = dict() d2 = {} print_dict(d1) print_dict(d2) Explanation: Constructing and allocating dictionaries The syntax for dictionaries i...
1,224
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Convolutional GANs In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called a Deep Convolutional GAN, or DCGAN for short. The D...
Python Code: %matplotlib inline import pickle as pkl import matplotlib.pyplot as plt import numpy as np from scipy.io import loadmat import tensorflow as tf !mkdir data Explanation: Deep Convolutional GANs In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called...
1,225
Given the following text description, write Python code to implement the functionality described below step by step Description: Angular Correlations of Amorphous Materials This notebook demonstrates caclulating the angular correlation of diffraction patterns recorded from an amorphous (or crystalline) material. The d...
Python Code: data_path = "data/09/PdNiP_test.hspy" %matplotlib inline import pyxem as pxm import hyperspy.api as hs pxm.__version__ data = hs.load("./data/09/PdNiP_test.hspy") Explanation: Angular Correlations of Amorphous Materials This notebook demonstrates caclulating the angular correlation of diffraction patterns ...
1,226
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy numpy je paket (modul) za (efikasno) numeričko računanje u Pythonu. Naglasak je na efikasnom računanju s nizovima, vektorima i matricama, uključivo višedimenzionalne stukture. Napisan ...
Python Code: from numpy import * Explanation: Numpy numpy je paket (modul) za (efikasno) numeričko računanje u Pythonu. Naglasak je na efikasnom računanju s nizovima, vektorima i matricama, uključivo višedimenzionalne stukture. Napisan je u C-u i Fortanu te koristi BLAS biblioteku. End of explanation v = array([1,2,3,4...
1,227
Given the following text description, write Python code to implement the functionality described below step by step Description: Intuit craft demonstration Kyle Willett (Fellow, Insight Data Science) <font color='red'>Create a reasonable definition(s) of rule performance.</font> The definition of rule performance I us...
Python Code: %matplotlib inline from matplotlib import pyplot as plt from sqlalchemy import create_engine from sqlalchemy_utils import database_exists, create_database import psycopg2 import pandas as pd # Requires v 0.18.0 import numpy as np import seaborn as sns sns.set_style("whitegrid") dbname = 'risk' username = '...
1,228
Given the following text description, write Python code to implement the functionality described below step by step Description: A Simple Time Series Analysis Of The S&P 500 Index This notebook presents some basic ideas from time series analysis applied to stock market data, specificially the daily closing value of th...
Python Code: %matplotlib inline import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm import seaborn as sb sb.set_style('darkgrid') #path = os.getcwd() + '\data\stock_data.csv' path = "/data/stock_data.csv" stock_data = pd.read_csv(path) stock_data['Date'] = stock...
1,229
Given the following text description, write Python code to implement the functionality described below step by step Description: Aula 04 - pandas Objetivos Análise séries temporais Ler, manipular e plotar dados tabulares Guia de group-by e outras operações tabulares avançadas Ler um CSV e mostrar apenas o início da ta...
Python Code: import pandas as pd pd.read_csv('./data/dados_pirata.csv').head() Explanation: Aula 04 - pandas Objetivos Análise séries temporais Ler, manipular e plotar dados tabulares Guia de group-by e outras operações tabulares avançadas Ler um CSV e mostrar apenas o início da tabela. End of explanation df = pd.read_...
1,230
Given the following text description, write Python code to implement the functionality described below step by step Description: Display Exercise 1 Imports Put any needed imports needed to display rich output the following cell Step1: Basic rich display Find a Physics related image on the internet and display it in t...
Python Code: %matplotlib inline import numpy as np from matplotlib import pyplot as plt from IPython.html.widgets import interact, interactive, fixed from IPython.display import display from IPython.html import widgets from IPython.display import Image assert True # leave this to grade the import statements Explanation...
1,231
Given the following text description, write Python code to implement the functionality described below step by step Description: Index - Back - Next Widget Events Special events Step1: The Button is not used to represent a data type. Instead the button widget is used to handle mouse clicks. The on_click method of t...
Python Code: from __future__ import print_function Explanation: Index - Back - Next Widget Events Special events End of explanation from IPython.html import widgets print(widgets.Button.on_click.__doc__) Explanation: The Button is not used to represent a data type. Instead the button widget is used to handle mouse cli...
1,232
Given the following text description, write Python code to implement the functionality described below step by step Description: Info from the web This notebook goes with a blog post at Agile*. We're going to get some info from Wikipedia, and some financial prices from Yahoo Finance. We'll make good use of the request...
Python Code: url = "http://en.wikipedia.org/wiki/Jurassic" # Line 1 Explanation: Info from the web This notebook goes with a blog post at Agile*. We're going to get some info from Wikipedia, and some financial prices from Yahoo Finance. We'll make good use of the requests library, a really nicely designed Python libra...
1,233
Given the following text description, write Python code to implement the functionality described below step by step Description: Numerical Differentiation Step1: Applications Step5: Question Image you're planning a mission to the South Pole Aitken Basin and want to explore some permanently shadowed craters. What fac...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as pl Explanation: Numerical Differentiation End of explanation from IPython.display import Image Image(url='http://wordlesstech.com/wp-content/uploads/2011/11/New-Map-of-the-Moon-2.jpg') Explanation: Applications: Derivative difficult to compu...
1,234
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This notebook gives suggests how to solve the problem of non-linear compressible flow using the automatic differentiation library included in PorePy. The Ad functionality in Po...
Python Code: import numpy as np import scipy.sparse as sps import matplotlib.pyplot as plt # Porepy modules import porepy as pp Explanation: Introduction This notebook gives suggests how to solve the problem of non-linear compressible flow using the automatic differentiation library included in PorePy. The Ad function...
1,235
Given the following text description, write Python code to implement the functionality described below step by step Description: Dates in timeseries models Step1: Getting started Step2: Right now an annual date series must be datetimes at the end of the year. Step3: Using Pandas Make a pandas TimeSeries or DataFram...
Python Code: from __future__ import print_function import statsmodels.api as sm import numpy as np import pandas as pd Explanation: Dates in timeseries models End of explanation data = sm.datasets.sunspots.load() Explanation: Getting started End of explanation from datetime import datetime dates = sm.tsa.datetools.date...
1,236
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Hierarchical Linear Regression Author Step1: In the dataset, we were provided with a baseline chest CT scan and associated clinical information for a set of patients. A patient has...
Python Code: import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt train = pd.read_csv('https://gist.githubusercontent.com/ucals/' '2cf9d101992cb1b78c2cdd6e3bac6a4b/raw/' '43034c39052dcf97d4b894d2ec1bc3f90f3623d9/' 'osic_...
1,237
Given the following text description, write Python code to implement the functionality described below step by step Description: Executed Step1: Notebook arguments sigma (float) Step2: Fitting models Models used to fit the data. 1. Simple Exponential In this model, we define the model function as an exponential tran...
Python Code: sigma = 0.016 time_window = 30 time_step = 5 time_start = -900 time_stop = 900 decimation = 20 t0_vary = True true_params = dict( tau = 60, # time constant init_value = 0.3, # initial value (for t < t0) final_value = 0.8, # final value (for t -> +inf) t0 = 0) ...
1,238
Given the following text description, write Python code to implement the functionality described below step by step Description: Installating R on WinPython This procedure applys for Winpython (Version of December 2015 and after) 1 - Downloading R binary Step1: 2 - checking and Installing R binary in the right place...
Python Code: import os import sys import io # downloading R may takes a few minutes (80Mo) try: import urllib.request as urllib2 # Python 3 except: import urllib2 # Python 2 # specify R binary and (md5, sha1) hash # R-3.4.3: r_url = "https://cran.r-project.org/bin/windows/base/R-3.4.3-win.exe" hashes=("0ff087...
1,239
Given the following text description, write Python code to implement the functionality described below step by step Description: FloPy SpatialReference demo A short demonstration of functionality in the SpatialReference class for locating the model in a "real world" coordinate reference system Step1: description Spat...
Python Code: import sys sys.path.append('../..') import os import numpy as np import matplotlib.pyplot as plt import flopy from flopy.utils.reference import SpatialReference import flopy.utils.binaryfile as bf % matplotlib inline outpath = 'temp/' Explanation: FloPy SpatialReference demo A short demonstration of functi...
1,240
Given the following text description, write Python code to implement the functionality described below step by step Description: Artificial Intelligence Nanodegree Machine Translation Project In this notebook, sections that end with '(IMPLEMENTATION)' in the header indicate that the following blocks of code will requi...
Python Code: import helper # Load English data english_sentences = helper.load_data('data/small_vocab_en') # Load French data french_sentences = helper.load_data('data/small_vocab_fr') print('Dataset Loaded') Explanation: Artificial Intelligence Nanodegree Machine Translation Project In this notebook, sections that end...
1,241
Given the following text description, write Python code to implement the functionality described below step by step Description: Heat In this example the laser-excitation of a sample Structure is shown. It includes the actual absorption of the laser light as well as the transient temperature profile calculation. Setup...
Python Code: import udkm1Dsim as ud u = ud.u # import the pint unit registry from udkm1Dsim import scipy.constants as constants import numpy as np import matplotlib.pyplot as plt %matplotlib inline u.setup_matplotlib() # use matplotlib with pint units Explanation: Heat In this example the laser-excitation of a sample...
1,242
Given the following text description, write Python code to implement the functionality described below step by step Description: 7. Maximum Likelihood fit Step1: We use the pancake dataset, sampled at 300 random locations to produce a quite dense sample. Step2: First of, the variogram is calculated. We use Scott's r...
Python Code: import skgstat as skg from skgstat.util.likelihood import get_likelihood import numpy as np import matplotlib.pyplot as plt from scipy.optimize import minimize import warnings from time import time import matplotlib.pyplot as plt warnings.filterwarnings('ignore') Explanation: 7. Maximum Likelihood fit End ...
1,243
Given the following text description, write Python code to implement the functionality described below step by step Description: hypothesis Test the hypothesis about alcohol consumption and life expectancy Specifically, is how quantity litters alcohol consumption per year in a country is related a life expectancy, or ...
Python Code: ''' Categoriacal explanatory variable with five levels ''' alcohol_map = {1: '>=0 <5', 2: '>=5 <10', 3: '>=10 <15', 4: '>=15 <20', 5: '>=20 <25'} data2['alcohol'] = pd.cut(data1.alcohol,[0,5,10,15,20,25], labels=[i for i in alcohol_map.values()]) data2["alcohol"] = data2["alcohol...
1,244
Given the following text description, write Python code to implement the functionality described below step by step Description: ``` Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the Li...
Python Code: ![ -d nested-transformer ] || git clone --depth=1 https://github.com/google-research/nested-transformer !cd nested-transformer && git pull !pip install -qr nested-transformer/requirements.txt Explanation: ``` Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License,...
1,245
Given the following text description, write Python code to implement the functionality described below step by step Description: Store the data to HDF5 file for rapid analysis and calculation This tutorial discuss the analyses that can be performed using the dnaMD Python module included in the do_x3dna package. The tu...
Python Code: import os import numpy as np import matplotlib.pyplot as plt import dnaMD %matplotlib inline try: os.remove('cdna.h5') except: pass Explanation: Store the data to HDF5 file for rapid analysis and calculation This tutorial discuss the analyses that can be performed using the dnaMD Python module incl...
1,246
Given the following text description, write Python code to implement the functionality described below step by step Description: 레버리지와 아웃라이어 레버리지 (Leverage) 개별적인 데이터 표본이 회귀 분석 결과에 미치는 영향은 레버리지(leverage)분석을 통해 알 수 있다. 레버리지는 래의 target value $y$가 예측된(predicted) target $\hat{y}$에 미치는 영향을 나타낸 값이다. self-influence, self-sens...
Python Code: from sklearn.datasets import make_regression X0, y, coef = make_regression(n_samples=100, n_features=1, noise=20, coef=True, random_state=1) # add high-leverage points X0 = np.vstack([X0, np.array([[4],[3]])]) X = sm.add_constant(X0) y = np.hstack([y, [300, 150]]) plt.scatter(X0, y) plt.show() model = sm.O...
1,247
Given the following text description, write Python code to implement the functionality described below step by step Description: Check ensemble of OpenMM temperature replica exchange simulations Note Step1: Ensemble validation is particularly useful for validating enhanced sampling methods such as temperature replica...
Python Code: # enable plotting in notebook %matplotlib notebook Explanation: Check ensemble of OpenMM temperature replica exchange simulations Note: This notebook can be run locally by cloning the Github repository. The notebook is located in doc/examples/openmm_replica_exchange.ipynb. The input and output files of the...
1,248
Given the following text description, write Python code to implement the functionality described below step by step Description: Apply logistic regression to categorize whether a county had high mortality rate due to contamination 1. Import the necessary packages to read in the data, plot, and create a logistic regres...
Python Code: import pandas as pd %matplotlib inline import numpy as np from sklearn.linear_model import LogisticRegression Explanation: Apply logistic regression to categorize whether a county had high mortality rate due to contamination 1. Import the necessary packages to read in the data, plot, and create a logistic ...
1,249
Given the following text description, write Python code to implement the functionality described below step by step Description: This example is a Jupyter notebook. You can download it or run it interactively on mybinder.org. Linear regression Data The true parameters of the linear regression Step1: Generate data Ste...
Python Code: import numpy as np k = 2 # slope c = 5 # bias s = 2 # noise standard deviation # This cell content is hidden from Sphinx-generated documentation %matplotlib inline np.random.seed(42) Explanation: This example is a Jupyter notebook. You can download it or run it interactively on mybinder.org. Linear regress...
1,250
Given the following text description, write Python code to implement the functionality described below step by step Description: MySQL-python It is an interface to MySQL that Step1: WARNING Step2: It is recommend to interpolate sql using the DB API. It knows how to deal with strings, integers, booleans, None... Quer...
Python Code: # let's create a testing database # CREATE DATABASE IF NOT EXISTS mod_mysqldb DEFAULT CHARACTER SET 'UTF8' DEFAULT COLLATE 'UTF8_GENERAL_CI'; # GRANT ALL PRIVILEGES ON mod_mysqldb.* TO 'user'@'localhost' IDENTIFIED BY 'user'; # let's connect to our database import MySQLdb as mysql conn = mysql.connect('loc...
1,251
Given the following text description, write Python code to implement the functionality described below step by step Description: GPyTorch Regression With KeOps Introduction KeOps is a recently released software package for fast kernel operations that integrates wih PyTorch. We can use the ability of KeOps to perform e...
Python Code: import math import torch import gpytorch from matplotlib import pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 Explanation: GPyTorch Regression With KeOps Introduction KeOps is a recently released software package for fast kernel operations that integrates wih PyTorch. We can use the a...
1,252
Given the following text description, write Python code to implement the functionality described below step by step Description: Step3: Computing for Mathematics - 2020/2021 individual coursework Important Do not delete the cells containing Step7: b. $1/2$ Available marks Step11: c. $3/4$ Available marks Step15: d....
Python Code: import random def sample_experiment(): ### BEGIN SOLUTION Returns true if a random number is less than 0 return random.random() < 0 number_of_experiments = 1000 sum( sample_experiment() for repetition in range(number_of_experiments) ) / number_of_experiments ### END SOLUTION q1_a_...
1,253
Given the following text description, write Python code to implement the functionality described below step by step Description: Convert data to NILMTK format and load into NILMTK Step1: NILMTK uses an open file format based on the HDF5 binary file format to store both the power data and the metadata. The very first...
Python Code: !! pip install -U Pillow==6.1.0 Explanation: Convert data to NILMTK format and load into NILMTK End of explanation from nilmtk.dataset_converters import convert_redd convert_redd('../datasets/REDD/low_freq', '../datasets/REDD/low_freq.h5') Explanation: NILMTK uses an open file format based on the HDF5 bina...
1,254
Given the following text description, write Python code to implement the functionality described below step by step Description: Space Time Scan Using SatScan Start SaTScan and make a new session Under the "Input" tab Step1: Save to SatScan format Embarrasingly, we now seem to have surpassed SaTScan in terms of speed...
Python Code: %matplotlib inline from common import * #datadir = os.path.join("//media", "disk", "Data") datadir = os.path.join("..", "..", "..", "..", "..", "Data") south_side, points = load_data(datadir) grid = grid_for_south_side() import open_cp.stscan as stscan import open_cp.stscan2 as stscan2 trainer = stscan.STS...
1,255
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="images/charizard.png" alt="Expert" width="200"> Expert level Welcome to the expert level! For this level, I'm assuming you are somewhat familiar with the Python programming languag...
Python Code: %matplotlib notebook # Import the MNE-Python module, which contains all the data analysis routines we need import mne print('MNE-Python imported.') # Configure the graphics engine from matplotlib import pyplot as plt plt.rc('figure', max_open_warning=100) %matplotlib notebook from mayavi import mlab # May...
1,256
Given the following text description, write Python code to implement the functionality described below step by step Description: Large Scale Text Classification for Sentiment Analysis Scalability Issues The sklearn.feature_extraction.text.CountVectorizer and sklearn.feature_extraction.text.TfidfVectorizer classes suff...
Python Code: from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer(min_df=1) vectorizer.fit([ "The cat sat on the mat.", ]) vectorizer.vocabulary_ Explanation: Large Scale Text Classification for Sentiment Analysis Scalability Issues The sklearn.feature_extraction.text.CountVector...
1,257
Given the following text description, write Python code to implement the functionality described below step by step Description: TruePeakDetector use example This algorithm implements the “true-peak” level meter as descripted in the second annex of the ITU-R BS.1770-2[1] or the ITU-R BS.1770-4[2] (default). Note Step1...
Python Code: import essentia.standard as es import numpy as np import matplotlib matplotlib.use('nbagg') import matplotlib.pyplot as plt import ipywidgets as wg from IPython.display import Audio from essentia import array as esarr plt.rcParams["figure.figsize"] =(9, 5) Explanation: TruePeakDetector use example This al...
1,258
Given the following text description, write Python code to implement the functionality described below step by step Description: Unit 2 Step1: 1. What is the output of the commands above? Now each time we call a function that’s in a library, we use the syntax Step2: 2. In the command above, why did we use pd.read_ta...
Python Code: import pandas as pd import matplotlib.pyplot as plt Explanation: Unit 2: Programming Design Lesson 14: Packages and Data Analysis Notebook Authors (fill in your two names here) Facilitator: (fill in name) Spokesperson: (fill in name) Process Analyst: (fill in name) Quality Control: (fill in name) If ther...
1,259
Given the following text description, write Python code to implement the functionality described below step by step Description: PyBroom Example - Multiple Datasets - Scipy Robust Fit This notebook is part of pybroom. This notebook demonstrate using pybroom when fitting a set of curves (curve fitting) using robust fit...
Python Code: %matplotlib inline %config InlineBackend.figure_format='retina' # for hi-dpi displays import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.pylab import normpdf import seaborn as sns from lmfit import Model import lmfit print('lmfit: %s' % lmfit.__version__) sns.set_style(...
1,260
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction In this notebook, we will demonstrate how to copy and paste Page resources within the SAME agent from a Source Flow to a Target Flow. These same methods/functions can be further...
Python Code: #If you haven't already, make sure you install the `dfcx-scrapi` library !pip install dfcx-scrapi Explanation: Introduction In this notebook, we will demonstrate how to copy and paste Page resources within the SAME agent from a Source Flow to a Target Flow. These same methods/functions can be further modif...
1,261
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow IO Authors. Step1: TensorFlow を使用した Azure Blob Storage <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: Azurite の...
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...
1,262
Given the following text description, write Python code to implement the functionality described below step by step Description: version 1.1 Введение (Introduction) Данный блокнот является дополнительным материалом к статье по демонстрации примеров анализа данных и линейной регрессии представленной публикации на пор...
Python Code: #import libraries import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import requests, bs4 import time from sklearn import model_selection from collections import OrderedDict from sklearn.preprocessing import StandardScaler from sklearn.model_selection import trai...
1,263
Given the following text description, write Python code to implement the functionality described below step by step Description: Aerobic metabolic model Import the necessary libraries Step1: Load the data Step2: Compute the aerobic metabolic model Step3: Plot the information related to the MAP determination using P...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from skcycling.data_management import Rider from skcycling.metrics import aerobic_meta_model from skcycling.utils.fit import log_linear_model from skcycling.utils.fit import linear_model from datetime import date Explanation: Aerobic met...
1,264
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: 2. Check the types of the variable that you take into account along the way. Step2: 3. Draw the histogram of total day minutes and total intl calls and interpret the ...
Python Code: #codes here import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv("https://raw.githubusercontent.com/Yorko/mlcourse.ai/master/data/telecom_churn.csv") df.head() Explanation: <a href="https://colab.research.google.com/github/gaargly/gaargly.github.io/b...
1,265
Given the following text description, write Python code to implement the functionality described below step by step Description: PageRank exercise Question 1 Consider three Web pages with the following links Step1: Suppose we compute PageRank with a β of 0.7, and we introduce the additional constraint that the sum of...
Python Code: from IPython.display import Image Image(filename='pagerank1.jpeg') Explanation: PageRank exercise Question 1 Consider three Web pages with the following links: End of explanation import numpy as np # Adjacency matrix # m1 = [ 0, 0, 0] # [0.5, 0, 0] # [0.5, 1, 1] m1 = np.matrix([[0, 0, 0],[0.5, 0...
1,266
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> <img src="../../img/ods_stickers.jpg"> Открытый курс по машинному обучению. Сессия № 2 </center> Автор материала Step1: Проведем небольшой EDA Step2: Для начала всегда неплохо бы ...
Python Code: # подгружаем все нужные пакеты import numpy as np import pandas as pd import seaborn as sns import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker %matplotlib inline # настройка внешнего вида графиков в seaborn sns.set_context( "notebook", font_scale = 1.5, rc = { ...
1,267
Given the following text description, write Python code to implement the functionality described below step by step Description: Autoregressive Moving Average (ARMA) Step1: Sunpots Data Step2: Does our model obey the theory? Step3: This indicates a lack of fit. In-sample dynamic prediction. How good does our model ...
Python Code: %matplotlib inline from __future__ import print_function import numpy as np from scipy import stats import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm from statsmodels.graphics.api import qqplot Explanation: Autoregressive Moving Average (ARMA): Sunspots data End of explanatio...
1,268
Given the following text description, write Python code to implement the functionality described below step by step Description: AI Explanations Step1: Run the following cell to create your Cloud Storage bucket if it does not already exist. Step2: Import libraries Import the libraries for this tutorial. Step3: Down...
Python Code: from datetime import datetime TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S") import os PROJECT_ID = "" # TODO: your PROJECT_ID here. os.environ["PROJECT_ID"] = PROJECT_ID BUCKET_NAME = PROJECT_ID # TODO: replace your BUCKET_NAME, if needed REGION = "us-central1" os.environ["BUCKET_NAME"] = BUCKET_NA...
1,269
Given the following text description, write Python code to implement the functionality described below step by step Description: Import Socorro crash data into the Data Platform We want to be able to store Socorro crash data in Parquet form so that it can be made accessible from re Step4: We create the pyspark dataty...
Python Code: !conda install boto3 --yes import logging logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) Explanation: Import Socorro crash data into the Data Platform We want to be able to store Socorro crash data in Parquet form so that it can be made accessible from re:dash. See Bug 1273657 fo...
1,270
Given the following text description, write Python code to implement the functionality described below step by step Description: Analyzing Pronto CycleShare Data with Python and Pandas This notebook originally appeared as a post on the blog Pythonic Perambulations. The content is BSD licensed. <!-- PELICAN_BEGIN_SUMMA...
Python Code: # !curl -O https://s3.amazonaws.com/pronto-data/open_data_year_one.zip # !unzip open_data_year_one.zip Explanation: Analyzing Pronto CycleShare Data with Python and Pandas This notebook originally appeared as a post on the blog Pythonic Perambulations. The content is BSD licensed. <!-- PELICAN_BEGIN_SUMMAR...
1,271
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2017 Google LLC. Step1: # 텐서 만들기 및 조작 학습 목표 Step2: ## 벡터 덧셈 텐서에서 여러 일반적인 수학 연산을 할 수 있습니다(TF API). 다음 코드는 각기 정확히 6개 요소를 가지는 두 벡터(1-D 텐서)를 만들고 조작합니다. Step3: ### 텐서 형태 형태는 텐서의 크기와 ...
Python Code: # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribute...
1,272
Given the following text description, write Python code to implement the functionality described below step by step Description: Spark + Python = PySpark Esse notebook introduz os conceitos básicos do Spark através de sua interface com a linguagem Python. Como aplicação inicial faremos o clássico examplo de contador d...
Python Code: ListaPalavras = ['gato', 'elefante', 'rato', 'rato', 'gato'] palavrasRDD = sc.parallelize(ListaPalavras, 4) print type(palavrasRDD) Explanation: Spark + Python = PySpark Esse notebook introduz os conceitos básicos do Spark através de sua interface com a linguagem Python. Como aplicação inicial faremos o cl...
1,273
Given the following text description, write Python code to implement the functionality described below step by step Description: Categorical Embeddings We will use the embeddings through the whole lab. They are simply represented by a matrix of tunable parameters (weights). Let us assume that we are given a pre-traine...
Python Code: import numpy as np embedding_size = 4 vocab_size = 10 embedding_matrix = np.arange(embedding_size * vocab_size, dtype='float32') embedding_matrix = embedding_matrix.reshape(vocab_size, embedding_size) print(embedding_matrix) Explanation: Categorical Embeddings We will use the embeddings through the whole l...
1,274
Given the following text description, write Python code to implement the functionality described below step by step Description: Interactive WebGL trajectory widget Note Step1: To enable these features, we first need to run enable_notebook to initialize the required javascript. Step2: The WebGL viewer engine is call...
Python Code: from __future__ import print_function import mdtraj as md traj = md.load_pdb('http://www.rcsb.org/pdb/files/2M6K.pdb') print(traj) Explanation: Interactive WebGL trajectory widget Note: this feature requires a 'running' notebook, connected to a live kernel. It will not work with a staticly rendered display...
1,275
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementing logistic regression from scratch The goal of this notebook is to implement your own logistic regression classifier. You will Step1: Load review dataset For this assignment, we ...
Python Code: import graphlab Explanation: Implementing logistic regression from scratch The goal of this notebook is to implement your own logistic regression classifier. You will: Extract features from Amazon product reviews. Convert an SFrame into a NumPy array. Implement the link function for logistic regression. Wr...
1,276
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id="ndvi_std_top"></a> NDVI STD Deviations from an established average z-score. <hr> Notebook Summary A baseline for each month is determined by measuring NDVI over a set time The data c...
Python Code: import sys import os sys.path.append(os.environ.get('NOTEBOOK_ROOT')) import time import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib.ticker import FuncFormatter import seaborn as sns from utils.data_cube_utilities.dc_load import get_product_exten...
1,277
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Gaussian Mixture Models and Expectation Maximisation in Shogun By Heiko Strathmann - heiko.strathmann@gmail.com - http Step2: Set up the model in Shogun Step3: Sampling from mixture...
Python Code: %pylab inline %matplotlib inline import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') # import all Shogun classes from modshogun import * from matplotlib.patches import Ellipse # a tool for visualisation def get_gaussian_ellipse_artist(mean, cov, nstd=1.96, color="red", linewidth=3): ...
1,278
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Python An introduction to Python for middle and high school students using Python 3 syntax. Getting started We're assuming that you already have Python 3.6 or higher installe...
Python Code: print('Hello, World!') Explanation: Introduction to Python An introduction to Python for middle and high school students using Python 3 syntax. Getting started We're assuming that you already have Python 3.6 or higher installed. If not, go to Python.org to download the latest for your operating system. Ver...
1,279
Given the following text description, write Python code to implement the functionality described below step by step Description: pandas pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language http Step1: Working...
Python Code: # Series import numpy as np import pandas as pd myArray = np.array([2,3,4]) row_names = ['p','q','r'] mySeries = pd.Series(myArray,index=row_names) print (mySeries) print (mySeries[0]) print (mySeries['p']) # Dataframes myArray = np.array([[2,3,4],[5,6,7]]) row_names = ['p','q'] col_names = ['One','Two','T...
1,280
Given the following text description, write Python code to implement the functionality described below step by step Description: Experiment Step1: Load and check data Step2: ## Analysis Experiment Details Step3: Does improved weight pruning outperforms regular SET Step4: No significant difference between the two a...
Python Code: %load_ext autoreload %autoreload 2 from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import glob import tabulate import pprint import click import numpy as np import pandas as pd from ray.tune.commands import * from nupic.research.framewo...
1,281
Given the following text description, write Python code to implement the functionality described below step by step Description: Discretize PV row sides and indexing In this section, we will learn how to Step1: Prepare PV array parameters Step2: Create discretization scheme Step3: Create a PV array Import the Order...
Python Code: # Import external libraries import matplotlib.pyplot as plt # Settings %matplotlib inline Explanation: Discretize PV row sides and indexing In this section, we will learn how to: create a PV array with discretized PV row sides understand the indices of the timeseries surfaces of a PV array plot a PV array ...
1,282
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'bcc', 'bcc-esm1', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: BCC Source ID: BCC-ESM1 Topic: Ocean Sub-Topics: Timestepping Framework, Advect...
1,283
Given the following text description, write Python code to implement the functionality described below step by step Description: <H1>Bidirectional connections as a function of the distance </H1> <P> We will analyze the probability of finding bidirectionally connected inhibitory synapses are over-represented as a funct...
Python Code: %pylab inline import warnings from inet import DataLoader, __version__ from inet.utils import II_slice print('Inet version {}'.format(__version__)) Explanation: <H1>Bidirectional connections as a function of the distance </H1> <P> We will analyze the probability of finding bidirectionally connected inhibit...
1,284
Given the following text description, write Python code to implement the functionality described below step by step Description: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about emb...
Python Code: import time import numpy as np import tensorflow as tf import utils Explanation: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural lang...
1,285
Given the following text description, write Python code to implement the functionality described below step by step Description: Temp Step1: Remove corrupted h5 files on the repo and remove all ZIP-files on the data repo Step2: Recreate all the ZIP folders Load the existing h5 files and use this to create the zip fi...
Python Code: from file_transfer.creds import URL, LOGIN, PASSWORD btos = dm.BaltradToS3(URL, LOGIN, PASSWORD, "lw-enram", profile_name="lw-enram") btos.transfer(name_match="_vp_", overwrite=True, limit=5, verbose=True) btos.transferred s3handle.create_zip_version(btos.transferred) import shutil shutil.rm...
1,286
Given the following text description, write Python code to implement the functionality described below step by step Description: Populations Step1: Let's create a population. Agent creation is here dealt with automatically. Still, it is possible to manually add or remove agents (Hence the IDs of the agents), what wil...
Python Code: import naminggamesal.ngpop as ngpop Explanation: Populations End of explanation pop_cfg={ 'voc_cfg':{ 'voc_type':'matrix', 'M':5, 'W':10 }, 'strat_cfg':{ 'strat_type':'naive', 'vu_cfg':{'vu_type':'BLIS_epirob'} }, 'interact_cfg':{ ...
1,287
Given the following text description, write Python code to implement the functionality described below step by step Description: Data science pipeline Step1: Primary object types Step2: What are the features? * TV Step3: Linear regression Pros Step4: Splitting X and y into training and testing sets Step5: Linear ...
Python Code: # conventional way to import pandas import pandas as pd # read CSV file directly from a URL and save the results data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0) # display the first 5 rows data.head() Explanation: Data science pipeline: pandas, seaborn, scikit-learn¶ Ag...
1,288
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) Explanation: Language Translation In this project, you’re going ...
1,289
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice 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', 'bcc', 'bcc-csm2-hr', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: BCC Source ID: BCC-CSM2-HR Topic: Seaice Sub-Topics: Dynamics, Thermodynam...
1,290
Given the following text description, write Python code to implement the functionality described below step by step Description: Partie 5 Step1: <a name="PbGeneral">Problèmatique générale</a> Objectif L'objectif principal de l'automatique ou de la théorie du contrôle est d'imposer un comportement dynamique spécifique...
Python Code: # -*- coding: utf-8 -*- from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> Pour afficher le code python, cliquer sur ...
1,291
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: My sample df has four columns with NaN values. The goal is to concatenate all the rows while excluding the NaN values.
Problem: import pandas as pd import numpy as np df = pd.DataFrame({'keywords_0':["a", np.nan, "c"], 'keywords_1':["d", "e", np.nan], 'keywords_2':[np.nan, np.nan, "b"], 'keywords_3':["f", np.nan, "g"]}) import numpy as np def g(df): df["keywords_all"] = df.apply(lamb...
1,292
Given the following text description, write Python code to implement the functionality described below step by step Description: Structures de données Plus de détails sur les listes Le type de données liste possède d’autres méthodes. Voici toutes les méthodes des objets listes Step1: Utiliser les listes comme de...
Python Code: ma_liste = [66.6, 333, 333, 1, 1234.5] print (ma_liste.count(333), ma_liste.count(66.6), ma_liste.count('x')) ma_liste2 = list(ma_liste) ma_liste2.sort() print (ma_liste2) ma_liste.insert(2, -1) ma_liste.append(333) ma_liste ma_liste.index(333) ma_liste.remove(333) print(ma_liste) ma_liste.reverse() ma_lis...
1,293
Given the following text description, write Python code to implement the functionality described below step by step Description: I combined all the code lines I said should be at the begining of your code. Step1: Importing mltools First you want to make sure it sits in the same folder or wherever you put your PYTHON_...
Python Code: from __future__ import division import numpy as np import matplotlib.pyplot as plt %matplotlib inline np.random.seed(0) Explanation: I combined all the code lines I said should be at the begining of your code. End of explanation !ls Explanation: Importing mltools First you want to make sure it sits in the ...
1,294
Given the following text description, write Python code to implement the functionality described below step by step Description: Examples on the use of roppy's FluxSection class The FluxSection class implements a staircase approximation to a section, starting and ending in psi-points and following U- and V-edges. No i...
Python Code: # Imports ======= The class depends on `numpy` and is part of `roppy`. To read the data `netCDF4` is needed. The graphic package `matplotlib` is not required for `FluxSection` but is used for visualisation in this notebook. # Imports import numpy as np import matplotlib.pyplot as plt from netCDF4 import Da...
1,295
Given the following text description, write Python code to implement the functionality described below step by step Description: Hierarchical Topic Models and the Nested Chinese Restaurant Process Tun-Chieh Hsu, Xialingzi Jin, Yen-Hua Chen I. Background Recently, complex probabilistic models are increasingly prevalent...
Python Code: import numpy as np from scipy.special import gammaln import random from collections import Counter import string import graphviz import pygraphviz import pydot Explanation: Hierarchical Topic Models and the Nested Chinese Restaurant Process Tun-Chieh Hsu, Xialingzi Jin, Yen-Hua Chen I. Background Recently,...
1,296
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice 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', 'mpi-m', 'mpi-esm-1-2-hr', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: MPI-M Source ID: MPI-ESM-1-2-HR Topic: Seaice Sub-Topics: Dynamics, T...
1,297
Given the following text description, write Python code to implement the functionality described below step by step Description: Goal Question Step1: Init Step2: Using nestly Step3: Plotting results Step4: Sandbox Enrichment of TP for abundant incorporators? What is the abundance distribution of TP and FP? Are mor...
Python Code: workDir = '/home/nick/notebook/SIPSim/dev/bac_genome1210/' genomeDir = '/home/nick/notebook/SIPSim/dev/bac_genome1210/genomes/' R_dir = '/home/nick/notebook/SIPSim/lib/R/' Explanation: Goal Question: how is incorporator identification accuracy affected by the percent isotope incorporation of taxa? Using ge...
1,298
Given the following text description, write Python code to implement the functionality described below step by step Description: CS446/519 - Class Session 7 - Transitivity (Clustering Coefficients) In this class session we are going to compute the local clustering coefficient of all vertices in the undirected human pr...
Python Code: from igraph import Graph from igraph import summary import pandas import numpy import timeit from pympler import asizeof import bintrees Explanation: CS446/519 - Class Session 7 - Transitivity (Clustering Coefficients) In this class session we are going to compute the local clustering coefficient of all ve...
1,299
Given the following text description, write Python code to implement the functionality described below step by step Description: AutoML Text entity extractionn model Installation Install the latest version of AutoML SDK. Step1: Install the Google cloud-storage library as well. Step2: Restart the Kernel Once you've i...
Python Code: ! pip3 install google-cloud-automl Explanation: AutoML Text entity extractionn model Installation Install the latest version of AutoML SDK. End of explanation ! pip3 install google-cloud-storage Explanation: Install the Google cloud-storage library as well. End of explanation import os if not os.getenv("AU...