Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
11,800
<ASSISTANT_TASK:> Python Code: #subject lines that have dates, e.g. 12/01/99 [line for line in subjects if re.search("\d\d/\d\d/\d\d", line)] [line for line in subjects if re.search("[aeiou][aeiou][aeiou][aeiou]", line)] [line for line in subjects if re.search("F[wW]:", line)] [line for line in subjects if res.search...
<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 your own character classes Step2: metacharacters Step3: aside Step4: metacharacters 3 Step5: more metacharacters
11,801
<ASSISTANT_TASK:> Python Code: %pylab inline import numpy, pandas from rep.utils import train_test_split from sklearn.metrics import roc_auc_score data = pandas.read_csv('toy_datasets/Higgs.csv', sep='\t') labels = data['Label'].values labels = labels == 's' sample_weight = data['Weight'].values train_data, test_data,...
<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 for Higgs Boson Challenge Step2: Variables used in training Step3: Metric definition Step4: Compute threshold vs metric quality ...
11,802
<ASSISTANT_TASK:> Python Code: import string print(string.ascii_uppercase) if 'b' in string.ascii_uppercase: print("Yes, the letter is in string.ascii_uppercase") else: print("No, the string is not in string.ascii_uppercase") print(string.ascii_lowercase) print(string.whitespace) <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: Our initial example will use the uppercase letters that are in the string library. Step2: Here we will check to see if a letter is in the strin...
11,803
<ASSISTANT_TASK:> Python Code: counter = 1 while counter <= 10: print(counter) counter = counter + 1 print("end") counter = 1 product = 1 while counter <= 5: product = product * counter print("counter: ", counter) print("product: ", product) counter = counter + 1 print(product) ...
<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: Упражнение
11,804
<ASSISTANT_TASK:> Python Code: import numpy as np x = np.array([0, 1, 1, 1, 3, 1, 5, 5, 5]) y = np.array([0, 2, 3, 4, 2, 4, 3, 4, 5]) a = 1 b = 4 result = ((x == a) & (y == b)).argmax() if x[result] != a or y[result] != b: result = -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:
11,805
<ASSISTANT_TASK:> Python Code: # Run this cell to set up the notebook, but please don't change it. # These lines import the Numpy and Datascience modules. import numpy as np from datascience import * # These lines do some fancy plotting magic. import matplotlib %matplotlib inline import matplotlib.pyplot as plt plt.sty...
<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. Preliminaries Step2: Question 1.2 Step3: Question 1.3 Step4: Question 1.5 Step5: Question 1.6 Step6: Since we don't know what the popula...
11,806
<ASSISTANT_TASK:> Python Code: from __future__ import print_function, division %matplotlib inline import numpy as np import brfss import thinkstats2 import thinkplot df = brfss.ReadBrfss(nrows=None) def SampleRows(df, nrows, replace=False): indices = np.random.choice(df.index, nrows, replace=replace) sample =...
<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: Scatter plots Step2: The following function selects a random subset of a DataFrame. Step3: I'll extract the height in cm and the weight in kg ...
11,807
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_linnerud linnerud = load_linnerud() chinups = linnerud.data[:,0] plt.hist( # complete plt.hist( # complete # complete # complete plt.hist(# complete plt.hist(chinups, histtype = 'step') # this is the code for the rug plot plt.plot(chinups, np.zeros_li...
<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 1a Step2: Already with this simple plot we see a problem - the choice of bin centers and number of bins suggest that there is a 0% pro...
11,808
<ASSISTANT_TASK:> Python Code: # Author: Tommy Clausner <tommy.clausner@gmail.com> # # License: BSD (3-clause) import os import os.path as op import mne from mne.datasets import sample print(__doc__) data_path = sample.data_path() sample_dir = op.join(data_path, 'MEG', 'sample') subjects_dir = op.join(data_path, 'subj...
<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 paths Step2: Load example data Step3: Setting up SourceMorph for SourceEstimate Step4: We also need to specify the set of vertices to m...
11,809
<ASSISTANT_TASK:> Python Code: #installing pandas libraries !pip install pandas-datareader !pip install --upgrade html5lib==1.0b8 #There is a bug in the latest version of html5lib so install an earlier version #Restart kernel after installing html5lib import pandas as pd #pandas library from pandas_datareader import 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: <h2>Imports</h2> Step2: <h2>The structure of a dataframe</h2> Step3: <h3>Accessing columns and rows</h3> Step4: <h3>Getting column data</h3> ...
11,810
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from scipy.special import expit line = np.linspace(-3, 3, 100) plt.figure(figsize=(10,8)) plt.plot(line, np.tanh(line), label="tanh") plt.plot(line, np.maximum(line, 0), label="relu") plt.plot(line, expit(line), label='...
<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: For a small neural network with a single hidden layer with three nodes, the full formula for computing ŷ in the case of regression would be (whe...
11,811
<ASSISTANT_TASK:> Python Code: from numpy.linalg import pinv from Orange.classification import Learner, Model class LinearRegression(Learner): def fit(self, X, Y, W=None): coef = pinv(X.T.dot(X)).dot(X.T).dot(Y) return LinearRegressionModel(coef) class LinearRegressionModel(Model): def __init__(...
<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 that the above simplified version of linear regression does not fit the intercept and ignores instance weights. Step2: We see that the err...
11,812
<ASSISTANT_TASK:> Python Code: import yaml # Set `PATH` to include the directory containing TFX CLI and skaffold. PATH=%env PATH %env PATH=/home/jupyter/.local/bin:{PATH} !python -c "import tfx; print('TFX version: {}'.format(tfx.__version__))" !python -c "import kfp; print('KFP version: {}'.format(kfp.__version__))" ...
<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: Validate lab package version installation Step2: Note Step3: Note Step4: The config.py module configures the default values for the environme...
11,813
<ASSISTANT_TASK:> Python Code: tocrawl = [] def crawl(url): html = download(url) page = parse(html) urls = extract_links(page) tocrawl.append(urls) return tocrawl starter_url = "www.example.com" tocrawl = crawl(starter_url) while len(tocrawl) != 0: for url in tocrawl: crawl(url) #!/usr/...
<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: Evidemment c'est un tout petit peu plus compliqué que ça... Step2: Définissons ensuite l'encodage pour prendre en compte les accents Step3: un...
11,814
<ASSISTANT_TASK:> Python Code: %%writefile ComplaintDistribution.py from mrjob.job import MRJob class ComplaintDistribution(MRJob): def mapper(self, _, lines): line = lines[:30] if "Debt collection" in line: self.increment_counter('Complaint', 'Debt collection', 1) elif "Mortgage...
<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: HW 3.2 Analyze the performance of your Mappers, Combiners and Reducers using Counters Step2: Please use multiple mappers and reducers for these...
11,815
<ASSISTANT_TASK:> Python Code: import pandas as pd iowadf= pd.read_csv("Class05_iowa_data.csv") iowadf.head() # The sales data looks like it isn't a float like we want it to be (the presence of a $ in front is my clue that there may be something wrong.) Let's look at the data types to be sure. iowadf.dtypes # Sure enou...
<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 only lose 25 rows out of 13,000. I'm going to go with that- it simplifies further computations. Step2: We now want the sum of all of the Sal...
11,816
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns plt.rcParams["figure.figsize"] = (20,5) # This can be the default, or else, you can also specify this every time you generate a graph import vincent vincent.core.initialize_note...
<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 the CSV file Step2: Basic Exploration Step3: Our dataset seems really clean, without any missing values, which is wonderful! Step4: We...
11,817
<ASSISTANT_TASK:> Python Code: # Authors: Chris Holdgraf <choldgraf@gmail.com> # Jona Sassenhagen <jona.sassenhagen@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) import mne import numpy as np import matplotlib.pyplot as plt # Load the data from the internet path = mne.da...
<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 use this metadata attribute to select subsets of Epochs. This Step2: Next we'll choose a subset of words to keep. Step3: Note that trad...
11,818
<ASSISTANT_TASK:> Python Code: IMAGE_PATH = "datasets/CIFAR10" import os, subprocess from urllib.request import urlretrieve dataFile = "test.zip" if not os.path.isdir(IMAGE_PATH): os.makedirs(IMAGE_PATH) urlretrieve("https://mmlspark.azureedge.net/datasets/CIFAR10/test.zip", IMAGE_PATH + ".zip")...
<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 images are loaded from the directory (for fast prototyping, consider loading a fraction of Step2: When collected from the DataFrame, the im...
11,819
<ASSISTANT_TASK:> Python Code: plt.imshow(plt.imread('./res/find_connected.png')) plt.figure(figsize=(12,8)) plt.imshow(plt.imread('./res/fig21_1.png')) # Exercises plt.figure(figsize=(15,8)) plt.imshow(plt.imread('./res/fig21_2.png')) # Exercises plt.imshow(plt.imread('./res/fig21_4.png')) plt.imshow(plt.imread('....
<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: 21.2 Linked-list representation of disjoint sets Step2: MAKE-SET and FIND-SET requires $O(1)$ time. Step3: 21.3 Disjoint-set forests Step4...
11,820
<ASSISTANT_TASK:> Python Code: def parse(line): Parses a line from the colors dataset. items = tf.string_split([line], ",").values rgb = tf.string_to_number(items[1:], out_type=tf.float32) / 255.0 color_name = items[0] chars = tf.one_hot(tf.decode_raw(color_name, tf.uint8), depth=256) length = tf.cast(tf.sh...
<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: Case study Step7: To show the use of control flow, we write the RNN loop by hand, rather than using a pre-built RNN model. Step9: We will now ...
11,821
<ASSISTANT_TASK:> Python Code: import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG ! pip3 install -U google-cloud-storage $USER_FLAG ! pip3 install $USER kfp --upgra...
<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: Install the latest GA version of google-cloud-storage library as well. Step2: Install the latest GA version of KFP SDK library as well. Step3: ...
11,822
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt # Module with the neural net classes import DNN import Solvers N = 100 data = np.concatenate((np.random.multivariate_normal(mean=[0, 0], cov=[[0.5, 0],[0, 0.5]], size=N), np.ra...
<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 wil demonstrate the nonlinear representation capabilities fot the multilayer feedforward network with the XOR problem. First, let's create a ...
11,823
<ASSISTANT_TASK:> Python Code: import json from pybbn.graph.variable import Variable from pybbn.graph.node import BbnNode from pybbn.graph.edge import Edge, EdgeType from pybbn.graph.dag import Bbn a = BbnNode(Variable(0, 'a', ['t', 'f']), [0.2, 0.8]) b = BbnNode(Variable(1, 'b', ['t', 'f']), [0.1, 0.9, 0.9, 0.1]) bbn ...
<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: Deserializing Step2: Serde a join tree Step3: Deserializing Step4: Updating the conditional probability tables (CPTs) of a BBN nodes in a jun...
11,824
<ASSISTANT_TASK:> Python Code: import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG ! pip3 install -U google-cloud-storage $USER_FLAG if os.environ["IS_TESTING"]: ...
<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: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Step3: Before you begin Step4: Region Step5:...
11,825
<ASSISTANT_TASK:> Python Code: import arviz as az import stan import numpy as np import matplotlib.pyplot as plt # enable PyStan on Jupyter IDE import nest_asyncio nest_asyncio.apply() np.random.seed(26) xdata = np.linspace(0, 50, 100) b0, b1, sigma = -2, 1, 3 ydata = np.random.normal(loc=b1 * xdata + b0, scale=sigma)...
<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: For the example we will use a linear regression. Step3: Now we will write the Stan code, keeping in mind that it must be able to compute the po...
11,826
<ASSISTANT_TASK:> Python Code: ### import flame module from flame import Machine ### specify lattice file location lat_file = "LS1FS1_lattice.lat" ### read lattice file in with open(lat_file, 'rb') as inf: # create lattice data object M M = Machine(inf) ### Initialize simulation parameters # states 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: - Plot energy history Step2: - plot x, y centroid and rms of overall beam Step3: - python object data are easy to manage Step4: - plot beam ...
11,827
<ASSISTANT_TASK:> Python Code: a = {'x': 1, 'z': 3} b = {'y': 2, 'z': 4} # 需在两 dict 中执行查找操作 (先从 a 中找,若是找不到,再在 b 中找) from collections import ChainMap c = ChainMap(a,b) print(c['x']) print(c['y']) print(c['z']) len(c) list(c.keys()) list(c.values()) c['z'] = 10 c['w'] = 80 del c['x'] c_old = ChainMap(a,b) c_old type(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: 一个 ChainMap 接受多个 dict 将他们在逻辑上变为一个 dict 然后 这些 dict 不是真的合并在一起了 ChainMap 类只是在内部创建了一个容纳这些 dict 的 list and 重新定义了一些常用的 dict 操作来遍历这些列表 大部分 dict 都是正常使用的...
11,828
<ASSISTANT_TASK:> Python Code: from crpropa import * ## settings for MHD model (must be set according to model) filename_bfield = "clues_primordial.dat" ## filename of the magnetic field gridOrigin = Vector3d(0,0,0) ## origin of the 3D data, preferably at boxOrigin gridSize = 1024 #...
<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 make use of periodicity of the provided data grid, use Step2: to not follow particles forever, use Step3: Uniform injection Step4: Injecti...
11,829
<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.display import display def random_line(m, b, sigma, size=10): Create a line y = m*x + b + N(0,sigma**2) between x=[-1.0,1.0] Param...
<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: Line with Gaussian noise Step5: Write a function named plot_random_line that takes the same arguments as random_line and creates a random line ...
11,830
<ASSISTANT_TASK:> Python Code: %matplotlib inline from jyquickhelper import add_notebook_menu add_notebook_menu() import numpy as np l = [1, 42, 18 ] a = np.array(l) print(a) print(a.dtype) print(a.ndim) print(a.shape) print(a.size) a b = np.array(l, dtype=float) print(b) print(b.dtype) l[0] = 1.0 bb = np.array(l) 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: Numpy arrays Step2: Creation d'un array Step3: On peut indiquer explicitement le dtype lors de la création de l'array. Sinon, Numpy sélectionn...
11,831
<ASSISTANT_TASK:> Python Code: #load libraries import pandas as pd import numpy as np #Supervised learning from sklearn.model_selection import train_test_split from sklearn.svm import SVC #Load data set from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() cancer =pd.DataFrame(cancer.data) canc...
<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 overfits quite substantially, with a perfect score on the training set and only 63% accuracy on the test set. Step2: Preprocessing d...
11,832
<ASSISTANT_TASK:> Python Code: import io, os, sys, types from IPython import get_ipython from IPython.nbformat import current from IPython.core.interactiveshell import InteractiveShell def find_notebook(fullname, path=None): find a notebook, given its fully qualified name and an optional path This turns "...
<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: Import hooks typically take the form of two objects Step5: Notebook Loader Step7: The Module Finder Step8: Register the hook Step9: After th...
11,833
<ASSISTANT_TASK:> Python Code: from csp import * %psource CSP s = UniversalDict(['R','G','B']) s[5] %psource different_values_constraint %pdoc parse_neighbors %psource MapColoringCSP australia, usa, france %psource queen_constraint %psource NQueensCSP eight_queens = NQueensCSP(8) import copy class InstruCSP(CS...
<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: Review Step2: The _ init _ method parameters specify the CSP. Variable can be passed as a list of strings or integers. Domains are passed as ...
11,834
<ASSISTANT_TASK:> Python Code: %matplotlib inline from sklearn import datasets from sklearn import linear_model import matplotlib.pyplot as plt import sklearn print sklearn.__version__ # boston data boston = datasets.load_boston() y = boston.target ' '.join(dir(boston)) boston['feature_names'] regr = linear_model.Linea...
<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: 使用sklearn做logistic回归 Step2: 使用sklearn实现贝叶斯预测 Step3: naive_bayes.GaussianNB Gaussian Naive Bayes (GaussianNB) Step4: cross-validation Step5...
11,835
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nasa-giss', 'giss-e2-1h', 'land') # 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...
11,836
<ASSISTANT_TASK:> Python Code: %pylab inline # Import helper module from helpers import ex02 # Load one-way BLAST results into a data frame called data_fwd data_fwd = ex02.read_data("pseudomonas_blastp/B728a_vs_NCIMB_11764.tab") # Show first few lines of the loaded data data_fwd.head() # Show descriptive statistics 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: The first thing we do is load in the BLASTP output we generated, so that we can plot some of the key features. We do that using the ex02.read_da...
11,837
<ASSISTANT_TASK:> Python Code: from astropy.io import ascii, fits import pylab as plt %matplotlib inline from astropy import wcs import numpy as np import xidplus from xidplus import moc_routines import pickle xidplus.__path__[0] #Folder containing maps imfolder=xidplus.__path__[0]+'/../test_files/' pswfits=imfolder+'...
<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 image and catalogue filenames Step2: Load in images, noise maps, header info and WCS information Step3: Load in catalogue you want to fit ...
11,838
<ASSISTANT_TASK:> Python Code: %%writefile ../../user_models/cylinder_Bscan_2D.in #title: B-scan from a metal cylinder buried in a dielectric half-space #domain: 0.240 0.210 0.002 #dx_dy_dz: 0.002 0.002 0.002 #time_window: 3e-9 #material: 6 0 1 0 half_space #waveform: ricker 1 1.5e9 my_ricker #hertzian_dipole: z 0.040 ...
<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 differences between this input file and the one from the A-scan are the x coordinates of the source and receiver, and the commands needed to...
11,839
<ASSISTANT_TASK:> Python Code: data = pd.read_csv('bracket-05.tsv', sep='\t') data = data.\ query('rd1_win > 0').\ rename(columns=dict(rd1_win=1, rd2_win=2, rd3_win=3, rd4_win=4, rd5_win=5, rd6_win=6, rd7_win=7))\ [['team_name', 'team_seed', 1, 2, 3, 4, 5, 6, 7]] data.head() data[8] = 0 for col in range(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: The numbered columns represent the probability that a team will win in that round of the tournament. This of course means that they had to win a...
11,840
<ASSISTANT_TASK:> Python Code: #Implements functional expansions from functions.FE import FE #Evaluates accuracy in a dataset for a particular classifier from fitness import Classifier #Implements gafe using DEAP toolbox import ga from sklearn.preprocessing import MinMaxScaler import numpy as np import pandas as pd 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: Import modules from scikit-learn, numpy and pandas to help us deal with the data Step2: Load data using pandas. We will use the famous Iris Dat...
11,841
<ASSISTANT_TASK:> Python Code: !find export/probs/ %%bash LOCAL_DIR=$(find export/probs | head -2 | tail -1) BUCKET=ai-analytics-solutions-kfpdemo gsutil rm -rf gs://${BUCKET}/mlpatterns/batchserving gsutil cp -r $LOCAL_DIR gs://${BUCKET}/mlpatterns/batchserving gsutil ls gs://${BUCKET}/mlpatterns/batchserving %%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: Load model into BigQuery for batch serving Step2: Now, do it at scale, on consumer complaints about financial products and services
11,842
<ASSISTANT_TASK:> Python Code: import os import zipfile from math import sqrt import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns sns.set_style('darkgrid') %matplotlib inline # Put files in current direc...
<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: Unzipping files with house sales data Step2: Loading Sales data, Sales training data, and Sales test data Step3: Convert to DataFrame data to ...
11,843
<ASSISTANT_TASK:> Python Code: def number_to_words(n): Given a number n between 1-1000 inclusive return a list of words for the number. n=str(n) key = {1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine', 10:'ten', 11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', ...
<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: Project Euler Step2: Now write a set of assert tests for your number_to_words function that verifies that it is working as expected. Step4: No...
11,844
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import pylab # Required imports from wikitools import wiki from wikitools import category # import nltk import nltk from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords from tes...
<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. Corpus acquisition. Step2: You can try with any other categories. Take into account that the behavior of topic modelling algorithms may depe...
11,845
<ASSISTANT_TASK:> Python Code: !pip install -q opencv-python import os import tensorflow.compat.v2 as tf import tensorflow_hub as hub import numpy as np import cv2 from IPython import display import math # Load the model once from TF-Hub. hub_handle = 'https://tfhub.dev/deepmind/mil-nce/s3d/1' hub_model = hub.load(hub...
<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: 导入 TF-Hub 模型 Step4: 演示文本到视频检索
11,846
<ASSISTANT_TASK:> Python Code: a = 1 a b = 'pew' b %matplotlib inline import matplotlib.pyplot as plt from pylab import * x = linspace(0, 5, 10) y = x ** 2 figure() plot(x, y, 'r') xlabel('x') ylabel('y') title('title') show() import numpy as np num_points = 130 y = np.random.random(num_points) plt.plot(y) %%latex \be...
<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: This is some text, here comes some latex Step2: Apos? Step3: Javascript plots Step4: bokeh
11,847
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt ydata = np.genfromtxt('dataForNathan.csv', delimiter=',')[:-1] xdata = np.arange(ydata.size)+1 plt.figure(figsize=(7,7)); plt.xlim(0,64) plt.plot(xdata, ydata); plt.scatter(xdata,ydata, c='k') plt.show() import scipy.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: He is choosing to model the function as the difference of Gamma distributions
11,848
<ASSISTANT_TASK:> Python Code: import os from gensim import corpora, models %load_ext memory_profiler import scipy scipy.show_config() MODELS_DIR = "../Data/models/lda_standard" num_topics = 10 dictionary = corpora.Dictionary.load(os.path.join(MODELS_DIR,'twentyNewsGroup.dict')) corpus = corpora.MmCorpus(os.path.join(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 settings Step2: Additional parameters Step3: Testing LDA with iterations with 3 workers Step4: Number of topics Step5: Number of pas...
11,849
<ASSISTANT_TASK:> Python Code: # Install jdk8 !apt-get install openjdk-8-jdk-headless -qq > /dev/null import os # Set environment variable JAVA_HOME. os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64" !update-alternatives --set java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java !java -version # Install lat...
<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: Install Analytics Zoo Step2: Data-Parallel Pandas with XShards for Distributed Deep Learning Step3: Init Orca Context Step4: Data Preprocessi...
11,850
<ASSISTANT_TASK:> Python Code: print('"{}" = "{}"'.format('A', ord('A'))) print('"{}" = "{}"'.format('a', ord('a'))) print('"{}" = "{}"'.format(88, chr(88))) print('"{}" = "{}"'.format(112, chr(112))) for n in range(5): print(n) for char in ['p', 'y', 't', 'h', 'o', 'n']: print(char) for char in "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: To implement an ASCII version of gematria in Python, we need to turn each letter into a number and add them all together. So, to start, note th...
11,851
<ASSISTANT_TASK:> Python Code: import sympy as sy import numpy as np from sympy import * r = Symbol('r') I = integrate(exp(-2*r**2)*r**2,(r,0,+oo)) C = sqrt(1/I) print(latex(simplify(C))) E = C**2*integrate((-2*r**4+3*r**2-r)*exp(-2*r**2),(r,0,oo)) print('Expected value is %0.4f Ha.'%E) # Hydrogen atom energy equation...
<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: So the normalized 1s wavefunction is $\tilde{R}_{10}(r) = \frac{2}{\sqrt[4]{\pi}} 2^{\frac{3}{4}} e^{-r^2} = (\frac{128}{\pi}) ^ {\frac{1}{4}} e...
11,852
<ASSISTANT_TASK:> Python Code: import pandas as pd import featuretools as ft from featuretools.selection import ( remove_highly_correlated_features, remove_highly_null_features, remove_single_value_features, ) from featuretools.primitives import NaturalLanguage from featuretools.demo.flight import load_flig...
<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: Remove Highly Null Features Step2: We look at the above feature matrix and decide to remove the highly null features Step3: Notice that callin...
11,853
<ASSISTANT_TASK:> Python Code: def pretty_print_review_and_label(i): print(labels[i] + "\t:\t" + reviews[i][:80] + "...") g = open('reviews.txt','r') # What we know! reviews = list(map(lambda x:x[:-1],g.readlines())) g.close() g = open('labels.txt','r') # What we WANT to know! labels = list(map(lambda x:x[:-1].uppe...
<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: Lesson Step3: Project 1 Step4: We'll create three Counter objects, one for words from postive reviews, one for words from negativ...
11,854
<ASSISTANT_TASK:> Python Code: print("Happy birthday to you.") print("Happy birthday to you.") print("Happy birthday, dear Chris.") print("Happy birthday to you.") print("Happy birthday to you.") print("Happy birthday to you.") print("Happy birthday, dear Thomas.") print("Happy birthday to you.") def birthdaySong(nam...
<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: But what if we wanted to reuse this code to congratulate someone else, e.g. named Thomas? There's basically two (fundamentally different) approa...
11,855
<ASSISTANT_TASK:> Python Code: from enum import Enum import itertools import random from collections import Counter import numpy as np from plotting import * from multiprocessing import Pool from tqdm import tqdm_notebook %matplotlib inline class Party(Enum): D = 1 R = 2 color_trans = {Party.D:'blue', Par...
<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'll need a way to track which party the Senate & President are part of. For now, let's just stick with the two major parties and create...
11,856
<ASSISTANT_TASK:> Python Code: with open('input.txt', 'rt') as f: moves = next(f).rstrip().split(',') import re import numpy as np import copy def shuffle(p, moves): s = copy.copy(p) for move in moves: spin = re.search('s(\d+)', move) swapx = re.search('x(\d+)\/(\d+)', move) swapp = ...
<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: Test Step2: Solution Step3: Part 2 Step4: Test Step5: Solution
11,857
<ASSISTANT_TASK:> Python Code: class PixWord2Vec: # vocabulary indexing index2word = None word2indx = None # embeddings vector embeddings = None # Normailized embeddings vector final_embeddings = None # hidden layer's weight and bias softmax_weights = None softma...
<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: 設計 Graph Step3: Build Category2Vec Step4: 測試 Category Vec Step5: 開始轉換成向量 Step6: Load TagVectors Step7: 進行隨機抽樣驗證
11,858
<ASSISTANT_TASK:> Python Code: import os import numpy as np import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import Dense, Activation from keras.optimizers import SGD from keras.utils import np_utils def unpickle(file): import cPickle fo = open(file, 'rb') dict = cPickle...
<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: b) Función para escalar data entre rango (-1,1) o bien normalización. Step2: A continuación se cargará un batch del dataset y se mostrarán imág...
11,859
<ASSISTANT_TASK:> Python Code: %pylab inline #from skimage.io import imread import matplotlib.gridspec as gridspec plt.rcParams['image.interpolation'] = 'none' plt.rcParams['image.cmap'] = 'gray' figsize(4,4) size = 256 img = np.zeros((size,size), dtype=np.uint8) t = linspace(start=0, stop=50*pi, endpoint=False, num=si...
<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: Use this image with clear direction of fibers. Step3: The function we want to make better Step4: Per block optimation Step5: Threshold Step6:...
11,860
<ASSISTANT_TASK:> Python Code: # Additional Libraries %matplotlib inline import matplotlib.pyplot as plt # Import relevant libraries: import time import numpy as np import pandas as pd from sklearn.neighbors import KNeighborsClassifier from sklearn import preprocessing from sklearn.preprocessing import MinMaxScaler fro...
<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: Local, individual load of updated data set (with weather data integrated) into training, development, and test subsets. Step2: The Best RF Clas...
11,861
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib as mpl import pandas as pd import json import pandas as pd import csv import os import re import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn import svm from sklearn.linear_model 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: This is a function that we'll use later to plot the results of a linear SVM classifier Step2: Load in the sample JSON file and view its content...
11,862
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt from random import normalvariate, uniform, weibullvariate # Make several sets of data; one randomly sampled # from a normal distribution and others that aren't. n = 100 d_norm = [normalvariate(0,1) for x in range(n)] d_unif = [unifo...
<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: Make probability plots Step2: Interesting. Normal distribution follows the quantiles well and has the highest $R^2$ value, but both the uniform...
11,863
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt # import lsst sims maf modules import lsst.sims.maf import lsst.sims.maf.db as db import lsst.sims.maf.metrics as lsst_metrics import lsst.sims.maf.slicers as slicers import lsst.sims.maf.stackers as stackers import lsst.sims.maf.plots as...
<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: General Input Step2: SQL Query Step3: Metrics Step4: Slicer Step5: Plot functions and customization Step6: Bundles Step7: Plot a light cur...
11,864
<ASSISTANT_TASK:> Python Code: import usau.reports import usau.fantasy from IPython.display import display, HTML import pandas as pd pd.options.display.width = 200 pd.options.display.max_colwidth = 200 pd.options.display.max_columns = 200 def display_url_column(df): Helper for formatting url links df.url = df.url.a...
<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: Stats Quality for 2016 D-I College Nationals Step2: Since we should already have the data downloaded as csv files in this repository, we will n...
11,865
<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 # This is a bit of magic to make matplotlib figures appear inline in the notebook # rather than in a new window. %matplotlib inline plt.rcPa...
<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...
11,866
<ASSISTANT_TASK:> Python Code: import gambit gambit.__version__ g = gambit.Game.read_game("poker.efg") g g.players g.players["Alice"] g.players["Alice"].infosets g.players.chance g.players.chance.infosets g.players.chance.infosets[0].actions deal = g.players.chance.infosets[0] deal.actions["A"].prob deal.acti...
<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: Gambit version 16.0.0 is the current development version. You can get it from http Step2: Inspecting a game Step3: Gambit's .efg format is a ...
11,867
<ASSISTANT_TASK:> Python Code: %pylab inline import sklearn from sklearn.linear_model import LogisticRegression from sklearn.datasets import load_digits from sklearn.pipeline import Pipeline from sklearn.decomposition import PCA digits = load_digits() X_digits = digits.data y_digits = digits.target logistic = LogisticR...
<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: Finding the best model
11,868
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import time import machine_learning_helper as machine_learning_helper import metrics_helper as metrics_helper import sklearn.neighbors, sklearn.linear_model, sklearn.ensemble, sklearn.naive_bayes from sklearn.model_selection import KFold, train_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: Read .csv files Step2: Construct sessions data frame Step3: 1. From data frame to matrix Step4: 2. From data frame to matrix Step5: For Me...
11,869
<ASSISTANT_TASK:> Python Code: # Copyright 2019 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
<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: Running a Tapas fine-tuned checkpoint Step2: Fetch models fom Google Storage Step3: Imports Step5: Load checkpoint for prediction Step7: Pre...
11,870
<ASSISTANT_TASK:> Python Code: # Load the network. This network, while in reality is a directed graph, # is intentionally converted to an undirected one for simplification. G = cf.load_physicians_network() # Make a Circos plot of the graph from nxviz import CircosPlot c = CircosPlot(G) c.draw() # Example code. def 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: Step2: Question Step3: In reality, NetworkX already has a function that counts the number of triangles that any given node is involved in. This is pro...
11,871
<ASSISTANT_TASK:> Python Code: # As usual, a bit of setup import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver impo...
<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: Batch Normalization Step2: Batch normalization Step3: Batch Normalization Step4: Batch Normalization Step5: Fully Connected Nets with Batch ...
11,872
<ASSISTANT_TASK:> Python Code:: from sklearn.linear_model import Ridge from sklearn.metrics import mean_squared_error, mean_absolute_error # initialise & fit a ridge regression model with alpha set to 1 # if the model is overfitting, increase the alpha value model = Ridge(alpha=1) model.fit(X_train, y_train) # create 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:
11,873
<ASSISTANT_TASK:> Python Code: import numpy as np import xgboost import shap N = 40000 M = 2 # randomly create binary features for (is_young, and is_female) X = (np.random.randn(N,2) > 0) * 1 # force the first sample to be a young boy X[0,0] = 1 X[0,1] = 0 # you survive only if you are young or female y = ((X[:,0] + X...
<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 dataset following an OR function Step2: Train an XGBoost model to mimic this OR function Step3: Explain the prediction for a young bo...
11,874
<ASSISTANT_TASK:> Python Code: import sys print('{0[0]}.{0[1]}'.format(sys.version_info)) pi = 3.1416 radio = 5 area= pi * radio**2 print(area) color_list_1 = set(["White", "Black", "Red"]) color_list_2 = set(["Red", "Green"]) color_list_1 - color_list_2 path = 'C:/Users/Margarita/Documents/Mis_documentos/Biologia_...
<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: 2. Calcule el área de un circulo de radio 5 Step2: 3. Escriba código que imprima todos los colores de que están en color_list_1 y no estan pres...
11,875
<ASSISTANT_TASK:> Python Code: from itertools import accumulate, islice def cubocta(): Classic Generator: Cuboctahedral / Icosahedral #s https://oeis.org/A005901 yield 1 # nuclear ball f = 1 while True: elem = 10 * f * f + 2 # f for frequency yield elem # <--- pause /...
<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: Oregon Curriculum Network <br /> Step3: Octet Truss Step4: Each number in Pascal's Triangle may be understood as the number of unique pathways...
11,876
<ASSISTANT_TASK:> Python Code: y_sum = [0] * len(vol[0,:,0]) for i in range(len(vol[0,:,0])): y_sum[i] = sum(sum(vol[:,i,:])) ax = sns.barplot(x=range(len(y_sum)), y=y_sum, color="b") ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) from scipy.signal import argrelextrema def local_minima(a): return argr...
<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: Above, we see a histogram of y_sum that indicates that there is a local minimum at the 12th layer of y-sampling, which colocates with where we a...
11,877
<ASSISTANT_TASK:> Python Code: import math import shutil import numpy as np import pandas as pd import tensorflow as tf print(tf.__version__) tf.logging.set_verbosity(tf.logging.INFO) pd.options.display.max_rows = 10 pd.options.display.float_format = '{:.1f}'.format df = pd.read_csv("https://storage.googleapis.com/ml_...
<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: Next, we'll load our data set. Step2: Examine the data Step3: In this exercise, we'll be trying to predict median_house_value. It will be our ...
11,878
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import ipywidgets as widgets from traitlets import Unicode, validate class HelloWidget(widgets.DOMWidget): _view_name = Unicode('HelloView').tag(sync=True) _view_module = Unicode('hello').tag(sync=True) %%javascript define('hello', ["jupyter...
<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: Building a Custom Widget - Hello World Step2: sync=True traitlets Step3: Define the view Step4: Render method Step5: Test Step6: Making the...
11,879
<ASSISTANT_TASK:> Python Code: import torch as T import torch.autograd import numpy as np ''' Define a scalar variable, set requires_grad to be true to add it to backward path for computing gradients It is actually very simple to use backward() first define the computation graph, then call backward() ''' x = T.randn(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: Simplicity of using backward() Step2: The simple operations defined a forward path $z=(2x)^3$, $z$ will be the final output tensor we would lik...
11,880
<ASSISTANT_TASK:> Python Code: edges = set([(1, 2), (3, 1), (3, 2), (2, 4)]) edges = set([(1, 2), (3, 1), (3, 2), (2, 4)]) edges_list = [i[0] for i in edges] + [i[1] for i in edges] nodes = set(edges_list) edges_number = len(edges) nodes_number = len(nodes) print "Número de nodos: " + str(nodes_number) print "Número de...
<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: Ejercicios Graphs, Paths & Components Step6: Ejercicio - Matriz de Adyacencia Step12: D## Ejercicio - Sparseness Step20: En la matriz de adya...
11,881
<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,882
<ASSISTANT_TASK:> Python Code: # Import everything that we are going to need... but not more import pandas as pd import xarray as xr import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap, cm %matplotlib inline DF=pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])], ...
<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 main advantages of using xarray versus plain netCDF4 are Step2: ...or import local dataset Step3: Extract variable from dataset Step4: Ac...
11,883
<ASSISTANT_TASK:> Python Code: import scipy import numpy as np import pandas as pd import matplotlib.pyplot as plt import sklearn.cross_validation as cv # Extra plotting functionality import visplots from sklearn import preprocessing, metrics from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import 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: 2. Exploring and pre-processing data Step2: At this point, you should try to explore the first few rows of the imported wine DataFrame using th...
11,884
<ASSISTANT_TASK:> Python Code: import pandas as pd import io from scipy import integrate string = ''' Time A 2017-12-18-19:54:40 -50187.0 2017-12-18-19:54:45 -60890.5 2017-12-18-19:54:50 -28258.5 2017-12-18-19:54:55 -8151.0 2017-12-18-19:55:00 -9108.5 2017-12-18-19:55:05 -12047.0 2017...
<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,885
<ASSISTANT_TASK:> Python Code: # Import necessary packages import tensorflow as tf import tqdm import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import MNIST data so we have something for our experiments from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step6: Neural network classes for testing Step9: There are quite a few comments in the code, so those should answer most of your questions. However, l...
11,886
<ASSISTANT_TASK:> Python Code: !pip install -I "phoebe>=2.2,<2.3" %matplotlib inline import phoebe from phoebe import u # units import numpy as np import matplotlib.pyplot as plt logger = phoebe.logger() b = phoebe.default_binary() b.add_dataset('lc', times=np.linspace(0,20,501)) b.run_compute(detach=True, model='my...
<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 always, let's do imports and initialize a logger and a new Bundle. See Building a System for more details. Step2: Now we'll add datasets St...
11,887
<ASSISTANT_TASK:> Python Code: %pylab inline --no-import-all #plt.rc('text', usetex=True) plt.rcParams['figure.figsize'] = (6.0, 6.0) #plt.rcParams['savefig.dpi'] = 60 import george from george.kernels import ExpSquaredKernel, My2ExpLEEKernel, MySignificanceKernel from scipy.stats import chi2, norm length_scale_of_corr...
<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: Now lets histogram the values of the random field. Step3: Define the threshold for counting upcrossings Step4: Check the code to count upcross...
11,888
<ASSISTANT_TASK:> Python Code: # handy graph library for python import igraph # science import numpy as np from collections import defaultdict # plot things import tabulate import matplotlib.pyplot as plt %matplotlib inline # get some toy graph data so we can demonstrate these properties network = igraph.Nexus.get("kap...
<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 quick graph vocabulary refresher Step2: degree Step3: Degree centrality Step4: Eigenvector Centrality Step5: One potential problem with ei...
11,889
<ASSISTANT_TASK:> Python Code: from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection fig = plt.figure() ax = Axes3D(fig) x = [1,0,0] y = [0,1,0] z = [0,0,1] verts = [zip(x, y,z)] ax.add_collection3d(Poly3DCollection(verts, edgecolor="k", lw=5, alpha=0.4)) ax.text(1, 0, 0, "(1,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: 다음 함수는 생성된 점들을 2차원 삼각형 위에서 볼 수 있도록 그려주는 함수이다. Step2: 만약 이 문제를 단순하게 생각하여 서로 독립인 0과 1사이의 유니폼 확률 변수를 3개 생성하고 이들의 합이 1이 되도록 크기를 정규화(normalize)하면 다음...
11,890
<ASSISTANT_TASK:> Python Code: # Setup feedback system from learntools.core import binder binder.bind(globals()) from learntools.computer_vision.ex2 import * import numpy as np import tensorflow as tf import matplotlib.pyplot as plt plt.rc('figure', autolayout=True) plt.rc('axes', labelweight='bold', labelsize='large',...
<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: Apply Transformations Step2: You can run this cell to see some standard kernels used in image processing. Step3: 1) Define Kernel Step4: Now ...
11,891
<ASSISTANT_TASK:> Python Code: from pyturb.gas_models import ThermoProperties tp = ThermoProperties() print(tp.species_list[850:875]) tp.is_available('Air') from pyturb.gas_models import PerfectIdealGas from pyturb.gas_models import SemiperfectIdealGas # Air as perfect gas: perfect_air = PerfectIdealGas('Air') # Air a...
<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 Perfect and Semiperfect Ideal Gas classes Step2: To retrieve the thermodynamic properties you can print the thermo_prop from the gas Ste...
11,892
<ASSISTANT_TASK:> Python Code: import numpy as np np.set_printoptions(suppress=True, precision=1) fw = np.array([200,200,50,50,50,50,200,200]) f = np.array([fw,fw,fw,fw]) print(f) F = np.fft.fft2(f) print(F) frestaurado = np.fft.ifft2(F) print(frestaurado) Faux = np.zeros_like(F) Faux[0,0] = F[0,0] print(Faux) fr0 = 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: Aprendizados Step2: Rotação Step3: Processamento Step4: Visualização
11,893
<ASSISTANT_TASK:> Python Code: from sklearn.grid_search import GridSearchCV from sklearn.svm import SVC from sklearn.datasets import load_digits from sklearn.cross_validation import train_test_split digits = load_digits() X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target) import numpy as 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: Define parameter grid Step2: A GridSearchCV object behaves just like a normal classifier. Step3: Exercises
11,894
<ASSISTANT_TASK:> Python Code: import pixiedust pixiedust.enableJobMonitor() # @hidden_cell # Enter your S3 access key (e.g. 'A....K') s3_access_key = '...' # Enter your S3 secret key (e.g. 'S....K') s3_secret_key = '...' # Enter your S3 bucket name (e.g. 'my-source-bucket') s3_bucket = '...' # Enter your csv file nam...
<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: Configure Amazon S3 connectivity Step2: Load CSV data Step3: Explore the loaded data using PixieDust
11,895
<ASSISTANT_TASK:> Python Code: import requests from bs4 import BeautifulSoup url = "http://www.theguardian.com/discussion/p/4fqc7" r = requests.get(url) html = r.text soup = BeautifulSoup(html, "html.parser") comments = soup.select(".d-comment__main") comment_authors = soup.select(".d-comment__author") print len (comme...
<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: Extract the comments Step2: Create comment stemmer and TFIDF vectorizer Step3: Vectorize extracted comments Step4: These are the vectorized c...
11,896
<ASSISTANT_TASK:> Python Code: k = 4 for n in range(2 * k): print abs(n - k), for n in range(2 * k): print abs(n - (k - 1)), for n in range(2 * k): print abs(n - (k - 1)) + k, def row_value(k, i): i %= (2 * k) # wrap the index at the row boundary. return abs(i - (k - 1)) + k k = 5 for i in rang...
<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: Subtract $k$ from the index and take the absolute value Step2: Not quite. Subtract $k - 1$ from the index and take the absolute value Step3: G...
11,897
<ASSISTANT_TASK:> Python Code: # connect to PostgreSQL using psycopg2 # !pip install psycopg2-binary import psycopg2 # Connect to an existing database and create the test table with psycopg2.connect("dbname=yugabyte user=yugabyte host=localhost port=5433") as yb_conn: cur = yb_conn.cursor() # use this dro...
<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: Define the query to compute the histogram Step3: Fetch the histogram data into a pandas dataframe Step4: Histogram plotting
11,898
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pickle as pkl import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data') def model_inputs(real_dim, z_dim): inputs_real = tf.placeholde...
<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: Model Inputs Step2: Generator network Step3: Discriminator Step4: Hyperparameters Step5: Build network Step6: Discriminator and Generator L...
11,899
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) import os.path as op import numpy as np from numpy.random import randn from scipy import stats as stats import mne from mne import (io, spatia...
<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 Step2: Read epochs for all channels, removing a bad one Step3: Transform to source space Step4: Transform to common cortical s...