Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
3,000
<ASSISTANT_TASK:> Python Code: %pylab inline import os import urllib dataset = 'mnist.pkl.gz' def reporthook(a,b,c): print "\rdownloading: %5.1f%%"%(a*b*100.0/c), if not os.path.isfile(dataset): origin = "https://github.com/mnielsen/neural-networks-and-deep-learning/raw/master/data/mnist.pkl.gz" ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 下載 mnist 資料 Step2: 載入訓練資料 train_set 和測試資料 test_set Step3: 查看 mnist 資料的概況,用 .shape 看 np.array 的形狀 Step4: 資料的第一部份,每一筆都是一個 28x28 的圖片(28*28=784...
3,001
<ASSISTANT_TASK:> Python Code: titanic_data = titanic.drop(['PassengerId','Name','Ticket'],1) titanic_data.head() sb.boxplot(x='Pclass',y='Age',data=titanic_data) def age_approx(cols): age = cols[0] pclass = cols[1] if pd.isnull(age): if pclass == 1: return 37 elif pclass == 2:...
<SYSTEM_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 need to take care of the missing data for Age variable. Need to approximate- one way, to take mean age for all the missing values. Step2: I...
3,002
<ASSISTANT_TASK:> Python Code: import os as os import pandas as pd import numpy as np from scipy import stats, integrate import matplotlib.pyplot as plt import matplotlib as mpl import seaborn as sns from statsmodels.distributions.empirical_distribution import ECDF import datetime as dt plt.style.use('seaborn-whitegrid...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Use the bash =) Step2: So parsing does not work, do it manually Step3: Some statistics about the payment. Step4: So thats the statistic about...
3,003
<ASSISTANT_TASK:> Python Code: #This guided coding excercise requires associated .csv files: CE1.csv, CH1.csv, CP1.csv, Arnold1.csv, Bruce1.csv, and Tom1.csv #make sure you have these supplemental materials ready to go in your active directory before proceeding #Let's start coding! We first need to make sure our prelim...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Scene 2 Step2: Chris Hemsworth Step3: Our data looks good! The axes are a little strange, but we just want to make sure we have data we can wo...
3,004
<ASSISTANT_TASK:> Python Code: N = 10000 x = np.random.normal(0, np.pi, N) y = np.sin(x) + np.random.normal(0, 0.2, N) p = figure(webgl=True) p.scatter(x, y, alpha=0.1) show(p) !conda list | egrep "jupyter|notebook" p = figure(plot_height=200, sizing_mode='scale_width') p.scatter(x, y, alpha=0.1) show(p) N = 4000 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: Responsive in notebook
3,005
<ASSISTANT_TASK:> Python Code: # col() selects columns from a data frame, year() works on dates, and udf() creates user # defined functions from pyspark.sql.functions import col, year, udf # Plotting library and configuration to show graphs in the notebook import matplotlib.pyplot as plt %matplotlib inline df = sqlCon...
<SYSTEM_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 the data set Step2: Year collected by continent Step4: There are a lot of things that are not continents there! While iDigBio cleans s...
3,006
<ASSISTANT_TASK:> Python Code: #general imports import matplotlib.pyplot as plt import pygslib import numpy as np #make the plots inline %matplotlib inline #get the data in gslib format into a pandas Dataframe mydata= pygslib.gslib.read_gslib_file('../datasets/cluster.dat') # This is a 2D file, in this GSLIB ve...
<SYSTEM_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 for work Step2: Testing histplot
3,007
<ASSISTANT_TASK:> Python Code: df = pd.read_csv('data/apib12tx.csv') df.describe() df.corr() df.plot(kind="scatter", x="MEALS", y="API12B") df.plot(kind="scatter", x="AVG_ED", y="API12B") data = np.asarray(df[['API12B','MEALS']]) x, y = data[:, 1:], data[:, 0] lr = LinearRegression() lr.fit(x, y) # plot the linear...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Checking out correlations Step2: The percentage of students enrolled in free/reduced-price lunch programs is often used as a proxy for poverty....
3,008
<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: Getting started Step2: Authenticate your GCP account Step3: ML Workflow using a BigQuery model Step4: Define Constants Step6: Unused Feature...
3,009
<ASSISTANT_TASK:> Python Code: import pandas as pd df = pd.DataFrame({'key1': ['a', 'a', 'b', 'b', 'a', 'c'], 'key2': ['one', 'two', 'one', 'two', 'one', 'two']}) def g(df): return df.groupby('key1')['key2'].apply(lambda x: (x=='one').sum()).reset_index(name='count') result = g(df.copy()) <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:
3,010
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np from sklearn.tree import DecisionTreeClassifier, export_graphviz from IPython.display import Image from sklearn.externals.six import StringIO from sklearn.cross_validation import train_test_split import matplotlib.pyplot as plt %matplotlib inline RAN...
<SYSTEM_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 Step2: Column Meanings Step3: We firstly category Sun_hours into three levels Step4: Preprocessing (Handling Missing Values) Step...
3,011
<ASSISTANT_TASK:> Python Code: !pip install modin[all] import modin.pandas as pd import pandas ############################################# ### For the purpose of timing comparisons ### ############################################# import time import ray ray.init() from IPython.display import Markdown, display def 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: For further instructions on how to install Modin with conda or for specific platforms or engines, see our detailed installation guide. Step2: D...
3,012
<ASSISTANT_TASK:> Python Code: import tensorflow as tf import numpy as np np.set_printoptions(suppress=True) sess = tf.InteractiveSession() # Imports for visualization import PIL.Image from cStringIO import StringIO from IPython.display import clear_output, Image, display import scipy.ndimage as nd import scipy.signal...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Load image Step11: We need to find the chessboard squares within the image (assuming images will vary, boards will vary in color, etc. between ...
3,013
<ASSISTANT_TASK:> Python Code: # Initialize PYTHONPATH for pyopencga import sys import os from pprint import pprint cwd = os.getcwd() print("current_dir: ...."+cwd[-10:]) base_modules_dir = os.path.dirname(cwd) print("base_modules_dir: ...."+base_modules_dir[-10:]) sys.path.append(base_modules_dir) from pyopencga.openc...
<SYSTEM_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 credentials for LogIn Step2: Creating ConfigClient for server connection configuration Step3: LogIn with user credentials
3,014
<ASSISTANT_TASK:> Python Code: def generate_autocorrelated_data(theta, mu, sigma, N): X = np.zeros((N, 1)) for t in range(1, N): X[t] = theta * X[t-1] + np.random.normal(mu, sigma) return X def newey_west_SE(data): ind = range(0, len(data)) ind = sm.add_constant(ind) model = regression.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: Data Step2: Exercise 1 Step3: b. Standard Deviation Step4: c. Standard Error Step5: d. Confidence Intervals Step6: Exercise 2 Step7: Exerc...
3,015
<ASSISTANT_TASK:> Python Code: first_digit(100) first_digit(399) import random def do_drawing(bucket_size, runs): digits = [first_digit(random.randint(1,bucket_size)) for x in range(runs)] return digits import collections counters=[(top_end, collections.Counter(do_drawing(top_end, 100))) for top_end in range(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now, we're going to simulate picking numbers out of a hat, doing it 'runs' times. The bucket_size is the number of nubmer in the hat. Step2: No...
3,016
<ASSISTANT_TASK:> Python Code: # set up imports import numpy import statsmodels.nonparametric.smoothers_lowess import matplotlib.pyplot as plt from scipy.optimize import minimize %matplotlib inline # softmax response function def softmax(q,temp): p=numpy.exp(q[0]/temp)/(numpy.exp(q[0]/temp)+numpy.exp(q[1]/temp...
<SYSTEM_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 need to generate some data. Step2: Now, we want to fit a model to the behavior above. It is challenging to estimate both the learnin...
3,017
<ASSISTANT_TASK:> Python Code: # Create a string my_str = 'This is my string' # Split it... my_str_split = my_str.split() print(my_str_split) # ... and restore (join) it again my_str_joined = ' '.join(my_str_split) # ' ' means join with space print(my_str_joined) # Find first occurence of word containing 'str' print(my...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Count words in Hamlet Step2: Use collections to do the same thing
3,018
<ASSISTANT_TASK:> Python Code: import em1d import numpy as np nx = 120 box = 4 * np.pi dt = 0.1 tmax = 50.0 ndump = 10 ppc = 500 ufl = [0.4, 0.0, 0.0] uth = [0.001,0.001,0.001] right = em1d.Species( "right", -1.0, ppc, ufl = ufl, uth = uth ) ufl[0] = -ufl[0] left = em1d.Species( "left", -1.0, ppc, ufl = ufl, uth...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Initializing a ZPIC simulation requires setting the simulation box and timestep Step2: Next we need to describe the particle species in the sim...
3,019
<ASSISTANT_TASK:> Python Code: %config InlineBackend.figure_format = 'retina' %matplotlib inline import numpy as np import scipy as sp import matplotlib.pyplot as plt import pandas as pd import seaborn as sns sns.set_style("white") import util df = util.load_burritos() N = df.shape[0] m_corr = ['Google','Yelp','Hunge...
<SYSTEM_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: Correlation matrix Step3: Correlation Step4: Positive correlation Step5: Positive correlation Step6: Positive correlation ...
3,020
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis A. Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import mne from mne import io from mne.datasets import sample from mne.cov import compute_covariance print(__doc__) data_path = samp...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Set parameters Step2: Compute covariance using automated regularization Step3: Show whitening
3,021
<ASSISTANT_TASK:> Python Code: report_files = ["/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing6_200_512_04drb/encdec_noing6_200_512_04drb.json", "/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing10_200_512_04drb/encdec_noing10_200_512_04drb.json", "/Users/bking/IdeaP...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Perplexity on Each Dataset Step2: Loss vs. Epoch Step3: Perplexity vs. Epoch Step4: Generations Step5: BLEU Analysis Step6: N-pairs BLEU An...
3,022
<ASSISTANT_TASK:> Python Code: PROJECT_ID_BILLING = "" # Set the project ID ! gcloud config set project $PROJECT_ID_BILLING import sys # If you are running this notebook in Colab, run this cell and follow the # instructions to authenticate your GCP account. This provides access to your # Cloud Storage bucket and lets ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Authenticate your GCP account Step2: Create a BigQuery dataset Step3: Validate that your dataset created successfully (this will throw an erro...
3,023
<ASSISTANT_TASK:> Python Code: # Load CSV into a dataframe named nba # Print the number of rows and columns in the dataframe # Print the first row of data # Print the mean of each column %matplotlib inline # Use seaborn or pandas to plot the scatter matrix # Use a clustering model like K-means to cluster the play...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Remember to import the pandas library to get access to Dataframes. Dataframes are two-dimensional arrays (matrices) where each column can be of ...
3,024
<ASSISTANT_TASK:> Python Code: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False) DO NOT MODIFY THIS CELL def fully_connected(prev_layer, num_units): Create a fully connectd layer with the given layer...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step3: Batch Normalization using tf.layers.batch_normalization<a id="example_1"></a> Step6: We'll use the following function to create convolutional l...
3,025
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from qutip import * from qutip.expect import expect_rho_vec from matplotlib import rcParams rcParams['font.family'] = 'STIXGeneral' rcParams['mathtext.fontset'] = 'stix' rcParams['font.size'] = '14' N = 15 w0 = 0.5 * 2...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Direct photo-detection Step2: Highly efficient detection Step3: Highly inefficient photon detection Step4: Efficient homodyne detection Step5...
3,026
<ASSISTANT_TASK:> Python Code: import numpy as np import igraph import timeit import itertools def enumerate_matrix(gmat, i): return np.nonzero(gmat[i,:])[1].tolist() def enumerate_adj_list(adj_list, i): return adj_list[i] def enumerate_edge_list(edge_list, i): inds1 = np.where(edge_list[:,0] == i)[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: Now, define a function that returns the index numbers of the neighbors of a vertex i, when the Step2: Define a function that enumerates the ne...
3,027
<ASSISTANT_TASK:> Python Code: from theano import function, config, shared, sandbox import theano.tensor as T import numpy import time vlen = 10 * 30 * 768 # 10 x #cores x # threads per core iters = 1000 rng = numpy.random.RandomState(22) x = shared(numpy.asarray(rng.rand(vlen), config.floatX)) f = function([], T.exp(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Yup, it looks like it is not using the GPU Step2: I do, and the solution says it has something to do with my path not being set properly. Lets...
3,028
<ASSISTANT_TASK:> Python Code: Ax = [-1, 3, -4, 5, 1, -6, 2, 1] def solution_1(A): addition_list = list() list_index = 1 addition_list.append(A[0]) try: if len(A) >= 0 and len(A) <= 100000: for i, int_in_arr in enumerate(A): # print i, " ", int_in_arr ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: V- 1 - used numpy to sum soon realized numpy does not work on codality. I have usually required more time working on solutions when solving some...
3,029
<ASSISTANT_TASK:> Python Code: from __future__ import division import graphlab products = graphlab.SFrame('amazon_baby_subset.gl/') products.head() # The same feature processing (same as the previous assignments) # --------------------------------------------------------------- import json with open('important_words....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load and process review dataset Step2: Just like we did previously, we will work with a hand-curated list of important words extracted from the...
3,030
<ASSISTANT_TASK:> Python Code: # import packages import numpy as np import matplotlib.pyplot as plt from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters 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: Problem Statement Step3: Each dot corresponds to a position on the football field where a football player has hit the ball with his/her head af...
3,031
<ASSISTANT_TASK:> Python Code:: from numpy import array from pickle import load from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical from keras.utils import plot_model from keras.models import Model from keras.layers import Input fr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
3,032
<ASSISTANT_TASK:> Python Code: index.output_prefix index.save('prakhar') index[vec_lsi] index.output_prefix index2 = similarities.Similarity.load('/home/prakhar/Documents/test/shard/prakhar') index2.output_prefix index2[vec_lsi] #index2.output_prefix #index2.output_prefix = '/home/prakhar/Documents/gentestOLD/prakhar...
<SYSTEM_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, user needs to provide only the file name, as file will now be saved inside "shard" directory. Step2: Now, for portability the user needs t...
3,033
<ASSISTANT_TASK:> Python Code: import numpy as np x = [1,2,3] y = [4,5,6] x + y B = np.array([[1,2,3], [4,5,6]]) # habiendo corrido import numpy as np B + 2*B # Python sabe sumar y multiplicar arrays como algebra lineal np.matmul(B.transpose(), B) # B^t*B B[1,1] B[1,:] B[:,2] B[0:2,0:2] B.shape vec = np.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: Step1: Lo que el codigo anterior hace es asociar al nombre np todas las herramientas de la libreria numpy. Ahora podremos llamar funciones de numpy com...
3,034
<ASSISTANT_TASK:> Python Code: import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152 os.environ["CUDA_VISIBLE_DEVICES"] = "" #os.environ['THEANO_FLAGS'] = "device=gpu2" from keras.models import load_model from keras.models import Sequential from keras.layers.core import Dense, Dropout from keras.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: Data preparation (keras.dataset) Step2: Training Step3: Plotting Network Performance Trend
3,035
<ASSISTANT_TASK:> Python Code: import math import matplotlib.pyplot as plt import tensorflow as tf import tensorflow_datasets as tfds from tensorflow import keras from tensorflow.keras import layers # Dataset hyperparameters unlabeled_dataset_size = 100000 labeled_dataset_size = 5000 image_size = 96 image_channels = 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: Hyperparameter setup Step2: Dataset Step3: Image augmentations Step4: Encoder architecture Step5: Supervised baseline model Step6: Self-sup...
3,036
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'bnu', 'sandbox-1', 'toplevel') # 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...
3,037
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import matplotlib %matplotlib inline matplotlib.rc('savefig', dpi=120) import warnings warnings.simplefilter("ignore", Warning) from matplotlib import dates import sunpy sunpy.system_info() from sunpy.net import hek client = hek.HEKClien...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: SunPy version (stable) 0.5 Step2: We can find out when this event occured Step3: and where it occurred Step4: Lightcurves! Step5: The data i...
3,038
<ASSISTANT_TASK:> Python Code: import libpysal as ps import numpy as np import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns import pandas as pd import geopandas as gpd from giddy.markov import FullRank_Markov income_table = pd.read_csv(ps.examples.get_path("usjoin.csv")) income_table.head() pci = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Full Rank Markov Step2: Full rank Markov transition probability matrix Step3: Full rank first mean passage times Step4: Geographic Rank Marko...
3,039
<ASSISTANT_TASK:> Python Code: from IPython.display import Image Image("Malaga_map.jpg") Image("workflow.jpg") #Import all necesary modules as follows: #import flexible container object, designed to store hierarchical data structures in memory import xml.etree.cElementTree as ET #import function to supply missing valu...
<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: <body> In order to complete the project the following steps shown in the diagram below must be followed <body> Step3: 1. Audit data Step4: 2. ...
3,040
<ASSISTANT_TASK:> Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 变量简介 Step2: 创建变量 Step3: 变量与张量的定义方式和操作行为都十分相似,实际上,它们都是 tf.Tensor 支持的一种数据结构。与张量类似,变量也有 dtype 和形状,并且可以导出至 NumPy。 Step4: 大部分张量运算在变量上也可以按预期运行,不过变量...
3,041
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import fourstate import itertools import networkx as nx import numpy as np import operator bhs = fourstate.FourState() fig, ax = plt.subplots() ax.bar([0.5,1.5,2.5], -1./bhs.evals[1:], width=1) ax.set_xlabel(r'Eigenvalue', fontsize=16) 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: By doing this we get a few variables initialized. First, a symmetric transition count matrix, $\mathbf{N}$, where we see that the most frequent ...
3,042
<ASSISTANT_TASK:> Python Code: salmon = pd.read_table("../data/salmon.dat", delim_whitespace=True, index_col=0) plt.scatter(x=salmon.spawners, y=salmon.recruits) fig, axes = plt.subplots(1, 2, figsize=(14,6)) xvals = np.arange(salmon.spawners.min(), salmon.spawners.max()) fit1 = np.polyfit(salmon.spawners, salmon.recr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: On the one extreme, a linear relationship is underfit; on the other, we see that including a very large number of polynomial terms is clearly ov...
3,043
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np from sklearn.model_selection import cross_val_score df = pd.read_csv('../scikit/tweets.csv') target = df['is_there_an_emotion_directed_at_a_brand_or_product'] text = df['tweet_text'] # We need to remove the empty rows from the text before we pass int...
<SYSTEM_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 SVM is 67% accurate.
3,044
<ASSISTANT_TASK:> Python Code: # boilerplate code import os from cStringIO import StringIO import numpy as np from functools import partial import PIL.Image from IPython.display import clear_output, Image, display, HTML import tensorflow as tf #!wget https://storage.googleapis.com/download.tensorflow.org/models/incept...
<SYSTEM_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='loading'></a> Step6: To take a glimpse into the kinds of patterns that the network learned to recognize, we will try to generate images ...
3,045
<ASSISTANT_TASK:> Python Code: %matplotlib inline from keras.models import model_from_json from keras.optimizers import SGD from os import path from train import infer_sizes import models cache_dir = '../cache/mpii-cooking/' # Change me! orig_path = path.join(cache_dir, 'keras-checkpoints/checkpoints/model-iter-16640...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Configuration and metadata (layer size) gathering Step2: Load a model Step3: Upgrade the model Step4: Save a description of the model and its...
3,046
<ASSISTANT_TASK:> Python Code: import json # ukazkova data message = [ {"time": 123, "value": 5}, {"time": 124, "value": 6}, {"status": "ok", "finish": [True, False, False]}, ] # zabalit zpravu js_message = json.dumps(message) # show result print(type(js_message)) print(js_message) # unpack message messag...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Následuje příklad, ve kterém se vezme JSON text z předchozího příkladu a zpátku se z něj složí objekt. Step2: Ve formátu json můžou být libovol...
3,047
<ASSISTANT_TASK:> Python Code: import os,sys import numpy %matplotlib inline import matplotlib.pyplot as plt import statsmodels.tsa.stattools from dcm_sim import sim_dcm_dataset sys.path.insert(0,'../') from utils.graph_utils import show_graph_from_adjmtx,show_graph_from_pattern # first we simulate some data using our ...
<SYSTEM_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 compute Granger causality across all pairs of timeseries
3,048
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from line_profiler import LineProfiler from sklearn.metrics.pairwise import pairwise_distances import seaborn as sns from sklearn import datasets from sklearn.base import ClassifierMixin from sklearn.datasets import fetch_mldata from skle...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: IRIS Step2: MNIST Step3: Задание 5
3,049
<ASSISTANT_TASK:> Python Code: import sisl import sisl.viz # First, we create the geometry BN = sisl.geom.graphene(atoms=["B", "N"]) # Create a hamiltonian with different on-site terms H = sisl.Hamiltonian(BN) H[0, 0] = 2 H[1, 1] = -2 H[0, 1] = -2.7 H[1, 0] = -2.7 H[0, 1, (-1, 0)] = -2.7 H[0, 1, (0, -1)] = -2.7 H[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: For this notebook we will create a toy "Boron nitride" tight binding Step2: Note that we could have obtained this hamiltonian from any other so...
3,050
<ASSISTANT_TASK:> Python Code: import numpy as np lst = [10, 20, 30, 40] arr = np.array([10, 20, 30, 40]) print(lst) print(arr) print(lst[0], arr[0]) print(lst[-1], arr[-1]) print(lst[2:], arr[2:]) lst[-1] = 'a string inside a list' lst arr[-1] = 'a string inside an array' print('Data type :', arr.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: NumPy, at its core, provides a powerful array object. Let's start by exploring how the NumPy array differs from a Python list. Step2: Elemen...
3,051
<ASSISTANT_TASK:> Python Code: import numpy as np import tensorflow as tf from collections import Counter with open('../sentiment_network/reviews.txt', 'r') as f: reviews = f.read() with open('../sentiment_network/labels.txt', 'r') as f: labels = f.read() reviews[:2000] from string import punctuation all_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: Data preprocessing Step2: Encoding the words Step3: Encoding the labels Step4: If you built labels correctly, you should see the next output....
3,052
<ASSISTANT_TASK:> Python Code: # This is a Python comment # the next line is a line of Python code print("Hello World!") # These two lines turn on inline plotting %matplotlib inline import matplotlib.pyplot as plt plt.plot([1,2,3]) a = 1 a + 1 b = 2.1 b + 1 a + b type(a + b) c = 1.5 + 0.5j # complex numbers 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: Cells can also be used to create textual materials using the markup language Markdown. Step2: <img class="logo" src="images/python-logo.png" ...
3,053
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import astropy.io.fits as fits plt.style.use('ggplot') plt.rc('axes', grid=False) # turn off the background grid for images data_file = "./MyData/bsg01.fits" my_fits_file = fits.open(data_file) my_fits_file.info() 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: FITS files consist of at least two parts - Header and Data Step2: FITS format preserves the full dynamic range of data Step3: You can use mask...
3,054
<ASSISTANT_TASK:> Python Code: def equvInverse(arr , N , P ) : cntElem = 0 for i in range(0 , N ) : if(( arr[i ] * arr[i ] ) % P == 1 ) : cntElem = cntElem + 1   return cntElem  if __name__== "__main __": arr =[1 , 6 , 4 , 5 ] N = len(arr ) P = 7 print(equvInverse(arr , N , P ) )  <END_TAS...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
3,055
<ASSISTANT_TASK:> Python Code: class newNode : def __init__(self , data ) : self . data = data self . left = self . right = None   def deleteLeaves(root , x ) : if(root == None ) : return None  root . left = deleteLeaves(root . left , x ) root . right = deleteLeaves(root . right , x ) if(root ....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
3,056
<ASSISTANT_TASK:> Python Code: print("Hello man") def fibo(n): if n == 0: return 0 elif n == 1: return 1 return fibo(n-1) + fibo(n-2) %timeit fibo(20) %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 1, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Example code block Step2: Note Step3: Debugging with %pdb
3,057
<ASSISTANT_TASK:> Python Code: import csv def parse_registers(input_path): registers = [] with open(input_path, 'rt') as f_input: csv_reader = csv.reader(f_input, delimiter=' ') for line in csv_reader: registers.append((line[0], tuple(line[1:]))) return registers from collection...
<SYSTEM_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: Solution Step3: Part 2 Step4: Test Step5: Solution
3,058
<ASSISTANT_TASK:> Python Code: import numpy as np %pylab inline # Load the data # TODO # Normalize the data from sklearn import preprocessing X = preprocessing.normalize(X) # Set up a stratified 10-fold cross-validation from sklearn import cross_validation folds = cross_validation.StratifiedKFold(y, 10, shuffle=True) 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: 2016-11-04 Step2: 1. Decision trees Step3: Question Compute the mean and standard deviation of the area under the ROC curve of these 5 trees. ...
3,059
<ASSISTANT_TASK:> Python Code: # TEST import numpy as np import pandas as pd import larch.numba as lx from pytest import approx import larch.numba as lx # HIDDEN df_ca = pd.read_csv("example-data/tiny_idca.csv") cats = df_ca['altid'].astype(pd.CategoricalDtype(['Car', 'Bus', 'Walk'])).cat df_ca['altnum'] = cats.codes ...
<SYSTEM_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 guide, we'll take a look at building a discrete choice model using Larch. Step2: The basic structure of a choice model in Larch is cont...
3,060
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical reviews = pd.read_csv('reviews.txt', header=None) labels = pd.read_csv('labels.txt', header=None) from collections import Counter total_counts = Counter() for _, 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: Preparing the data Step2: Counting word frequency Step3: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in...
3,061
<ASSISTANT_TASK:> Python Code: import numpy as np from brainiak.reconstruct import iem as IEM import matplotlib.pyplot as plt import numpy.matlib as matlib import scipy.signal # Set up parameters n_channels = 6 cos_exponent = 5 range_start = 0 range_stop = 360 feature_resolution = 360 iem_obj = IEM.InvertedEncoding1D(...
<SYSTEM_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 example, we will assume that the stimuli are patches of different motion directions. These stimuli span a 360-degree, circular feature s...
3,062
<ASSISTANT_TASK:> Python Code: lva = v.model.node.storages.lva('IrrigationOnlyStorage') lva scaled_lva = lva * 2 scaled_lva # v.model.node.storages.load_lva(scaled_lva) # Would load the same table into ALL storages # v.model.node.storages.load_lva(scaled_lva,nodes=['StorageOnlyStorage','BothStorage']) # Will load 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: Specifying full supply and initial conditions Step2: Releases Step3: We can create each type of release mechanism.
3,063
<ASSISTANT_TASK:> Python Code: # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim.py module from modsim import * radian = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Unrolling Step2: And a few more parameters in the Params object. Step4: make_system computes rho_h, which we'll need to compute moment of iner...
3,064
<ASSISTANT_TASK:> Python Code: import re import numpy as np import pandas as pd import email #Plotting stuff %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns sns.set_context('poster') import hypergraph import os #for root, user, file in os.walk('/Users/jchealy/Downloads/maildir/'): root = '/Use...
<SYSTEM_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 data into hyperedges. We preserve order only in so far as the first element in each array is the sender. Email addresses may appear m...
3,065
<ASSISTANT_TASK:> Python Code: # first, define our isnobal spatiotemporal parameters isnobal_params = dict( # generate a 10x8x(n_timesteps) grid for each variable nlines=10, nsamps=8, # with a resolution of 1.0m each; samp is north-south, so it's negative dline=1.0, dsamp=-1.0, # set base fake origi...
<SYSTEM_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 Step2: The standard name above refers to the CF Conventions standard name. By using this, other netCDF software tools can interpret the ti...
3,066
<ASSISTANT_TASK:> Python Code: # The usual, we need to load some libraries from SimPEG import Mesh, Utils, Maps, PF from SimPEG import mkvc, Regularization, DataMisfit, Optimization, InvProblem, Directives,Inversion from SimPEG.Utils import mkvc from SimPEG.Utils.io_utils import download import numpy as np import scipy...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Setup Step2: Forward system Step3: Inverse problem Step4: View the inversion results
3,067
<ASSISTANT_TASK:> Python Code: %autosave 120 import numpy as np np.random.seed(1337) import datetime import graphviz from IPython.display import SVG import keras from keras import activations from keras import backend as K from keras.datasets import mnist from keras.layers import ( concatenate, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: deep learning understanding Step2: saliency Step3: class saliency map extraction Step4: class saliency map statistical uncertainties Step5: ...
3,068
<ASSISTANT_TASK:> Python Code: import numba import numpy as np import numexpr as ne import matplotlib.pyplot as plt def metric_python(x, y): standard Euclidean distance ret = x-y ret *= ret return np.sqrt(ret).sum() def inf_dist_python(x, Y): inf distance between row x and array 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: Step4: En esta actividad implementaremos una conocida métrica para medir disimilitud entre conjuntos Step8: Paso 2. Step9: Paso 3.
3,069
<ASSISTANT_TASK:> Python Code: def find_passes(duration): #instrument function calls sat_azel.calls = 0 # orbital period in seconds period = 24.0 * 60.0 * 60.0 / sat._n # coarse steps to find the points near (enough) to elevation peaks time_coarse = np.arange(0, INTERVAL_SECONDS, period/STEPS_PE...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Find time to compute using pyephem.observer.next_pass() Step2: Speedup factor and percentage reduction.
3,070
<ASSISTANT_TASK:> Python Code: %matplotlib inline from SeisCL import SeisCL import matplotlib.pyplot as plt import numpy as np seis = SeisCL() # Constants for the modeling seis.ND = 2 N = 200 seis.N = np.array([N, 2*N]) seis.dt = dt = 0.25e-03 seis.dh = dh = 2 seis.NT = NT = 1000 seis.seisout = 1 seis.f0 = 20 # Source...
<SYSTEM_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 first create a constant velocity model, with one source in the middle Step2: To output a movie, we have to set the input 'movout' to a numbe...
3,071
<ASSISTANT_TASK:> Python Code: from skimage import data color_image = data.chelsea() print(color_image.shape) plt.imshow(color_image); red_channel = color_image[:, :, 0] # or color_image[..., 0] plt.imshow(red_channel); red_channel.shape from skimage import io color_image = io.imread('../images/balloon.jpg') 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: Step1: Slicing and indexing Step2: But when we plot the red channel... Step3: Obviously that's not red at all. The reason is that there's nothing to ...
3,072
<ASSISTANT_TASK:> Python Code: Yummly API Example "id": "Garlic-Cheese-Chicken-1041442", "recipeName": "Garlic Cheese Chicken", "ingredients": ["melted butter", "garlic cloves", "garlic powder", "salt", "corn flakes", "shredded cheddar chee...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Engine
3,073
<ASSISTANT_TASK:> Python Code: #The Python Imaging Library (PIL) from PIL import Image, ImageDraw # Basic math and color tools import math, colorsys, numpy # Mathematical plotting import matplotlib as mpl from matplotlib import colors as mplcolors import matplotlib.pyplot as plt # Displaying real graphical images (pict...
<SYSTEM_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 sets up the colors we want in our fractal image. Step2: Let's use over Mandelbrot test function to check some examples of "c" Step3: 3. G...
3,074
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'messy-consortium', 'sandbox-3', 'seaice') # 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: 2...
3,075
<ASSISTANT_TASK:> Python Code: from price import * import matplotlib.pyplot as plt player1, player2 = MakePlayers(path='../code') MakePrice1(player1, player2) plt.legend(); class Pdf(object): def Density(self, x): raise UnimplementedMethodException() def MakePmf(self, xs): pmf = Pmf() 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: This shows the distribution of prices for these Step2: Density takes a value, x, and returns the Step3: __init__ takes mu and sigma, which are...
3,076
<ASSISTANT_TASK:> Python Code: cmr=CMR("../cmr.cfg") results = cmr.searchGranule(entry_title='MODIS/Aqua Near Real Time (NRT) Thermal Anomalies/Fire 5-Min L2 Swath 1km (C005)', temporal="2016-04-11T12:00:00Z,2016-04-11T13:00:00Z") for res in results: print(res.getDownloadUrl()) results = 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: Fires in Nepal Step2: Further subset using bounding box
3,077
<ASSISTANT_TASK:> Python Code: # prepare some imports import numpy as np from sklearn.datasets import fetch_mldata import matplotlib.pyplot as plt %matplotlib inline # plot samples from MNIST mnist = fetch_mldata('MNIST original') for i in range(9): plt.subplot(3, 3, i+1) sample = mnist.data[20000+i] sampl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Here are a few examples from the data set (samples $20000-20009$) Step2: A common task then looks like this Step3: Note that data matrices in ...
3,078
<ASSISTANT_TASK:> Python Code: # first, get some text: import fileinput try: import ujson as json except ImportError: import json documents = [] for line in fileinput.FileInput("example_tweets.json"): documents.append(json.loads(line)["text"]) print("One document: \"{}\"".format(documents[0])) from nltk.s...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1) Document Step2: 2) Tokenization Step3: 3) Text corpus Step4: 4) Stop words Step5: 5) Vectorize Step6: Bag of words
3,079
<ASSISTANT_TASK:> Python Code: # Set up code checking # This can take a few seconds from learntools.core import binder binder.bind(globals()) from learntools.feature_engineering.ex2 import * import numpy as np import pandas as pd from sklearn import preprocessing, metrics import lightgbm as lgb clicks = pd.read_parque...
<SYSTEM_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 next code cell repeats the work that you did in the previous exercise. Step3: Next, we define a couple functions that you'll use to test th...
3,080
<ASSISTANT_TASK:> Python Code: import graphlab from __future__ import division import numpy as np graphlab.canvas.set_target('ipynb') products = graphlab.SFrame('amazon_baby.gl/') def remove_punctuation(text): import string return text.translate(None, string.punctuation) # Remove punctuation. review_clean = ...
<SYSTEM_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 amazon review dataset Step2: Extract word counts and sentiments Step3: Now, let's remember what the dataset looks like by taking a quick ...
3,081
<ASSISTANT_TASK:> Python Code: # # Simple python program to calculate s as a function of t. # Any line that begins with a '#' is a comment. # Anything in a line after the '#' is a comment. # lam=0.01 # define some variables: lam, dt, s, s0 and t. Set initial values. dt=1.0 s=s0=100.0 t=0.0 def f_s(s,t): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now lets add a plot. Turn on the "pylab" environment Step2: Good! Next collect some lists of data (slist and tlist) and use the "plot" function...
3,082
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np # math import pandas as pd # manipulating data import matplotlib.pyplot as plt # graphing import os # useful for handling filenames etc. from scipy.stats import pearsonr # calculat...
<SYSTEM_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 remove all the NaN values using the Pandas DataFrame.dropna function. Step2: Now let's use the Pandas DataFrame.corr function to make a c...
3,083
<ASSISTANT_TASK:> Python Code: # Enter your username: YOUR_GMAIL_ACCOUNT = '******' # Whatever is before @gmail.com in your email address # Libraries for this section: import os import cv2 import pickle import numpy as np from sklearn import preprocessing # Directories: PREPROC_DIR = os.path.join('/home', YOUR_GMAIL_AC...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step3: Feature Engineering Functions Step5: Harris Corner Detector Histograms Step8: Building Feature Vectors Step9: Standardize and save
3,084
<ASSISTANT_TASK:> Python Code: remote_yaml = 'https://raw.githubusercontent.com/teamdigitale/api-starter-kit/master/openapi/simple.yaml.src' render_markdown(f''' [Swagger Editor]({oas_editor_url(remote_yaml)}) is a simple webapp for editing OpenAPI 3 language specs. ''') render_markdown(f''' 1- open [this incomplete 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: Start with Metadata Step2: Custom fields
3,085
<ASSISTANT_TASK:> Python Code: project = 'Input your PROJECT ID' region = 'Input GCP region' # For example, 'us-central1' output = 'Input your GCS bucket name' # No ending slash !python3 -m pip install 'kfp>=0.1.31' --quiet import kfp.deprecated.components as comp dataflow_python_op = comp.load_component_from_url( ...
<SYSTEM_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 Pipeline SDK Step2: Load the component using KFP SDK Step3: Use the wordcount python sample Step4: Example pipeline that uses the com...
3,086
<ASSISTANT_TASK:> Python Code: import numpy as np np.random.seed(42) import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import tensorflow as tf tf.set_random_seed(42) xs = [0., 1., 2., 3., 4., 5., 6., 7.] # feature (independent variable) ys = [-.82, -.94, -.12, .26, .39, .64, 1.02, 1.] # labels (de...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Create a very small data set Step2: Define variables -- the model parameters we'll learn -- and initialize them with "random" values Step3: On...
3,087
<ASSISTANT_TASK:> Python Code: %%bash date system_profiler SPSoftwareDataType bsmaploc="/Users/Shared/Apps/bsmap-2.74/" cd /Volumes/web/halfshell/working-directory/ !ls -lh mkdir 16-10-29 cd 16-10-29 # Genome cd ../data !curl -O http://owl.fish.washington.edu/halfshell/working-directory/16-10-24/Ostrea_lurida-Scaff-...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <img src="http Step2: <img src="http
3,088
<ASSISTANT_TASK:> Python Code: import importlib import os import sys def is_interactive(): import __main__ as main return not hasattr(main, '__file__') # defaults shell_mode = not is_interactive() plot_graphs = importlib.util.find_spec("matplotlib") is not None and not shell_mode # Matplotlib if (plot_graphs):...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: TB Hamiltonian Step2: Kwant routines Step3: Apply parameters and extract the Hamiltonian Step4: Dump Hamiltonian ordered along the position o...
3,089
<ASSISTANT_TASK:> Python Code: from pyquil import Program, get_qc qc = get_qc('Aspen-8') cals = qc.compiler.calibration_program from pyquil.quilatom import Qubit, Frame from pyquil.quilbase import Pulse, Capture, DefMeasureCalibration qubit = Qubit(0) measure_defn = next(defn for defn in cals.calibrations ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Peeking at a MEASURE calibration Step2: There are a few things note about the above Step3: An almost-trivial example Step4: Raw capture resul...
3,090
<ASSISTANT_TASK:> Python Code: import os import sys spark_home = os.environ['SPARK_HOME'] = '/Users/ozimmer/GoogleDrive/berkeley/w261/spark-2.0.0-bin-hadoop2.6' if not spark_home: raise ValueError('SPARK_HOME enviroment variable is not set') sys.path.insert(0,os.path.join(spark_home,'python')) sys.path.insert(0,os....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Non-RDD Example Step2: DataProc - submit a job
3,091
<ASSISTANT_TASK:> Python Code: !python --version def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(rig...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Basics of Python Step2: Basic data types Step3: Note that unlike many languages, Python does not have unary increment (x++) or decrement (x--)...
3,092
<ASSISTANT_TASK:> Python Code: # execute example code here from sklearn import datasets from sklearn.ensemble import RandomForestClassifier iris = datasets.load_iris() RFclf = RandomForestClassifier().fit(iris.data, iris.target) # complete # complete print(np.shape(# complete print(# complete print( # complete pri...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Generally speaking, the procedure for scikit-learn is uniform across all machine-learning algorithms. Models are accessed via the various module...
3,093
<ASSISTANT_TASK:> Python Code: # Numpy handles matrix multiplication, see http://www.numpy.org/ import numpy as np # PyPlot is a matlab like plotting framework, see https://matplotlib.org/api/pyplot_api.html import matplotlib.pyplot as plt # This line makes it easier to plot PyPlot graphs in Jupyter Notebooks %matplotl...
<SYSTEM_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 regressor class Step2: Using the regressor Step3: Revisiting the training process Step4: Looking at the data we see that it is possible t...
3,094
<ASSISTANT_TASK:> Python Code: metadata_tb = Table.read_table('data/poemeta.csv', keep_default_na=False) metadata_tb.show(5) reception_mask = (metadata_tb['recept']=='reviewed') + (metadata_tb['recept']=='random') clf_tb = metadata_tb.where(reception_mask) clf_tb.show(5) # Create list that will contain a series of di...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We see above a recept column that has their reception status. We want to look at reviewed and random, just like Underwood and Sellers did Step2:...
3,095
<ASSISTANT_TASK:> Python Code: import nltk text = nltk.word_tokenize("And now for something completely different") nltk.pos_tag(text) nltk.tag.str2tuple('fly/NN') # tagged_words() 是一個已經表示成tuple形態的資料 nltk.corpus.brown.tagged_words() # 用參數 tagset='universal' 可以換成簡單的tag nltk.corpus.brown.tagged_words(tagset='universal') ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 上面的範例中,CC是對等連接詞、RB是副詞、IN是介系詞、NN是名詞、JJ則是形容詞。如果想知道詳細的tag定義,可以用nltk.help.upenn_tagset('RB')來查詢。 Step2: corpus中也有tagged sentences Step3: Mapping W...
3,096
<ASSISTANT_TASK:> Python Code: # restart your notebook if prompted on Colab try: import verta except ImportError: !pip install verta HOST = "app.verta.ai" PROJECT_NAME = "Census Income Classification" EXPERIMENT_NAME = "Logistic Regression" WORKSPACE = "Demos" # import os # os.environ['VERTA_EMAIL'] = # os.en...
<SYSTEM_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 example features Step2: Phase 1 Step3: Prepare hyperparameters Step4: Instantiate client Step5: Train models Step6: Revisit Workflow S...
3,097
<ASSISTANT_TASK:> Python Code: Make a request from the Forecast.io API for where you were born (or lived, or want to visit!) import requests !pip3 install requests #new york response = requests.get("https://api.forecast.io/forecast/94bc3fa3628bfad686b10e7054c67f71/40.7141667, -74.0063889") data = response.json() 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: 2) What's the current wind speed? How much warmer does it feel than it actually is? Step2: 3) The first daily forecast is the forecast for toda...
3,098
<ASSISTANT_TASK:> Python Code: from bs4 import BeautifulSoup from urllib.request import urlopen html = urlopen("http://static.decontextualize.com/cats.html").read() document = BeautifulSoup(html, "html.parser") cafe_list = list() cafe_table = document.find('table', {'class': 'cafe-list'}) tbody = cafe_table.find('tbod...
<SYSTEM_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 tackle the list of cafes first. In the cell below, write some code that creates a list of dictionaries with information about each cafe, a...
3,099
<ASSISTANT_TASK:> Python Code: print(glob.glob('data/inflammation*.csv')) # loop here counter = 0 for filename in glob.glob('data/*.csv'): #counter+=1 counter = counter + 1 print("number of files:", counter) counter = 0 for filename in glob.glob('data/infl*.csv'): #counter+=1 counter = counter + 1 prin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: results in a list of strings, we can loop oer Step2: We can ask Python to take different actions, depending on a condition, with an if statemen...