Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
11,500
<ASSISTANT_TASK:> Python Code: # Solution of the RRE def x(t,x0=3,a=10.0,mu=1.0): return (x0-a/mu)*np.exp(-t*mu)+a/mu t = np.linspace(0,3) x0list = np.array([0.5,1,15]) sns.set_palette("Reds",n_colors=3) for x0 in x0list: pl.plot(t,x(t,x0),linewidth=4) pl.title('Population numbers for different initial condition...
<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 note that there is a stationary solution, $x(t)=a/\mu$. From the exponential in the solution, we can see that this is an attracting fixed poi...
11,501
<ASSISTANT_TASK:> Python Code: #The points awarded this cell corresopnd to partial credit and/or documentation ### BEGIN SOLUTION def power(x, p=2): '''Computes x^p Args: x: input number p: input power, defaults to 2 returns: x^p as a floating point ''' return x**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: Create a function which sums the numbers between its first (inclusive) and second argument (exclusive). For example, if you pass in 3 and 6, it ...
11,502
<ASSISTANT_TASK:> Python Code: well_PE_Miss = train.loc[train["PE"].isnull(),"Well Name"].unique() well_PE_Miss train.loc[train["Well Name"] == well_PE_Miss[0]].count() train.loc[train["Well Name"] == well_PE_Miss[1]].count() (train.groupby("Well Name"))["PE"].mean() (train.groupby("Well Name"))["PE"].median() train["...
<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 two wells have all PE missed Step2: The PE of all wells have no strong variance; For now, fillin the Missing value of median Step3: ### Bu...
11,503
<ASSISTANT_TASK:> Python Code: import pandas as pd import pinkfish as pf pf.update_cache_symbols(symbols=['msft', 'orcl', 'tsla']) pf.remove_cache_symbols(symbols=['tsla']) pf.update_cache_symbols() # WARNING!!! - if you uncomment the line below, you'll wipe out # all the symbols in your cache directory #pf.remove_...
<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: Update time series for the symbols below. Step2: Remove the time series for TSLA Step3: Update time series for all symbols in the cache direct...
11,504
<ASSISTANT_TASK:> Python Code: # Imports here import numpy as np import torch.nn as nn import torch.optim as optim import torch from torchvision import datasets,transforms,utils,models import matplotlib.pyplot as plt import os import time import copy !ls -r flower_data/ data_dir = 'flower_data' train_dir = data_dir + ...
<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 the data Step2: Label mapping Step3: Building and training the classifier Step4: Save the checkpoint Step5: testing Step6: Loading the...
11,505
<ASSISTANT_TASK:> Python Code: import os.path as op import numpy as np import mne from mne.datasets import sample from mne.minimum_norm import read_inverse_operator, apply_inverse from mne.simulation import simulate_stc, simulate_evoked seed = 42 # parameters for inverse method method = 'sLORETA' snr = 3. lambda2 = 1....
<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: First, we set some parameters. Step2: Load the MEG data Step3: Estimate the background noise covariance from the baseline period Step4: Gener...
11,506
<ASSISTANT_TASK:> Python Code: %run "../src/start_session.py" %run "../src/recurrences.py" %run "../src/sums.py" from sympy.abc import i from oeis import oeis_search, ListData import knowledge sys.setrecursionlimit(10000000) s = oeis_search(id=45) s(data_only=True)#, data_representation=ListData(upper_limit=20)) with...
<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: OEIS Step2: Recurrence Step3: Unfolding Step4: Involution Step5: Subsuming Step6: We can abstract the following conjecture Step7: Instanti...
11,507
<ASSISTANT_TASK:> Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst %%bash pip freeze | grep google-cloud-bigquery==1.6.1 || \ pip install google-cloud-bigquery==1.6.1 %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight...
<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: Verify tables exist Step2: Model 4 Step3: Get training information and evaluate Step4: Now let's evaluate our trained model on our eval datas...
11,508
<ASSISTANT_TASK:> Python Code: import numpy as np # plotting and graphics settings import matplotlib.pyplot as plt %pylab inline try: import seaborn as sns # pretty graphics. not strictly necessary. sns.set_context("notebook") sns.set_style("whitegrid") except: pass # with less pretty graphics time, ...
<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 can then load the data from the text file and store each of the three columns as a vector Step2: This is not very enlightening. Of course, w...
11,509
<ASSISTANT_TASK:> Python Code: #First let's make a function def even_check(num): if num%2 ==0: return True lst =range(20) filter(even_check,lst) filter(lambda x: x%2==0,lst) <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: Step1: Now let's filter a list of numbers. Note Step2: filter() is more commonly used with lambda functions, this because we usually use filter for a ...
11,510
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import networkx as nx from netgraph import Graph fig, (ax1, ax2) = plt.subplots(1, 2) triangle = [(0, 1), (0, 2), (1, 1), (1, 2), (2, 0)] node_positions = { 0 : np.array([0.2, 0.2]), 1 : np.array([0.5, 0.8]), 2 : np.array([0.8...
<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: Node and edge label properties can also be changed individually after an
11,511
<ASSISTANT_TASK:> Python Code: from migrating_catalyst import * data = DataLoaders(loaders['train'], loaders['valid']).cuda() @before_batch_cb def cb(self, xb, yb): return (xb[0].view(xb[0].size(0), -1),),yb metrics=[accuracy,top_k_accuracy] learn = Learner(data, model, loss_func=F.cross_entropy, opt_func=Adam, ...
<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: To use it in fastai, we first convert the Catalyst dict into a DataLoaders object Step2: Using callbacks Step3: The Catalyst example also modi...
11,512
<ASSISTANT_TASK:> Python Code: # Create hidden linear model. w_true = [-0.3, 0.5] polybasis = lambda x, p: PolynomialFeatures(p).fit_transform(x) linear_model = lambda x, w=w_true: polybasis(x, len(w) - 1).dot(w).reshape(len(x), 1) utils.plot(({'x': np.linspace(-1., 1.)[:, None], 'model': linear_model},)) # Make noisy...
<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: Least squares parameter estimation Step2: More generally, the task is to estimate the model weights $\weights$ from the linear model Step3: Ba...
11,513
<ASSISTANT_TASK:> Python Code: # First check the Python version import sys if sys.version_info < (3,4): print('You are running an older version of Python!\n\n', 'You should consider updating to Python 3.4.0 or', 'higher as the libraries built for this course', 'have only been tested in...
<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: Session 4 Step2: <a name="part-1---pretrained-networks"></a> Step3: Now we can load a pre-trained network's graph and any labels. Explore the...
11,514
<ASSISTANT_TASK:> Python Code: %%cython cdef f1(int x): return x*x cpdef f2(int x): return x*x cpdef f3(int x): return f1(x) #dir() f2(3) f1(3) f3(3) %%cython cpdef fibseq(float[:] x): cdef int n cdef int i n = len(x) x[0] = 1. x[1] = 1. for i in range(2,n): x[i] = x[i...
<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: f1 is not visible since defined via "cdef" Step2: filling an numpy array Step3: basic Step4: distance function (pure python and cython)
11,515
<ASSISTANT_TASK:> Python Code: import numpy as np SECH_FWHM_CONV = 1./2.6339157938 t_width = 1.0*SECH_FWHM_CONV # [τ] print('t_width', t_width) mb_solve_json = { "atom": { "fields": [ { "coupled_levels": [[0, 1]], "rabi_freq_t_args": { "n_pi": 2.0, "centre": 0.0, ...
<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: Two-Level Step2: We'll just check that the pulse area is what we want. Step3: Solve the Problem Step4: Plot Output Step5: Analysis
11,516
<ASSISTANT_TASK:> Python Code: import synimagegen import matplotlib.pyplot as plt import numpy as np import os %matplotlib inline ground_truth,cv,x_1,y_1,U_par,V_par,par_diam1,par_int1,x_2,y_2,par_diam2,par_int2 = synimagegen.create_synimage_parameters(None,[0,1],[0,1],[256,256],dt=0.0025) frame_a = synimagegen.genera...
<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: Example 1 Step2: Example 2 Step3: Example 3
11,517
<ASSISTANT_TASK:> Python Code: %tensorflow_version 2.x import os import numpy as np import tensorflow as tf from tqdm import tqdm from matplotlib import pyplot %matplotlib inline print("Tensorflow version " + tf.__version__) WEIGHTS_FILE='./bayesian_fashionMNIST.h5' GITHUB_REPO='https://github.com/rahulremanan/python_...
<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: Specify variables Step2: Fashion MNIST dataset Step3: Define the Bayesian deep-learning model Step4: Using the TPU Step5: Train Step6: Trai...
11,518
<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') dummy_fields = ['seas...
<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 prepare the data Step2: Checking out the data Step3: Dummy variables Step4: Scaling target variables Step5: Splitting the data into...
11,519
<ASSISTANT_TASK:> Python Code: import glob # to extend file name pattern to list import cv2 # OpenCV for image processing from cv2 import aruco # to find ArUco markers import numpy as np # for matrices import matplotlib.pyplot as plt # ...
<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: Template matching Step2: Both the image used for processing and the template are converted to grayscale images to boost efficiency. Step3: Cha...
11,520
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np employments = pd.read_csv('employment_above_15.csv') employments[0:5] #Selecting a column and displaying its first 5 elements employments.get('1991')[0:5] employments.get('Country')[0:5] def max_employment(countries, employment): i = employ...
<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: Importing it takes some time Step2: 05 - NumPy Arrays Step3: Let's look at the element type of few array which numpy calls dtype Step4: |S11 ...
11,521
<ASSISTANT_TASK:> Python Code: # import os module import os os.getcwd() # The following command provides the details of the imported package definition # help(os.listdir()) # save the following code as example.py def add(a,b): return a+b # now you can import example.py # import example # example.add(5,4) import 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: User Defined Module Step2: Import with renaming Step3: from...import statement Step4: To import all definitions from the module just specify ...
11,522
<ASSISTANT_TASK:> Python Code: def add_together(one, two): one = one + two return one def mutiply_and_add(one, two): one = add_together(one, two) return one * one temparary_value = mutiply_and_add(2, 3) print(temparary_value) print(mutiply_and_add(2, 3)) number_1 = 10 number_2 = 30 print(len(str(number...
<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: Interating over a collection Step3: Iterating over a list of strings Step4: Default Parameters Step6: Bonus
11,523
<ASSISTANT_TASK:> Python Code: from ieml.usl.usl import usl u = usl("[E:.b.E:B:.- E:S:. (E:.-wa.-t.o.-' E:.-'wu.-S:.-'t.o.-',)(a.T:.-) > ! E:.l.- (E:.wo.- E:S:.-d.u.-')]") u.check() print(u) u1 = usl("[E:.b.E:B:.- E:S:. (E:.-'wu.-S:.-'t.o.-', E:.-wa.-t.o.-' )(a.T:.-) > ! E:.l.- (E:.wo.- E:S:.-d.u.-')]") u1.check() prin...
<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 ieml lexicons are stored on github, they have to be downloaded first Step2: The ieml.ieml_database.IEMLDatabase is responsible of reading a...
11,524
<ASSISTANT_TASK:> Python Code: %%bash pio init-model \ --model-server-url http://prediction-python3.community.pipeline.io \ --model-type python3 \ --model-namespace default \ --model-name python3_zscore \ --model-version v1 \ --model-path . %%bash pio predict \ --model-test-request-path ./data/test_requ...
<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: Predict with Model (CLI) Step2: Predict with Model under Mini-Load (CLI) Step3: Predict with Model (REST)
11,525
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.html import widgets from IPython.html import svgwrite from IPython.display import display s = <svg width="100" height="100"> <circle cx="50"...
<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: Interact with SVG display Step4: Write a function named draw_circle that draws a circle using SVG. Your function should take the parameters of ...
11,526
<ASSISTANT_TASK:> Python Code: import numpy as np # used for generating random numbers def int_to_big(x): if x == 0: return [0] z = [] while x > 0: t = x % 10 z.append(t) x //= 10 trim(z) return z def big_to_int(x): z, p = 0, 1 for d in x: z += p * 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: Step1: Convertion utility functions Step2: Multiplication utility functions Step3: Karatsuba's algorithm Step4: Multiplication and testing Step5: G...
11,527
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical reviews = pd.read_csv('reviews.txt', header=None) labels = pd.read_csv('labels.txt', header=None) from collections import Counter total_counts = Counter() for idx,...
<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: Preparing the data Step2: Counting word frequency Step3: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in...
11,528
<ASSISTANT_TASK:> Python Code: # Start pylab inline mode, so figures will appear in the notebook %matplotlib inline import numpy as np # Generating a random array X = np.random.random((3, 5)) # a 3 x 5 array print(X) # Accessing elements # get a single element print(X[0, 0]) # get a row print(X[1]) # get a column pri...
<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: Numpy Arrays Step2: There is much, much more to know, but these few operations are fundamental to what we'll Step3: Matplotlib Step4: There a...
11,529
<ASSISTANT_TASK:> Python Code: n = 10000 steps_to_exit = [] for i in range(n): x = 0 steps = 0 while -7 < x < 7: x += np.random.choice([-1, 1]) # step left or right steps += 1 steps_to_exit.append(steps) print("Gemiddeld aantal stappen tot suiker: {:.3f}".format(mean(steps_to_exit)...
<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: Oefening 2 Step2: Oefening 3 Step3: Oefening 4 Step4: Met behulp van Monte Carlo simulatie kun je de integraal wel vrij eenvoudig benaderen. ...
11,530
<ASSISTANT_TASK:> Python Code: from IPython.display import Image from IPython.core.display import HTML from rsplib.processing import RSPSource, StreamReasoner jasper = StreamReasoner("http://jasper", 8183); jasper.status() jasper.register_stream("AarhusTrafficData158505", "http://aarhustrafficdata158505:4001/sgraph"...
<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 one we assume that RDF Stream are up and running from Part 1. If you did not followed part one please follow the link below and complete the...
11,531
<ASSISTANT_TASK:> Python Code: import tensorflow as tf a = tf.constant([2]) b = tf.constant([3]) c = tf.add(a,b) session = tf.Session() result = session.run(c) print(result) session.close() with tf.Session() as session: result = session.run(c) print(result) Scalar = tf.constant([2]) Vector = tf.constant(...
<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: <a id="ref3"></a> Step2: After that, let's make an operation over these variables. The function tf.add() adds two elements (you could also use ...
11,532
<ASSISTANT_TASK:> Python Code: # -*- coding: utf-8 -*- import os import re import time import codecs import argparse TIME_FORMAT = '%Y-%m-%d %H:%M:%S' BASE_FOLDER = "C:/Users/sethf/source/repos/chinesepoem/" # os.path.abspath(os.path.dirname(__file__)) DATA_FOLDER = os.path.join(BASE_FOLDER, 'data') DEFAULT_FIN = os.pa...
<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: 分词不是很成功,我们转向直接用汉字字符来代替分段,我们保留标点符号
11,533
<ASSISTANT_TASK:> Python Code: a = spot.translate('a U b U c') a.show('.#') a.highlight_edges([2, 4, 5], 1) a.highlight_edge(6, 2).highlight_states((0, 1), 0) print(a.to_str('HOA', '1')) print() print(a.to_str('HOA', '1.1')) b = spot.translate('X (F(Ga <-> b) & GF!b)'); b r = b.accepting_run(); r r.highlight(5) # ...
<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 # option of print_dot() can be used to display the internal number of each transition Step2: Using these numbers you can selectively hightl...
11,534
<ASSISTANT_TASK:> Python Code: def build_dictionaries(mess): discharge, charge, impedance = {}, {}, {} for i, element in enumerate(mess): step = element[0][0] if step == 'discharge': discharge[str(i)] = {} discharge[str(i)]["amb_temp"] = str(element[1][0][0]) ...
<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: Save as json Step2: Loop through all files Step3: 2. Example of loading and plotting impedance data Step4: Plot
11,535
<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: 使用 Keras 和 Tensorflow Hub 对电影评论进行文本分类 Step2: 下载 IMDB 数据集 Step3: 探索数据 Step4: 我们再打印下前十个标签。 Step5: 构建模型 Step6: 现在让我们构建完整模型: Step7: 层按顺序堆叠以构建分...
11,536
<ASSISTANT_TASK:> Python Code: import dowhy from dowhy import CausalModel from rpy2.robjects import r as R %load_ext rpy2.ipython import numpy as np import pandas as pd import graphviz import networkx as nx np.set_printoptions(precision=3, suppress=True) np.random.seed(0) def make_graph(adjacency_matrix, labels=None)...
<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: Utility function Step2: Experiments on the Auto-MPG dataset Step3: Causal Discovery with Causal Discovery Tool (CDT) Step4: As you can see, n...
11,537
<ASSISTANT_TASK:> Python Code: from __future__ import print_function from IPython.display import Image import base64 Image(data=base64.decodestring("iVBORw0KGgoAAAANSUhEUgAAAMYAAABFCAYAAAARv5krAAAYl0lEQVR4Ae3dV4wc1bYG4D3YYJucc8455yCSSIYrBAi4EjriAZHECyAk3rAID1gCIXGRgIvASIQr8UTmgDA5imByPpicTcYGY+yrbx+tOUWpu2e6u7qnZ7qXVFP...
<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: We're going to be building a model that recognizes these digits as 5, 0, and 4. Step3: Working with the images Step4: The first 10 pixels are ...
11,538
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.html import widgets from IPython.display import display, SVG s = ' <svg width="100" height="100"> <circle cx="50" cy="50" r="20" fill="aquamari...
<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: Interact with SVG display Step3: Write a function named draw_circle that draws a circle using SVG. Your function should take the parameters of ...
11,539
<ASSISTANT_TASK:> Python Code: import os CWD = os.getcwd() import os import girder_client from pandas import read_csv from histomicstk.annotations_and_masks.polygon_merger import Polygon_merger from histomicstk.annotations_and_masks.masks_to_annotations_handler import ( get_annotation_documents_from_contours, ) AP...
<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. Connect girder client and set parameters Step2: 2. Polygon merger Step3: Required arguments for initialization Step4: maskpaths Step5: No...
11,540
<ASSISTANT_TASK:> Python Code: # import requirments from IPython.display import Image from IPython.display import display from IPython.display import HTML from datetime import * import json from copy import * from pprint import * import pandas as pd import numpy as np import matplotlib.pyplot as plt import json from g...
<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: JS with IPython? Step2: Python data | D3 Viz Step3: Passing data from IPython to JS Step6: Passing data from JS to IPython Step7: Click "Set...
11,541
<ASSISTANT_TASK:> Python Code: class Dog: def __init__(self, name): self.age = 0 self.name = name self.noise = "Woof!" self.food = "dog biscuits" def make_sound(self): print(self.noise) def eat_food(self): print("Eating " + self.food + ".") ...
<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 the above examples, it becomes clear that there is much repetition, and we can make the code more compact. Let us abstract common functionali...
11,542
<ASSISTANT_TASK:> Python Code: import numpy as np from sklearn.neural_network import MLPRegressor from sklearn import preprocessing from sklearn.cross_validation import train_test_split import matplotlib.pyplot as plt import matplotlib.patches as mpatches from sklearn.metrics import r2_score # in order to test the resu...
<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: Importing preprocessing data Step2: Sorting out data (for plotting purposes) Step3: Artificial Neural Network (Gridsearch, DO NOT RUN) Step4:...
11,543
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 1 %matplotlib inline from pygsf.geometries.shapes.space3d import * p1 = Point3D(1.0, 2.4, 0.2) # definition of a PPoint3Doint instance p2 = Point3D(0.9, 4.2, 10.5) p1.distance(p2) # 3D distance between two points pl1 = CPlane3D.fromPoints(Point3D(0,...
<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. Introduction Step2: We import all classes/methods from the geometry sub-module Step3: 2. Basic spatial data types Step4: When considering ...
11,544
<ASSISTANT_TASK:> Python Code: # Useful Functions def mode(l): # Count the number of times each element appears in the list counts = {} for e in l: if e in counts: counts[e] += 1 else: counts[e] = 1 # Return the elements that appear the most times ...
<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: Exercise 1 Step3: b. Mean of returns Step4: Exercise 2 Step5: b. Median of the returns. Step6: Exercise 3 Step7: b. Mode of...
11,545
<ASSISTANT_TASK:> Python Code: import warnings from sklearn.exceptions import ConvergenceWarning warnings.filterwarnings("ignore", category=ConvergenceWarning) import itertools import time import numpy as np import pandas as pd from sklearn import model_selection from sklearn import linear_model from sklearn import met...
<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: Prepare Data Step2: Prepare Hyperparameters Step3: Run Validation Step4: Pick the best hyperparameters and train the full data Step5: Calcul...
11,546
<ASSISTANT_TASK:> Python Code: #Verify we are in the lesson1 directory %pwd %matplotlib inline import os, sys sys.path.insert(1, os.path.join(sys.path[0], '../utils')) from utils import * from vgg16 import Vgg16 from PIL import Image from keras.preprocessing import image from sklearn.metrics import confusion_matrix cu...
<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 validation set and sample Step3: This was original output Step4: Training & 10% for Validation numbers Step5: Finetuning ...
11,547
<ASSISTANT_TASK:> Python Code: ## only needed for plotting in a jupyter notebook. %matplotlib inline ## Code Block 1 import copy import numpy as np from matplotlib import pyplot as plt from landlab import imshow_grid from landlab.components import OverlandFlow, FlowAccumulator from landlab.io import read_esri_ascii ##...
<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 we import the data for the watershed we want to route flow on. You will want to change this code block for the different scenarios. Initiall...
11,548
<ASSISTANT_TASK:> Python Code: import o2sclpy import matplotlib.pyplot as plot import numpy import sys plots=True if 'pytest' in sys.modules: plots=False link=o2sclpy.linker() link.link_o2scl() fc=o2sclpy.find_constants(link) ħc=fc.find_unique('ħc','MeV*fm') print('ħc = %7.6e\n' % (ħc)) cu=link.o2scl_settings.ge...
<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: Link the O$_2$scl library Step2: Get the value of $\hbar c$ from an O$_2$scl find_constants object Step3: Get a copy (a pointer to) the O$_2$s...
11,549
<ASSISTANT_TASK:> Python Code: import stable_baselines stable_baselines.__version__ import os import numpy as np import matplotlib.pyplot as plt import seaborn as sns import gym from stable_baselines.common.policies import MlpPolicy from stable_baselines.common.vec_env import DummyVecEnv from stable_baselines import 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: Import Policy, RL agent, ... Step3: Define a Callback Function Step4: Create and wrap the environment Step5: Define and train the PPO agent S...
11,550
<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 ...
<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...
11,551
<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: Ragged Tensors Step2: Overview Step3: There are also a number of methods and operations that are Step4: And just like normal tensors, you can...
11,552
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline import plotly.tools as tls import plotly.plotly as py import cufflinks as cf import plotly plotly.offline.init_notebook_mode() cf.offline.go_offline() df = 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: The previous import code requires that you have pandas, numpy and matplotlib installed. If you are using conda Step2: Import data file with pan...
11,553
<ASSISTANT_TASK:> Python Code: #--- Libraries import pandas as pd # stats packages import numpy as np # linear algebra packages import matplotlib.pyplot as plt # ploting packages import seaborn as sns # more plotting routines from scipy.stats import beta # funti...
<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: Example Step2: Extended sampling
11,554
<ASSISTANT_TASK:> Python Code: # %load partSix.py # Neural Networks Demystified # Part 6: Training # # Supporting code for short YouTube series on artificial neural networks. # # Stephen Welch # @stephencwelch ## ----------------------- Part 1 ---------------------------- ## import numpy as np # X = (hours sleeping, ho...
<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: &#9989; DO THIS Step2: 2. Modify code to be more flexible Step3: 3. Use our ANN on the "Digits" dataset. Step5: The following is copied and p...
11,555
<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: tf.function으로 성능 향상하기 Step2: 에러 출력을 위한 헬퍼 함수를 정의합니다 Step3: 기초 Step4: 다른 함수 내부에 사용할 수 있습니다. Step5: tf.function은 즉시 실행 모드 보다 빠릅니다. 특히 그래프에 작은 ...
11,556
<ASSISTANT_TASK:> Python Code: #Load the necessary modules from mechanize import Browser import pandas as pd from IPython.core.display import HTML import requests def extract_sub_string(string, start, finish): extract a substring between the 'start' substring and the first occurence of 'finish' substring afte...
<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: We need a function to parse the HTML data after extracting the result. Step3: Now we extract the result pages against each of the id(1 to 66000...
11,557
<ASSISTANT_TASK:> Python Code: from nipype import Function def square_func(x): return x ** 2 square = Function(["x"], ["f_x"], square_func) square.run(x=2).outputs.f_x from nipype import MapNode square_node = MapNode(square, name="square", iterfield=["x"]) square_node.inputs.x = [0, 1, 2, 3] square_node.run().out...
<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 see that this function just takes a numeric input and returns its squared value. Step2: What if we wanted to square a list of numbers? We co...
11,558
<ASSISTANT_TASK:> Python Code: from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm vgg_dir = 'tensorflow_vgg/' # Make sure vgg exists if not isdir(vgg_dir): raise Exception("VGG directory doesn't exist!") class DLProgress(tqdm): last_block = 0 def hook(self, block_...
<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: Flower power Step2: ConvNet Codes Step3: Below I'm running images through the VGG network in batches. Step4: Building the Classifier Step5: ...
11,559
<ASSISTANT_TASK:> Python Code: %matplotlib inline # standard imports import numpy as np import matplotlib.pyplot as plt import skrf as rf rf.stylely() P_f = 1 # forward power in Watt Z = 50 # source internal impedance, line characteristic impedance and load impedance L = 10 # line length in [m] freq = rf.Frequency(...
<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: A simple transmission line Step2: Assuming the source generates an input power of $P_f$ with a phase $\phi$, with such a line the voltage and c...
11,560
<ASSISTANT_TASK:> Python Code: import seaborn as sns import metapack as mp import pandas as pd import numpy as np import matplotlib.pyplot as plt from IPython.display import display from publicdata.chis import * %matplotlib inline sns.set_context('notebook') idx = pd.IndexSlice # Convenience redefinition. #pkg = mp.j...
<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: RASP Diabetes Rates Step3: Poverty, Age and Race Step4: Compare to CHIS Step5: AskCHIS, By Race, 55-64 Step6: AskCHIS, By Race, 55-64, Male ...
11,561
<ASSISTANT_TASK:> Python Code: # Create a list of countries, then print the results allies = ['USA','UK','France','New Zealand', 'Australia','Canada','Poland']; allies # Print the length of the list len(allies) # Add an item to the list, then print the results allies.append('China'); allies # Sort list, then ...
<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: Tuples Step2: Dictionaries Step3: Sets
11,562
<ASSISTANT_TASK:> Python Code: ### Imports from smact import Element, element_dictionary, ordered_elements from smact.screening import smact_filter from datetime import datetime import itertools import multiprocessing all_el = element_dictionary() # A dictionary of all element objects # Say we are just interested in...
<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 define the elements we are interested in Step2: We will investiage ternary M1-M2-O combinations exhaustively, where M1 and M2 are different ...
11,563
<ASSISTANT_TASK:> Python Code: import em1ds as zpic #v_the = 0.001 v_the = 0.02 #v_the = 0.20 electrons = zpic.Species( "electrons", -1.0, ppc = 64, uth=[v_the,v_the,v_the]) sim = zpic.Simulation( nx = 500, box = 50.0, dt = 0.0999/2, species = electrons ) sim.filter_set("sharp", ck = 0.99) #sim.filter_set("gaussian", 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: We run the simulation up to a fixed number of iterations, controlled by the variable niter, storing the value of the EM field $E_z$ at every tim...
11,564
<ASSISTANT_TASK:> Python Code: import numpy as np np.__version__ __author__ = "kyubyong. kbpark.linguist@gmail.com. https://github.com/kyubyong" x = np.array([0., 1., 30, 90]) print "sine:", np.sin(x) print "cosine:", np.cos(x) print "tangent:", np.tan(x) x = np.array([-1., 0, 1.]) print "inverse sine:", np.arcsin(x2...
<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: Trigonometric functions Step2: Q2. Calculate inverse sine, inverse cosine, and inverse tangent of x, element-wise. Step3: Q3. Convert angles f...
11,565
<ASSISTANT_TASK:> Python Code: import pandas as pd df=pd.read_csv('https://raw.githubusercontent.com/' 'sassoftware/sas-viya-programming/master/data/cars.csv') df.head(10) df.dtypes df[['MSRP','Horsepower']].describe() df.mean() subdf=df[['Make','Model','Horsepower']] subdf.head(15) df=df.set_index...
<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 that reads CSV files into DataFrames is called read_csv. In the simplest form, you supply it with a filename or URL. The cars data ...
11,566
<ASSISTANT_TASK:> Python Code: if 2 + 3 == 5: x = 5 + 3 mensaje = "Verdadero!" else: x = 5 - 3 mensaje = "Falso!" print(x) print(mensaje) type(True) type(5) type(3.1416) lista_vacia = [] print(lista_vacia) #O equivalentemente lista_vacia = list() print(lista_vacia) semana = ["Lunes", "Martes", ...
<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: De esta manera, Python estandariza el aspecto del código desde la definición del lenguaje. Step2: Los operadores para variables booleanas son s...
11,567
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Joan Massich <mailsik@gmail.com> # # License: BSD Style. import os.path as op import mne from mne.channels.montage import get_builtin_montages from mne.datasets import fetch_fsaverage from mne.viz import set_3d_title, ...
<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: Check all montages against a sphere Step2: Check all montages against fsaverage
11,568
<ASSISTANT_TASK:> Python Code:: from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(ds.data, ds.target, test_size = 0.20) <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:
11,569
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.linear_model import Ridge from semana2_datos import * X_1 = np.array([[1,x] for x, y in data_1]) Y_1 =...
<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: Dataset Step2: Gráficos Step3: Modelo a partir de la ecuación normal de mínimos cuadrados Step4: Ahora, graficamos la recta contra los datos ...
11,570
<ASSISTANT_TASK:> Python Code: import pandas as pd pd? pd.Categorical cdr = pd.read_excel('data/CDR_data.xlsx', dtype={0:str, 1:str}) cdr.head() cdr["Direction"].value_counts() cdr.loc[cdr["Direction"] == "Incoming", "Dir"] = "->" cdr.loc[cdr["Direction"] == "Missed", "Dir"] = "-X" cdr['Call'] = cdr['Out'] + cdr['Di...
<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: Interaktive Hilfe Step2: Die weitere Funktionalität der Pandas-Bibliothek können wir erkunden, indem wir die Methoden von Pandas ansehen. Dazu ...
11,571
<ASSISTANT_TASK:> Python Code: import spot from spot.seminator import seminator from spot.jupyter import display_inline import buddy spot.setup(show_default=".n") aut1 = spot.automaton(HOA: v1 States: 3 Start: 0 AP: 1 "a" Acceptance: 1 Inf(0) --BODY-- State: 0 [0] 0 [!0] 1 [0] 2 State: 1 [!0] 1 [0] 0 {0} State: 2 [0]...
<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: We first create an example automaton using HOA. Step3: The following semi-deterministic automata demonstrate three strategies to "cut", i.e., w...
11,572
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import graphviz from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import mean_squared_error as mse from sklearn.model_selection import cross_val_score from sklearn.model_selectio...
<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 preprocessing Step2: Regression tree Step3: Randomly defined train and test set Step4: Know, we want to define the max_depht parameter t...
11,573
<ASSISTANT_TASK:> Python Code: import pandas as pd #PandasPandas %matplotlib inline import matplotlib.pyplot as plt import numpy as np print('PandaPandaPanda ', pd.__version__) df=pd.read_csv('NHLQUANT.csv') plt.plot(df.index,df['Grit']) df.head(10) df.mean() pd.to_numeric(df, errors='ignore') y=df["Age"] z=df["Gri...
<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 has Grit? Step2: AHHH Step3: This is the way my quantitative data looks. Most of the column headers are self explanatory, but i'll go into...
11,574
<ASSISTANT_TASK:> Python Code: import iris import numpy as np a1b = iris.load_cube(iris.sample_data_path('A1B_north_america.nc')) e1 = iris.load_cube(iris.sample_data_path('E1_north_america.nc')) print(e1.summary(True)) print(a1b) scenario_difference = a1b - e1 print(scenario_difference) # # edit space for user code ...
<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: 6.1 Cube Arithmetic<a id='arithmetic'></a> Step2: Notice that the resultant cube's name is now unknown. Also, the resultant cube's attributes ...
11,575
<ASSISTANT_TASK:> Python Code: import numpy as np # From Python lists or iterators n1 = np.array( [0,1,2,3,4,5,6] ) n2 = np.array( range(6) ) # Using numpy iterators n3 = np.arange( 10, 20, 0.1) n3 <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: Step1: Vector creation
11,576
<ASSISTANT_TASK:> Python Code: import loman comp = loman.Computation() holdings = Type,Symbol,Qty,CostBasis Equity,AVGO,126,22680 Equity,EVHC,349,22685 Equity,STT,287,22673 Equity,DAL,454,22700 Equity,DY,283,22640 Future,ESM7,-1,0 Cash,USD,2000, comp.add_node('holdings', value=holdings) from io import StringIO import...
<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: The first thing we shall need is holdings data. For this example, we assume that holdings data is provided in a CSV format, and insert that CSV ...
11,577
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from numba import jit import math import dbscanf2py # Import the extension module file dbscanf2py.so # A pure python funcion def sum_0(arr): M, N = arr.shape result = 0 for i in range(M): for j in ...
<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: Sum function Step2: Let's %timeit Step3: Factorial functions Step4: Let's %timeit Step7: Dbscan clustering algorithm Step8: Dbscan with F2P...
11,578
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_boston bunch = load_boston() print(bunch.DESCR) X, y = pd.DataFrame(data=bunch.data, columns=bunch.feature_names.astype(str)), bunch.target X.head() SEED = 22 np.random.seed = SEED from sklearn.model_selection import train_test_split X_train, X_test, y_...
<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: Измерять качество будем с помощью метрики среднеквадратично...
11,579
<ASSISTANT_TASK:> Python Code: import pandas as pd # For data frames. import matplotlib.pyplot as plt # For plotting. from skidl.pyspice import * # For describing circuits and interfacing to ngspice. !ls -F ~/tmp/skywater-pdk/libraries/sky130_fd_pr/latest/cells/ !ls -F ~/tmp/skywater-pdk/libraries/...
<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: Getting the Skywater PDK Step2: For my purposes, I only needed a simple NFET and PFET to build some logic gates. I figured 1.8V versions of the...
11,580
<ASSISTANT_TASK:> Python Code: from __future__ import division, print_function %matplotlib inline #path = "data/state/" path = "data/state/sample/" from importlib import reload # Python 3 import utils; reload(utils) from utils import * from IPython.display import FileLink batch_size=64 batches = get_batches(path+'tra...
<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: Setup batches Step2: Rather than using batches, we could just import all the data into an array to save some processing time. (In most examples...
11,581
<ASSISTANT_TASK:> Python Code: def search(start, goal, next_states): Frontier = { start } Visited = set() Parent = { start: start } while Frontier: NewFrontier = set() for s in Frontier: for ns in next_states(s): if ns not in Visited and ns not in Frontier:...
<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: Given a state and a parent dictionary Parent, the function path_to returns a path leading to the given state. Step2: Display Code Step3: The f...
11,582
<ASSISTANT_TASK:> Python Code: import numpy as np from numba import vectorize, jit, float64 from quantecon.util import tic, toc import matplotlib.pyplot as plt α = 4 n = 200 x = np.empty(n) x[0] = 0.2 for t in range(n-1): x[t+1] = α * x[t] * (1 - x[t]) plt.plot(x) plt.show() def quad(x0, n): x = x0 ...
<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: Problem 1 Step2: Here's a typical time series Step3: Here's a function that simulates for n periods, starting from x0, and returns only the fi...
11,583
<ASSISTANT_TASK:> Python Code: #$HIDE_INPUT$ import pandas as pd ks = pd.read_csv('../input/kickstarter-projects/ks-projects-201801.csv', parse_dates=['deadline', 'launched']) ks.head(6) print('Unique values in `state` column:', list(ks.state.unique())) # Drop live projects ks = ks.query('state != "l...
<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 state column shows the outcome of the project. Step2: Using this data, how can we use features such as project category, currency, funding ...
11,584
<ASSISTANT_TASK:> Python Code: # Necessary imports import time from IPython import display import numpy as np from matplotlib.pyplot import imshow from PIL import Image, ImageOps import tensorflow as tf %matplotlib inline from tensorflow.examples.tutorials.mnist import input_data # Read the mnist dataset mnist = input_...
<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: Our feed forward neural network will look very similar to our softmax classifier. However, now we have multiple layers and non-linear activation...
11,585
<ASSISTANT_TASK:> Python Code: import shap import transformers import nlp import torch import numpy as np import scipy as sp # load a BERT sentiment analysis model tokenizer = transformers.DistilBertTokenizerFast.from_pretrained("distilbert-base-uncased") model = transformers.DistilBertForSequenceClassification.from_pr...
<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: Single instance text plot Step2: Multiple instance text plot Step3: Summarizing text explanations Step4: Note that how you summarize the impo...
11,586
<ASSISTANT_TASK:> Python Code: # These are the libraries will be useing for this lab. import torch import matplotlib.pylab as plt import torch.functional as F # Create a tensor x x = torch.tensor(2.0, requires_grad = True) print("The tensor x: ", x) # Create a tensor y according to y = x^2 y = x ** 2 print("The resu...
<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: <!--Empty Space for separating topics--> Step2: Then let us create a tensor according to the equation $ y=x^2 $. Step3: Then let us take the d...
11,587
<ASSISTANT_TASK:> Python Code: print(__doc__) import numpy as np np.random.seed(1234) import matplotlib.pyplot as plt from skopt.space import Space from skopt.sampler import Sobol from skopt.sampler import Lhs from skopt.sampler import Halton from skopt.sampler import Hammersly from skopt.sampler import Grid from scipy...
<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: Random sampling Step2: Sobol Step3: Classic latin hypercube sampling Step4: Centered latin hypercube sampling Step5: Maximin optimized hyper...
11,588
<ASSISTANT_TASK:> Python Code: %%bash pull_force_overwrite_local %%html <iframe width=800 height=600 src="http://pipeline.io"></iframe> import requests url = 'http://169.254.169.254/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip' headers = {'Metadata-Flavor': 'Google'} r = requests.get(...
<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: PipelineAI Step2: All Code in GitHub Repo Step3: Get Allocation Index Step4: Helper Scripts Step5: Find Script from Anywhere Step6: Show pu...
11,589
<ASSISTANT_TASK:> Python Code: %matplotlib inline from __future__ import absolute_import from __future__ import division from __future__ import print_function import edward as ed import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from edward.models import Normal plt.style.use('ggplot') def build...
<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: First, simulate a toy dataset of 50 observations with a cosine relationship. Step2: Next, define a two-layer Bayesian neural network. Here, we ...
11,590
<ASSISTANT_TASK:> Python Code: import pandas as pd import matplotlib.pyplot as plt import datetime import pinkfish as pf import strategy # format price data pd.options.display.float_format = '{:0.2f}'.format %matplotlib inline # set size of inline plots '''note: rcParams can't be in same cell as import matplotlib or...
<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 global data Step2: Run Strategy Step3: View logs Step4: Generate strategy stats - display all available stats Step5: Equity curve Step6...
11,591
<ASSISTANT_TASK:> Python Code: transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils....
<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: Define a Neural Network Step2: Define a Loss function and optimizer Step3: Train the network Step4: Test the network on the test data Step5: ...
11,592
<ASSISTANT_TASK:> Python Code: # Import statements from pymatgen import Structure, Lattice, MPRester, Molecule from pymatgen.analysis.adsorption import * from pymatgen.core.surface import generate_all_slabs from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from matplotlib import pyplot as plt %matplotlib inline...
<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 create a simple fcc structure, generate it's distinct slabs, and select the slab with a miller index of (1, 1, 1). Step2: We make an instanc...
11,593
<ASSISTANT_TASK:> Python Code: conda update --all conda create -n fauenv python=3 conda info -e activate fauenv conda install -n fauenv numpy scipy matplotlib scikit-learn scikit-image ipython ipython-notebook conda install -n fauenv nose pip anaconda-client pillow ujson flask jinja2 natsort joblib numba pyside ...
<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: A new environment capsule with preset libraries installed for one or more of your projects can be created. fauenv is the name of the new python ...
11,594
<ASSISTANT_TASK:> Python Code: print x type(x) y=np.ones((2,3)) print y z=np.arange(2,8,1) alpha=np.reshape(z,(3,2)) print alpha beta= np.random.randn(3,4) print beta gamma=beta*2.0 print gamma a=[3,4,5] a=np.array(a) type(a) a=np.random.randint(0,10,(2,3)) b=np.random.randint(0,10,(2,3)) print a print b print "eleme...
<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: I need a matrix like this Step2: np array operator Step3: Sliccing Step4: Goto opencv/build/python/2.7 folder.
11,595
<ASSISTANT_TASK:> Python Code: work_directory_name = 'kubeflow' ! mkdir -p $work_directory_name %cd $work_directory_name ## Download kfctl v0.7.0 ! curl -LO https://github.com/kubeflow/kubeflow/releases/download/v0.7.0/kfctl_v0.7.0_linux.tar.gz ## Unpack the tar ball ! tar -xvf kfctl_v0.7.0_linux.tar.gz ## Creat...
<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: Download kfctl Step2: If you are using AI Platform Notebooks, your environment is already authenticated. Skip the following cell. Step3: Set u...
11,596
<ASSISTANT_TASK:> Python Code: from pomegranate import * import numpy as np %pylab inline rigged = State( DiscreteDistribution({'H': 0.8, 'T': 0.2}), name="rigged" ) unrigged = State( DiscreteDistribution({'H': 0.5, 'T': 0.5}), name="unrigged" ) non_cheater = HiddenMarkovModel( name="non-cheater" ) non_cheater.add_st...
<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 start by creating our hmm's. Since this is a simple example, we will only have 2 states, rigged and unrigged, with discrete distributions....
11,597
<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: TFX — Running a simple pipeline manually in a Colab Notebook Step2: Import packages Step3: Check the versions Step4: Download example data St...
11,598
<ASSISTANT_TASK:> Python Code: ## Fake dataset: class Sampler: def __init__(self, prob_table): total_prob = 0.0 if type(prob_table) is dict: for key, value in prob_table.items(): total_prob += value elif type(prob_table) is list: prob_table_gen = {} ...
<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: Parts of Speech Step2: Simple Grammar Step4: Utilities Step5: Create a Mapping from numbers to words Step6: To send our sentences in one big...
11,599
<ASSISTANT_TASK:> Python Code: %matplotlib inline %load_ext autoreload %autoreload 2 import os, sys, time import pickle as pkl import numpy as np import pandas as pd from sklearn.base import BaseEstimator from sklearn.linear_model import LogisticRegression from sklearn.multiclass import OneVsRestClassifier 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: Load data. Step2: Feature normalisation. Step3: Naive baseline Step6: Binary relevance baseline Step7: Cross validation according to F1. Ste...