text_prompt
stringlengths
168
30.3k
code_prompt
stringlengths
67
124k
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: List data structure Step3: 2. Creating list with different types - 100xp, Status Step4: 3. Select the valid list -- 50xp, status Step6: 4 L...
<ASSISTANT_TASK:> Python Code: After measuring the height of your family, you decide to collect some information on the house you're living in. The areas of the different parts of your house are stored in separate variables for now, as shown in the script. Instructions: + Create a list, "areas", that contain the ar...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Define a preprocessing function Step2: Here, x, y and s are Tensors that represent input features. The first Step3: The transformed_data conte...
<ASSISTANT_TASK:> Python Code: !pip install -U tensorflow_transform !pip install pyarrow import pkg_resources import importlib importlib.reload(pkg_resources) import os import tempfile import tensorflow as tf import tensorflow_transform as tft import tensorflow_transform.beam as tft_beam from tensorflow_transform.tf_me...
<SYSTEM_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 dtw module contains a single function named dtw as well. Step2: Let's define two sequences Step3: Compute DTW Step4: You can plot the acc...
<ASSISTANT_TASK:> Python Code: %pylab inline from dtw import dtw x = array([0, 0, 1, 1, 2, 4, 2, 1, 2, 0]).reshape(-1, 1) y = array([1, 1, 1, 2, 2, 2, 2, 3, 2, 0]).reshape(-1, 1) plot(x) plot(y) dist, cost, acc, path = dtw(x, y, dist=lambda x, y: norm(x - y, ord=1)) print 'Minimum distance found:', dist imshow(acc....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Make some test data Step2: The cube has the dimensions 40x40x40 voxels and the StdDev of the noise is 0.5. Step3: The filter operates inplace,...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import advancedfilters as af def buildTestVolume(size,sigma) : vol = np.zeros([size,size,size]) margin = size // 4 vol[margin:-margin,margin:-margin,margin:-margin]=1 vol = vol + np.random.normal(0,1,size=vol.shape)*sigma...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'miroc', 'nicam16-9d-l78', 'aerosol') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We now consider a first-order Kepler splitting (Wisdom-Holman map) Step2: We now set sim.integrator to none, so that REBOUND doesn't do anythin...
<ASSISTANT_TASK:> Python Code: import rebound import reboundx import numpy as np import matplotlib.pyplot as plt %matplotlib inline def makesim(): sim = rebound.Simulation() sim.G = 4*np.pi**2 sim.add(m=1.) sim.add(m=1.e-4, a=1.) sim.add(m=1.e-4, a=1.5) sim.move_to_com() return sim sim = ma...
<SYSTEM_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 MNE, epochs refers to a collection of single trials or short segments Step2: To create time locked epochs, we first need a set of events tha...
<ASSISTANT_TASK:> Python Code: import os.path as op import numpy as np import mne data_path = mne.datasets.sample.data_path() fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(fname) raw.set_eeg_reference() # set EEG average reference order = np.arange(raw.info['nchan']) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Language Translation Step3: Explore the Data Step6: Implement Preprocessing Function Step8: Preprocess all the data and save it Step10: Chec...
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) view_sentence_range = (0, 10) DON'T MODIFY AN...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Undirected Graphs Step2: Directed Graphs Step3: What can nodes be? Step4: Reading in Data
<ASSISTANT_TASK:> Python Code: # Import networkx and also matplotlib.pyplot for visualization import networkx as nx import matplotlib.pyplot as plt %matplotlib inline # Create an empty undirected graph G = nx.Graph() # Add some nodes and edges. Adding edges aslo adds nodes if they don't already exist. G.add_node('Jan...
<SYSTEM_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 script goes along the blog post Step2: Next step is to use those saved bottleneck feature activations and train our own, very simple fc la...
<ASSISTANT_TASK:> Python Code: import warnings warnings.filterwarnings('ignore') %matplotlib inline %pylab inline import matplotlib.pylab as plt import numpy as np from distutils.version import StrictVersion import sklearn print(sklearn.__version__) assert StrictVersion(sklearn.__version__ ) >= StrictVersion('0.18.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: Read the SDSS training sample. Step2: Next, assemble the full catalog of forced-PSF Gaia sources from DR8. Step3: Make some plots and develop ...
<ASSISTANT_TASK:> Python Code: import os, pdb import fitsio import numpy as np import matplotlib.pyplot as plt from glob import glob from astropy.table import vstack, Table from astrometry.libkd.spherematch import match_radec import seaborn as sns sns.set(context='talk', style='ticks', font_scale=1.4) %matplotlib inlin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: II) MEASUREMENTS Step2: Baro Step3: GPS Step4: GPS velocity Step5: Acceleration Step6: III) PROBLEM FORMULATION Step7: Initial uncertainty...
<ASSISTANT_TASK:> Python Code: m = 50000 # timesteps dt = 1/ 250.0 # update loop at 250Hz t = np.arange(m) * dt freq = 0.05 # Hz amplitude = 5.0 # meter alt_true = 405 + amplitude * np.cos(2 * np.pi * freq * t) height_true = 6 + amplitude * np.cos(2 * np.pi * freq * t) vel_true = - amplitude * (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: Deep & Cross Network (DCN) Step2: Toy Example Step3: Let's generate the data that follows the distribution, and split the data into 90% for tr...
<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: TV Script Generation Step3: Explore the Data Step6: Implement Preprocessing Functions Step9: Tokenize Punctuation Step11: Preprocess all the...
<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 = (0, 10) DON'T MODIFY ANYTHING IN THIS CELL import num...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Certain classifiers in scikit-learn can also return the probability of a predicted class label via the predict_proba method. Using the predicted...
<ASSISTANT_TASK:> Python Code: import numpy as np np.argmax(np.bincount([0, 0, 1], weights=[0.2, 0.2, 0.6])) ex = np.array([[0.9, 0.1], [0.8, 0.2], [0.4, 0.6]]) p = np.average(ex, axis=0, weights=[0.2, 0.2, 0.6]) p np.argmax(p) from ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now we will define the physical constants of our system, which will also establish the unit system we have chosen. We'll use SI units here. Belo...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt #Physical Constants (SI units) G=6.67e-11 #Universal Gravitational constant in m^3 per kg per s^2 AU=1.5e11 #Astronomical Unit in meters = Distance between sun and earth daysec=24.0*60*60 #seconds in a day #####run sp...
<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: Uruchomiene Aplikacji
<ASSISTANT_TASK:> Python Code: print("Hello world!") #wyrównanie do nawiasu otwierającego foo = moja_dluga_funkcja(zmienna_jeden, zmienna_dwa zmienna_trzy, zmienna_cztery) # zwiększone wcięcia aby rozróżnić funkcję od ciała funkcji def moja_dluga_funkcja( zmienna_jeden, zmienna_dwa, zm...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Name and Embarked are dropped from the dataset because passenger name and embarking location shouldn't have any meaningful correlation with thei...
<ASSISTANT_TASK:> Python Code: %pylab inline import pandas as pd import matplotlib.pylab as plt import seaborn as sns import statsmodels.api as sm # read the data and inspect titanic = pd.read_csv('titanic-data.csv') print titanic.info() titanic.head() # drop those columns we are not interested in. titanic.drop(["Name"...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Please ignore any incompatibility warnings and errors. Step2: ROUGE-L Step3: The hypotheses and references are expected to be tf.RaggedTensors...
<ASSISTANT_TASK:> Python Code: # TODO 1: Install TF.Text TensorFlow library !pip install -q "tensorflow-text==2.8.*" import tensorflow as tf import tensorflow_text as text hypotheses = tf.ragged.constant([['captain', 'of', 'the', 'delta', 'flight'], ['the', '1990', 'transcript']]) ref...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Get our environment set up Step2: Next, we'll redo all of the work that we did in the tutorial. Step3: 1) Examine another column Step4: Do yo...
<ASSISTANT_TASK:> Python Code: from learntools.core import binder binder.bind(globals()) from learntools.data_cleaning.ex5 import * print("Setup Complete") # modules we'll use import pandas as pd import numpy as np # helpful modules import fuzzywuzzy from fuzzywuzzy import process import chardet # read in all our data...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Confirm you're using PyTorch version 1.1.0 Step2: Converting NumPy arrays to PyTorch tensors Step3: Here <tt>torch.DoubleTensor</tt> refers to...
<ASSISTANT_TASK:> Python Code: import torch import numpy as np torch.__version__ arr = np.array([1,2,3,4,5]) print(arr) print(arr.dtype) print(type(arr)) x = torch.from_numpy(arr) # Equivalent to x = torch.as_tensor(arr) print(x) # Print the type of data held by the tensor print(x.dtype) # Print the tensor object typ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Resources Step2: Event counting Step3: Broadcast Variables Step4: The dictionary table is sent out twice to worker nodes, one for each call S...
<ASSISTANT_TASK:> Python Code: import numpy as np import string from pyspark import SparkContext sc = SparkContext('local[*]') ulysses = sc.textFile('data/Ulysses.txt') ulysses.take(10) num_lines = sc.accumulator(0) def tokenize(line): table = dict.fromkeys(map(ord, string.punctuation)) return line.translate(...
<SYSTEM_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. About python Step2: 1.1 Jupyter notebook Step3: NEW NOTEBOOK Step4: BUTTONS TO REMOVE AND RENAME Step5: CELLS IN JUPYTER NOTEBOOKS Step6:...
<ASSISTANT_TASK:> Python Code: pd.read_ "../class2/" "data/Fatality.csv" ##Some code to run at the beginning of the file, to be able to show images in the notebook ##Don't worry about this cell #Print the plots in this screen %matplotlib inline #Be able to plot images saved in the hard drive from IPython.display 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: First we look into the era5-pds bucket zarr folder to find out what variables are available. Assuming that all the variables are available for a...
<ASSISTANT_TASK:> Python Code: %matplotlib notebook import xarray as xr import datetime import numpy as np from dask.distributed import LocalCluster, Client import s3fs import cartopy.crs as ccrs import boto3 import matplotlib.pyplot as plt bucket = 'era5-pds' #Make sure you provide / in the end prefix = 'zarr/2008/01...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Sparse 2d interpolation Step2: The following plot should show the points on the boundary and the single point in the interior Step3: Use meshg...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import numpy as np sns.set_style('white') from scipy.interpolate import griddata # YOUR CODE HERE x = np.hstack((np.arange(-5, 6), np.full(10, 5), np.arange(-5, 5), np.full(9, -5), [0])) y = np.hstack((np.full(11, 5...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Find the error metric of always predicting that it will take 2120 seconds to get an answer. This the baseline metric against which to report mod...
<ASSISTANT_TASK:> Python Code: %%bigquery SELECT bqutil.fn.median(ARRAY_AGG(TIMESTAMP_DIFF(a.creation_date, q.creation_date, SECOND))) AS time_to_answer FROM `bigquery-public-data.stackoverflow.posts_questions` q JOIN `bigquery-public-data.stackoverflow.posts_answers` a ON q.accepted_answer_id = a.id %%bigquery WIT...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Metropolis MCMC Step2: Dipolar interaction energy Step3: Total energy Step4: The Monte-Carlo algorithm Step5: Parameter set up Step6: Run t...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d from tqdm import tqdm_notebook #import tqdm import magpy as mp %matplotlib inline def e_anisotropy(moments, anisotropy_axes, V, K, particle_id): cos_t = np.sum(moments[particle_id, :]*anisotrop...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: $\dfrac{\partial f_{1}(c,p)}{\partial p} = 0 = $
<ASSISTANT_TASK:> Python Code: f1 = (1/2)*r_c*c**2+(1/4)*u_c*c**4+(1/6)*v_c*c**6-E*p+(1/2)*r_p*p**2-gamma*c*p pmin = solve(f1.diff(c),p)[0] pmin E_cp = solve(f1.diff(p),E)[0] E_cp expand(E_cp.subs(p,pmin)) <END_TASK>
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Image Classification Step2: Explore the Data Step5: Implement Preprocess Functions Step8: One-hot encode Step10: Randomize Data Step12: Che...
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' class DLProgress(tqdm): last_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: CONTENTS Step2: Next we build our models. The text file we will use to build them is Flatland, by Edwin A. Abbott. We will load it from here. I...
<ASSISTANT_TASK:> Python Code: from text import * from utils import open_data from notebook import psource psource(UnigramWordModel, NgramWordModel, UnigramCharModel, NgramCharModel) flatland = open_data("EN-text/flatland.txt").read() wordseq = words(flatland) P1 = UnigramWordModel(wordseq) P2 = NgramWordModel(2, wor...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Scatter plots Step2: Histogram
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np x = np.random.randn(100) y = np.random.randn(100) plt.scatter(x, y, marker='*', color='red'); x = np.random.randn(100) plt.hist(x, bins=5); <END_TASK>
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 디버깅? de+bugg+ing => 버그를 잡는다 Step2: 만약 안에 있는 것을 exit()로 종료하지 않고 dd로 밖에서 강제 종료할 경우 Step3: print를 쓰면 직관적으로 볼 수 있지만 안 좋은 이유는 결과에 영향을 미치기 때문 Step4:...
<ASSISTANT_TASK:> Python Code: for i in range(3): a = i * 7 #0, 7, 14 b = i + 2 #2, 3, 4 c = a * b # 0, 21, 56 #만약 이 range값이 3017, 5033일 경우에는 무슨 값인지 알 수 없다. 이 때 쉽게 a,b,c값이 무엇인지 찾는 방법을 소개 name = "KiPyo Kim" age = 29 from IPython import embed embed() for i in range(3): a = i * 7 b = i + 2 c = 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: with a 2D input xarray dataarray at a given time Step2: with a 2D + time input xarray dataarray Step3: Compute a laplacian Step4: plotting th...
<ASSISTANT_TASK:> Python Code: import xarray as xr from matplotlib import pyplot as plt %matplotlib inline from oocgcm.oceanmodels.nemo import grids #- Parameter coordfile = '/Users/lesommer/data/NATL60/NATL60-I/NATL60_coordinates_v4.nc' maskfile = '/Users/lesommer/data/NATL60/NATL60-I/NATL60_v4.1_cdf_byte_mask.nc' fi...
<SYSTEM_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. Initial Exploration Step2: 3. Initial Model Step3: 3.1 Precompute Step4: 3.2 Augment Step5: 3.3 Increase Size Step6: 6. Individual Predi...
<ASSISTANT_TASK:> Python Code: %reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.imports import * from fastai.torch_imports import * from fastai.transforms import * from fastai.model import * from fastai.dataset import * from fastai.sgdr import * from fastai.plots import * from fastai.conv_learner imp...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Generate fake dataset Step2: Hyperparameters Step3: Visualize training sequences Step4: Prepare datasets Step5: Peek at the data Step6: Ben...
<ASSISTANT_TASK:> Python Code: # using Tensorflow 2 %tensorflow_version 2.x import numpy as np from matplotlib import pyplot as plt import tensorflow as tf print("Tensorflow version: " + tf.__version__) #@title Display utilities [RUN ME] from enum import IntEnum import numpy as np class Waveforms(IntEnum): SINE1 = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Model Inputs Step2: Generator network Step3: Discriminator Step4: Hyperparameters Step5: Build network Step6: Discriminator and Generator L...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pickle as pkl import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data') def model_inputs(real_dim, z_dim): inputs_real = tf.placeholde...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 2 - Overview of the Problem set Step2: We added "_orig" at the end of image datasets (train and test) because we are going to preprocess them. ...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import h5py import scipy from PIL import Image from scipy import ndimage from lr_utils import load_dataset %matplotlib inline # Loading the data (cat/non-cat) train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dat...
<SYSTEM_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 a climlab Process? Step2: We have an array of temperatures in degrees Celsius. Let's see how big this array is Step3: Every state var...
<ASSISTANT_TASK:> Python Code: # We start with the usual import statements %matplotlib inline import numpy as np import matplotlib.pyplot as plt import climlab # create a new model with all default parameters (except the grid size) mymodel = climlab.EBM_annual(num_lat = 30) # What did we just do? print mymodel mymo...
<SYSTEM_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, $\S$ 6) Step2: $f(x) = x\log x$ Step3: Backtracking Step4: Выбор шага S...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt USE_COLAB = False if not USE_COLAB: plt.rc("text", usetex=True) import numpy as np C = 10 alpha = -0.5 q = 0.9 num_iter = 10 sublinear = np.array([C * k**alpha for k in range(1, num_iter + 1)]) linear = np.array([C * q**k for k in 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: Color threshold Step2: Based on the histogram of the hue, threshold the hue such that only the yellowish colors remain. Step3: Add the cities ...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import io import matplotlib.pyplot as plt import numpy as np import os import pandas import seaborn as sns import skimage import skimage.color import skimage.data import skimage.feature import skimage.filters import skimage.future import skimage.io import skimage.morpho...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
<ASSISTANT_TASK:> Python Code: import pandas as pd df = pd.DataFrame({'product': [1179160, 1066490, 1148126, 1069104, 1069105, 1160330, 1069098, 1077784, 1193369, 1179741], 'score': [0.424654, 0.424509, 0.422207, 0.420455, 0.414603, 0.168784, 0.168749, 0.168738, 0.168703, 0.168684]}) products = [1066...
<SYSTEM_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 client Step2: Wrap an existing Docker container image using ContainerOp Step3: Creating a Dockerfile Step4: Build docker image Step5: ...
<ASSISTANT_TASK:> Python Code: import kfp import kfp.gcp as gcp import kfp.dsl as dsl import kfp.compiler as compiler import kfp.components as comp import datetime import kubernetes as k8s # Required Parameters PROJECT_ID='<ADD GCP PROJECT HERE>' GCS_BUCKET='gs://<ADD STORAGE LOCATION HERE>' # Optional Parameters, but...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Check a number of cores Step2: Simple parallel summation Step3: Parallel sum
<ASSISTANT_TASK:> Python Code: from IPython import parallel c=parallel.Client() dview=c.direct_view() dview.block=True c.ids import numpy as np x=np.arange(100) dview.scatter('x',x) print c[0]['x'] print c[1]['x'] print c[-1]['x'] dview.execute('import numpy as np; y=np.sum(x)') ys=dview.gather('y') total=np.sum(ys)...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Config Contants Step2: in the variable "b" we are going to assign a constant with the initial value of "5" Step3: In the following variable "o...
<ASSISTANT_TASK:> Python Code: import tensorflow as tf # check tf version print(tf.__version__) a = tf.constant(2) b = tf.constant(5) operation = tf.add(a, b, name='cons_add') with tf.Session() as ses: print ses.run(operation) sub_operation = tf.subtract(a, b, name='cons_subtraction') x = tf.constant([[-1.37 ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Python for STEM Teachers<br/>Oregon Curriculum Network Step3: <div align="center">graphic by Kenneth Snelson</div>
<ASSISTANT_TASK:> Python Code: import json series_types = ["Don't Know", "Other nonmetal", "Alkali metal", "Alkaline earth metal", "Nobel gas", "Metalloid", "Halogen", "Transition metal", "Post-transition metal", "Lanthanoid", "Actinoid"] class Element...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Chapter 7 - Sets Step2: Curly brackets surround sets, and commas separate the elements in the set Step3: Please note that sets are unordered. ...
<ASSISTANT_TASK:> Python Code: %%capture !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Data.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/images.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Extra_Material.zip !unzip Data.zip -d ../ !unz...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Problema Prático 4.11 Step2: Exemplo 4.12 Step3: Problema Prático 4.12 Step4: Máxima Transferência de Potência Step5: Problema Prático 4.13
<ASSISTANT_TASK:> Python Code: print("Exemplo 4.11") #Superposicao #Analise Fonte de Tensao #Req1 = 4 + 8 + 8 = 20 #i1 = 12/20 = 3/5 A #Analise Fonte de Corrente #i2 = 2*4/(4 + 8 + 8) = 8/20 = 2/5 A #in = i1 + i2 = 1A In = 1 #Req2 = paralelo entre Req 1 e 5 #20*5/(20 + 5) = 100/25 = 4 Rn = 4 print("Corrente In:",In,"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: Using Pandas I will read the twitter json file, convert it to a dataframe, set the index to 'created at' as datetime objects, then write it to a...
<ASSISTANT_TASK:> Python Code: # load json twitter data twitter_json = r'data/twitter_01_20_17_to_3-2-18.json' # Convert to pandas dataframe tweet_data = pd.read_json(twitter_json) # read the json data into a pandas dataframe tweet_data = pd.read_json(twitter_json) # set column 'created_at' to the index tweet_data.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: Check the head of the DataFrame. Step2: How many rows and columns are there? Step3: What is the average Purchase Price? Step4: What were the ...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import seaborn as sns data = pd.read_csv('https://s3-ap-southeast-1.amazonaws.com/intro-to-ml-minhdh/EcommercePurchases.csv') data.head() data.shape data["Purchase Price"].mean() data["Purchase Price"].max() data["Purchase Price"].min() data[dat...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: get two random trees Step2: Plan for counting quartets (Illustrated below) Step3: Example to sample tips from each quartet edge Step4: Exampl...
<ASSISTANT_TASK:> Python Code: import toytree import itertools import numpy as np t0 = toytree.rtree.unittree(10, seed=0) t1 = toytree.rtree.unittree(10, seed=1) toytree.mtree([t0, t1]).draw(ts='p', height=200); t0.draw( ts='p', node_colors="lightgrey", edge_widths=3, edge_colors=t0.get_edge_values_ma...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Interaktive Hilfe Step2: Die weitere Funktionalität der Pandas-Bibliothek können wir erkunden, indem wir die Methoden von Pandas ansehen. Dazu ...
<ASSISTANT_TASK:> Python Code: import pandas as pd pd? pd.Categorical cdr = pd.read_csv('data/CDR_data.csv') cdr.head() cdr.info() len(cdr) cdr.CallTimestamp = pd.to_datetime(cdr.CallTimestamp) cdr.Duration = pd.to_timedelta(cdr.Duration) cdr.info() cdr.Duration.mean() phone_owners = pd.read_excel("data/phoneow...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Below I'm plotting an example image from the MNIST dataset. These are 28x28 grayscale images of handwritten digits. Step2: We'll train an autoe...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', validation_size=0) img = mnist.train.images[2] plt.imshow(img.reshape((28, 28)), cmap='...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Note Step2: The output of .tail() shows that there are more than 300 million datapoints (one per person), each with a location in Web Mercator ...
<ASSISTANT_TASK:> Python Code: import datashader as ds import datashader.transfer_functions as tf import dask.dataframe as dd import numpy as np %%time #df = dd.from_castra('data/census.castra') df = dd.read_hdf('data/census.hdf', key='census') #df = df.cache(cache=dict) import warnings warnings.filterwarnings('ignore...
<SYSTEM_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 fake "observations" Step2: We'll set the initial model to be close to the correct values, but not exact. In practice, we would instead ...
<ASSISTANT_TASK:> Python Code: #!pip install -I "phoebe>=2.3,<2.4" import phoebe from phoebe import u # units import numpy as np logger = phoebe.logger('error') b = phoebe.default_binary() b.set_value('ecc', 0.2) b.set_value('per0', 25) b.set_value('teff@primary', 7000) b.set_value('teff@secondary', 6000) b.set_value(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: If 'tensorflow-hub' isn't one of the outputs above, then you'll need to install it. Uncomment the cell below and execute the commands. After doi...
<ASSISTANT_TASK:> Python Code: %%bash pip freeze | grep tensor !pip3 install tensorflow-hub==0.4.0 !pip3 install --upgrade tensorflow==1.13.1 import os import tensorflow as tf import numpy as np import tensorflow_hub as hub import shutil PROJECT = 'cloud-training-demos' # REPLACE WITH YOUR PROJECT ID BUCKET = 'cloud-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: Simulation of kinematic motion model Step2: Implementation of EKF for $\sigma$-model Step3: Define state transition function $F$ Step4: Compu...
<ASSISTANT_TASK:> Python Code: # Import dependencies from __future__ import division, print_function %matplotlib inline import scipy import sympy from sympy import Symbol, symbols, Matrix, sin, cos, latex from sympy.interactive import printing printing.init_printing() sympy.init_printing(use_latex="mathjax", fontsize='...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Python posee por defecto un tipo de datos que se asemeja(listas), pero es numéricamente ineficiente Step2: Caracteristicas y utilidades princip...
<ASSISTANT_TASK:> Python Code: #Importamos el modulo numpy con el alias np import numpy as np #Creo un array a = np.array([1,0,0]) a type(a) #Ejemplo creo una lista de Python de 0 a 1000 y calculo el cuadrado de cada elemento L = range(1000) %%timeit [i**2 for i in L] #Ahora hago lo mismo con Numpy a = np.arange(1000...
<SYSTEM_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...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'inpe', 'sandbox-1', 'ocean') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "emai...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Notes
<ASSISTANT_TASK:> Python Code: from scipy import stats import numpy as np # making kde values = np.arange(10) kde = stats.gaussian_kde(values) np.median(kde.resample(100000)) def KDE_make_means(kde, size=10): func = lambda x : np.random.randint(0, x.n, size=x.d) kde.means = [kde.dataset[:, func(kde)] for i in 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: Importa a planilha que contem os dados utilizados. Esta planilha foi importada de www.kaggle.com Step2: Normaliza a coluna 'Value' (valor do jo...
<ASSISTANT_TASK:> Python Code: #importando bibliotecas que iremos usar %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns; sns.set() import warnings import os from numpy import arange from scipy.stats import skew from sklearn.utils import shuffle from scipy.s...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: And here is another one Step2: In our example we want to apply some vector arithmetics. Step3: Now, what is the length of this new vector? Ste...
<ASSISTANT_TASK:> Python Code: x = 5 y = 7 x2 = -3 # oops maybe the choice of variable names is not optimal y2 = 17 x3 = x + x2 y3 = y + y2 print(x3, y3) from math import sqrt length_3 = sqrt(x3 * x3 + y3 * y3) print length_3 length_1 = sqrt(x * x + y * y) print length_1 def length(x, y): return sqrt(x* 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: Python's or Step2: Python's concept of truthiness Step3: Slowly scroll through the output of the following cell, Step4: There was some confus...
<ASSISTANT_TASK:> Python Code: # meld is a great visual difference program # http://meldmerge.org/ # the following command relies on the directory structure on my computer # tdd-demo comes from https://github.com/james-prior/tdd-demo/ !cd ~/projects/tdd-demo;git difftool -t meld -y 389df2a^ 389df2a False or False 0 or...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: This is all we need, GPy/Paramz will handle the rest for you Step2: This is the model plot before optimization Step3: And then the optimized ...
<ASSISTANT_TASK:> Python Code: # Get the parameters for Rprop of climin: climin.Rprop? class RProp(Optimizer): # We want the optimizer to know some things in the Optimizer implementation: def __init__(self, step_shrink=0.5, step_grow=1.2, min_step=1e-06, max_step=1, changes_max=0.1, *args, **kwargs): su...
<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: The notMNIST dataset is too large for many computers to handle. It contains 500,000 images for just training. You'll be using a subset of this...
<ASSISTANT_TASK:> Python Code: import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfil...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: But, did you know that they are both referring to the same 7 object? In other words, variables in Python are always references or pointers to da...
<ASSISTANT_TASK:> Python Code: x = y = 7 print(x,y) x = y = 7 print(id(x)) print(id(y)) from lolviz import * callviz(varnames=['x','y']) name = 'parrt' userid = name # userid now points at the same memory as name print(id(name)) print(id(userid)) you = [1,3,5] me = [1,3,5] print(id(you)) print(id(me)) callviz(varn...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Helper functions Step2: Load raw trip data Step3: Processing Time and Date Step4: Plotting weekly rentals Step5: The rentals show that over ...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) # for auto-reloading external modules # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipy...
<SYSTEM_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 sample script for calculate CLV of Lorenz 63 model is placed at examples/clv.rs Step2: Tangency of CLVs
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np ! cargo run --release --example clv > clv.csv df = np.arccos(pd.read_csv("clv.csv")) for col in df.columns: plt.figure() plt.title(col) df[col].hist(bins=100) plt.xlim(0, 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: Plot the contributions to the detected components (i.e., the forward model)
<ASSISTANT_TASK:> Python Code: # Author: Alexandre Barachant <alexandre.barachant@gmail.com> # Jean-Remi King <jeanremi.king@gmail.com> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne import Epochs from mne.decoding import SPoC from mne.datasets.fieldtrip_cmc import data_path 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: Each module has a unique name which can be used to assign a priority level for messages generated by that module. Step2: The default logging le...
<ASSISTANT_TASK:> Python Code: !head -n12 $LISA_HOME/logging.conf !head -n30 $LISA_HOME/logging.conf | tail -n5 import logging from conf import LisaLogging LisaLogging.setup(level=logging.INFO) from env import TestEnv te = TestEnv({ 'platform' : 'linux', 'board' : 'juno', 'host' ...
<SYSTEM_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 define a computational graph composed of operations and tensors Step2: Then use a session to execute the graph Step3: Graphs can be exec...
<ASSISTANT_TASK:> Python Code: # import and check version import tensorflow as tf # tf can be really verbose tf.logging.set_verbosity(tf.logging.ERROR) print(tf.__version__) # a small sanity check, does tf seem to work ok? hello = tf.constant('Hello TF!') sess = tf.Session() print(sess.run(hello)) sess.close() a = tf...
<SYSTEM_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 data and view Step2: Manipulate data Step3: Now build the model Step4: Initiate the Bayesian sampling Step5: Plot the traces and tak...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline from pymc3 import Model, Normal, Lognormal, Uniform, trace_to_dataframe, df_summary data = pd.read_csv('/5studies.csv') data.head() plt.figure(figsize =(10,10)) for study in 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: Human evaluation of visual metrics Step2: First download the dataset containing all evaluations. Step3: Then decorate it with whether the crop...
<ASSISTANT_TASK:> Python Code: # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
<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: Gramáticas Independientes del Contexto (CFG) Step3: Fíjate cómo hemos definido nuestra gramática Step4: Con el objeto grammar1 ya creado, crea...
<ASSISTANT_TASK:> Python Code: from __future__ import print_function from __future__ import division import nltk g1 = S -> NP VP NP -> Det N | Det N PP | 'I' VP -> V NP | VP PP PP -> P NP Det -> 'an' | 'my' N -> 'elephant' | 'pajamas' V -> 'shot' P -> 'in' grammar1 = nltk.CFG.fromstring(g1) analyzer = nltk.ChartPar...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Controlling for Random Negatve vs Sans Random in Imbalanced Techniques using S, T, and Y Phosphorylation. Step2: Y Phosphorylation Step3: T Ph...
<ASSISTANT_TASK:> Python Code: from pred import Predictor from pred import sequence_vector from pred import chemical_vector par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"] for i in par: print("y", i) y = Predictor() y.load_data(file="Data/Training/clean_s_filtered.csv") ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Measurement 0 Step2: Measurement 1 Step3: Measurement 2
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np from pathlib import Path from scipy.stats import linregress dir_ = r'C:\Data\Antonio\data\8-spot 5samples data\2013-05-15/' filenames = [str(f) for f in Path(dir_).glob('*.hdf5'...
<SYSTEM_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 image is not science-ready yet... Step2: Why is this? Step3: Let's create a better image! Step4: Compare to the original! Step5: Reduce...
<ASSISTANT_TASK:> Python Code: science_image_path_g = 'data/seo_m66_g-band_180s_apagul_1.fits' #Type the path to your image sci_g = fits.open(science_image_path_g) sci_im_g = fits.open(science_image_path_g)[0].data plt.imshow(sci_im_g,cmap='gray', vmax=1800, norm=matplotlib.colors.LogNorm()) plt.colorbar() dark_image_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Usage Step2: Token is defined as a namedtuple (v0.3.2+) with the following fields Step3: Using MeCab Options Step4: The exapmle below uses do...
<ASSISTANT_TASK:> Python Code: # Version for this notebook !pip list | grep mecabwrap from mecabwrap import tokenize, print_token for token in tokenize('すもももももももものうち'): print_token(token) token from mecabwrap import do_mecab out = do_mecab('人生楽ありゃ苦もあるさ', '-Owakati') print(out) from mecabwrap import do_mecab_vec...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: BERT Preprocessing with TF Text Step2: Our data contains two text features and we can create a example tf.data.Dataset. Our goal is to create a...
<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: (2) max features Ste...
<ASSISTANT_TASK:> Python Code: # baseline confirmation, implying that model has to perform at least as good as it from sklearn.dummy import DummyClassifier clf_Dummy = DummyClassifier(strategy='most_frequent') clf_Dummy = clf_Dummy.fit(X_train, y_train) print('baseline score =>', round(clf_Dummy.score(X_test, y_test),...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Question Step2: Question 1 Step3: Question 2 Step4: Question 3 Step5: Section 3 Step6: Part 2 Step8: Section 4
<ASSISTANT_TASK:> Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt ''' count_times = the time since the start of data-taking when the data was taken (in seconds) count_rates = the number of counts since the last time data was taken, at the time in count_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: prepare data Step2: Step3: load weight Step4: feed forward Step5: cost function Step6: regularized cost function
<ASSISTANT_TASK:> Python Code: %reload_ext autoreload %autoreload 2 import sys sys.path.append('..') from helper import nn from helper import logistic_regression as lr import numpy as np X_raw, y_raw = nn.load_data('ex4data1.mat', transpose=False) X = np.insert(X_raw, 0, np.ones(X_raw.shape[0]), axis=1) X.shape y_raw...
<SYSTEM_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 an array of 10 zeros Step2: Create an array of 10 ones Step3: Create an array of 10 fives Step4: Create an array of the integers from ...
<ASSISTANT_TASK:> Python Code: import numpy as np np.zeros(10) np.ones(10) np.ones(10) * 5 np.arange(10,51) np.arange(10,51,2) np.arange(9).reshape(3,3) np.eye(3) np.random.rand(1) np.random.randn(25) np.arange(1,101).reshape(10,10) / 100 np.linspace(0,1,20) mat = np.arange(1,26).reshape(5,5) mat # WRITE CO...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Ejemplo 2 funciona Step2: Fonction Step6: Trabajo futuro
<ASSISTANT_TASK:> Python Code: import numpy as np from scipy import integrate from matplotlib.pylab import * import numpy as np from scipy import integrate import matplotlib.pyplot as plt def vdp1(t, y): return np.array([y[1], (1 - y[0]**2)*y[1] - y[0]]) t0, t1 = 0, 20 # start and end t = np.linspac...
<SYSTEM_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 Data Step2: Preparing Data Step3: Units Step4: Coordinates Step5: Projections Step6: The cartopy Globe can similarly be accessed vi...
<ASSISTANT_TASK:> Python Code: import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt import xarray as xr # Any import of metpy will activate the accessors import metpy.calc as mpcalc from metpy.testing import get_test_data # Open the netCDF file as a xarray Dataset data = xr.ope...
<SYSTEM_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 return ... to give a value back to the caller. A function that doesn’t explicitly return a value automatically returns None. Step2: Questio...
<ASSISTANT_TASK:> Python Code: # a simple function that looks like a mathematical function # define a function called add_two_numbers that take 2 arguments: num1 and num2 def add_two_numbers(num1, num2): # Under the def must be indented return num1 + num2 # use the return statment to tell the function what to 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: Fitting data to probability distributions Step2: The first step is recognizing what sort of distribution to fit our data to. A couple of observ...
<ASSISTANT_TASK:> Python Code: x = np.array([ 1.00201077, 1.58251956, 0.94515919, 6.48778002, 1.47764604, 5.18847071, 4.21988095, 2.85971522, 3.40044437, 3.74907745, 1.18065796, 3.74748775, 3.27328568, 3.19374927, 8.0726155 , 0.90326139, 2.34460034, 2.14199217, 3.27446744, 3.5887...
<SYSTEM_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 órbita del Planeta Nueve Step2: Vamos a crear un objeto State para representar Planeta Nueve, añadiendo a los parámetros estimados del artíc...
<ASSISTANT_TASK:> Python Code: !conda install -qy poliastro --channel poliastro # Instala las dependencias con conda !pip uninstall poliastro -y #!pip install -e /home/juanlu/Development/Python/poliastro.org/poliastro !pip install https://github.com/poliastro/poliastro/archive/planet9-fixes.zip # Instala la versión 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: As always, let's do imports and initialize a logger and a new bundle. See Building a System for more details. Step2: Adding Datasets Step3: R...
<ASSISTANT_TASK:> Python Code: !pip install -I "phoebe>=2.2,<2.3" %matplotlib inline import phoebe from phoebe import u # units import numpy as np import matplotlib.pyplot as plt logger = phoebe.logger() b = phoebe.default_binary() b.add_dataset('lc', times=np.linspace(0,1,201), dataset='mylc') b.run_compute(irrad_m...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Testing Step2: Experimenting with saving as Pandas.DataFrame.to_feather(.) Step3: Another way to create submission file Step4: Creating FileL...
<ASSISTANT_TASK:> Python Code: %reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.imports import * from fastai.transforms import * from fastai.conv_learner import * from fastai.model import * from fastai.dataset import * from fastai.sgdr import * from fastai.plots import * PATH = "data/dogscats/" sz=22...
<SYSTEM_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 graph data from a json file Step2: Get the number of nodes Step3: Define the list of edges Step4: Define the Graph object from Edges Ste...
<ASSISTANT_TASK:> Python Code: import igraph as ig import json data = [] with open('miserables.json') as f: for line in f: data.append(json.loads(line)) data=data[0] data print data.keys() N=len(data['nodes']) N L=len(data['links']) Edges=[(data['links'][k]['source'], data['links'][k]['target'])...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Download data Step2: Clean data Step3: Plot the closing quotes over time to get a fisrt impression about the historical market trend by using ...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt from plotly.offline import init_notebook_mode,iplot import plotly.graph_objs as go %matplotlib inline init_notebook_mode(connected=True) import quandl sp500=quandl.get("YAHOO/INDEX_GSPC",start_date="2000-01-03",end_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) Step2: Se trabajará con SVHN o Street View House Numbers, se puede observar que las imágenes con las que se trabajará, efectivamente pertene...
<ASSISTANT_TASK:> Python Code: import scipy.io as sio import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import random from keras.utils import np_utils from keras.models import Sequential, Model from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolut...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Unpack to extract structure Step2: Votes are still crammed in a dictionary. Let's unpack it. Step3: Quick data visualization Step4: Represent...
<ASSISTANT_TASK:> Python Code: reviews = gl.SFrame.read_csv('../data/yelp/yelp_training_set_review.json', header=False) reviews reviews[0] reviews=reviews.unpack('X1','') reviews reviews = reviews.unpack('votes', '') reviews reviews.show() reviews['date'] = reviews['date'].str_to_datetime(str_format='%Y-%m-%d') 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: Step1: Fine-tuning a BERT model Step2: Imports Step3: Resources Step4: You can get a pre-trained BERT encoder from TensorFlow Hub Step5: The data S...
<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: The below is the same code as last post with a couple modifications Step2: Now, I will do the same model building procedure as last time. There...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import json import codecs import warnings import matplotlib.pyplot as plt %matplotlib inline race_metadata = pd.read_csv('~/election-twitter/elections-twitter/data/race-metadata.csv') race_metadata_2016 = pd.read_csv('~/election-twitter/elections-twi...
<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: Background Subtraction and Source Detection Step3: Problem 1) Simple 1-D Background Estimation Step4: Problem 1.2) Estimate a the background a...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from matplotlib.ticker import MultipleLocator %matplotlib notebook def pixel_plot(pix, counts, fig=None, ax=None): '''Make a pixelated 1D plot''' if fig is None and ax is None: fig, ax = plt.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: Part B
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.ndimage as ndimage img = ndimage.imread("noisy.png", flatten = True) ### BEGIN SOLUTION ### END SOLUTION import scipy.ndimage as ndimage img = ndimage.imread("noisy.png", flatten = True) t1 = 30 s1 = 5 a1 ...
<SYSTEM_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: 导入 Fashion MNIST 数据集 Step3: 加载数据集会返回四个 NumPy 数组: Step4: 浏览数据 Step5: 同样,训练集中有 60,000 个标签: Step6: 每个标签都是一个 0 到 9 之间的整数:...
<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: Load Medical Appointment Data Step2: Feature Analysis Step3: Rank2D Step4: Diagnostic Interpretation from Rank2D(Covariance) Step5: Diagnost...
<ASSISTANT_TASK:> Python Code: import os import sys # Modify the path sys.path.append("..") import pandas as pd import yellowbrick as yb import matplotlib.pyplot as plt data = pd.read_csv("data/No-show-Issue-Comma-300k.csv") data.head() data.columns = ['Age','Gender','Appointment Registration','Appointment Date', ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Problem 1) Density Estimation Step2: Problem 1a Step3: Already with this simple plot we see a problem - the choice of bin centers and number ...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from sklearn.datasets import load_linnerud linnerud = load_linnerud() chinups = linnerud.data[:,0] plt.hist(chinups, histtype = "step", lw = 3) plt.hist(chinups, bins = 5, histtype="step", lw = 3) plt.hist(chinups, a...