Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
3,200
<ASSISTANT_TASK:> Python Code: mod = pysces.model('lin4_fb') mod.doLoad() # this method call is necessary to ensure that future `doLoad` method calls are executed correctly sc = psctb.Symca(mod) sc.do_symca() sc.cc_results sc.cc_results.ccJR1_R4 sc.cc_results.ccJR1_R4.expression sc.cc_results.ccJR1_R4.numerator s...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Additionally Symca has the following arguments Step2: do_symca has the following arguments Step3: Inspecting an individual control coefficient...
3,201
<ASSISTANT_TASK:> Python Code: from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", reshape=False) X_train, y_train = mnist.train.images, mnist.train.labels X_validation, y_validation = mnist.validation.images, mnist.validation.labels X_test, y_test ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The MNIST data that TensorFlow pre-loads comes as 28x28x1 images. Step2: Visualize Data Step3: Preprocess Data Step4: Setup TensorFlow Step5:...
3,202
<ASSISTANT_TASK:> Python Code: # Import all necessary libraries, this is a configuration step for the exercise. # Please run it before the simulation code! import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # Show the plots in the Notebook. plt.switch_backend("nbagg") # Initial...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1. Initialization of setup Step2: 2. Finite Differences setup Step3: 3. Finite Volumes setup Step4: 4. Initial condition Step5: 4. Solution ...
3,203
<ASSISTANT_TASK:> Python Code: from __future__ import print_function # We'll need numpy for some mathematical operations import numpy as np # matplotlib for displaying the output import matplotlib.pyplot as plt import matplotlib.style as ms ms.use('seaborn-muted') %matplotlib inline # and IPython.display for audio outp...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: By default, librosa will resample the signal to 22050Hz. Step2: Harmonic-percussive source separation Step3: Chromagram Step4: MFCC Step5: B...
3,204
<ASSISTANT_TASK:> Python Code: %%javascript // From https://github.com/kmahelona/ipython_notebook_goodies $.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js') def add(n1, n2): return n1 + n2 def multiply(n1, n2): return n1 * n2 def exponentiate(n1, n2): Raise n1 to th...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Basics Step5: Well, we only want these functions to work if both inputs are numbers. So we could do Step8: But this is yucky Step9: This is d...
3,205
<ASSISTANT_TASK:> Python Code: import bs4 # read in the xml file soup = bs4.BeautifulSoup(open('Ode.xml'), 'html.parser') # get the text content inside the "EEBO" tag text = soup.find('eebo').get_text() # print the text print(text) import bs4 # read in the xml file soup = bs4.BeautifulSoup(open('Ode.xml'), 'html.parse...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <h2 style='color
3,206
<ASSISTANT_TASK:> Python Code: import xgboost as xgb import shap from sklearn.model_selection import train_test_split import pandas as pd X,y = shap.datasets.boston() X.head() print(y.shape) # predict house price y[4:10] y = pd.DataFrame(y) y.head() # for regression method, I can not use stratify split with this metho...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Summarize Feature Importance Step2: Check Individual Cases
3,207
<ASSISTANT_TASK:> Python Code: # A bit of setup import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.neural_net import TwoLayerNet %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Implementing a Neural Network Step2: We will use the class TwoLayerNet in the file cs231n/classifiers/neural_net.py to represent instances of o...
3,208
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import torch a, b = load_data() c = (a[:, -1:] + b[:, :1]) / 2 result = torch.cat((a[:, :-1], c, b[:, 1:]), dim=1) <END_TASK>
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
3,209
<ASSISTANT_TASK:> Python Code: import warnings warnings.filterwarnings('ignore') from tardis import run_tardis import tardis tardis.logger.setLevel(0) tardis.logging.captureWarnings(False) def display_table(sim): '''Display a table of velocities and radiative temperatures at each iteration ''' # ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The command run_tardis allows users to provide a set of callbacks to the simulation. These callbacks are called at the end of each iteration. ...
3,210
<ASSISTANT_TASK:> Python Code: from bravado.client import SwaggerClient client = SwaggerClient.from_url('https://www.genomenexus.org/v2/api-docs', config={"validate_requests":False,"validate_responses":False,"validate_swagger_spec":False}) print(client) dir(client) for a in dir(client): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Connect with cBioPortal API Step2: Annotate cBioPortal mutations with Genome Nexus Step3: Check overlap SIFT/PolyPhen-2
3,211
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np import pints import pints.plot import pints.toy # Define model parameters parameters = [2, 0.015, 500, 10, 1.1, 0.05] f_0, r, k, sigma_base, eta, sigma_rel = parameters # Instantiate logistic growth model with f(t=0) = f_0 model = pints.t...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Inference of model parameters Step2: Infer parameters with Haario Adaptive Covariance MCMC Step3: Show quantitative and visual diagnostics of ...
3,212
<ASSISTANT_TASK:> Python Code: import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') import shogun as sg import numpy as np import matplotlib.pyplot as plt %matplotlib inline #number of data points. n=100 #generate a random 2d line(y1 = mx1 + c) m = np.random.randint(1,10) c = np.random.randint(1,10)...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Some Formal Background (Skip if you just want code examples) Step2: Step 2 Step3: Step 3 Step4: Step 5 Step5: In the above figure, the blue ...
3,213
<ASSISTANT_TASK:> Python Code: __version__ = '0.1.0' __status__ = 'Development' __date__ = '2017-May-25' __author__ = 'Jay Narhan' import os import pandas as pd import numpy as np from collections import Counter META_ROOT = os.path.realpath('../../Meta_Data_Files') + '/' DDSM_META = META_ROOT + 'Ddsm_png.c...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <h2>Read DDSM Meta Data Step2: <h2>Read in MIAS Meta Data Step3: <h3>Create meta_data_all.csv</h3> Step4: Step5: <h2>Creating Meta Data for...
3,214
<ASSISTANT_TASK:> Python Code: import codecs with codecs.open("imdb_labelled.txt", "r", "utf-8") as arquivo: vetor = [] for linha in arquivo: vetor.append(linha) with codecs.open("amazon_cells_labelled.txt", "r", "utf-8") as arquivo: for linha in arquivo: vetor.append(linha) with codecs.op...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Depois, devemos retirar cada quebra de linha no final de cada linha, ou seja, os '\n'. Step2: A seguir, retiramos os dois últimos caracteres so...
3,215
<ASSISTANT_TASK:> Python Code: class Mesa(object): cantidad_de_patas = None color = None material = None mi_mesa = Mesa() mi_mesa.cantidad_de_patas = 4 mi_mesa.color = 'Marrón' mi_mesa.material = 'Madera' print 'Tendo una mesa de {0.cantidad_de_patas} patas de color {0.color} y esta hecha de {0.materia...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Ahora, si siempre voy a tener que definir esas características de la mesa para poder usarla, lo más cómodo es definir el método __init__ que sir...
3,216
<ASSISTANT_TASK:> Python Code: from bruges.transform import CoordTransform corner_ix = [[0, 0], [0, 3], [3, 0]] corner_xy = [[5000, 6000], [5000-23.176, 6000+71.329], [5000+142.658, 6000+46.353]] transform = CoordTransform(corner_ix, corner_xy) for i in range(4): for j in range(4)...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Adding (x, y) coordinates
3,217
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt np.random.seed(10) dossageEffectiveness = abs(np.random.normal(5.0, 1.5, 1000)) repurchaseRate = (dossageEffectiveness + np.random.normal(0, 0.1, 1000)) * 3 repurchaseRate/=np.max(repurchaseRate) plt.scatter(dossageEffe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Modify this to a multivariate/polynomial regression example Step2: Make distribution more complicated to see if scikit-learn can fit it Step3: ...
3,218
<ASSISTANT_TASK:> Python Code: %matplotlib nbagg import numpy as np import matplotlib.pyplot as plt from plots import plot_tree_interactive plot_tree_interactive() from plots import plot_forest_interactive plot_forest_interactive() from sklearn import grid_search from sklearn.datasets import load_digits from sklearn...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Decision Tree Classification Step2: Random Forests Step3: Selecting the Optimal Estimator via Cross-Validation Step4: Exercises
3,219
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nerc', 'sandbox-2', 'aerosol') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "em...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
3,220
<ASSISTANT_TASK:> Python Code: import os import sys # Modify the path sys.path.append("..") import yellowbrick as yb import matplotlib.pyplot as plt from download import download_all from sklearn.datasets.base import Bunch ## The path to the test data sets FIXTURES = os.path.join(os.getcwd(), "data") ## Dataset ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Load Text Corpus for Example Code Step3: t-SNE Step4: Frequency Distribution Visualization Step5: Note that the FreqDistVisualizer does not p...
3,221
<ASSISTANT_TASK:> Python Code: from __future__ import unicode_literals, print_function from axon.api import loads, dumps from axon.objects import node, attribute, Attribute, Node from axon.objects import Builder, register_builder from axon import dump_as_str, as_unicode, factory, reduce from xml.etree import ElementTre...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: There are reduce functions for ElementTree.Element and ElementTree.ElementTree types from xml.etree package. These functions will used for dumpi...
3,222
<ASSISTANT_TASK:> Python Code: import sys # system module import pandas as pd # data package import matplotlib.pyplot as plt # graphics module import datetime as dt # date and time module import numpy as np # foundation for Pan...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data Step2: Analysis Step3: Does size matter Step4: Do clusters of CompSci programs in a state make female participation more likely? Step5: ...
3,223
<ASSISTANT_TASK:> Python Code: from petal_helper import * # Detect TPU, return appropriate distribution strategy try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print('Running on TPU ', tpu.master()) except ValueError: tpu = None if tpu: tf.config.experimental_connect_to_cluster(tpu) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Create Distribution Strategy Step2: Loading the Competition Data Step3: Explore the Data Step4: Examine the shape of the data. Step5: Peek a...
3,224
<ASSISTANT_TASK:> Python Code: %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_data_train LIMIT 0 %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_data_eval LIMIT 0 %%bigqu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lab Task #1 Step2: Create two SQL statements to evaluate the model. Step3: Lab Task #2 Step4: Create three SQL statements to EVALUATE the mod...
3,225
<ASSISTANT_TASK:> Python Code: import pandas as pd id=["Train A","Train A","Train A","Train B","Train B","Train B"] arrival_time = ["0"," 2016-05-19 13:50:00","2016-05-19 21:25:00","0","2016-05-24 18:30:00","2016-05-26 12:15:00"] departure_time = ["2016-05-19 08:25:00","2016-05-19 16:00:00","2016-05-20 07:45:00","2016-...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
3,226
<ASSISTANT_TASK:> Python Code: df = pd.read_csv('totaal.csv') df = df.set_index('id') df['start'] = pd.to_datetime(df['start']) # Starttijden converteren naar datetimes df['einde'] = pd.to_datetime(df['einde']) # Eindtijden converteren naar datetimes df['duur'] = df['einde'] - df['start'] # Hoe lang parkeert iedereen? ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Vervolgens kijken we of we het correct is ingeladen Step2: Starttijden Step3: Eindtijden Step4: Duur Step5: Interessant! Van de distributie ...
3,227
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'sandbox-3', 'ocnbgchem') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contri...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
3,228
<ASSISTANT_TASK:> Python Code: import tensorflow as tf print(tf.__version__) mnist = tf.keras.datasets.fashion_mnist (training_images, training_labels), (test_images, test_labels) = mnist.load_data() import matplotlib.pyplot as plt plt.imshow(training_images[0]) print(training_labels[0]) print(training_images[0]) t...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The Fashion MNIST data is available directly in the tf.keras datasets API. You load it like this Step2: Calling load_data on this object will g...
3,229
<ASSISTANT_TASK:> Python Code: from nipype import Node, JoinNode, Workflow # Specify fake input node A a = Node(interface=A(), name="a") # Iterate over fake node B's input 'in_file? b = Node(interface=B(), name="b") b.iterables = ('in_file', [file1, file2]) # Pass results on to fake node C c = Node(interface=C(), name=...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: As you can see, setting up a JoinNode is rather simple. The only difference to a normal Node are the joinsource and the joinfield. joinsource sp...
3,230
<ASSISTANT_TASK:> Python Code: %matplotlib widget !pip install nanslice import urllib.request import tarfile url = 'https://osf.io/hmtyr/download' urllib.request.urlretrieve(url, 'nanslice_example.tar.gz') tgz = tarfile.open('nanslice_example.tar.gz') tgz.extractall() tgz.close() data_dir = 'nanslice_example/' import n...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Basic Slicing Step2: However, if you are going to use the same image multiple times, e.g. a structural template image, then it makes sense to l...
3,231
<ASSISTANT_TASK:> Python Code: import os import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd import tensorflow as tf from google.cloud import bigquery from tensorflow.keras.utils import to_categorical from tensorflow.keras.models import Sequential from tensorflow.keras.layers...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Explore time series data Step3: The function clean_data below does three things Step6: Read data and preprocessing Step7: Let's plot a few ex...
3,232
<ASSISTANT_TASK:> Python Code: from pyspark import SparkContext sc = SparkContext(master = 'local') from pyspark.sql import SparkSession spark = SparkSession.builder \ .appName("Python Spark SQL basic example") \ .config("spark.some.config.option", "some-value") \ .getOrCreate() cuse = sp...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Decision tree classification with pyspark Step2: Process categorical columns Step3: Build StringIndexer stages Step4: Build OneHotEncoder sta...
3,233
<ASSISTANT_TASK:> Python Code: from __future__ import unicode_literals, print_function import boto3 import json import numpy as np import pandas as pd import spacy from verta import Client client = Client('http://localhost:3000/') proj = client.set_project('Tweet Classification') expt = client.set_experiment('SpaCy') ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: ...and instantiate Verta's ModelDB Client. Step2: Prepare Data Step3: Capture and Version Model Ingredients Step4: You may verify through the...
3,234
<ASSISTANT_TASK:> Python Code: import numpy as np n=200 x_tr = np.linspace(0.0, 2.0, n) y_tr = np.exp(3*x_tr) import random mu, sigma = 0,50 random.seed(1) y = y_tr + np.random.normal(loc=mu, scale= sigma, size=len(x_tr)) import matplotlib.pyplot as plt %matplotlib inline plt.plot(x_tr,y,".",mew=3); plt.plot(x_tr, y_tr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The red curve is defined by the function Step2: Let's fit a simple linear model on $y$ and $x$. Step3: Well, that's not really good... We can...
3,235
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import desolver as de import desolver.backend as D D.set_float_fmt('float64') def Fij(ri, rj, G): rel_r = rj - ri return G*(1/D.norm(rel_r, ord=2)**3)*rel_r def rhs(t, state, masses, G): total_acc = D.zeros_like(state) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Specifying the Dynamical System Step2: NOTE Step3: I've added 3 massive bodies at the ends of a scalene triangle Step4: The Numerical Integra...
3,236
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np from sklearn import datasets, metrics, model_selection, preprocessing, pipeline import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import autosklearn...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Note Step2: Print the final ensemble constructed by auto-sklearn
3,237
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np from scipy import stats import seaborn as sns from matplotlib import pyplot as plt sns.set_style('white') data = pd.io.stata.read_stata('data/us_job_market_discrimination.dta') # number of callbacks for black-sounding names print(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Permutation Step2: T-test
3,238
<ASSISTANT_TASK:> Python Code: w, h, b, d, c1, c2, k1, k2, r_sys, r_ref = symbols("w, h, b, d, c_1, c_2, k_1, k_2, r_{sys}, r_{ref}", real=True) # Constraints for hyperboloids: k1_constraint = k1 > 2 k2_constraint = k2 > 2 c1_constraint = c1 > 0 c2_constraint = c2 > 0 xw, yw, zw = symbols("x_w, y_w, z_w", real=True) # ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: System Height Step2: Lens Hole Radius Step3: Line passing through points $P_w$ and $F_1$ Step4: Let $\lambda_1 = 1 - s_1$, so that Step5: So...
3,239
<ASSISTANT_TASK:> Python Code: def fit_normal_to_hist(h): if not all(h==0): bins =np.array([-2.0,-1.0,-0.5,0.0,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,5.0]) orig_hist = np.array(h).astype(float) norm_hist = orig_hist/float(sum(orig_hist)) mid_points = (bins[1:] + bins[:-1])/2 popt,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: bins =np.array([-2.0,-1.0,-0.5,0.0,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,5.0]) Step2: h = df.iloc[10,mask]
3,240
<ASSISTANT_TASK:> Python Code: from pprint import * import pyspark from pyspark import SparkConf, SparkContext sc = None print(pyspark.status) conf = (SparkConf() .setMaster("local") .setAppName("MyApp") .set("spark.executor.memory", "1g")) if sc is None: sc = SparkContext(conf = conf) p...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 配置环境SparkConf和创建SparkContext运行环境对象。 Step2: 显示Spark的配置信息。 Step3: Spark的文本RDD操作。 Step4: 从RDD中按照文本方式进行关键词查询。 Step5: Spark的DataFrame操作。 Step6: ...
3,241
<ASSISTANT_TASK:> Python Code: import numpy as np import holoviews as hv hv.notebook_extension('matplotlib') fractal = hv.Image(np.load('mandelbrot.npy')) ((fractal * hv.HLine(y=0)).hist() + fractal.sample(y=0)) %%opts Points [scaling_factor=50] Contours (color='w') dots = np.linspace(-0.45, 0.45, 19) layouts = {y: (f...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Fundamentally, a HoloViews object is just a thin wrapper around your data, with the data always being accessible in its native numerical format,...
3,242
<ASSISTANT_TASK:> Python Code: import cvxpy as cp import numpy as np import scipy as scipy # Fix random number generator so we can repeat the experiment. np.random.seed(0) # Dimension of matrix. n = 10 # Number of samples, y_i N = 1000 # Create sparse, symmetric PSD matrix S A = np.random.randn(n, n) # Unit normal gau...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Solve for several $\alpha$ values Step2: Result plots
3,243
<ASSISTANT_TASK:> Python Code: from __future__ import print_function, division % matplotlib inline import warnings warnings.filterwarnings('ignore') import math import numpy as np from thinkbayes2 import Pmf, Cdf, Suite, Joint, EvalNormalPdf import thinkplot import pandas as pd import matplotlib.pyplot as plt df = pd....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: From Step2: Next, let's create vectors of our ages and heights. Step3: Now let's visualize our data to make sure that linear regression is app...
3,244
<ASSISTANT_TASK:> Python Code: # from typing import Callable, Sequence # used ? import flax from flax import linen as nn # Simple module with matmul layer. Note that we could build this in many # different ways using the `scope` for parameter handling. class Matmul: def __init__(self, features): self.feat...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Functional core Step2: Stateless Linen module Step3: Linen module with state Step4: Modify MNIST example
3,245
<ASSISTANT_TASK:> Python Code: # Run some setup code for this notebook. import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt import numpy.linalg as la import seaborn as sns import itertools import pandas as pd sns.set_style('whitegrid') # create a palette generator...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We would now like to classify the test data with the kNN classifier. Recall that we can break down this process into two steps Step2: Inline Qu...
3,246
<ASSISTANT_TASK:> Python Code: import subprocess import numpy as np from IPython.display import Image PI = np.pi POV_SCENE_FILE = "hopf_fibration.pov" POV_DATA_FILE = "torus-data.inc" POV_EXE = "povray" COMMAND = "{} +I{} +W500 +H500 +Q11 +A0.01 +R2".format(POV_EXE, POV_SCENE_FILE) IMG = POV_SCENE_FILE[:-4] + ".png" d...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step3: Hopf inverse map and stereographic projection Step7: Circle passes through three points Step10: Convert vector/matrix to POV-Ray format Step12...
3,247
<ASSISTANT_TASK:> Python Code: import itertools import os import sys os.environ['OPENBLAS_NUM_THREADS'] = '1' import numpy as np import pandas as pd from scipy import sparse import content_wmf import batched_inv_joblib import rec_eval DATA_DIR = '/hdd2/dawen/data/ml-20m/pro/' unique_uid = list() with open(os.path.join...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load pre-processed data Step2: Train the model
3,248
<ASSISTANT_TASK:> Python Code: # Authors: Marijn van Vliet <w.m.vanvliet@gmail.com> # Ezequiel Mikulan <e.mikulan@gmail.com> # Manorama Kadwani <manorama.kadwani@gmail.com> # # License: BSD-3-Clause import os import shutil import mne data_path = mne.datasets.sample.data_path() subjects_dir = data_path...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Exporting surfaces to Blender Step2: Editing in Blender Step3: Back in Python, you can read the fixed .obj files and save them as Step4: Edit...
3,249
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'fio-ronm', 'sandbox-3', 'aerosol') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name",...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
3,250
<ASSISTANT_TASK:> Python Code: def prime(n ) : if(n <= 1 ) : return False  if(n <= 3 ) : return True  if(n % 2 == 0 or n % 3 == 0 ) : return False  i = 5 while i * i <= n : if(n % i == 0 or n %(i + 2 ) == 0 ) : return False  i += 6  return True  def isVowel(c ) : c = c . lower()...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
3,251
<ASSISTANT_TASK:> Python Code: import pandas as pd # proposition = "PROPOSITION 064- MARIJUANA LEGALIZATION. INITIATIVE STATUTE." proposition = "PROPOSITION 062- DEATH PENALTY. INITIATIVE STATUTE." props = pd.read_csv("http://www.firstpythonnotebook.org/_static/committees.csv") contribs = pd.read_csv("http://www.first...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Read in data on committees and contributions Step2: Number of committees per proposition Step3: Filter for proposition of interest Step4: All...
3,252
<ASSISTANT_TASK:> Python Code: import pandas as pd from opengrid.library import misc from opengrid.library import houseprint from opengrid.library import caching import charts hp = houseprint.Houseprint() cache_water = caching.Cache(variable='water_daily_min') df_cache = cache_water.get(sensors=hp.get_sensors(sensorty...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We demonstrate the caching for the minimal daily water consumption (should be close to zero unless there is a water leak). We create a cache ob...
3,253
<ASSISTANT_TASK:> Python Code: import numpy as np import dask.array as da from fmks.data.cahn_hilliard import generate_cahn_hilliard_data import dask.threaded import dask.multiprocessing def time_ch(num_workers, get, shape=(48, 200, 200), chunks=(1, 200, 200), n_steps=10...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The function time_ch calls generate_cahn_hilliard_data to generate the data. generate_cahn_hilliard_data returns the microstructure and response...
3,254
<ASSISTANT_TASK:> Python Code: from pymatgen.entries.computed_entries import ComputedEntry from pymatgen.entries.compatibility import MaterialsProjectCompatibility, \ MaterialsProject2020Compatibility from pymatgen.ext.matproj import MPRester # retrieve with MPRester() as m:...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Default behavior - MaterialsProject2020Compatibility Step2: You can examine the energy corrections via the energy_adjustments attribute Step3:...
3,255
<ASSISTANT_TASK:> Python Code: from __future__ import division %pylab inline from scipy import stats import numpy as np b= stats.bernoulli(.5) # fair coin distribution nsamples = 100 # flip it nsamples times for 200 estimates xs = b.rvs(nsamples*200).reshape(nsamples,-1) phat = np.mean(xs,axis=0) # estimated p # edge...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: In a previous coin-flipping discussion, we discussed estimation of the Step2: <!-- # @@@CODE src-statistics/Confidence_Intervals.py fromto
3,256
<ASSISTANT_TASK:> Python Code: import gzip import pickle import numpy as np import sklearn.svm as svm def load_data(): with gzip.open('../mnist.pkl.gz', 'rb') as f: train, validate, test = pickle.load(f, encoding="latin1") X_train = np.array([np.reshape(x, (784, )) for x in train[0]]) X_test ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The function $\texttt{load_data}()$ returns a pair of the form Step2: Let us see what we have read Step3: We define a support vector machine w...
3,257
<ASSISTANT_TASK:> Python Code: import numpy as np import scipy as sp from sklearn import datasets iris = datasets.load_iris() digits = datasets.load_digits() boston = datasets.load_boston() from sklearn import svm model = svm.SVC(gamma=0.002, C=100.) print(model.gamma) model.set_params(gamma=.001) print(model.gamma) m...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Même avant scikit-learn Step2: Nous pouvons regarder l'image. Step3: À savoir (mais pour un autre jour) Step4: Le classifieur le plus simple...
3,258
<ASSISTANT_TASK:> Python Code: df['citizenship'].value_counts().head() df.groupby('citizenship')['networthusbillion'].sum().sort_values(ascending=False) us_pop = 318.9 #billion (2014) us_bill = df[df['citizenship'] == 'United States'] print("There are", us_pop/len(us_bill), "billionaires per billion people in the Unit...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Who are the top 10 richest billionaires? Step2: What's the average wealth of a billionaire? Male? Female? Step3: Who is the poorest billionair...
3,259
<ASSISTANT_TASK:> Python Code: import dateutils import dateutil.parser import pandas as pd parking_df = pd.read_csv("small-violations.csv") parking_df parking_df.dtypes import datetime parking_df.head()['Issue Date'].astype(datetime.datetime) import pandas as pd parking_df = pd.read_csv("small-violations.csv") parking_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1. I want to make sure my Plate ID is a string. Can't lose the leading zeroes! Step2: 2. I don't think anyone's car was built in 0AD. Discard ...
3,260
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt data_path = 'Bike-Sharing-Dataset/hour.csv' rides = pd.read_csv(data_path) rides.head() rides[:24*10].plot(x='dteday', y='cnt', figsize=(10,4)) day_r...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 加载和准备数据 Step2: 数据简介 Step3: 查看每天的骑行数据,对比2011年和2012年 Step4: 虚拟变量(哑变量) Step5: 调整目标变量 Step6: 我们将数据拆分为两个数据集,一个用作训练,一个在网络训练完后用来验证网络。因为数据是有时间序列特性的...
3,261
<ASSISTANT_TASK:> Python Code: # Define your group, for this exercise mygroup = "A" # <- change the letter in quotes # Import Python libraries import os # This lets us interact with the operating system import pandas as pd # This allows us to use dataframes import seaborn as sns # This gives us pre...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: After executing the code cell, you should see a table of values. The table has columns named gene1 and gene2, and rows that are indexed starting...
3,262
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ncc', 'noresm2-mm', 'atmos') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "emai...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
3,263
<ASSISTANT_TASK:> Python Code: # Authors: Tal Linzen <linzen@nyu.edu> # Denis A. Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import numpy as np import mne from mne.datasets import sample from mne.stats.regression import linear_regression print(__doc__) data_path = sample.data_path() raw_fn...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Set parameters and read data Step2: Run regression
3,264
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import matplotlib.pyplot as pl from astropy.wcs import WCS from scipy import constants import cygrid np.set_printoptions(precision=1) def gaincurve(elev, a0, a1, a2): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Introduction Step2: Atmospheric temperature is approximately given by ambient temperature at ground. Step3: Calculate telescope sensitivity (a...
3,265
<ASSISTANT_TASK:> Python Code: # You can use any Python source file as a module by executing an import statement in some other Python source file # The import statement combines two operations; it searches for the named module, then it binds the # results of that search to a name in the local scope. import os, json, ma...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Locating the CSV files Step2: Lab Task 1 Step3: Next, let's define our features we want to use and our label(s) and then load in the dataset f...
3,266
<ASSISTANT_TASK:> Python Code: odd_1000 = [x**2 for x in range(0, 1000) if x % 2 == 1] # 리스트의 처음 다섯 개 항목 odd_1000[:5] odd_3x7 = [x for x in range(0, 1000) if x % 2 == 1 and x % 7 == 0] # 리스트의 처음 다섯 개 항목 odd_3x7[:5] def square_plus1(x): return x**2 + 1 odd_3x7_spl = [square_plus1(x) for x in odd_3x7] # 리스트의 처음 다섯 ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 문제 Step2: 문제 Step3: csv 파일 읽어들이기 Step4: 문제 Step5: 문제 Step6: 문제 Step7: 넘파이의 linspace() 함수 활용 Step8: 문제 Step9: 넘파이 활용 기초 2 Step10: 문제
3,267
<ASSISTANT_TASK:> Python Code: import torch import torch.nn as nn # we'll use this a lot going forward! import numpy as np import matplotlib.pyplot as plt %matplotlib inline X = torch.linspace(1,50,50).reshape(-1,1) # Equivalent to # X = torch.unsqueeze(torch.linspace(1,50,50), dim=1) torch.manual_seed(71) # to obta...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Create a column matrix of X values Step2: Create a "random" array of error values Step3: Create a column matrix of y values Step4: Plot the r...
3,268
<ASSISTANT_TASK:> Python Code: import pints import pints.plot import pints.toy import matplotlib.pyplot as plt import numpy as np model = pints.toy.GoodwinOscillatorModel() real_parameters = model.suggested_parameters() times = model.suggested_times() values = model.simulate(real_parameters, times) plt.figure() plt.s...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The model also provides suggested parameters and sampling times, allowing us to run a simulation Step2: This gives us all we need to create a p...
3,269
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import LeaveOneOut from sklearn import linear_model, neighbors %matplotlib inline plt.style.use('ggplot') # dataset path data_dir = "." sample_data = pd.read_csv(data_dir+"/hw1.csv", delimi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step3: The response variable is quality. Step4: Exercise 2.1 (5 pts) Compare the leave-one-out risk with the empirical risk for linear regression, on ...
3,270
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import pandas as pd plt.style.use('ggplot') # Anaconda on Windows will get warning df=pd.read_csv('train.csv') df.head() df.hist( figsize=(16, 10)) df.describe() df.keys() df2=df.drop(['Name','PassengerId','Cabin','Ticket'],1) df2.h...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Loading data from CSV Step2: Show first 5 records Step3: Histogram Step4: Show statistic Step5: Show list of column names Step6: Drop some ...
3,271
<ASSISTANT_TASK:> Python Code: from IPython.display import HTML HTML('<iframe src="http://conda.pydata.org/docs/_downloads/conda-cheatsheet.pdf" width="700" height="400"></iframe>') # importing numpy # performance list sum # performance array sum %timeit np.sum(array) one_dim_array = two_dim_array = # size & shape ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Main objectives of this workshop Step2: Array creation Step3: Basic slicing Step4: [start Step5: 2. Drawing Step6: Operations & linalg Step...
3,272
<ASSISTANT_TASK:> Python Code: df.fillna('n/a',inplace=True) su=df[df['type_of_property'].str.contains('Apartment')] mu=df[df['type_of_property'].str.contains('Apartments')] print(len(mu)) print(len(su)) su['propertyinfo_value'] len(su[~(su['propertyinfo_value'].str.contains('bd') | su['propertyinfo_value'].str.contain...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 带卧室但没厕所 Step2: 这里通过自定义函数来分类处理数据,从sucln['xxx']出来的是Series,parse_info中读入的row参数,是来自Series的一行文字
3,273
<ASSISTANT_TASK:> Python Code: from modsim import System # If this doesn't work, move this file into your /code folder. # It needs to be in the same folder as modsim.py. def func1(input1, input2): print("Input 1 = ", input1) print("Input 2 = ", input2) output = input1 + input2 print("Output = ", output...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Let's write a function, like they do in ModSim notebooks all the time. We'll give it some parameters just to make it feel important. Step2: All...
3,274
<ASSISTANT_TASK:> Python Code: import holoviews as hv hv.notebook_extension(bokeh=True) hv.Element(None, group='Value', label='Label') import numpy as np points = [(0.1*i, np.sin(0.1*i)) for i in range(100)] hv.Curve(points) np.random.seed(7) points = [(0.1*i, np.sin(0.1*i)) for i in range(100)] errors = [(0.1*i, np....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: In addition, Element has key dimensions (kdims), value dimensions (vdims), and constant dimensions (cdims) to describe the semantics of indexing...
3,275
<ASSISTANT_TASK:> Python Code: def naivesum_list(N): Naively sum the first N integers A = 0 for i in list(range(N + 1)): A += i return A %load_ext memory_profiler %memit naivesum_list(10**4) %memit naivesum_list(10**5) %memit naivesum_list(10**6) %memit naivesum_list(10**7) %memit naivesum_list(10*...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Iterators and Generators Step2: We will now see how much memory this uses Step4: We see that the memory usage is growing very rapidly - as the...
3,276
<ASSISTANT_TASK:> Python Code: from __future__ import division, print_function # отключим всякие предупреждения Anaconda import warnings warnings.filterwarnings('ignore') import numpy as np import pandas as pd %matplotlib inline import seaborn as sns from matplotlib import pyplot as plt plt.rcParams['figure.figsize'] =...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: А теперь практический пример Step2: Напишем вспомогательную функцию, которая будет возвращать решетку для дальнейшей красивой визуализации. Ste...
3,277
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne.datasets import spm_face from mne.preprocessing import ICA, create_eog_epochs from m...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load and filter data, set up epochs Step2: Visualize fields on MEG helmet Step3: Compute forward model Step4: Compute inverse solution
3,278
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline import pyqg # create the model object m = pyqg.BTModel(L=2.*np.pi, nx=256, beta=0., H=1., rek=0., rd=None, tmax=40, dt=0.001, taveint=1, ntd=4) # in this example we u...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: McWilliams performed freely-evolving 2D turbulence ($R_d = \infty$, $\beta =0$) experiments on a $2\pi\times 2\pi$ periodic box. Step2: Initial...
3,279
<ASSISTANT_TASK:> Python Code: # Import some libraries that will be necessary for working with data and displaying plots # To visualize plots in the notebook %matplotlib inline import matplotlib import matplotlib.pyplot as plt import numpy as np import scipy.io # To read matlab files import pylab from test_helpe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1. Objectives Step2: Numpy arrays can be defined directly using methods such as np.arange(), np.ones(), np.zeros(), as well as random number ge...
3,280
<ASSISTANT_TASK:> Python Code: True True = 13 True and False True or False False and False or True True or False and False # Importa dalla libreria solo i tre operatori logici from operator import and_, or_, not_ not_(or_(True, and_(False, True))) not (True or (False and True)) True == True 6*3 < 7*2 14*2 == 4*7 fr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: In qualsiasi linguaggio di programmazione, oltre ad espressioni aritmetiche, è possibile valutare delle espressioni logiche, utilizzando gli ope...
3,281
<ASSISTANT_TASK:> Python Code: data = range(1, 6) pie = Pie(sizes=data) fig = Figure(marks=[pie], animation_duration=1000) # Add `animation_duration` (in milliseconds) to have smooth transitions display(fig) Nslices = 5 pie.sizes = np.random.rand(Nslices) pie.sort = True pie.selected_style = {"opacity": "1", "stroke...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: As with all bqplot Marks, pie data can be dynamically modified Step2: Sort the pie slices by ascending size Step3: Setting different styles fo...
3,282
<ASSISTANT_TASK:> Python Code: import numpy as np a = np.arange(6) b = a print("a =\n",a) print("b =\n",b) b.shape = (2,3) # mudança no shape de b, print("\na shape =",a.shape) # altera o shape de a b[0,0] = -1 # mudança no conteúdo de b print(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Observe que mesmo no retorno de uma função, a cópia explícita pode não acontecer. Veja o exemplo a Step2: Cópia rasa Step3: Slice - Fatiamento...
3,283
<ASSISTANT_TASK:> 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) view_sentence_range = (0, 10) DON'T MODIFY AN...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Language Translation Step3: Explore the Data Step6: Implement Preprocessing Function Step8: Preprocess all the data and save it Step10: Chec...
3,284
<ASSISTANT_TASK:> 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 writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 量子化認識トレーニングの総合ガイド Step2: 量子化認識モデルを定義する Step3: 一部のレイヤーを量子化する Step4: この例では量子化するものを決定するためにレイヤーの種類が使用されていますが、特定のレイヤーを量子化する上で最も簡単な方法は、name プロパティを設...
3,285
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt from IPython.display import Image %matplotlib inline # image courtesy of Raschka, Sebastian. Python machine learning. Birmingham, UK: Packt Publishing, 2015. Print. Image(filename='learning-curve.png', width=600) from sklearn import datasets import numpy ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Plotting our own learning curves Step2: Notice how we plot the standard deviation too; in addition to seeing whether the training and test accu...
3,286
<ASSISTANT_TASK:> 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 print(sm.datasets.sunspots.NOTE) dta = sm.datasets.sunspots.loa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Sunpots Data Step2: Does our model obey the theory? Step3: This indicates a lack of fit. Step4: Exercise Step5: Let's make sure this model i...
3,287
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import os import tfx_utils def _make_default_sqlite_uri(pipeline_name): return os.path.join(os.environ['HOME'], 'airflow/tfx/metadata', pipeline_name, 'metadata.db') def get_metadata_store(pipeline_name): return tfx_utils.TFXReadonlyMetadataSt...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now print out the model artifacts Step2: Now analyze the model performance Step3: Now plot the artifact lineage
3,288
<ASSISTANT_TASK:> Python Code: NAME = "Michelle Appel" NAME2 = "Verna Dankers" NAME3 = "Yves van Montfort" EMAIL = "michelle.appel@student.uva.nl" EMAIL2 = "verna.dankers@student.uva.nl" EMAIL3 = "yves.vanmontfort@student.uva.nl" %pylab inline plt.rcParams["figure.figsize"] = [20,10] def true_mean_function(x): re...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lab 3 Step2: Part 1 Step3: 1. Sampling from the Gaussian process prior (30 points) Step4: 1.2 computeK( X1, X2, thetas ) (10 points) Step5: ...
3,289
<ASSISTANT_TASK:> Python Code: %pylab notebook from __future__ import print_function import datacube import xarray as xr from datacube.helpers import ga_pq_fuser from datacube.storage import masking from datacube.storage.masking import mask_to_dict from matplotlib import pyplot as plt dc = datacube.Datacube(app='combin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: retrieve the NBAR and PQ for the spatiotemporal range of interest Step2: Plotting an image, view the transect and select a location to retrieve...
3,290
<ASSISTANT_TASK:> Python Code: from pyannote.core import SlidingWindowFeature, SlidingWindow # one 4-dimensional feature vector extracted every 100ms from a 200ms window frame = SlidingWindow(start=0.0, step=0.100, duration=0.200) # random for illustration purposes data = np.random.randn(100, 4) features = SlidingWind...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: SlidingWindowFeature are used to manage feature vectors extracted on a sliding window (e.g. MFCC in audio processing). Step2: Cropping Step3: ...
3,291
<ASSISTANT_TASK:> Python Code: import os import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd import tensorflow as tf from google.cloud import bigquery from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard from tensorflow.keras.layers import ( GRU, LSTM, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Explore time series data Step4: The function clean_data below does three things Step7: Read data and preprocessing Step8: Let's plot a few ex...
3,292
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd import glob import os import scipy as sp from scipy import stats from tools.plt import color2d #from the 'srcole/tools' repo from matplotlib import cm # Load cities info df_cities = pd.read_csv('/gh...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load dataframes Step2: 1. What are most popular categories? Step3: 2. What are the most common restaurant chains? Step4: 2a. Correlations in ...
3,293
<ASSISTANT_TASK:> Python Code: import pymongo as pm client = pm.MongoClient() client.drop_database("tutorial") import bson.son as son # start a client client = pm.MongoClient() # connect to a database db = client.tutorial # get a collection coll = db.test_collection example_0 = {} example_1 = {"name": "Michael", "ag...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: "Hello World!" Step2: Documents follow the JSON format and MongoDB stores them in a binary version of it (BSON). Step3: Note that we can also...
3,294
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from compecon import BasisChebyshev, NLP, nodeunif from compecon.demos import demo alpha= 1.0; eta= 1.5; D = lambda p: p** (-eta) n= 25; a= 0.1; b= 3.0 S= BasisChebyshev(n, a, b, labels= ['price'], l=['supply']) p= ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: and set the $\alpha$ and $\eta$ parameters Step2: For convenience, we define a lambda function to represent the demand. Note Step3: We will ap...
3,295
<ASSISTANT_TASK:> Python Code: # 数値計算やデータフレーム操作に関するライブラリをインポートする import numpy as np import pandas as pd # URL によるリソースへのアクセスを提供するライブラリをインポートする。 # import urllib # Python 2 の場合 import urllib.request # Python 3 の場合 # 図やグラフを図示するためのライブラリをインポートする。 import matplotlib.pyplot as plt %matplotlib inline # 線形回帰を行なうライブラリ from sklearn...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <h3 STYLE="background Step2: <h3 STYLE="background Step3: 以上の結果は、説明変数と目的変数の関係が次の回帰式で表されることを示しています。 Step4: 結果を 2 次元座標上にプロットすると、以下のようになります。青線が回...
3,296
<ASSISTANT_TASK:> Python Code: # keras.datasets.imdb is broken in TensorFlow 1.13 and 1.14 due to numpy 1.16.3 !pip install numpy==1.16.2 # All the imports! import tensorflow as tf import numpy as np from tensorflow.keras.preprocessing import sequence from numpy import array # Supress deprecation warnings import loggi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Note Step2: Create map for converting IMDB dataset to readable reviews Step3: Data Insight Step4: Pre-processing Data Step5: Create and buil...
3,297
<ASSISTANT_TASK:> Python Code: import pandas as pd # For monitoring duration of pandas processes from tqdm import tqdm, tqdm_pandas # To avoid RuntimeError: Set changed size during iteration tqdm.monitor_interval = 0 # Register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm` # (can use `tqdm_gui`, `tq...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The idea Step2: Begin noun filtering Step3: Association Rules Mining Filtering Step4: Some more stats
3,298
<ASSISTANT_TASK:> 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 pl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Product Quantization for Model Compression Step2: Product Quantization from Scratch Step3: Encode Step4: We can calculate the potential size/...
3,299
<ASSISTANT_TASK:> Python Code: # Installing sotware prerequisites via the python package index: !pip install -U numpy matplotlib sklearn pysptools wget #Import packages # Ensure that this code works on both python 2 and python 3 from __future__ import division, print_function, absolute_import, unicode_literals # basic ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The Data Step2: Convert to H5 Step3: Extracting the data and parameters Step4: Visualize the Amplitude Data Step5: 1. Singular Value Decompo...