Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
1,900
<ASSISTANT_TASK:> Python Code: #text goes here corpora = "" for fname in os.listdir("codex"): import sys if sys.version_info >= (3,0): with open("codex/"+fname, encoding='cp1251') as fin: text = fin.read() #If you are using your own corpora, make sure it's read correctly cor...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Agenda Step2: Constants Step3: Input variables Step4: Build the neural network Step5: Compiling it Step8: Law generation Step9: Model trai...
1,901
<ASSISTANT_TASK:> Python Code: __author__ = 'Adam Foster and Nick Dingwall' from centering_and_scaling import * %matplotlib inline # A dataset: data = np.random.multivariate_normal( mean=[4, 0], cov=[[5, 2], [2, 3]], size=250) X, y = data[:, 0], data[:, 1] # Subtract the mean from the features: empirical_mean = 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: TL;DR Step2: Notice that we have a different intercept, but the same slope. The predictions from these two models will be identical. For instan...
1,902
<ASSISTANT_TASK:> Python Code: # Tensorflow import tensorflow as tf print('Tested with TensorFlow 1.2.0') print('Your TensorFlow version:', tf.__version__) # Feeding function for enqueue data from tensorflow.python.estimator.inputs.queues import feeding_functions as ff # Rnn common functions from tensorflow.contrib.le...
<SYSTEM_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 Step2: We can search our word list for a word like "baseball", and then access its corresponding vector through the embedding matr...
1,903
<ASSISTANT_TASK:> Python Code: with open('../csv_files/metro_edges_no_duplicated_edges_no_cycles_speed_networkx.csv') as f: f.readline() # Source,Target,Weight,edge_name,edge_color,travel_seconds,longitude_Source,latitude_Source,longitude_Target,latitude_Target,distance_meters,speed_ms g = nx.parse_edgelist...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Top 35 stations with more neighbour stations Step2: Neighbours' count histogram Step3: Most of the stations are connected to two other station...
1,904
<ASSISTANT_TASK:> Python Code: import numpy as np def generate_prob(n = 100, p = 0.8, eps = 0.2): @param: n (int): 子样个数 @param: p (float): 伯努利分布成功概率 @param: eps (float): 容忍偏差, bias sample = [np.abs(np.random.binomial(n=1, p=p, size=n).mean() - p) for i in range(10000)] # 10000 仿真次数 Prob = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Dataset Step2: Plots Step3: 动态改变 $\epsilon$ Step4: 动态改变 $n$ Step5: 动态改变 $p$
1,905
<ASSISTANT_TASK:> Python Code: # The following code is adopted from Pat's Rolling Rain N-Year Threshold.pynb # Loading in hourly rain data from CSV, parsing the timestamp, and adding it # as an index so it's more useful rain_df = pd.read_csv('data/ohare_full_precip_hourly.csv') rain_df['datetime'] = pd.to_datetime(rain...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Rainfall Equivalent Step2: Plotting Rainfall vs. n-year storm threshold Step3: Calculate new n-year storm definitions
1,906
<ASSISTANT_TASK:> Python Code: import os import math import torch import pyro import pyro.distributions as dist from pyro.infer.autoguide import AutoDelta from pyro.optim import Adam from pyro.infer import SVI, Trace_ELBO, config_enumerate from pyro.contrib.tracking.extended_kalman_filter import EKFState from pyro.cont...
<SYSTEM_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, let's specify the measurements. Notice that we only measure the positions of the particle. Step2: We'll use a Delta autoguide to learn MA...
1,907
<ASSISTANT_TASK:> Python Code: import numpy as np import GPy %matplotlib inline #%config InlineBackend.figure_format = 'svg' from pylab import * np.random.seed(113321) # Prepare the data N,D,Q = 500, 100, 3 pi = 0.2 # sample from 3 random sine waves X = np.sin(2*np.pi*(np.random.rand(Q)[None,:]+.5)*(np.linspace(0.,3.,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: The obersved data $Y$ is generated by projecting the samples of the 3 sine waves onto a 100D space with a randomly generated weight matrix $W$. ...
1,908
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib as plt import seaborn as sns users = pd.read_csv('timeseries_users.csv') users.head() events = pd.read_csv('timeseries_events.csv') events.index = pd.to_datetime(events['event_date'], format='%Y-%m-%d %H:%M:%S') 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: <a id='data_exploration'></a> Step2: User's age mean is from 24 to 63 years old, with a mean of 41 years old. Step3: Many duplicated entries a...
1,909
<ASSISTANT_TASK:> Python Code: #@title Default title text # 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 o...
<SYSTEM_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 right software Step2: Decode the Telluride4 EEG Data Step3: Run complete jackknife test
1,910
<ASSISTANT_TASK:> Python Code: synden = np.zeros((len(sorted_x), len(sorted_y), len(sorted_z))) for r in rows: if r[-2] != 0: synden[sorted_x.index(r[0]), sorted_y.index(r[1]), sorted_z.index(r[2])] = np.float(r[-1])/np.float(r[-2]) x_sum = [0] * len(synden[:,0,0]) for i in range(len(synden[:,0,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: 2. Looking at the y-layer Step2: 3. How are synapses distributed within these possible cortex layers? Are they uniform? Step3: Surprisingly, i...
1,911
<ASSISTANT_TASK:> Python Code: import os, sys import itertools import re import json %matplotlib inline from random import randint import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import gzip from math import log, e from scipy import stats from math import sqrt mdf = pd.read...
<SYSTEM_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 the metrics Step2: Read the results file. Step3: Find the option with no metrics Step4: But no metrics == no phages! Step5: Find the op...
1,912
<ASSISTANT_TASK:> Python Code: import mltoolbox.image.classification as model from google.datalab.ml import * bucket = 'gs://' + datalab_project_id() + '-lab' preprocess_dir = bucket + '/flowerpreprocessedcloud' model_dir = bucket + '/flowermodelcloud' staging_dir = bucket + '/staging' !gsutil mb $bucket train_set = 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: Preprocess Step2: Train Step3: Check your job status by running (replace the job id from the one shown above) Step4: Predict Step5: Online p...
1,913
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt plt.rcParams['figure.dpi'] = 150 from skdaccess.framework.param_class import * from skdaccess.astro.spectra.stream import DataFetcher ap_spectra_url = AutoList([ 'https://dr14.sdss.org/sas/dr14/eboss/spectro/redux/v5_10_0/spectra/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: Import data fetcher Step2: Specify list of SDSS spectra URLs to retrieve Step3: Create data fetcher Step4: Access data and metadata Step5: P...
1,914
<ASSISTANT_TASK:> Python Code: import cvxopt as cvx from cvxopt import solvers as cvx_solvers Q = cvx.matrix([[0.,0.],[0.,0.]]) p = cvx.matrix([-1., 4.]) G = cvx.matrix([[-3., 1., 0.],[1., 2., -1.]]) h = cvx.matrix([6., 4., 3.]) sol = cvx_solvers.qp(Q, p, G, h) print(sol['x']) import scipy.optimize as opt import mysti...
<SYSTEM_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 Step2: EXERCISE Step3: EXERCISE Step4: EXERCISE Step5: EXERCISE Step6: EXERCISE Step7: EXERCISE Step8: EXERCISE
1,915
<ASSISTANT_TASK:> Python Code: from nipype.interfaces.io import DataSink ds = DataSink() ds.inputs.base_directory = 's3://mybucket/path/to/output/dir' ds.inputs.creds_path = '/home/neuro/aws_creds/credentials.csv' ds.inputs.encrypt_bucket_keys = True ds.local_copy = '/home/neuro/workflow_outputs/local_backup' <END_TA...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: With the "s3
1,916
<ASSISTANT_TASK:> Python Code: census = list(csv.reader(open("census.csv", 'r'))) for index, column in enumerate(census[0]): print("{} - {}: {}".format(index, column, census[1][index])) def get_race_count(census, column_indexes): return sum([int(census[1][index]) for index in column_indexes]) race_percentage = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Death by race
1,917
<ASSISTANT_TASK:> Python Code: from __future__ import division, print_function # Python 3 from sympy import init_printing init_printing(use_latex='mathjax',use_unicode=False) # Affichage des résultats %matplotlib inline from sympy import plot from sympy import sin from sympy.abc import x plot(sin(x)) plot(sin(...
<SYSTEM_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 librairie Sympy utilise matplotlib, une autre librairie de Python, pour faire des dessins. Pour activer l'affichage des graphiques dans Jupyt...
1,918
<ASSISTANT_TASK:> Python Code: %lsmagic time print("hi") %time ls -l -h !ls -l -h files = !ls -l -h files %%! ls -l pwd who %matplotlib inline import numpy as np import matplotlib.pyplot as plt %timeit np.linalg.eigvals(np.random.rand(100,100)) %%timeit a = np.random.rand(100, 100) np.linalg.eigvals(a) %%capture ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 缺省情况下,Automagic开关打开,不需要输入%符号,将会自动识别。 Step2: 执行Shell脚本。 Step3: 执行多行shell脚本。 Step4: 下面开始体验一下魔法操作符的威力。 Step5: <!--====--> cell magics的简单例子 Step...
1,919
<ASSISTANT_TASK:> Python Code: %projects set ml-autoawesome import os PROJECT = 'ml-autoawesome' # CHANGE THIS BUCKET = 'ml-autoawesome-cmle' # CHANGE THIS REGION = 'us-central1' # CHANGE THIS os.environ['PROJECT'] = PROJECT # for bash os.environ['BUCKET'] = BUCKET # for bash os.environ['REGION'] = REGION # for bas...
<SYSTEM_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> Step 1 Step3: <h2> 2. Preprocessing </h2> Step4: <h2> Local preprocessing, training and prediction </h2> Step5: <h3> Training </h3> Step...
1,920
<ASSISTANT_TASK:> Python Code: HISTORY = 4 NRUNS = 50 parameters = { 'chaos': 0, 'risk_x_average_variance': 1, 'dividends': 1, 'discount_rate': 0.001, 'intensity_of_choice':2, 'fundamentalist_adaptive_parameter':1, 'chartist_adaptive_parameter':1.9, 'bubble_sensitivity':1800, 'fitnes...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: initialization Step2: Sequence of events / simulation Step3: Log returns Step4: Sequence of events / simulation Step5: Log returns
1,921
<ASSISTANT_TASK:> Python Code: #CCL cosmology cosmo_ccl = ccl.Cosmology(Omega_c = 0.30711 - 0.048254, Omega_b = 0.048254, h = 0.677, sigma8 = 0.8822714165197718, n_s=0.96, Omega_k = 0, transfer_function='eisenstein_hu') #ccl_cosmo_set_high_prec (cosmo_ccl) cosmo_numcosmo, dist, ps_lin, ps_nln, hmfunc = create_nc_obj (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: Define proxy modelling Step2: initialize the ClusterAbundance object
1,922
<ASSISTANT_TASK:> Python Code: import pandas import numpy import toyplot import toyplot.pdf import toyplot.png import toyplot.svg print('Pandas version: ', pandas.__version__) print('Numpy version: ', numpy.__version__) print('Toyplot version: ', toyplot.__version__) column_names = ['MPG', 'Cylinder...
<SYSTEM_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 in the "auto" dataset. This is a fun collection of data on cars manufactured between 1970 and 1982. The source for this data can be found a...
1,923
<ASSISTANT_TASK:> Python Code: from poppy.creatures import PoppyHumanoid creature = PoppyHumanoid(simulator='vrep') creature.reset_simulation() import pypot creature.stop_simulation() pypot.vrep.close_all_connections() from poppy.creatures import PoppyHumanoid poppy = PoppyHumanoid(simulator='vrep') from __future__ ...
<SYSTEM_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 - Redémarrer la simulatiuon Step2: 4 - Eteindre la simulation Step3: 5 - Moteurs & capteurs Step4: Explication Step5: Explication Step6: ...
1,924
<ASSISTANT_TASK:> Python Code: new_data = new_data.to_crs("+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=37.5 +lon_0=-96 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs ") new_data['logBiomass'] = new_data.apply(lambda x : np.log(x.plotBiomass),axis=1) new_data['newLon'] = new_data.apply(lambda c : c.geometry.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: Add log of the Biomass Step2: Linear Regression Step3: STOPPPP!! Step4: Now with distance restriction (experimental!) Step5: Model Fitting U...
1,925
<ASSISTANT_TASK:> Python Code: !pip install -I "phoebe>=2.0,<2.1" import phoebe from phoebe import u # units logger = phoebe.logger() b = phoebe.default_binary() b.get_setting() b['setting'] b['plotting_backend@setting'] b['plotting_backend@setting'].choices b['log_history@setting'].description b['log_history@set...
<SYSTEM_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: Accessing Settings Step3:...
1,926
<ASSISTANT_TASK:> Python Code: import pandas as pd %matplotlib inline import matplotlib.pyplot as plt # package for doing plotting (necessary for adding the line) import statsmodels.formula.api as smf # package we'll be using for linear regression import matplotlib.pyplot as plt import matplotlib import pandas as pd 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: 2. Read in the hanford.csv file Step2: <img src="images/hanford_variables.png"> Step3: 4. Calculate the coefficient of correlation (r) and gen...
1,927
<ASSISTANT_TASK:> Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() %matplotlib inline from cpyquickhelper.examples.vector_container_python import ( RandomTensorVectorFloat, RandomTensorVectorFloat2) rnd = RandomTensorVectorFloat(10, 10) result = rnd.get_tensor_vector() print(result) res...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Two identical classes Step2: Scenarii
1,928
<ASSISTANT_TASK:> Python Code: from flow.scenarios import MergeScenario from flow.core.params import VehicleParams from flow.controllers import IDMController from flow.core.params import SumoCarFollowingParams # create an empty vehicles object vehicles = VehicleParams() # add some vehicles to this object of type "huma...
<SYSTEM_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 schematic of the above network is displayed in the figure below. As we can see, the edges at the start of the main highway and of the on-merge...
1,929
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cnrm-cerfacs', 'sandbox-2', 'atmoschem') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("...
<SYSTEM_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...
1,930
<ASSISTANT_TASK:> Python Code: randinds = np.random.permutation(len(digits.target)) # shuffle the values from sklearn.utils import shuffle data, targets = shuffle(digits.data, digits.target, random_state=0) # scale the data from sklearn.preprocessing import StandardScaler scaler = StandardScaler().fit(data) data_scaled...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Prep is done, time for the model. Step2: We've defined the cost and accuracy functions, time to train our model.
1,931
<ASSISTANT_TASK:> Python Code: # Authors: Jean-Remi King <jeanremi.king@gmail.com> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD-3-Clause import matplotlib.pyplot as plt from sklearn.pipeline import make_pipeline from sklearn.preprocess...
<SYSTEM_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 train the classifier on all left visual vs auditory trials Step2: Score on the epochs where the stimulus was presented to the right. St...
1,932
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import fredpy as fp import matplotlib.pyplot as plt plt.style.use('classic') %matplotlib inline fp.api_key = '################################' fp.api_key = fp.load_api_key('fred_api_key.txt') u = fp.series('UNRATE') plt.plot(u.data.index,u.data.v...
<SYSTEM_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 API key Step2: or by reading from a text file containing only the text of the API key in the first line Step3: If fred_api_key.txt is not...
1,933
<ASSISTANT_TASK:> Python Code: grammar = S -> NP VP S -> VP NP -> DET N VP -> V[SUBCAT=tr] NP VP -> V[SUBCAT=intr] DET -> "das" N -> "Kind" | "Buch" V[SUBCAT=tr] -> "lies" V[SUBCAT=tr] -> "liest" V[SUBCAT=intr] -> "schlaf" V[SUBCAT=intr] -> "schläft" pos_sentences = [ "das Kind schläft", "das Kind liest das B...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Übungsblatt 8 Step2: Hier wurde versucht, Aufforderungssätze zu modellieren. Allerdings akzeptiert diese Grammatik immer noch viele ungrammatis...
1,934
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'miroc', 'sandbox-3', '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...
1,935
<ASSISTANT_TASK:> Python Code: import gensim import os import collections import random # Set file names for train and test data test_data_dir = '{}'.format(os.sep).join([gensim.__path__[0], 'test', 'test_data']) lee_train_file = test_data_dir + os.sep + 'lee_background.cor' lee_test_file = test_data_dir + os.sep + 'l...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: What is it? Step2: Define a Function to Read and Preprocess Text Step3: Let's take a look at the training corpus Step4: And the testing corpu...
1,936
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] view_sentence_range = (100, 110) DON'T MODIFY ANYTHING IN THIS CELL import ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: TV Script Generation Step3: Explore the Data Step6: Implement Preprocessing Functions Step9: Tokenize Punctuation Step11: Preprocess all the...
1,937
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt #print(plt.style.available) plt.style.use('presentation') G = 6.67E-11 # Constante de gravitation universelle en m(3)*s(-2)*kg(-1) Mt = 5.98E24 # Masse de la terre en kg Rt = 6378E3 # Rayon de la terre en m Wt = (2*np.pi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Définissons ensuite les constantes utilisées Step2: 1. Movement orbital Step3: 1.2 Fonctions accélération Step4: Exemple Step5: Exemple Step...
1,938
<ASSISTANT_TASK:> Python Code: # imports import pandas as pd import numpy as np import time import os from tabulate import tabulate import sys from operator import add from pyspark import SparkContext from pyspark.sql import SparkSession from pyspark.sql import SQLContext from pyspark.sql import functions as F #https:/...
<SYSTEM_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 types Step2: Dealing with Outliers Step3: Winsorize for Outliers Step4: New Chart Step5: Label Encoding Step6: Feature interaction Ste...
1,939
<ASSISTANT_TASK:> Python Code: import numpy as np %matplotlib inline temp_cidade1 = np.array([33.15,32.08,32.10,33.25,33.01,33.05,32.00,31.10,32.27,33.81]) temp_cidade2 = np.array([35.17,36.23,35.22,34.33,35.78,36.31,36.03,36.23,36.35,35.25]) temp_cidade3 = np.array([22.17,23.25,24.22,22.31,23.18,23.31,24.11,23.53,24....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Vamos calcular a média de temperatura de cada cidade e utilizá-la para gerar um gráfico Step2: Agora, vamos criar um gráfico de barras utilizan...
1,940
<ASSISTANT_TASK:> Python Code: import ipyvolume import ipyvolume as ipv import vaex ds = vaex.example() N = 10000 ipv.figure() quiver = ipv.quiver(ds.data.x[:N], ds.data.y[:N], ds.data.z[:N], ds.data.vx[:N], ds.data.vy[:N], ds.data.vz[:N], size=1, size_selected=5, color_selec...
<SYSTEM_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 load some data from vaex, but only use the first 10 000 samples for performance reasons of Bokeh. Step2: We make a quiver plot using ipyvolu...
1,941
<ASSISTANT_TASK:> Python Code: def get_words(url): import requests words = requests.get(url).content.decode('latin-1') word_list = words.split('\n') index = 0 while index < len(word_list): word = word_list[index] if ';' in word or not word: word_list.pop(index) el...
<SYSTEM_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>Read the text being analyzed and count the proportion of positive and negative words in the text</h4> Step2: <h4>Compute sentiment by looki...
1,942
<ASSISTANT_TASK:> Python Code: # Load image import cv2 import numpy as np from matplotlib import pyplot as plt # Load image as grayscale image = cv2.imread('images/plane_256x256.jpg', cv2.IMREAD_GRAYSCALE) # Create kernel kernel = np.array([[0, -1, 0], [-1, 5,-1], [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: Load Image As Greyscale Step2: Sharpen Image Step3: View Image
1,943
<ASSISTANT_TASK:> Python Code: import subprocess completed = subprocess.run(['ls', '-l']) completed completed = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE) completed import subprocess try: completed = subprocess.run( 'echo to stdout; echo to stderr 1>&2; exit 1', shell=True, stdou...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Capturing Output Step2: Suppressing Output Step3: Execute on shell Step4: if you don't run this command on a shell, this is a error, because ...
1,944
<ASSISTANT_TASK:> Python Code: import pints import pints.toy as toy import numpy as np import matplotlib.pyplot as plt # Load a forward model model = toy.LogisticModel() # Create some toy data real_parameters = [0.015, 500] times = np.linspace(0, 1000, 100) org_values = model.simulate(real_parameters, times) # Add nois...
<SYSTEM_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 Pints' standard 1d histograms Step2: Customise the plots
1,945
<ASSISTANT_TASK:> Python Code: import logging import time from contextlib import contextmanager import os from multiprocessing import Process import psutil import numpy as np import pandas as pd from numpy.random import RandomState from sklearn import decomposition from sklearn.cluster import MiniBatchKMeans from sklea...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Dataset preparation Step2: Create a train/test split Step3: We'll use very simple preprocessing with stemming to tokenize each document. YMMV;...
1,946
<ASSISTANT_TASK:> Python Code: mod = 1000000007 arr =[[ None for i in range(1001 ) ] for j in range(1001 ) ] def Preprocess() : arr[0 ][0 ] = 1 for i in range(1 , 1001 ) : arr[i ][0 ] = 1 for j in range(1 , i ) : arr[i ][j ] =(arr[i - 1 ][j - 1 ] + arr[i - 1 ][j ] ) % mod  arr[i ][i ] = 1   def ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
1,947
<ASSISTANT_TASK:> Python Code: # Authors: Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) import os.path as op import numpy as np import matplotlib.pyplot as plt import mne from mne import find_events, fit_dipole from mne.datasets.brainstorm import bst_phantom_elekta from mne.io import read_raw_fif pr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The data were collected with an Elekta Neuromag VectorView system at 1000 Hz Step2: Data channel array consisted of 204 MEG planor gradiometers...
1,948
<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: TensorFlow 2 início rápido para especialistas Step2: Carregue e prepare o [conjunto de dados MNIST] (http Step3: Use tf.data para agrupar e em...
1,949
<ASSISTANT_TASK:> Python Code: # Load libraries from sklearn import datasets from sklearn.preprocessing import StandardScaler from sklearn.cluster import AgglomerativeClustering # Load data iris = datasets.load_iris() X = iris.data # Standarize features scaler = StandardScaler() X_std = scaler.fit_transform(X) # Cre...
<SYSTEM_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 Iris Flower Data Step2: Standardize Features Step3: Conduct Agglomerative Clustering Step4: Show Cluster Membership
1,950
<ASSISTANT_TASK:> Python Code: %matplotlib inline import netCDF4 import matplotlib.pyplot as plt dataurl = "http://thredds.socib.es/thredds/dodsC/mooring/conductivity_and_temperature_recorder/buoy_canaldeibiza-scb_sbe37006/L1/dep0003_buoy-canaldeibiza_scb-sbe37006_L1_latest.nc" with netCDF4.Dataset(dataurl) as ds: ...
<SYSTEM_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 data from a mooring located in the Ibiza Channel.<br/> Step2: Read the file Step3: The variable storing the temperature is not cal...
1,951
<ASSISTANT_TASK:> Python Code: # Librerias utilizadas import pandas as pd import sys import urllib import os import numpy as np # Configuracion del sistema print('Python {} on {}'.format(sys.version, sys.platform)) print('Pandas version: {}'.format(pd.__version__)) import platform; print('Running on {} {}'.format(platf...
<SYSTEM_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 descarga de datos se realiza desde el sitio Beta de INEGI. Los datos de la Encuesta Intercensal 2015 se encuentran en http Step2: Las ligas ...
1,952
<ASSISTANT_TASK:> Python Code: R=5. def z(x,y): return sqrt(x**2+y**2+R**2.) x = linspace(-10,10,100) #Definiendo el dominio en x y = linspace(-10,10,100) #Definiendo el dominio en y X, Y = meshgrid(x, y) #Formando la grilla x,y fig = figure(figsize=(6,6)) ax = fig.gca(projection='3d') surf = ax.plot_surface(X, Y, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Todo luce un poco mejor usando coordenadas polares en el plano xy Step2: Cono (R=0)
1,953
<ASSISTANT_TASK:> Python Code: import numpy as NUM import pylab as PYLAB import arcpy as ARCPY import numpy as NUM import SSDataObject as SSDO import scipy as SCIPY import pandas as PANDAS inputFC = r'../data/CA_Polygons.shp' ssdo = SSDO.SSDataObject(inputFC) ssdo.obtainData(ssdo.oidName, ['PCR2008', 'POPDEN08', 'PERC...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Initialize Data Object, Select Fields and Obtain Data Step2: Make Use of PANDAS Data Frame Step3: Push PANDAS Data Frame to R Data Frame - Use...
1,954
<ASSISTANT_TASK:> Python Code: #Importation des librairies utilisées import pandas as pd import numpy as np import pickle import functools from tqdm import tqdm import keras.models as km import keras.layers as kl N = 100000 DATA_DIR = "" X = np.load(DATA_DIR+"data/description_coque.npy")[:N] print(X.shape) print(X[: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: Téléchargement des données Step2: Exercice Vérifiez que toutes les séquences sont bien de tailles 197. Step3: Mise en forme des données Step4...
1,955
<ASSISTANT_TASK:> Python Code: import pandas as pd # The Dataset comes from: # https://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits # Load up the data. with open('../Datasets/optdigits.tes', 'r') as f: testing = pd.read_csv(f) with open('../Datasets/optdigits.tra', 'r') as f: training = ...
<SYSTEM_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 have a look at these bitmaps of handwritten digits Step2: Train the SVM Classifier Step3: Checkpoint Step4: The model's prediction was ...
1,956
<ASSISTANT_TASK:> Python Code: from fastai.collab import * from fastai.tabular import * user,item,title = 'userId','movieId','title' path = untar_data(URLs.ML_SAMPLE) path ratings = pd.read_csv(path/'ratings.csv') ratings.head() data = CollabDataBunch.from_df(ratings, seed=42) y_range = [0,5.5] learn = collab_learner...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Collaborative filtering example Step2: That's all we need to create and train a model Step3: Movielens 100k Step4: Here's some benchmarks on ...
1,957
<ASSISTANT_TASK:> Python Code: !pip install -I "phoebe>=2.1,<2.2" %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['q'] = 0.8 b['ecc'] = 0.1 b['irrad_method'] = 'none' b.add_dataset('orb', times=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: This first line is only necessary for ipython noteboooks - it allows the plots to be shown on this page instead of in interactive mode Step2: A...
1,958
<ASSISTANT_TASK:> Python Code: import os import logging from datetime import datetime import numpy as np import tensorflow as tf import tensorflow_transform as tft import tensorflow.keras as keras from google.cloud import aiplatform as vertex_ai from google.cloud.aiplatform import hyperparameter_tuning as hp_tuning 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: Setup Google Cloud project Step2: Set configurations Step3: Create Vertex TensorBoard instance Step4: Initialize workspace Step5: Initialize...
1,959
<ASSISTANT_TASK:> Python Code: import collections Person = collections.namedtuple('Person', 'name age') bob = Person(name='Bob', age=30) print('\nRepresentation:', bob) jane = Person(name='Jane', age=29) print('\nField by name:', jane.name) print('\nFields by index:') for p in [bob, jane]: print('{} is {} years old...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Just like a regular tuple, a namedtuple is immutable. This restriction allows tuple instances to have a consistent hash value, which makes it po...
1,960
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd %matplotlib inline df1 = pd.read_csv('../data/df1',index_col=0) df2 = pd.read_csv('../data/df2') df1['A'].hist() import matplotlib.pyplot as plt plt.style.use('ggplot') df1['A'].hist() plt.style.use('bmh') df1['A'].hist() plt.style.use('dark_back...
<SYSTEM_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 informacion Step2: Hojas de estilo Step3: Utilizando estilos Step4: Ahora tu grafica se visulizara de la siguiente manera Step5: Por lo p...
1,961
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('C:\Anaconda2\envs\dato-env\Lib\site-packages') import graphlab sales = graphlab.SFrame('kc_house_data.gl/') train_data,test_data = sales.random_split(.8,seed=0) # Let's compute the mean of the House Prices in King County in 2 different ways. prices = sales['...
<SYSTEM_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 house sales data Step2: Split data into training and testing Step3: Useful SFrame summary functions Step4: As we see we get the same ans...
1,962
<ASSISTANT_TASK:> Python Code: from fretbursts import * sns = init_notebook() filename = "./data/0023uLRpitc_NTP_20dT_0.5GndCl.hdf5" d = loader.photon_hdf5(filename) loader.alex_apply_period(d) d.calc_bg(bg.exp_fit, time_s=30, tail_min_us='auto', F_bg=1.7) d.burst_search() ph = d.get_ph_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: Getting the timestamps Step2: This are streams of all timestamps (both inside and outside the bursts). Step3: Masks are arrays of booleans (Tr...
1,963
<ASSISTANT_TASK:> Python Code: import networkx as nx import matplotlib.pyplot as plt import numpy as np import pandas as pd import json from collections import defaultdict from datetime import datetime, date from random import randint from networkx.readwrite.json_graph import node_link_data %matplotlib inline G = nx.re...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step4: 2009 H1N1 lineage trace Step5: 2013 H7N9 lineage trace
1,964
<ASSISTANT_TASK:> Python Code: import numpy as np # In Jupyter, all commands starting with ! are mapped as SHELL commands !head stockholm_td_adj.dat np.genfromtxt? st_temperatures = np.genfromtxt('stockholm_td_adj.dat', skip_header=1) st_temperatures.shape st_temperatures[:10, ] st_te...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Comma-separated values (CSV) Step2: DYI Step3: Numpy's native file format Step4: See also Step5: NumPy for Matlab Users (really?) Step6: If...
1,965
<ASSISTANT_TASK:> Python Code: !wget -O - 'http://www.cs.nyu.edu/~roweis/data/nips12raw_str602.tgz' > /tmp/nips12raw_str602.tgz import tarfile filename = '/tmp/nips12raw_str602.tgz' tar = tarfile.open(filename, 'r:gz') for item in tar: tar.extract(item, path='/tmp') import os, re from smart_open import smart_open ...
<SYSTEM_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 following sections we will load the data, pre-process it, train the model, and explore the results using some of the implementation's fun...
1,966
<ASSISTANT_TASK:> Python Code: text = Als der Abend herbeikam und die Freunde in einer weitumherschauenden Laube saßen, trat eine ansehnliche Figur auf die Schwelle, welche unser Freund sogleich für den Barbier von heute früh erkannte. Auf einen tiefen, stummen Bückling des Mannes erwiderte Lenardo: Ihr kommt, wie imme...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Table of Contents Step2: Textblob installieren Step3: Achtung Step4: Das Gute daran, ist, dass wir - wie oben - über dieses Objekt iterieren...
1,967
<ASSISTANT_TASK:> Python Code: x = 1 y = 2 z = x + y z * 3 from math import sin sin(2) my_result = sin(2) my_result = sin(2) print(my_result) print('hello') hello = 'Hello, world!' print(hello) print('The man said:', hello, 'How are you?') name = input('What is your name?') age = input('What is your age?') 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: In good mathematical tradition, I've named various things x, y and z and re-used them in various lines of the program. You are free to choose wh...
1,968
<ASSISTANT_TASK:> Python Code: from pytadbit.mapping.full_mapper import full_mapping r_enz = 'MboI' ! mkdir -p results/iterativ/$r_enz ! mkdir -p results/iterativ/$r_enz/01_mapping # for the first side of the reads full_mapping(gem_index_path='/media/storage/db/reference_genome/Homo_sapiens/hg38/hg38.gem', ...
<SYSTEM_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 full mapping function can be used to perform either iterative or fragment-based mapping, or a combination of both. Step2: And for the secon...
1,969
<ASSISTANT_TASK:> Python Code: from pymldb import Connection mldb = Connection() inceptionUrl = 'file://mldb/mldb_test_data/models/inception_dec_2015.zip' print mldb.put('/v1/functions/fetch', { "type": 'fetcher', "params": {} }) print mldb.put('/v1/functions/inception', { "type": 'tensorflow.graph', "...
<SYSTEM_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 a TensorFlow graph Step2: Scoring an image Step3: This is great! With only 3 REST calls we were able to run a deep neural network on a...
1,970
<ASSISTANT_TASK:> Python Code: # Versão da Linguagem Python from platform import python_version print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version()) # Instala o TensorFlow #!pip install -q tensorflow==2.5 # Imports import sklearn import numpy as np import tensorflow as tf import matplotli...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Carregando os Dados (Imagens) Step2: Pré-Processamento dos Dados Step3: Label encoding (convertendo string para valor numérico) Step4: Datase...
1,971
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pyfolio as pf stock_rets = pf.utils.get_symbol_rets('FB') out_of_sample = stock_rets.index[-40] pf.create_bayesian_tear_sheet(stock_rets, live_start_date=out_of_sample) help(pf.bayesian.run_model) # Run model that assumes returns to be T-distributed trace = 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: Fetch the daily returns for a stock Step2: Create Bayesian tear sheet Step3: Lets go through these row by row Step4: For example, to run a mo...
1,972
<ASSISTANT_TASK:> Python Code: # Import external libraries import matplotlib.pyplot as plt # Settings %matplotlib inline pvarray_parameters = { 'n_pvrows': 4, # number of pv rows 'pvrow_height': 1, # height of pvrows (measured at center / torque tube) 'pvrow_width': 1, # width of ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Prepare PV array parameters Step2: Create a PV array and its shadows Step3: Plot the PV array. Step4: As we can see in the plot above Step5: ...
1,973
<ASSISTANT_TASK:> Python Code: import pathlib import os from typing import Dict, List, Mapping, Optional, Sequence, Tuple, Union import uuid import zlib from IPython.display import HTML import matplotlib.animation as animation import matplotlib.pyplot as plt import numpy as np import tensorflow as tf import tensorflow_...
<SYSTEM_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 location Step2: Create dataset Step3: Load one example Step10: Visualize TF Example Step12: Display animation Step14: Config Step15: ...
1,974
<ASSISTANT_TASK:> Python Code: %%writefile ../../user_models/cylinder_Ascan_2D.in #title: A-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.100 ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Geometry of a metal cylinder buried in a dielectric half-space Step2: By examining the spectrum of a Ricker waveform it is evident much higher ...
1,975
<ASSISTANT_TASK:> Python Code: from __future__ import print_function, division import matplotlib as mpl import matplotlib.pyplot as plt %matplotlib inline import numpy as np import pandas as pd import textwrap import os import sys import warnings warnings.filterwarnings('ignore') # special things from pivottablejs 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: Notebook Extensions Step2: Snippets Menu Step3: Python Markdown -- Maybe doesn't work right now for some reason? Step4: Collapsible Headings
1,976
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import json import matplotlib.pyplot as plt %matplotlib inline loans = pd.read_csv('lending-club-data.csv') loans.head(2) loans.columns features = ['grade', # grade of the loan 'term', # the term of the loan ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Getting the data ready Step2: Extracting the target and the feature columns Step3: Transform categorical data into binary features Step4: Let...
1,977
<ASSISTANT_TASK:> Python Code: # First import the model. Here we use the HBV version from wflow.wflow_sbm import * import IPython from IPython.display import display, clear_output %pylab inline #clear_output = IPython.core.display.clear_output # Here we define a simple fictious reservoir reservoirstorage = 15000 def 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: Set model run-time parameters Step2: Here we make a pit in the middle of the main river. This will be the inflow to the reservoir Step3: Run f...
1,978
<ASSISTANT_TASK:> Python Code: from sklearn.preprocessing import OneHotEncoder encoder = OneHotEncoder() x0 = np.random.choice(3, 10) x0 encoder.fit(x0[:, np.newaxis]) X = encoder.transform(x0[:, np.newaxis]).toarray() X dfX = pd.DataFrame(X, columns=encoder.active_features_) dfX from sklearn.datasets import load_bost...
<SYSTEM_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: 분산 분석을 이용한 모형 비교
1,979
<ASSISTANT_TASK:> Python Code: import pandas as pd df = pd.read_csv('tmdb_5000_movies.csv.gz', compression='gzip') df.info() df.head() df = df[['title', 'tagline', 'overview', 'genres', 'popularity']] df.tagline.fillna('', inplace=True) df['description'] = df['tagline'].map(str) + ' ' + df['overview']...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Your Turn Step2: Extract TF-IDF Features Step3: Cluster Movies using K-Means Step4: Affinity Propagation Step5: Hierarchical Clustering Step...
1,980
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np # Our data is cleaned by cleaning utility code df = pd.read_csv('Clean_Data_Adults_1.csv') # Separate labels and Features df_labels = df['Depressed'] df_feats = df.drop(['Depressed', 'Unnamed: 0'], axis=1, inplace=False) X = df_feats.get_values() # ...
<SYSTEM_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. State assumptions about your data Step2: 5. Compute accuracy Step3: 6. Plot accuracy vs. sample size in simulation Step4: 7. Apply method ...
1,981
<ASSISTANT_TASK:> Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', '..', 'notebook_format')) from formats import load_style load_style(plot_style=False) os.chdir(path) # 1. magic for inline pl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Approximate Nearest Neighborhood Search with Navigable Small World Step2: Given the output matrix, we would like to compute each of its nearest...
1,982
<ASSISTANT_TASK:> Python Code: import math a = math.sqrt(16.0) b = math.ceil(111.3) c = math.floor(89.9) print(a, b, c) import math print(math.pi) PI = math.pi a = math.sqrt(PI) b = math.ceil(PI) c = math.floor(PI) print(a, b, c) import csv f = open("nfl.csv") csvreader = csv.reader(f) nfl = list(csvreader) print(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: Answer Step2: 4 Step3: Answer Step4: 5 Step5: 6
1,983
<ASSISTANT_TASK:> Python Code: import numpy as np np.random.seed(42) import tensorflow as tf tf.set_random_seed(42) from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) epochs = 20 batch_size = 128 display_progress = 40 # after this many batches, ou...
<SYSTEM_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: Set neural network hyperparameters Step3: Set parameters for each layer Step4: Define placeholder Tensors for inputs and lab...
1,984
<ASSISTANT_TASK:> Python Code: # Setup a target configuration conf = { # Platform and board to target "platform" : "linux", "board" : "juno", # Login credentials "host" : "192.168.0.1", "username" : "root", "password" : "", # Local installation path "tftp" : { ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Attributes Step2: Functions Step3: A special TestEnv attribute is <b>target</b>, which represent a <b>devlib instance</b>.<br> Step4: Sample ...
1,985
<ASSISTANT_TASK:> Python Code: import quandl data = quandl.get('NIKKEI/INDEX') data[:5] data_normal = (((data['Close Price']).to_frame())[-10000:-1])['Close Price'] data_normal[-10:-1] # 最新のデータ10件を表示 data_normal = data_normal.fillna(method='pad').resample('W-MON').fillna(method='pad') data_normal[:5] type(data_normal....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 抜けデータが目立ったため、週単位でのデータを入手します Step2: データの用い方 Step3: 以下のグラフから、2000年ごろのデータからの推測でも十分に予測が行える可能性が伺えます。 Step4: ARIMAモデルでモデル推定を行うための下準備として、株価の変化量を取得しま...
1,986
<ASSISTANT_TASK:> Python Code: from examples.cfd import plot_field, init_hat import numpy as np %matplotlib inline # Some variable declarations nx = 50 ny = 50 nt = 100 xmin = 0. xmax = 2. ymin = 0. ymax = 1. dx = (xmax - xmin) / (nx - 1) dy = (ymax - ymin) / (ny - 1) # Initialization p = np.zeros((nx, ny)) pd = np.z...
<SYSTEM_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 now pretty much use our previous implementation, although we will use pd instead of pn for consistency with the original. Our boundary co...
1,987
<ASSISTANT_TASK:> Python Code: # Imports. from typing import List import astropy.io.ascii import astropy.table import h5py import numpy import sklearn.linear_model import sklearn.cross_validation # Globals. # This file stores the ATLAS-CDFS and SWIRE-CDFS catalogues. CROWDASTRO_PATH = '../data/crowdastro_swire.h5' # Th...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step4: Crowdastro ATLAS-CDFS Catalogue Step5: Making predictions Step6: Generating the catalogue
1,988
<ASSISTANT_TASK:> Python Code: %run "../src/start_session.py" %run "../src/recurrences.py" c = IndexedBase('c') checks_recurrence_spec=recurrence_spec(recurrence_eq=Eq(c[n]/(n+1), 2/(n+1) + c[n-1]/n), recurrence_symbol=c, variables=[n]) ch...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Introduction Step2: Function do_unfolding_steps allow us to perform unfolding or unrolling on occurrences of the inductively defined symbol. Do...
1,989
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import tensorflow as tf CONTENT_FILE = '/home/ishiyama/image_style_transfer/image/input/test_input_01.JPG' STYLE_FILE = '/home/ishiyama/image_style_transfer/image/style/test_style_01.jpg' class Image(np.ndarray): 画像を扱うためのnumpy.ndarray XX...
<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: Image Style Transferの実装 Step4: VGGを実装する Step6: Maxプーリング層を実装する Step9: 畳込みとプーリング処理の途中経過を保持するクラスを実装する Step10: VGGの畳込みとプーリング層を構築する Step11: 画像を合...
1,990
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import numexpr as ne import numba import math import random import matplotlib.pyplot as plt import scipy as sp import sys %load_ext Cython def primes_python(n): primes = [False, False] + [True] * (n - 2) i= 2 while i < n: # We do ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Table of Contents Step2: Let's evaluate the performance for the first version Step3: And now we write our first Cython version, by just adding...
1,991
<ASSISTANT_TASK:> Python Code: data_rang = 9 pr_type = ['a', 'b', 'c', 'd'] p_type = [ np.random.choice(pr_type) for i in range(data_rang) ] data = {'product_name' : ['x0', 'x1', 'x3', 'x2', 'x4', 'x5', 'x6', 'x7', 'x8'], 'T1': np.random.randint(100, size = [data_rang]), 'T2': np.random.randint(100, size ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: main function Step2: 查询函数, 通过输入指定产品名和起止时间参数, 返回该产品在该类中的销售排名 Step3: another form of datafram
1,992
<ASSISTANT_TASK:> Python Code: import os from skimage import io from skimage.color import rgb2gray from skimage import transform from math import ceil IMGSIZE = (100, 100) def load_images(folder, scalefactor=(2, 2), labeldict=None): images = [] labels = [] files = os.listdir(folder) for file in (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: Step2: Training LeNet Step3: Training Random Forests Step4: So training on raw pixel values might not be a good idea. Let's build a feature extractor...
1,993
<ASSISTANT_TASK:> Python Code: from pynq.overlays.base import BaseOverlay from pynq.lib.video import * base = BaseOverlay("base.bit") hdmiin_frontend = base.video.hdmi_in.frontend hdmiin_frontend.start() hdmiin_frontend.mode hdmiout_frontend = base.video.hdmi_out.frontend hdmiout_frontend.mode = hdmiin_frontend.mod...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: HDMI Frontend Step2: Creating the device will signal to the computer that a monitor is connected. Starting the frontend will wait attempt to de...
1,994
<ASSISTANT_TASK:> Python Code: from flexx import app, ui, react app.init_notebook() # A bit of boilerplate to import an example app import sys #sys.path.insert(0, r'C:\Users\almar\dev\flexx\examples\ui') sys.path.insert(0, '/home/almar/dev/pylib/flexx/examples/ui') from twente_temperature import Twente ui.Button(text=...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Any widget can be shown by using it as a cell output Step2: Because apps are really just Widgets, we can show our app in the same way Step3: A...
1,995
<ASSISTANT_TASK:> Python Code: def fact(n ) : res = 1 for i in range(2 , n + 1 ) : res = res * i  return res  def nCr(n , r ) : return fact(n ) //(( fact(r ) * fact(n - r ) ) )  n = 2 print("Number ▁ of ▁ Non - Decreasing ▁ digits : ▁ ", nCr(n + 9 , 9 ) ) <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:
1,996
<ASSISTANT_TASK:> Python Code: import pandas as pd import re import sys import numpy as np textfile = open('tournamentinfo.txt') text_table = [line.strip() for line in textfile.readlines()] text_table player_state = [] player_number = [] id_data = [] name_data = [] state = '([A-Z]{2})' number = '([0-9]{1})' dash =...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Reading the text file into the Ipython Notebook Step2: First i want to seperate the lines so i will strip them, and store them in a list using ...
1,997
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import iris import iris.plot as iplt import iris.coord_categorisation import cf_units import numpy %matplotlib inline infile = '/g/data/ua6/DRSv2/CMIP5/NorESM1-M/rcp85/mon/ocean/r1i1p1/hfbasin/latest/hfbasin_Omon_NorESM1-M_rcp85_r1i1p1_200601-210012.nc' cu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Ocean heat transport in CMIP5 models Step5: So for any given year, the annual mean shows ocean heat transport away from the tropics. Step6: So...
1,998
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt from pandas_datareader.data import DataReader endog = DataReader('UNRATE', 'fred', start='1954-01-01') hp_cycle, hp_trend = sm.tsa.filters.hpfilter(endog, lamb=129600) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Hodrick-Prescott (HP) filter Step2: Unobserved components and ARIMA model (UC-ARIMA) Step3: Unobserved components with stochastic cycle (UC) S...
1,999
<ASSISTANT_TASK:> Python Code: from enum import Enum class AccountType(Enum): SAVINGS = 1 CHECKING = 2 AccountType.SAVINGS AccountType.SAVINGS == AccountType.SAVINGS AccountType.SAVINGS == AccountType.CHECKING AccountType.SAVINGS.name class BankAccount(): def __init__(self,owner,accountType): se...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: An Enum stands for an enumeration, it's a convenient way for you to define lists of things. Typing Step2: returns a Python representation of an...