Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
5,400
<ASSISTANT_TASK:> Python Code: # Import relevant modules %matplotlib inline %load_ext autoreload %autoreload 2 import numpy as np import matplotlib.pyplot as plt from matplotlib import rcParams from NPTFit import psf_correction as pc # Module for determining the PSF correction from __future__ import print_function pc_...
<SYSTEM_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 Step4: Example 4
5,401
<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: Eager execution basics Step2: Tensors Step3: Each Tensor has a shape and a datatype Step4: The most obvious differences between NumPy arrays ...
5,402
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd # data package import matplotlib.pyplot as plt # graphics import datetime as dt # date tools, used to note current date # these are new import os # operating system tools (check files) import requests,...
<SYSTEM_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=movielens></a> Step2: Exercise. Something to do together. suppose we wanted to save the files on our computer. How would we do it? Woul...
5,403
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import scipy as sp import matplotlib as mpl import matplotlib.cm as cm import matplotlib.pyplot as plt import pandas as pd pd.set_option('display.width', 500) pd.set_option('display.max_columns', 100) pd.set_option('display.notebook_repr_html', True) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Using sklearn Step2: Remember that the form of data we will use always is Step3: In the Linear Regression Mini Project, the last (extra credit...
5,404
<ASSISTANT_TASK:> Python Code: with open('/resources/data/Example2.txt','w') as writefile: writefile.write("This is line A") with open('/resources/data/Example2.txt','r') as testwritefile: print(testwritefile.read()) with open('/resources/data/Example2.txt','w') as writefile: writefile.write("This is line...
<SYSTEM_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 read the file to see if it worked Step2: We can write multiple lines Step3: The method .write() works similar to the method .readline()...
5,405
<ASSISTANT_TASK:> Python Code: import dendropy import pandas as pd data = pd.read_csv('../Data/PyronParityData.csv', index_col=0, header=False) taxa = dendropy.TaxonSet() mle = dendropy.Tree.get_from_path('../TotalOpt/annotatedTO_0param_2598364.dated', 'newick', taxon_set=taxa, preserve_underscores=True) for idx, nd...
<SYSTEM_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 data and tree. Step2: Iterate over the tips of the trees and annotate with data (in this case, whether the tip is viviparous or oviparous)...
5,406
<ASSISTANT_TASK:> Python Code: # !pip install phiflow from phi.flow import * x = math.stack({'Sun': (0, 0), 'Earth': (10, 0), 'Mars': (0, 12)}, instance('planets')) x vis.plot(PointCloud(x, bounds=Box(x=(-2, 12), y=(-1, 13)))) v = math.rotate_vector(x, PI/2) v = math.divide_no_nan(v, math.vec_length(v)) vis.plot(Po...
<SYSTEM_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 use the convenience import of Φ<sub>Flow</sub> which imports the core submodules, such as math and vis. Step2: Let's define the initial posi...
5,407
<ASSISTANT_TASK:> Python Code: import os # The Google Cloud Notebook product has specific requirements IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version") # Google Cloud Notebook requires dependencies to be installed with '--user' USER_FLAG = "" if IS_GOOGLE_CLOUD_NOTEBOOK: USER_FLAG...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Restart the kernel Step2: Set up your Google Cloud project Step3: Otherwise, set your project ID here. Step4: Set project ID Step5: Timestam...
5,408
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt a = np.array([-2, 3, 4, -5, 5]) print(a) a[[1, 3]] a[a > 0] print(a) print(a > 0) a[(a > 0) & (a < 5)] pop_dict = {'Germany': 81.3, 'Belgium': 11.3, 'France': 64.3, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: More on NumPy indexing Step2: Fancy indexing Step3: Boolean indexing Step4: Note that the index array has the same size as and type of boolea...
5,409
<ASSISTANT_TASK:> Python Code: import numpy as np objective = np.poly1d([1.3, 4.0, 0.6]) print objective import scipy.optimize as opt x_ = opt.fmin(objective, [3]) print "solved: x={}".format(x_) %matplotlib inline x = np.linspace(-4,1,101.) import matplotlib.pylab as mpl mpl.plot(x, objective(x)) mpl.plot(x_, objecti...
<SYSTEM_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 "optimizer" Step2: Additional components Step3: The gradient and/or hessian Step4: The penalty functions Step5: Optimizer classification...
5,410
<ASSISTANT_TASK:> Python Code: import numpy as np from math import pi import matplotlib.pyplot as plot %matplotlib notebook x = np.arange(-5, 5.001, 0.0001) y = (x**4)-(16*(x**2)) + 16 plot.plot(x,y,'c') plot.grid(True) print('Para a f(x) = ax^2 + bx+ c, diga os valores de a, b e c:\n') a = float(input('Valor de 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: Questão 2 Step2: Questão 3 Step3: Questão 4
5,411
<ASSISTANT_TASK:> Python Code: import sys import os sys.path.append(os.environ.get('NOTEBOOK_ROOT')) %matplotlib inline from datetime import datetime import numpy as np import utils.data_cube_utilities.dc_utilities as utils from utils.data_cube_utilities.clean_mask import landsat_qa_clean_mask from utils.data_cube_util...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <span id="coastal_change_classifier_plat_prod">Choose Platform and Product &#9652;</span> Step2: <span id="coastal_change_classifier_define_ext...
5,412
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np from sklearn import metrics, preprocessing, linear_model dirRawData = '/home/john/Projects/RepoNumerAI/data/raw/numerai_datasets/19_03_2017/' dirOutputData = '/home/john/Projects/RepoNumerAI/data/processed/' # Set seed for reproducibility np.random....
<SYSTEM_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 paths to the Data Step2: Transform the loaded CSV data into numpy arrays Step3: This is your model that will learn to predict
5,413
<ASSISTANT_TASK:> Python Code: !pip install git+https://github.com/google/starthinker CLOUD_PROJECT = 'PASTE PROJECT ID HERE' print("Cloud Project Set To: %s" % CLOUD_PROJECT) CLIENT_CREDENTIALS = 'PASTE CREDENTIALS HERE' print("Client Credentials Set To: %s" % CLIENT_CREDENTIALS) FIELDS = { 'auth_read': 'user', ...
<SYSTEM_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. Get Cloud Project ID Step2: 3. Get Client Credentials Step3: 4. Enter Google Analytics Timeline Parameters Step4: 5. Execute Google Analyt...
5,414
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cas', 'fgoals-f3-h', 'seaice') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "em...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 2...
5,415
<ASSISTANT_TASK:> Python Code: !pip install stim import stim circuit = stim.Circuit() # First, the circuit will initialize a Bell pair. circuit.append_operation("H", [0]) circuit.append_operation("CNOT", [0, 1]) # Then, the circuit will measure both qubits of the Bell pair in the Z basis. circuit.append_operation("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: 3. Create a simple circuit, and sample from it. Step2: You can sample from the circuit using the circuit.compile_sampler() method to get a samp...
5,416
<ASSISTANT_TASK:> Python Code: import pandas as pd %ls %ls rr-intro-data-v0.2/intro/data/ gap_5060 = pd.read_csv('rr-intro-data-v0.2/intro/data/gapminder-5060.csv') gap_5060_CA = gap_5060.loc[gap_5060['country'] == 'Canada'] %matplotlib inline gap_5060_CA.plot(kind='line', x='year', y='lifeExp') pass gap_5060.loc...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Notebook Step2: Both the magic functions and the python ones support tab-completion Step3: Data Step4: Task 1 Step5: Visualize Step6: Task ...
5,417
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import holoviews as hv from IPython.display import HTML hv.notebook_extension() xs = range(10) ys = np.exp(xs) table = hv.Table((xs, ys), kdims=['x'], vdims=['y']) table hv.Scatter(table) + hv.Curve(table) + hv.Bars(table) print(repr(hv.Scatter({'...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Simple Dataset Step2: However, this data has many more meaningful visual representations, and therefore the first important concept is that Dat...
5,418
<ASSISTANT_TASK:> Python Code: x = 5**3 print(x) import math # Calculate square root of 25 x = math.sqrt(25) print (x) # Calculate cube root of 64 cr = round(64 ** (1. / 3)) print(cr) import math print (9**0.5) print (math.sqrt(9)) import math x = math.log(16, 4) print(x) import math # Natural log of 29 print (math...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Multiplying a number by itself twice or three times to calculate the square or cube of a number is a common operation, but you can raise a numbe...
5,419
<ASSISTANT_TASK:> Python Code: import numpy as np import theano from theano import tensor #from blocks import initialization from blocks.bricks import Identity, Linear, Tanh, MLP, Softmax from blocks.bricks.lookup import LookupTable from blocks.bricks.recurrent import SimpleRecurrent, Bidirectional, BaseRecurrent from ...
<SYSTEM_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 the output layer needs to gather the two hidden layers (one from each direction) Step2: Note that in order to double the input we had to a...
5,420
<ASSISTANT_TASK:> Python Code: %pylab inline data_dir = "./Data/Weather/" !curl -o $data_dir/STAT.pickle http://mas-dse-open.s3.amazonaws.com/Weather/STAT.pickle import pickle STAT,STAT_description=pickle.load(open(data_dir+'/STAT.pickle','r')) STAT.keys() STAT_description Scalars=['mean','std','low1000','low100','hi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Downloading Pickled data from S3 Step2: Get the statistics from the Pickle File Step3: Script for plotting yearly plots Step4: Plot the follo...
5,421
<ASSISTANT_TASK:> Python Code: from nupic.engine import Network, Dimensions # Create Network instance network = Network() # Add three TestNode regions to network network.addRegion("region1", "TestNode", "") network.addRegion("region2", "TestNode", "") network.addRegion("region3", "TestNode", "") # Set dimensions on fir...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Render with nupic.frameworks.viz.NetworkVisualizer, which takes as input any nupic.engine.Network instance Step2: That's interesting, but not n...
5,422
<ASSISTANT_TASK:> Python Code: # Print periodic table to orient ourselves Element.print_periodic_table() # Generate list of non-radioactive elements (noble gases omitted) def desired_element(elem): omit = ['Po', 'At', 'Rn', 'Fr', 'Ra'] return not e.is_noble_gas and not e.is_actinoid and not e.symbol in omit ele...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: How complete is the Materials Project database? Step2: Ternaries Step3: Why is there a discrepancy between the number of unique ternaries of t...
5,423
<ASSISTANT_TASK:> Python Code: import itertools import string import functools letters = string.ascii_lowercase vocab = list(map(''.join, itertools.product(letters, repeat=2))) from random import choices def zipf_pdf(k): return 1/k**1.07 def exponential_pdf(k, base): return base**k def new_document(n_words, pdf...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Based on the way we are choosing words, we say that 410 pairs out of 1000 documents have a high enough jaccard to call them similar. This seems ...
5,424
<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 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: Session 2 - Training a Network w/ Tensorflow Step2: <a name="assignment-synopsis"></a> Step3: Remember, having series of linear followed by no...
5,425
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from IPython.html import widgets from IPython.html.widgets import interact from IPython.display import display tab1_children = [widgets.ButtonWidget(description="ButtonWidget"), widgets.CheckboxWidget(description="Checkb...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Build-it Widgets Step2: Simple Example Step3: Now we will test it using a code cell Step4: Using interact function Step5: Controlling a Char...
5,426
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'inpe', 'sandbox-1', 'landice') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "em...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
5,427
<ASSISTANT_TASK:> Python Code: from pyturb.gas_models import GasMixture gas_mix = GasMixture(gas_model='Perfect') gas_mix.add_gas('O2', mass=0.5) gas_mix.add_gas('H2', mass=0.5) gas_mix.mixture_gases gas_mix2 = GasMixture(gas_model='Perfect') gas_mix2.add_gas('O2', moles=0.5) gas_mix2.add_gas('H2', moles=0.5) gas_mix...
<SYSTEM_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 inspect the gas mixture contidions, we can use Pandas Dataframe contained in gas_mixture Step2: Note that the gas_mixture dataframe contains...
5,428
<ASSISTANT_TASK:> Python Code: import numpy as np import theano import theano.tensor as tt import kalman # True values T = 500 # Time steps sigma2_eps0 = 3 # Variance of the observation noise sigma2_eta0 = 10 # Variance in the update of the mean # Simulate data np.rando...
<SYSTEM_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 will use the same data as in the 01_RandomWalkPlusObservation notebook. Step2: Next, we create all the tensors required to describe our mode...
5,429
<ASSISTANT_TASK:> Python Code: import supp_functions as fce import xarray as xr import pandas as pd import statsmodels.api as sm import numpy as np import matplotlib.pyplot as plt s_year = 1979 e_year = 2009 vari ='t' in_dir = '~/' in_netcdf = in_dir + 'jra55_tmp_1960_2009_zm.nc' ds = xr.open_dataset(in_netcdf) 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 opening Step2: Variable and period of analysis selection Step3: Deseasonalizing Step4: Regressor loading Step5: Regression function Ste...
5,430
<ASSISTANT_TASK:> Python Code: from numpy.random import standard_normal # Gaussian variables N = 1000; P = 5 X = standard_normal((N, P)) W = X - X.mean(axis=0,keepdims=True) print(dot(W[:,0], W[:,1])) from sklearn.decomposition import PCA S=PCA(whiten=True).fit_transform(X) print(dot(S[:,0], S[:,1])) from numpy.rand...
<SYSTEM_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'll skip ahead and use a pre-canned PCA routine from scikit-learn (but we'll dig into it a bit later!) Let's see what happens to the transforme...
5,431
<ASSISTANT_TASK:> Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() import pyensae.datasource pyensae.datasource.download_data("matrix_distance_7398.zip", website = "xd") import pandas df = pandas.read_csv("matrix_distance_7398.txt", sep="\t", header=None, names=["v1","v2","distance"]) df....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: La programmation dynamique est une façon de résoudre de manière similaire une classe de problèmes d'optimisation qui vérifie la même propriété. ...
5,432
<ASSISTANT_TASK:> Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/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: In the previous chapter we developed a population model where net growth during each time step is proportional to the current population. This m...
5,433
<ASSISTANT_TASK:> Python Code: dataset = nilmtk.DataSet('/data/mine/vadeec/merged/ukdale.h5') dataset.set_window("2014-06-01", "2014-07-01") BUILDING = 1 elec = dataset.buildings[BUILDING].elec fridge = elec['fridge'] activations = fridge.get_activations() print("Number of activations =", len(activations)) activatio...
<SYSTEM_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, to speed up processing, we'll set a "window of interest" so NILMTK will only consider one month of data. Step2: Get the ElecMeter associa...
5,434
<ASSISTANT_TASK:> Python Code: (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train[:100] y_train = y_train[:100] print(x_train.shape) # (60000, 28, 28) print(y_train.shape) # (60000,) print(y_train[:3]) # array([7, 2, 1], dtype=uint8) # Initialize the image regressor. reg = ak.ImageRegressor(...
<SYSTEM_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 second step is to run the ImageRegressor. It is recommended have more Step2: Validation Data Step3: You can also use your own validation ...
5,435
<ASSISTANT_TASK:> Python Code: import os PATH="/Users/david/Desktop/CourseWork/TheArtOfDataScience/claritycontrol/code/scripts/" # use your own path os.chdir(PATH) import clarity as cl # I wrote this module for easier operations on data import clarity.resources as rs import csv,gc # garbage memory collection :) impor...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step 1 Step1: Histogram data preparation Step2: Scale data Step3: Setup Step Step4: Steps 4 & 5 Step5: Step 6 Step6: Step 7
5,436
<ASSISTANT_TASK:> Python Code: from pypot.creatures import PoppyErgoJr poppy = PoppyErgoJr(use_http=True, use_snap=True) # If you want to use another robot (humanoid, torso, ...) adapt this code #from pypot.creatures import PoppyTorso #poppy = PoppyTorso(use_http=True, use_snap=True) # If you want to use the robot 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: Second\ Step2: 2.a. Access to API to get values Step3: 2.b. Get value - with single input - Step4: http Step5: 2.b Get value - with multiple...
5,437
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import linear_model import math from scipy import stats %matplotlib inline data = pd.read_csv('Default.csv') data = data.drop('Unnamed: 0',axis = 1) #change Yes, No to 1, 0. data['def_chg'] = data.default...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Part 1 Step2: Part 3 Step3: In statistics, the p-value represents the probablity of extreme value by assuming H0 is true. When p-value is smal...
5,438
<ASSISTANT_TASK:> Python Code: # imports / display plots in cell output %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.stats as ss import pandas as pd import seaborn as sns import statsmodels # Bayesian Model Selection (bor = .6240) # Model 1: inverse temperature, stickiness, learni...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Experiment 1 Step2: Experiment 2 Step3: Experiment 2 Step4: Experiment 3 Step5: Experiment 3 Step6: Experiment 4 Step7: Experiment 4 Step8...
5,439
<ASSISTANT_TASK:> Python Code: def expect_value(k, p): steps = [k / p / (k - i) for i in range(k)] return sum(steps) k = 10 ps = [1., .5, .33, .25, .2, .1] count = np.vectorize(lambda p: expect_value(k, p), otypes=[np.float])(ps) plt.scatter(ps, count) plt.xlabel('Lion probability') plt.ylabel('Purchase count'...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Если бы в каждом яйце был львенок, нужно было бы в среднем купить 29.29 яиц, чтобы собрать коллекцию. Но когда львенок в каждом третьем - это уж...
5,440
<ASSISTANT_TASK:> Python Code: import numpy as np %matplotlib inline import matplotlib import matplotlib.pyplot as plt import matplotlib.animation from IPython.display import HTML font = {'size' : 15} matplotlib.rc('font', **font) m = 16 L = 2*np.pi xi=np.fft.fftfreq(m)*m/(L/(2*np.pi)) print(xi) from ipywidgets imp...
<SYSTEM_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 FFT, aliasing, and filtering Step2: As you can see, the return vector starts with the nonnegative wavenumbers, followed by the negative wav...
5,441
<ASSISTANT_TASK:> Python Code: import time import numpy as np import tensorflow as tf import utils from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import zipfile dataset_folder_path = 'data' dataset_filename = 'text8.zip' dataset_name = 'Text8 Dataset' class DLProgress(tq...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load the text8 dataset, a file of cleaned up Wikipedia articles from Matt Mahoney. The next cell will download the data set to the data folder. ...
5,442
<ASSISTANT_TASK:> Python Code: #импортируем библиотеки import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.datasets import make_blobs from sklearn.cluster import DBSCAN plt.figure(figsize=(12, 12)) n_samples = 2300 random_state = 220 X, y = make_blobs(n_samples=n_samples, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Как видим распредение по кластерам оказалось вполне логичным, не смотря на выбор параметров по умолчанию, за исключением второго случая, но там ...
5,443
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mri', 'sandbox-1', 'aerosol') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "ema...
<SYSTEM_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...
5,444
<ASSISTANT_TASK:> Python Code: #include some package which we use later on import numpy as np #test np.ar -> tab a = np.array([1,2,3,4]) #test np.array -> shift-tab or np.array? 1+2 3+4 10/2 print(5+2) 3+2 a = 5+2 b = 9 a/b def sum(a,b): #indent is important in Python! return a+b sum(4,4) def sub(arg1,arg2): r...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Interactive Python basics
5,445
<ASSISTANT_TASK:> Python Code: !pygmentize message-dumper.yaml !kubectl apply -f message-dumper.yaml !pygmentize broker.yaml !kubectl create -f broker.yaml !pygmentize trigger.yaml !kubectl apply -f trigger.yaml !pygmentize sklearn-logging.yaml !kubectl apply -f sklearn-logging.yaml CLUSTER_IPS=!(kubectl -n istio-sy...
<SYSTEM_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 channel broker. Step2: Create a Knative trigger to pass events to the message logger. Step3: Create an sklearn model with associated ...
5,446
<ASSISTANT_TASK:> Python Code: s = 'Hello world!' print(s) print("length is", len(s)) us = 'Hello 世界!' print(us) print("length is", len(us)) bs = s.encode('utf-8') print(bs) print("length is", len(bs)) bus = us.encode('utf-8') print(bus) print("length is", len(bus)) print(bs.decode('utf-8')) print(bus.decode('utf-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: Now encode both strings to bytes. Step2: Decode back to strings. Step3: Big Endian vs Little Endian Step4: struct package Step5: struct.pack...
5,447
<ASSISTANT_TASK:> Python Code: # import libraries from __future__ import division import numpy as np import os import matplotlib.pyplot as plt from pyphysio.tests import TestData %matplotlib inline # import all pyphysio classes and methods import pyphysio as ph # import data and creating a signal ecg_data = TestData.e...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 4.1.1 Creation of custom segments Step2: And then use the function CustomSegments to use the defined instants for the segmentation Step3: Then...
5,448
<ASSISTANT_TASK:> Python Code: # list my_list = [1, 4, 5, 9] print(my_list) type(my_list) # accessing each element by index print(my_list[2]) len(my_list) # assigning new value my_list[1] = 12 print(my_list) # append an element at the end my_list.append(7) print(my_list) help(list) # String my_name = 'Anne' # it is als...
<SYSTEM_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 1.4 Step2: Exercises 1.4.1
5,449
<ASSISTANT_TASK:> Python Code: import numpy as np import tulipy as ti ti.TI_VERSION DATA = np.array([81.59, 81.06, 82.87, 83, 83.61, 83.15, 82.84, 83.99, 84.55, 84.36, 85.53, 86.54, 86.89, 87.77, 87.29]) def print_info(indicator): print("Type:", indicator.type) print("Full ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Information about indicators are exposed as properties Step2: Single outputs are returned directly. Indicators returning multiple outputs use S...
5,450
<ASSISTANT_TASK:> Python Code: # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de> # # License: BSD (3-clause) import numpy as np import mne from mne.datasets import sample from mne.inverse_sparse import mixed_norm, make_stc_from_dipoles 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: Run solver Step2: Plot dipole activations Step3: Plot residual Step4: Generate stc from dipoles Step5: View in 2D and 3D ("glass" brain like...
5,451
<ASSISTANT_TASK:> Python Code: import tensorflow as tf import tensorflow.contrib.slim as slim import numpy as np import gym import matplotlib.pyplot as plt %matplotlib inline try: xrange = xrange except: xrange = range env = gym.make('CartPole-v0') gamma = 0.99 def discount_rewards(r): take 1D float array...
<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 Policy-Based Agent Step3: Training the Agent
5,452
<ASSISTANT_TASK:> Python Code: %matplotlib notebook import matplotlib import matplotlib.pyplot as plt import numpy as np SIZE = 20 prob = np.random.uniform(low=0.0, high=1.0, size=SIZE) prob = prob/np.sum(prob) x = range(0,len(prob)) plt.figure(figsize=(10,2)) plt.bar(x, prob, 0.3) plt.xticks(x, x) plt.show() result ...
<SYSTEM_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 create a probability vector! Step2: Using np.random.choice you can use the probability vector to pick random number that will follow the ...
5,453
<ASSISTANT_TASK:> Python Code: i = -7 j = 123 print(i, j) x = 3.14159 y = -42.3 print(x * y) k = 1.5e3 l = 3e-2 print(k) print(l) s = "ATGTCGTCTACAACACT" t = 'Serine' u = "It's a string with apostrophes" v = A string that extends over multiple lines print(v) a = True b = False print(a, b) z = None print(z) a = Tr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Floats Step2: Floating point numbers can also carry an <tt>e</tt> suffix that states which power of ten they operate at. Step4: Strings Step5:...
5,454
<ASSISTANT_TASK:> Python Code: import chaospy normal = chaospy.Normal(mu=2, sigma=2) normal samples = normal.sample(4, seed=1234) samples from matplotlib import pyplot pyplot.hist(normal.sample(10000, seed=1234), 30) pyplot.show() normal.sample([2, 2], seed=1234) import numpy numpy.random.seed(1234) normal.sample(4...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The distribution have a few methods that the user can used, which has names Step2: These can be used to create e.g. histograms Step3: The inpu...
5,455
<ASSISTANT_TASK:> Python Code: !pip install -qq git+git://github.com/lindermanlab/ssm-jax-refactor.git try: import ssm except ModuleNotFoundError: %pip install -qq ssm import ssm import jax.numpy as np import jax.random as jr import jax.experimental.optimizers as optimizers from jax import jit, value_and_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Imports and Plotting Functions Step2: Sample some synthetic data from the Poisson LDS Step3: Inference
5,456
<ASSISTANT_TASK:> Python Code: print las._text lasio.ExcelConverter(las).write('example.xlsx') import pandas xls_header_sheet = pandas.read_excel('example.xlsx', sheetname='Header') xls_header_sheet xls_data_sheet = pandas.read_excel('example.xlsx', sheetname='Curves') xls_data_sheet converter = lasio.ExcelConvert...
<SYSTEM_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 use the ExcelConverter object to produce an Excel spreadsheet Step2: we can import this spreadsheet back into Python directly using pandas ...
5,457
<ASSISTANT_TASK:> Python Code: import time import sys import random from pybel.utils import get_version from pybel.struct.mutation import infer_child_relations from pybel_tools.visualization import * from pybel.examples.statin_example import statin_graph, hmgcr_inhibitor, hmgcr, ec_11134 print(time.asctime()) print(sy...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Environment Step2: Dependencies Step3: Example Graph Step4: Propogation on Chemical Hierarchy Step5: Propogation on Protein Hierarchy
5,458
<ASSISTANT_TASK:> Python Code: # To visualize plots in the notebook %matplotlib inline # Imported libraries import csv import random import matplotlib import matplotlib.pyplot as plt import pylab import numpy as np from mpl_toolkits.mplot3d import Axes3D from sklearn.preprocessing import PolynomialFeatures 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: 1. Introduction Step2: 2.2. Classifiers based on the logistic model. Step3: 3.3. Nonlinear classifiers. Step4: 3. Inference Step5: Now, we s...
5,459
<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: Running TFLite models Step2: Create a basic model of the form y = mx + c Step3: Generate a SavedModel Step4: Convert the SavedModel to TFLite...
5,460
<ASSISTANT_TASK:> Python Code: import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for...
<SYSTEM_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: Extract Features Step3: Train SVM on features Step4: Inline question 1
5,461
<ASSISTANT_TASK:> Python Code: import pandas as pd import seaborn as sns import matplotlib as mpl import matplotlib.pyplot as plt import openaq import warnings warnings.simplefilter('ignore') %matplotlib inline # Set major seaborn asthetics sns.set("notebook", style='ticks', font_scale=1.0) # Increase the quality of 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: Choosing Locations Step2: Let's go ahead and filter our results to only grab locations that have been updated in 2017 and have at least 100 dat...
5,462
<ASSISTANT_TASK:> Python Code: %matplotlib inline from os.path import join, exists, expandvars import pandas as pd from IPython.display import display, Markdown import seaborn.xkcd_rgb as colors from tax_credit.plotting_functions import (pointplot_from_data_frame, boxplot_from...
<SYSTEM_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 local environment-specific values Step2: Find mock community pre-computed tables, expected tables, and "query" tables Step3: Restric...
5,463
<ASSISTANT_TASK:> Python Code: !hostname %load_ext autoreload %autoreload 2 %matplotlib inline import ipyrad import ipyrad.analysis as ipa import ipyparallel as ipp from ipyrad.analysis.popgen import Popgen from ipyrad import Assembly from ipyrad.analysis.locus_extracter import LocusExtracter ipyclient = ipp.Client(clu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Development of the Processor class to calculate all the stats Step2: Prototyping the dcons function to split alleles per base Step3: Loading p...
5,464
<ASSISTANT_TASK:> Python Code: import numpy as np # Matrix and vector computation package np.seterr(all='ignore') # ignore numpy warning like multiplication of inf import matplotlib.pyplot as plt # Plotting library from matplotlib.colors import colorConverter, ListedColormap # some plotting functions from matplotlib 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: Loss function, chain rule and its derivative Step2: Plot the cost function and as you can see it's convex and has global optimal minimum. Step3...
5,465
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline plt.style.use('ggplot') plt.rcParams['figure.figsize'] = (13,8) df = pd.read_csv("./winequality-red.csv") df.head() df.shape #df.loc[df.b > 0, 'd'] = 1 df.loc[df.quality > 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: Wine Category Step2: This is the frequency count for each category Step3: Visual Exploration Step4: Alcohol vs Category Step5: Exercise Step...
5,466
<ASSISTANT_TASK:> Python Code: test_sentences = [ "the men saw a car .", "the woman gave the man a book .", "she gave a book to the man .", "yesterday , all my trouble seemed so far away ." ] import nltk from nltk.corpus import treebank from nltk.grammar import ProbabilisticProduction, PCFG # Production...
<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: Aufgabe 2 &nbsp;&nbsp;&nbsp; Informationsextraktion per Syntaxanalyse Step3: Hausaufgaben Step5: Aufgabe 4 &nbsp;&nbsp;&nbsp; Mehr Semantik fü...
5,467
<ASSISTANT_TASK:> Python Code: from itertools import combinations import skrf as rf %matplotlib inline from pylab import * rf.stylely() wg = rf.wr10 wg.frequency.npoints = 101 dut = wg.random(n_ports = 4,name= 'dut') dut loads = [wg.load(.1+.1j), wg.load(.2-.2j), wg.load(.3+.3j), wg.loa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: First, we create a Media object, which is used to generate networks for testing. We will use WR-10 Rectangular waveguide. Step2: Next, lets gen...
5,468
<ASSISTANT_TASK:> Python Code: from msmbuilder.example_datasets import QuadWell from msmbuilder.msm import MarkovStateModel from msmbuilder.lumping import MVCA import numpy as np import scipy.cluster.hierarchy import matplotlib.pyplot as plt % matplotlib inline q = QuadWell(random_state=998).get() ds = q['trajectories...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Get the dataset Step2: Define a regular spatial clusterer Step3: Plot our MSM energies Step4: Make a model with out macrostating to get linka...
5,469
<ASSISTANT_TASK:> Python Code: # flipping signs of numbers... a = 5 b = -5 print(-a, -b) # len function x1 = [] x2 = "12" x3 = [1,2,3] print(len(x1), len(x2), len(x3)) x = [1,2,3] print(x[100]) # <--- IndexError! 100 is waayyy out of bounds string = "hello" print(string[0]) # first item print(string[len...
<SYSTEM_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, those bounds I have just given might sound a bit arbitrary, but actually I can explain exactly how they work. Consider the following pictur...
5,470
<ASSISTANT_TASK:> Python Code: import pandas as pd from pandas import DataFrame url="https://archive.ics.uci.edu/ml/machine-learning-databases/undocumented/connectionist-bench/sonar/sonar.all-data" df = pd.read_csv(url,header=None) df.describe() pd.options.display.max_columns=70 df.describe() import numpy as np 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: <h4>See all columns</h4> Step2: <h4>Examine the distribution of the data in column 4</h4> Step3: <h4>Examine the dependent variable</h4> Step4...
5,471
<ASSISTANT_TASK:> Python Code: import gdsfactory as gf c = gf.Component("pads") pt = c << gf.components.pad_array(orientation=270, columns=3) pb = c << gf.components.pad_array(orientation=90, columns=3) pt.move((70, 200)) c c = gf.Component("pads_with_routes_with_bends") pt = c << gf.components.pad_array(orientation=27...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: route_quad Step2: get_route_from_steps Step3: Bundle of routes (get_bundle_electrical) Step4: get bundle from steps
5,472
<ASSISTANT_TASK:> Python Code: def win_series(p, W=0, L=0): "Probability of winning best-of-7 series, given a probability p of winning a game." return (1 if W == 4 else 0 if L == 4 else p * win_series(p, W + 1, L) + (1 - p) * win_series(p, W, L + 1)) win_series(0.58) 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: In other words, if you have a 58% chance of winning a game, you have a 67% chance of winning the series. Step2: And here's a function to tabula...
5,473
<ASSISTANT_TASK:> Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License") # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The 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: Map Step2: Examples Step3: <table align="left" style="margin-right Step4: <table align="left" style="margin-right Step5: <table align="left"...
5,474
<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: Loading Remote Data in TFF Step2: Preparing the input data Step3: We'll construct a preprocessing function to transform the raw examples in th...
5,475
<ASSISTANT_TASK:> Python Code: # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, sof...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Introduction to scikit-learn Step2: That's a lot to take in. Let's examine this loaded data a little more closely. First we'll see what data ty...
5,476
<ASSISTANT_TASK:> Python Code:: import matplotlib.pyplot as plt from sklearn.cluster import KMeans # Step 1: Set range of clusters to try and # create inertia values dictionary clusters_range = (1,10) inertia_values = {} # Step 2: For each set of clusters fit a kmeans algorithm and add # inertia value to interia value...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
5,477
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np Apenas a partir dos valores obj = pd.Series([4, 7, -5, 3]) obj obj.values obj.index A partir dos valores e dos índices obj2 = pd.Series([4, 7, -5, 3], index=['d','b','a','c']) obj2 obj2.index A partir de um dictionary sdata = {'Ohio': 35000, '...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step5: Series Step6: Acessando elementos de uma Series Step12: Algumas operações permitidas em uma Series Step17: DataFrame Step27: Note que estas ...
5,478
<ASSISTANT_TASK:> Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd import visuals as vs # Supplementary code from sklearn.cross_validation import ShuffleSplit from IPython.display import display # Pretty display for notebooks %matplotlib inline # Load the Boston housing ...
<SYSTEM_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 Exploration Step2: Feature Observation Step4: Developing a Model Step5: Implementation Step6: Benefit of splitting the data set into Tr...
5,479
<ASSISTANT_TASK:> Python Code: import emcee from dustcurve import model import seaborn as sns import numpy as np from dustcurve import pixclass import matplotlib.pyplot as plt import pandas as pd import warnings from dustcurve import io from dustcurve import hputils from dustcurve import kdist import h5py from dustcurv...
<SYSTEM_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 see what our chains look like by producing trace plots Step2: Now we are going to use the seaborn distplot function to plot histograms of...
5,480
<ASSISTANT_TASK:> Python Code: import pandas as pd %matplotlib inline import numpy as np from sklearn.linear_model import LogisticRegression df = pd.read_csv("hanford.csv") df.head() df.mean() df.median() #range df["Exposure"].max() - df["Exposure"].min() #range df["Mortality"].max() - df["Mortality"].min() df.std() ...
<SYSTEM_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. Read in the hanford.csv file in the data/ folder Step2: 3. Calculate the basic descriptive statistics on the data Step3: 4. Find a reasonab...
5,481
<ASSISTANT_TASK:> Python Code: #|all_slow from transformers import GPT2LMHeadModel, GPT2TokenizerFast pretrained_weights = 'gpt2' tokenizer = GPT2TokenizerFast.from_pretrained(pretrained_weights) model = GPT2LMHeadModel.from_pretrained(pretrained_weights) ids = tokenizer.encode('This is an example of text, and') ids...
<SYSTEM_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 this tutorial, we will see how we can use the fastai library to fine-tune a pretrained transformer model from the transformers library by Hug...
5,482
<ASSISTANT_TASK:> Python Code: import time import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np from sklearn import preprocessing from sklearn.ensemble import RandomForestClassifier from sklearn.cross_validation import StratifiedShuffleSplit from sklearn.cross_validation import c...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <h2> Get the xcms data </h2> Step2: <h2> Get mappings between sample names, file names, and sample classes </h2> Step3: <h2> Convert class lab...
5,483
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from sklearn.model_selection import train_test_split features_dataframe = load_data() n = features_dataframe.shape[0] train_size = 0.8 test_size = 1 - train_size + 0.005 train_dataframe = features_dataframe.iloc[int(n * test_size):] test_dataframe = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
5,484
<ASSISTANT_TASK:> Python Code: # Authors: Christopher Holdgraf <choldgraf@berkeley.edu> # Alex Rockhill <aprockhill@mailbox.org> # # License: BSD-3-Clause from mne.io.fiff.raw import read_raw_fif import numpy as np from matplotlib import pyplot as plt from os import path as op import mne from mne.viz im...
<SYSTEM_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: Project 3D electrodes to a 2D snapshot Step3: Manually creating 2D electrode positions
5,485
<ASSISTANT_TASK:> Python Code: !pip install -r requirements.txt import pandas as pd import numpy as np df=pd.read_csv('talks.csv') df.head() year_labeled= year_predict= description_labeled = df[df.year==year_labeled]['description'] description_predict = df[df.year==year_predict]['description'] from sklearn.feature_e...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Exercise A Step2: Here is a brief description of the interesting fields. Step3: Quick Introduction to Text Analysis Step4: Extra Credit Step5...
5,486
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.style.use('ggplot') plt.rcParams['figure.figsize'] = (9,6) df = pd.read_csv("../data/creditRisk.csv") df.head() from plotnine import * ggplot(df, aes(x = "Income", y = "Credit History", color = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Plotting the Data Step2: Preparing Data Step3: Lets use a dictionary for encoding nominal variable Step4: Classifier - Logistic Regression St...
5,487
<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: ...
5,488
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'inpe', 'sandbox-2', 'toplevel') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "e...
<SYSTEM_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: 2...
5,489
<ASSISTANT_TASK:> Python Code: import numpy as np np.random.seed(123) %matplotlib inline import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (10, 6) plt.set_cmap("viridis") from skopt.benchmarks import branin as _branin def branin(x, noise_level=0.): return _branin(x) + noise_level * np.random.randn()...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Bayesian optimization or sequential model-based optimization uses a surrogate model Step2: This shows the value of the two-dimensional branin f...
5,490
<ASSISTANT_TASK:> Python Code: import time from collections import namedtuple import numpy as np import tensorflow as tf with open('anna.txt', 'r') as f: text=f.read() vocab = set(text) vocab_to_int = {c: i for i, c in enumerate(vocab)} int_to_vocab = dict(enumerate(vocab)) chars = np.array([vocab_to_int[c] for 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: First we'll load the text file and convert it into integers for our network to use. Here I'm creating a couple dictionaries to convert the chara...
5,491
<ASSISTANT_TASK:> Python Code: import sys import random import numpy as np import heapq import json import time BIG_PRIME = 9223372036854775783 def random_parameter(): return random.randrange(0, BIG_PRIME - 1) class Sketch: def __init__(self, delta, epsilon, k): Setup a new count-min sketch wit...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step5: Basic Idea of Count Min sketch Step6: Is it possible to make the sketch so coarse that its estimates are wrong even for this data set? Step7: ...
5,492
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cccma', 'sandbox-2', 'toplevel') # 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: 2...
5,493
<ASSISTANT_TASK:> Python Code: # Import libraries import pandas as pd import numpy as np # Turn off notebook package warnings import warnings warnings.filterwarnings('ignore') # print graphs in the document %matplotlib inline import seaborn as sns import statsmodels.formula.api as sm #Import Package model = sm.ols(fo...
<SYSTEM_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 with Pandas Step2: Generate the same graph as above, but this time log-transform the population variable Step3: Example Results ...
5,494
<ASSISTANT_TASK:> Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', '..', 'notebook_format')) from formats import load_style load_style(css_style='custom2.css', plot_style=False) os.chdir(path)...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Seq2Seq Step2: The next two code chunks Step3: The tokenizer is language specific, e.g. it knows that in the English language don't should be ...
5,495
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 AIP_CLIENT_WHEEL = "aiplatform_pipelines_client-0.1.0.caip20201123-py3-none-any.whl" AIP_CLIENT_WHEEL_GCS_LOCATION = ( f"gs://cloud-aiplatform-pipelines/releases/20201123/{AIP_CLIENT_WHEEL}" ) !gsutil cp {AIP_CLIENT_WHEEL_GCS_LOCATION} {AIP_CLIENT_W...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Setting up the notebook's environment Step2: Restart the kernel. Step3: Import notebook dependencies Step4: Configure GCP environment Step5: ...
5,496
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display def soliton(x, t, c, a): Return phi(x, t) for a soliton wave with constants c and a. p=.5*c*((1/np.cosh((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: Step2: Using interact for animation with data Step3: To create an animation of a soliton propagating in time, we are going to precompute the soliton d...
5,497
<ASSISTANT_TASK:> Python Code: # from __future__ import exam_success from __future__ import absolute_import from __future__ import print_function # Standard imports %matplotlib inline import os import sklearn import matplotlib.pyplot as plt import seaborn as sns import numpy as np import random import pandas as pd 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: 13.765.202 lines in train.csv Step2: Per wikipedia, a value of more than 421 mm/h is considered "Extreme/large hail" Step3: We regroup the d...
5,498
<ASSISTANT_TASK:> Python Code: from pprint import pprint # I, Python am built from types, such as builtin types: the_builtins = dir(__builtins__) # always here pprint(the_builtins[-10:]) # no need to import for the_string in ["list", "tuple", "dict", "int", "float"]: if the_string in the_builtins: print("...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lets check our understanding that the native types -- the ones we count on to build more complex types -- live in builtins Step4: And now for s...
5,499
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import statsmodels.api as sm from scipy import stats from matplotlib import pyplot as plt plt.rc("figure", figsize=(16,8)) plt.rc("font", size=14) print(sm.datasets.star98.NOTE) data = sm.datasets.star98.load(as_pandas=False) data.exog = sm.add_cons...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: GLM Step2: Load the data and add a constant to the exogenous (independent) variables Step3: The dependent variable is N by 2 (Success Step4: ...