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: Import all radars Step2: Import a specific radar Step3: Import a specific radar site
<ASSISTANT_TASK:> Python Code: # Import radar module %pylab inline from davitpy.pydarn.radar import * radars = network() print radars # How to get the total number of radars print len(radars) print radars.nradar # How to get a specific radar from the mountain of recorded radars print radars.getRadarByCode("bks") # is ...
<SYSTEM_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 module provide for each of the file resources a class, with for each of the classes the methods download_file and list_files defined Step2: ...
<ASSISTANT_TASK:> Python Code: import datamover as dm print(dm.LocalConnector.list_files, dm.LocalConnector.download_file) print(dm.S3Connector.list_files, dm.S3Connector.download_file) print(dm.FTPConnector.list_files, dm.FTPConnector.list_files) print(dm.GithubConnector.list_files, dm.GithubConnector.download_file) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Place text search Step2: Place details - get more information once we have a place Step3: Now let's look up a series of places! We'll store ou...
<ASSISTANT_TASK:> Python Code: import requests search_endpoint = 'https://maps.googleapis.com/maps/api/place/textsearch/json' search_params = { 'query': 'Länggass Stübli', 'key': 'AIzaSyCNx-klDCfhopV6W_QPFZ0iwv5sp1J0XwQ', 'language': 'en' } r = requests.get( search_endpoint, params=search_params) r.jso...
<SYSTEM_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 investigate sensitivity of the LogisiticModels to different seeds Step2: Essentially no difference when setting the seed for different ru...
<ASSISTANT_TASK:> Python Code: %matplotlib inline from vessel_scoring import data, utils from vessel_scoring.models import train_model_on_data from vessel_scoring.evaluate_model import evaluate_model, compare_models from IPython.core.display import display, HTML, Markdown import numpy as np import sys from sklearn impo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Then we need some imports Step3: We define a simple function that returns our training dataset as a Ray Dataset Step5: Now we define a simple ...
<ASSISTANT_TASK:> Python Code: !pip install -qU "ray[tune]" sklearn xgboost_ray comet_ml import ray from ray.air import RunConfig from ray.air.result import Result from ray.train.xgboost import XGBoostTrainer from ray.tune.integration.comet import CometLoggerCallback from sklearn.datasets import load_breast_cancer 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: Let's untar the file unless it has already been untarred. Step2: The UW3-500 dataset is a collection of text line images and corresponding grou...
<ASSISTANT_TASK:> Python Code: !test -f uw3-500.tgz || wget -nd http://www.tmbdev.net/ocrdata/uw3-500.tgz !test -d book || tar -zxvf uw3-500.tgz !ls book/0005/010001.* !dewarp=center report_every=500 save_name=test save_every=10000 ntrain=11000 ../clstmctc uw3-500.h5 !ls book/*/*.bin.png | sort -r > uw3.files !sed 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: The following code cell visualizes the audio waveform for your chosen example, along with the corresponding transcript. You also have the optio...
<ASSISTANT_TASK:> Python Code: from data_generator import vis_train_features # extract label and audio features for a single training example vis_text, vis_raw_audio, vis_mfcc_feature, vis_spectrogram_feature, vis_audio_path = vis_train_features() from IPython.display import Markdown, display from data_generator 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: Rectangle and Triangle Pulses Defined Step2: Consider an interactive version of the above Step3: More Signal Plotting Step5: Custom Piecewise...
<ASSISTANT_TASK:> Python Code: t = arange(-4,4,.01) x = cos(2*pi*t) plot(t,x) grid() t = arange(-5,5,.01) x_rect = ss.rect(t-3,2) x_tri = ss.tri(t+2,1.5) subplot(211) plot(t,x_rect) grid() ylabel(r'$\Pi((t-3)/2)$'); subplot(212) plot(t,x_tri) grid() xlabel(r'Time (s)') ylabel(r'$\Lambda((t+2)/1.5)$'); tight_layout() ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We Can Proud of Ourselves 💃 Step2: Are we done ?! 🍰 Step3: When a file does not exists or when the file is not a valid json we raise FileNo...
<ASSISTANT_TASK:> Python Code: ! pip install typeguard rollbar returns tenacity > /dev/null 2>&1 import contextlib import json import logging import pathlib import os from typing import Union import requests from typeguard import typechecked # Naive code snippets def get_relevant_restaurants(user): base_url = "http...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Network Step2: Graphviz Step3: ParameterGraph Step4: Parameter Step5: DomainGraph Step6: MorseDecomposition Step7: MorseGraph
<ASSISTANT_TASK:> Python Code: import DSGRN network = DSGRN.Network("network.txt") print(network) print(network.graphviz()) import graphviz graph = graphviz.Source(network.graphviz()) graph parametergraph = DSGRN.ParameterGraph(network) print("There are " + str(parametergraph.size()) + " nodes in the parameter graph...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Doubly Linked List Step2: Stack Step3: ```
<ASSISTANT_TASK:> Python Code: # Node of a Singly Linked List class Node: # constructor def __init__(self, data=None, next=None): self.data = data self.next = next # method of getter, setter for data def setData(self, data): self.data = data def getData(self): 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: Mutiple Plots on One Graph Step2: Save it to a File Step3: Adjust the Axes Step4: Add a Grid Step5: Change Line Types and Colors Step6: Lab...
<ASSISTANT_TASK:> Python Code: %matplotlib inline from scipy.stats import norm import matplotlib.pyplot as plt import numpy as np x = np.arange(-3, 3, 0.01) plt.plot(x, norm.pdf(x)) plt.show() plt.plot(x, norm.pdf(x)) plt.plot(x, norm.pdf(x, 1.0, 0.5)) plt.show() plt.plot(x, norm.pdf(x)) plt.plot(x, norm.pdf(x, 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: Vamos a hacer una prueba en primer lugar Step2: En la gráfica anterior podemos ver no solo la posición en el primer cuadro, si no tambien la ve...
<ASSISTANT_TASK:> Python Code: from generacion_trayectorias import grafica_trayectoria %matplotlib inline ts, qs, q̇s, q̈s = grafica_trayectoria(0, 2, 0, 1, 1000) from numpy import pi τ = 2*pi ts, q1, q̇1, q̈1 = grafica_trayectoria(0, 2, 0, τ/4, 100) ts, q2, q̇2, q̈2 = grafica_trayectoria(2, 4, τ/4, -τ/6, 100) ts, q...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Get the MNIST data Step2: Create the Network Step3: Set up the Loss Function Step4: Set up the Training Function Step5: Set up the Initializ...
<ASSISTANT_TASK:> Python Code: import numpy as np import tensorflow as tf import matplotlib.pyplot as plt %matplotlib inline import gzip import pickle # Seed for reproducibility np.random.seed(42) # Download the MNIST digits dataset (only if not present locally) import os import urllib.request mnist_data = './data/MN...
<SYSTEM_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 - Problem Statement Step2: The characters are a-z (26 characters) plus the "\n" (or newline character), which in this assignment plays a role...
<ASSISTANT_TASK:> Python Code: import numpy as np from utils import * import random data = open('dinos.txt', 'r').read() data= data.lower() chars = list(set(data)) data_size, vocab_size = len(data), len(chars) print('There are %d total characters and %d unique characters in your data.' % (data_size, vocab_size)) char...
<SYSTEM_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 an mp3 file Step2: Trim it and make it a 2d. Step3: Let's make it a batch of 4 items Step4: A Keras model Step5: The model has no tr...
<ASSISTANT_TASK:> Python Code: import librosa import kapre import tensorflow as tf from tensorflow.keras.models import Sequential import numpy as np from datetime import datetime now = datetime.now() print('%s/%s/%s' % (now.year, now.month, now.day)) print('Tensorflow: {}'.format(tf.__version__)) print('Librosa: {}'.fo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: First, let's a create a phase diagram to show the logistic map's fixed-point attractor at 0.655 when the growth rate parameter is set to 2.9 Ste...
<ASSISTANT_TASK:> Python Code: import IPython.display as IPdisplay import matplotlib.pyplot as plt import numpy as np import pandas as pd import pynamical from pynamical import simulate, save_fig, phase_diagram, phase_diagram_3d %matplotlib inline title_font = pynamical.get_title_font() label_font = pynamical.get_label...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We will use this helper funciton to write lists containing article ids, categories, and authors for each article in our database to local file. ...
<ASSISTANT_TASK:> Python Code: import os import tensorflow as tf import numpy as np from google.cloud import bigquery PROJECT = 'cloud-training-demos' # REPLACE WITH YOUR PROJECT ID BUCKET = 'cloud-training-demos-ml' # REPLACE WITH YOUR BUCKET NAME REGION = 'us-central1' # REPLACE WITH YOUR BUCKET REGION e.g. us-centr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Build a base image to work with fairing Step2: Start an AI Platform job
<ASSISTANT_TASK:> Python Code: BUCKET = "gs://" # your bucket here assert re.search(r'gs://.+', BUCKET), 'A GCS bucket is required to store your results.' !cat Dockerfile !docker build . -t {base_image} !docker push {base_image} additional_files = '' # If your code requires additional files, you can specify them her...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: First we'll load the text file and convert it into integers for our network to use. Step3: Now I need to split up the data into batches, and in...
<ASSISTANT_TASK:> Python Code: import time from collections import namedtuple import numpy as np import tensorflow as tf with open('anna.txt', 'r') as f: text=f.read() vocab = set(text) vocab_to_int = {c: i for i, c in enumerate(vocab)} int_to_vocab = dict(enumerate(vocab)) chars = np.array([vocab_to_int[c] for c ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Univariate normal Step3: Grid algorithm Step4: Update Step5: Posterior distribution of sigma Step6: Posterior distribution of mu Step7: Pos...
<ASSISTANT_TASK:> Python Code: # If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install empiricaldist # Get utils.py and create directories import os if not os.path.exists('utils.py'): !wget https:/...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: First reload the data we generated in notmist.ipynb. Step2: Reformat into a shape that's more adapted to the models we're going to train Step3:...
<ASSISTANT_TASK:> Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle pickle_file = 'notMNIST.pickle' with open(pickle_file, 'rb...
<SYSTEM_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. Build a Shyft model Step2: Create a collection of simulation cells Step4: So the first step is to extract these from the netcdf file, and g...
<ASSISTANT_TASK:> Python Code: # Pure python modules and jupyter notebook functionality # first you should import the third-party python modules which you'll use later on # the first line enables that figures are shown inline, directly in the notebook %matplotlib inline import os import datetime as dt import numpy as n...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Sockets are the endpoints of a bidirectional communications channel. Step2: To check if the socket is actually created one can check using the...
<ASSISTANT_TASK:> Python Code: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # This creates a socket # AF_INET => family ipv4. # SOCK_STREAM => TCP protocol. import socket def client_handler(client_sock): # Do things here # .send() Takes byte type object # b' it indicates that the ...
<SYSTEM_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 let's re-create Figure 2 Step2: Now let's see what the performance is as we vary different parameters. To do this, I'm using pytry, a simp...
<ASSISTANT_TASK:> Python Code: # the facilitation spikes def stim_1_func(t): index = int(t/0.001) if index in [100, 1100, 2100]: return 1000 else: return 0 # the trigger spikes def stim_2_func(t): index = int(t/0.001) if index in [90, 1500, 2150]: return 1000 else: ...
<SYSTEM_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 star value of different reviews to filter comments. Step2: <b>Cleaning and Preprocessing</b> Step3: <b>Preparing Document-Term Matrix</b> ...
<ASSISTANT_TASK:> Python Code: good_app = app.loc[app['weighted_rating'] >=4.0] bad_app = app.loc[app['weighted_rating'] <=2.5] good_app = good_app.reset_index(drop=True) bad_app = bad_app.reset_index(drop=True) category = app['category'] cate_list = [] for i in category.unique(): cate = i.lower() cate_list.app...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Map Basics Step2: The map above (run the code cell if you don't see it) shows a disconnected network of 10 intersections. The two intersections...
<ASSISTANT_TASK:> Python Code: # Run this cell first! from helpers import Map, load_map, show_map from student_code import shortest_path %load_ext autoreload %autoreload 2 map_10 = load_map('map-10.pickle') show_map(map_10) map_10.intersections # this shows that intersection 0 connects to intersections 7, 6, and 5 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: Comparing the Errors
<ASSISTANT_TASK:> Python Code: num_states = 8 gamma = 0.9 true_values = gamma**np.arange(num_states)[::-1] d_pi = np.ones(num_states)/num_states D_pi = np.diag(d_pi) print("True values:") print(true_values) print("On-policy distribution:") print(d_pi) def compute_value_dct(theta_lst, features): return [{s: np.dot(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: 2. Read in the hanford.csv file Step2: <img src="images/hanford_variables.png"> Step3: 4. Calculate the coefficient of correlation (r) and gen...
<ASSISTANT_TASK:> Python Code: import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import statsmodels.formula.api as smf df=pd.read_csv('/home/sean/git/algorithms/class6/data/hanford.csv') df df.describe() lm = smf.ols(formula="Mortality~Exposure",data=df).fit() lm.params intercept, slope = lm.pa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Assessing the veracity of semantic markup for dataset pages Step2: Import Modules Step3: Upload Dataset Step4: Load dataset in pandas.DataFra...
<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: Lets start by generating some behavioral data from the social influence task. Here green advice/choice is encoded as 0 and the blue advice/choic...
<ASSISTANT_TASK:> Python Code: import numpy as np from scipy import io import matplotlib.pyplot as plt import seaborn as sns import pandas as pd sns.set(style = 'white', color_codes = True) %matplotlib inline import sys import os import os cwd = os.getcwd() sys.path.append(cwd[:-len('befit/examples/social_influence')])...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Preprocessing Step2: Visualization of ELC usage data Step3: Calendar heat map of sign-ins Step4: Sign-ins by course Step5: Sign-ins by hour ...
<ASSISTANT_TASK:> Python Code: #@title #%%capture import numpy as np #Linear algebra import pandas as pd #Time series, datetime object manipulation import matplotlib.pyplot as plt #plotting #import seaborn as sb #plt.style.use('fivethirtyeight') #Plot style preferred by author. import calendar from tabulate import tab...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Creating counters Step2: Reading characters from input, and counting them. To add an item to the counter, simply increment its value. Step3: G...
<ASSISTANT_TASK:> Python Code: with open('../inputs/day06.txt', 'r') as f: data = [line.strip() for line in f.readlines()] from collections import Counter counters = [Counter() for i in range(0, len(data[0]))] for line in data: for index, char in enumerate(line): counters[index][char] += 1 answer = '...
<SYSTEM_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 Data Step2: Anomaly Models
<ASSISTANT_TASK:> Python Code: import os import numpy as np from pathlib import Path cwd = os.getcwd() os.chdir(Path(cwd).parents[1]) from lsanomaly import LSAnomaly import lsanomaly.notebooks.static_mix as demo n_samples = 20 offset = 2.5 X, xx, yy = demo.data_prep(n_samples=n_samples, offset=offset) sigma_candidate...
<SYSTEM_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 we can see one of the images. Step2: Train a network Step3: Saving and loading networks Step4: The simplest thing to do is simply save t...
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms import helper import fc_model # Define a transform to no...
<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: Bayesian Network in a Jupyter Notebook (BJN) Step11: Random structure and parameter generators Step13: Graph Utilities and Visualizations Step...
<ASSISTANT_TASK:> Python Code: import numpy as np import scipy as sc from scipy.special import gammaln from scipy.special import digamma %matplotlib inline from itertools import combinations import pygraphviz as pgv from IPython.display import Image from IPython.display import display def normalize(A, axis=None): N...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Install the Google cloud-storage library as well. Step2: Restart the Kernel Step3: Before you begin Step4: Region Step5: Timestamp Step6: A...
<ASSISTANT_TASK:> Python Code: ! pip3 install google-cloud-automl ! pip3 install google-cloud-storage import os if not os.getenv("AUTORUN"): # Automatically restart kernel after installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) PROJECT_ID = "[your-project-id]" ...
<SYSTEM_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: 创建嵌入向量层时,嵌入向量的权重会随机初始化(就像其他任何层一样)。在训练过程中,通过反向传播来逐渐调整这些权重。训练后,学习到的单词嵌入向量将粗略地编码单词之间的相似性(因为它们是针对训练模型的特定问题而学习的)。 Step...
<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:
<ASSISTANT_TASK:> Python Code:: import pandas as pd pd.get_dummies(df1.town) <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: Step5: More than one State object Step7: And here's run_simulation, which is a solution to the exercise at the end of the previous notebook. Step8: N...
<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 library from modsim import * # set the ra...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: In this part of the lecture we explain Stochastic Gradient Descent (SGD) which is an optimization method commonly used in neural networks. We wi...
<ASSISTANT_TASK:> Python Code: %matplotlib inline from fastai.learner import * # Here we generate some fake data def lin(a,b,x): return a*x+b def gen_fake_data(n, a, b): x = s = np.random.uniform(0,1,n) y = lin(a,b,x) + 0.1 * np.random.normal(0,3,n) return x, y x, y = gen_fake_data(50, 3., 8.) plt.scatter...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Theory and Algorithm Step2: The results for a single realization of the simulation are plotted below. As expected, the estimated bias value ten...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt fsize = 15 time_of_sim = 30 # s freq_acc = 50 # frequency of accelerometer measurements freq_meas = 2 dt = 1./freq_acc dt_meas = 1./freq_meas time_steps_acc = freq_acc*time_of_sim+1 time_steps_meas = freq_meas*time_of...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 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...
<ASSISTANT_TASK:> Python Code: from __future__ import division import graphlab products = graphlab.SFrame('amazon_baby_subset.gl/') import json with open('important_words.json', 'r') as f: important_words = json.load(f) important_words = [str(s) for s in important_words] # Remote punctuation def remove_punctuati...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Update the following notebook settings Step2: Ensure the repo is up to date Step3: Cherry picks for minor release Step4: Run tests localy Ste...
<ASSISTANT_TASK:> Python Code: %cd .. NEW_VERSION = '3.0.0' LAST_VERSION = '2.5.1' DEVELOP_VERSION = '2.6.0-develop' NEXT_FUTURE_VERSION = '3.0.0' MAJOR_RELEASE = True STABLE_BRANCH = '2.5-stable' GIT_REMOTE_UPSTREAM = 'origin' WORK_BRANCH = 'master' if MAJOR_RELEASE else STABLE_BRANCH CHERRY_PICKS = [] ! git checkou...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Listwise ranking Step2: We can then import all the necessary packages Step3: We will continue to use the MovieLens 100K dataset. As before, we...
<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: To initialize the extractor, you'll only need the starting and ending epoch of the time period you wish to visualize and the number of sample po...
<ASSISTANT_TASK:> Python Code: from poliastro.czml.extract_czml import CZMLExtractor from poliastro.examples import molniya start_epoch = molniya.epoch end_epoch = molniya.epoch + molniya.period N = 80 extractor = CZMLExtractor( start_epoch, end_epoch, N ) extractor.add_orbit(molniya, ...
<SYSTEM_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 section we will use the Boston Housing Data. Step2: <img src='https Step3: Model (Introducing Tensorboard) Step4: Learning in a TF S...
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_boston boston_dataset = load_boston() print(boston_dataset.DESCR) import pandas as pd from sklearn.datasets import load_boston import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split boston_dataset = load_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: Load config from default location. Step2: Create API endpoint instance as well as API resource instances (body and specification). Step3: Fill...
<ASSISTANT_TASK:> Python Code: from kubernetes import client, config config.load_kube_config() api_instance = client.AppsV1Api() dep = client.V1Deployment() spec = client.V1DeploymentSpec() name = "my-busybox" dep.metadata = client.V1ObjectMeta(name=name) spec.template = client.V1PodTemplateSpec() spec.template.meta...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Examples Step2: Example 1 Step3: Exemplo 3
<ASSISTANT_TASK:> Python Code: import numpy as np def phasecorr(f,h): F = np.fft.fftn(f) H = np.fft.fftn(h) T = F * np.conjugate(H) R = T/np.abs(T) g = np.fft.ifftn(R) return g.real testing = (__name__ == "__main__") if testing: import numpy as np import sys,os ia898path = os.path.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: Read data created in the previous chapter. Step2: <h2> Train and eval input functions to read from Pandas Dataframe </h2> Step3: Our input fun...
<ASSISTANT_TASK:> Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.6 import tensorflow as tf import pandas as pd import numpy as np import shutil print(tf.__version__) # In CSV, label is the first col...
<SYSTEM_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. Importing groundwater time series Step2: 2. Creating a Pastas TimeSeries object Step3: 3. Configuring a TimeSeries object Step4: Predefine...
<ASSISTANT_TASK:> Python Code: # Import some packages import pastas as ps import pandas as pd import matplotlib.pyplot as plt %matplotlib inline gwdata = pd.read_csv('../data/head_nb1.csv', parse_dates=['date'], index_col='date', squeeze=True) gwdata.plot(figsize=(15,4)) oseries = ps.TimeSeries(g...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 2. Read in the hanford.csv file Step2: <img src="images/hanford_variables.png"> Step3: 4. Calculate the coefficient of correlation (r) and gen...
<ASSISTANT_TASK:> Python Code: import pandas as pd %matplotlib inline import matplotlib.pyplot as plt # package for doing plotting (necessary for adding the line) import statsmodels.formula.api as smf # package we'll be using for linear regression df = pd.read_csv('hanford.csv') df.describe() df.corr() lm = smf.ols...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Exam Instructions Step2: MRjob class for calculating pairwise similarity using K-L Divergence as the similarity measure Step4: Questions Step5...
<ASSISTANT_TASK:> Python Code: import numpy as np from __future__ import division %reload_ext autoreload %autoreload 2 %%writefile kltext.txt 1.Data Science is an interdisciplinary field about processes and systems to extract knowledge or insights from large volumes of data in various forms (data in various forms, 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: 2D trajectory interpolation Step2: Use these arrays to create interpolated functions $x(t)$ and $y(t)$. Then use those functions to create the ...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import numpy as np from scipy.interpolate import interp1d # YOUR CODE HERE data = np.load("trajectory.npz") t = data["t"] x = data["x"] y = data["y"] assert isinstance(x, np.ndarray) and len(x)==40 assert isinstance...
<SYSTEM_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 source space Step2: Fixed dipole orientations Step3: Restricting the dipole orientations in this manner leads to the following Step4: The...
<ASSISTANT_TASK:> Python Code: import mne import numpy as np from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse data_path = sample.data_path() evokeds = mne.read_evokeds(data_path + '/MEG/sample/sample_audvis-ave.fif') left_auditory = evokeds[0].apply_baseline() fwd = mne....
<SYSTEM_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 we use
<ASSISTANT_TASK:> Python Code: # Author: Jaakko Leppakangas <jaeilepp@gmail.com> # # License: BSD (3-clause) import os.path as op from mayavi import mlab import mne from mne.datasets.sample import data_path print(__doc__) data_path = data_path() fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif') 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: Source of Data Step2: Illustrate Markdown Parsing Using mdparse Step5: Download And Pre-Process Data Step6: Note Step7: Cached pre-processed...
<ASSISTANT_TASK:> Python Code: from mdparse.parser import transform_pre_rules, compose import pandas as pd from tqdm import tqdm_notebook from fastai.text.transform import defaults df = pd.read_csv(f'https://storage.googleapis.com/issue_label_bot/language_model_data/000000000000.csv.gz').sample(5) df.head(1) pd.set_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: Check that the bornagain python module is correctly installed
<ASSISTANT_TASK:> Python Code: print('hello, world!') from __future__ import print_function #needed for python2/python3 compatibility try: import bornagain as ba print("successfully loaded bornagain module") major, minor = ba.major_version_number, ba.minor_version_number print("BornAgain version number...
<SYSTEM_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 need a function to actually time the reference implementation. We can do external timing use the time module, and the Java program also r...
<ASSISTANT_TASK:> Python Code: import sklearn.datasets import numpy as np import pandas as pd import subprocess import time def get_reference_timings(data, filename='tmp_data.csv', jarfile='/Users/leland/Source/HDBSCAN_Star/HDBSCAN_Star.jar', min_points=5, min_clust...
<SYSTEM_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've seen in a previous tutorial &lt;tut-raw-class&gt; how to plot data Step2: It may not be obvious when viewing this tutorial online, but by...
<ASSISTANT_TASK:> Python Code: import os import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file) raw.crop(tmax=60).load_data() ra...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Try TSNE and time it Step2: Try PCA instead Step3: Append all view_items for PCA processing Step4: Append all buy_items for PCA processing St...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import os from sklearn.manifold import TSNE from sklearn.decomposition import PCA os.chdir('/Users/Walkon302/Desktop/deep-learning-models-master/view2buy') # Read the preprocessed file, containing the user profile and item features from view2buy fold...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Tree ensembles (RandomForestClassifier)
<ASSISTANT_TASK:> Python Code: # import import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.grid_search import GridSearchCV from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.ensemble impo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The first thing we do is load in the BLASTP output we generated, so that we can plot some of the key features. We do that using the ex02.read_da...
<ASSISTANT_TASK:> Python Code: %pylab inline # Import helper module from helpers import rbbh # Load one-way BLAST results into a data frame called data_fwd data_fwd = rbbh.read_data("data/pseudomonas_blastp/B728a_vs_NCIMB_11764.tab") # Show first few lines of the loaded data data_fwd.head() # Show descriptive statist...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Env setup Step2: Object detection imports Step3: Model preparation Step4: Download Model Step5: Load a (frozen) Tensorflow model into memory...
<ASSISTANT_TASK:> Python Code: import numpy as np import os import six.moves.urllib as urllib import sys import tarfile import tensorflow as tf import zipfile from collections import defaultdict from io import StringIO from matplotlib import pyplot as plt from PIL import Image # This is needed since the notebook is sto...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Connect to Graphistry + Test Step2: Connect to TigerGraph and Test Step3: Query Tigergraph Step4: Visualize result of TigerGraph query Step5:...
<ASSISTANT_TASK:> Python Code: TIGER_CONFIG = { 'fqdn': 'http://MY_TIGER_SERVER:9000' } #!pip install graphistry import pandas as pd import requests ### COMMON ISSUES: wrong server, wrong key, wrong protocol, network notebook->graphistry firewall permissions import graphistry # To specify Graphistry account & serv...
<SYSTEM_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 some plot data Step2: Define range of data to make sparklines Step3: Output to new DataFrame of Sparklines Step4: Insert Sparklines in...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from scipy import stats import matplotlib.pyplot as plt %matplotlib inline import sparklines density_func = 78 mean, var, skew, kurt = stats.chi.stats(density_func, moments='mvsk') x_chi = np.linspace(stats.chi.ppf(0.01, density_func), ...
<SYSTEM_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 want to stop RP from reporting all sorts of stuff for this example so we set a specific environment variable to tell RP to do so. If you want...
<ASSISTANT_TASK:> Python Code: import sys, os, time # verbose = os.environ.get('RADICAL_PILOT_VERBOSE', 'REPORT') os.environ['RADICAL_PILOT_VERBOSE'] = 'ERROR' from adaptivemd import Project from adaptivemd import OpenMMEngine from adaptivemd import PyEMMAAnalysis from adaptivemd import File, Directory, WorkerSchedul...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Computing the eigenvalues and the eigenvectors Step2: The @ operator stands, in this context, for matrix multiplication. Step3: Modal Response...
<ASSISTANT_TASK:> Python Code: M = np.array(((2.0, 0.0), ( 0.0, 1.0))) K = np.array(((3.0,-2.0), (-2.0, 2.0))) p = np.array(( 0.0, 1.0)) w = 2.0 evals, Psi = eigh(K, M) Mstar = Psi.T@M@Psi Kstar = Psi.T@K@Psi pstar = Psi.T@p print(evals,end='\n\n') print(Psi,end='\n\n') print(Mstar,end='\n\n') print(Kstar,end='\n\n')...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <div id='intro' /> Step2: en donde cada punto interior (azul), representa un punto donde queremos conocer el valor de la función $u(x,y)$. Cons...
<ASSISTANT_TASK:> Python Code: import numpy as np from mpl_toolkits.mplot3d import axes3d from matplotlib import pyplot as plt from ipywidgets import interact from ipywidgets import IntSlider import sympy as sym import matplotlib as mpl mpl.rcParams['font.size'] = 14 mpl.rcParams['axes.labelsize'] = 20 mpl.rcParams['xt...
<SYSTEM_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 Motivating Example Using sklearn Step2: Remember that the form of data we will use always is Step3: Training and Test Datasets Step4: Tunin...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import scipy as sp import matplotlib as mpl import matplotlib.cm as cm from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt import pandas as pd pd.set_option('display.width', 500) pd.set_option('display.max_columns', 100) pd.se...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Setup Game Step2: Catcher Model Step3: Test the agent Step5: Show Playing
<ASSISTANT_TASK:> Python Code: import os, sys sys.path.append(os.path.join('..')) import keras.backend as K K.set_image_dim_ordering('th') # needs to be set since it defaults to tensorflow now from keras.models import Sequential from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.layers.core 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: Random sampling Step2: Sobol Step3: Classic Latin hypercube sampling Step4: Centered Latin hypercube sampling Step5: Maximin optimized hyper...
<ASSISTANT_TASK:> Python Code: print(__doc__) import numpy as np np.random.seed(123) import matplotlib.pyplot as plt from skopt.space import Space from skopt.sampler import Sobol from skopt.sampler import Lhs from skopt.sampler import Halton from skopt.sampler import Hammersly from skopt.sampler import Grid from 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: SeqRecord objects contain metadata Step2: The attributes can be modified as needed. Step3: Unstructured annotations are organised into a dicti...
<ASSISTANT_TASK:> Python Code: import Bio.SeqRecord as BSR import Bio.Seq as BS import Bio.Alphabet as BA # sequence seq = BS.Seq('MDGEDVQALVIDNGSGMCKA', BA.generic_protein) # sequence record record = BSR.SeqRecord(seq) print(record) # get sequence from record print(record.seq) # add identifier record.id = "AC500001"...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Thinking about how machine learning is normally performed, the idea of a train/test split makes sense. Real world systems train on the data they...
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier iris = load_iris() X, y = iris.data, iris.target classifier = KNeighborsClassifier() y import numpy as np rng = np.random.RandomState(0) permutation = rng.permutation(len(X)) X, y = X[permutation],...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Base manifold (three dimensional) Step2: Two dimensioanal submanifold - Unit sphere Step3: Christoffel symbols of the first kind Step4: One d...
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import sys from galgebra.printer import Format, xpdf Format() from sympy import symbols, sin, pi, latex, Array, permutedims from galgebra.ga import Ga from IPython.display import Math from sympy import cos, sin, symbols g3coords = (x,y,z) = symbols(...
<SYSTEM_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 import Step2: Fluctuation assay Step3: Figure 5 - Loss of heterozygosity
<ASSISTANT_TASK:> Python Code: # Load external dependencies from setup import * # Load internal dependencies import config,plot,utils %load_ext autoreload %autoreload 2 %matplotlib inline # Load data loh_length_df = pd.read_csv(dir_data+'seq/loh/homozygosity_length.csv') loh_length_df = loh_length_df.set_index("50kb_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: Part 0 Step2: Part 1 Step3: Try to use the following example of the scikit-learn help, to plot the classification regions for different pairs ...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np from sklearn import datasets from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler # Initialize the random generator seed to compare results np.random.seed(0) iris = datasets.load_iris() X = iris.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: Load a raw miniSASP file Step2: Get sun_intensities Step3: Plot as a function of Altitude
<ASSISTANT_TASK:> Python Code: from atmPy.instruments.miniSASP import miniSASP from atmPy.tools import plt_tools from atmPy.instruments.piccolo import piccolo %matplotlib inline plt_tools.setRcParams(plt) ms_raw = miniSASP.read_csv('./data/miniSASP_raw.txt') ms_raw.data.PhotoAsh.plot() sun_intensities = ms_raw.find_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: We first define the Tensorflow graph, and create some data. Step2: Export TensorFlow SavedModel Step3: Deploy Cluster Serving Step4: We confi...
<ASSISTANT_TASK:> Python Code: import tensorflow as tf tf.__version__ g = tf.Graph() with g.as_default(): # Graph Inputs features = tf.placeholder(dtype=tf.float32, shape=[None, 2], name='features') targets = tf.placeholder(dtype=tf.float32, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Es ist also sehr einfach in Python diese Funktion zu programmieren.Das hat aber nichts mit Machine Learning zu tun, sondern das ist das klassisc...
<ASSISTANT_TASK:> Python Code: # Definition der Funktion umrechnung def umrechnung(C): F = #Ihr Code hier# return #Ihr Code hier# # # Rufen Sie die definierte Funktion mit unterschiedlichen Werten (8,12.5,23,44.6) # einmal auf. Sie sollten die Ergebnisse (46.4, 54.5, 73.4, 112.28) erhalten. # Aufruf - Ersetzen ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Get the mutations that are segregating in each population Step2: Look at the raw data in the first element of each list Step3: Let's make that...
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import fwdpy as fp import pandas as pd from background_selection_setup import * mutations = [fp.view_mutations(i) for i in pops] for i in mutations: print(i[0]) mutations2 = [pd.DataFrame(i) for i in mutations] for i in mutations2: print(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: Load and prepare the data Step2: Checking out the data Step3: Dummy variables Step4: Scaling target variables Step5: Splitting the data into...
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt data_path = 'Bike-Sharing-Dataset/hour.csv' rides = pd.read_csv(data_path) rides.head() rides[:24*10].plot(x='dteday', y='cnt') dummy_fields = ['seas...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Keras provides a loading function similar to train_test_split from scikit-learn's Step2: The neural nets in Keras act on the feature matrix sli...
<ASSISTANT_TASK:> Python Code: import numpy as np np.random.seed(1337) # for reproducibility from keras.datasets import mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() img_rows, img_cols = 28, 28 X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) X_test = X_test.reshape(X_test.shape[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: quantulum3 Step2: Finding quantity statements in large texts Step3: Annotating a dataset Step4: We could then do something to split multiple ...
<ASSISTANT_TASK:> Python Code: sentences = [ '4 years and 6 months’ imprisonment with a licence extension of 2 years and 6 months', 'No quantities here', 'I measured it as 2 meters and 30 centimeters.', "four years and six months' imprisonment with a licence extension of 2 years and 6 months", 'it 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: <a name="multipanel"></a> Step2: So even with the sharing of axis information, there's still a lot of repeated code. This current version with ...
<ASSISTANT_TASK:> Python Code: import pandas as pd import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, DayLocator from siphon.simplewebservice.ndbc import NDBC %matplotlib inline # Read in some data df = NDBC.realtime_observations('42039') # Trim to the last 7 days df = df[df['time'] > (pd.Times...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: First we read in a plasmid from Havens et al. 2012 and isolate the EYFP sequence. Step2: Designing primers is straightforward - you just call d...
<ASSISTANT_TASK:> Python Code: import coral as cor plasmid = cor.seqio.read_dna("../files_for_tutorial/maps/pGP4G-EYFP.ape") eyfp_f = [f for f in plasmid.features if f.name == 'EYFP'][0] eyfp = plasmid.extract(eyfp_f) print len(eyfp) eyfp # Forward and reverse, one at a time using design_primer() forward = cor.design...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Step 1 Step2: Step 2 Step3: Step 3
<ASSISTANT_TASK:> Python Code: %reset ################################################################################ ### Import packages ################################################################################ import os import pandas as pd from scipy.spatial import distance as dist from scipy.cluster import h...
<SYSTEM_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 notebook we demo two equivalent ways of performing a two-sample Bayesian t-test to compare the mean value of two Gaussian populations us...
<ASSISTANT_TASK:> Python Code: import arviz as az import bambi as bmb import matplotlib.pyplot as plt import numpy as np import pandas as pd az.style.use("arviz-darkgrid") np.random.seed(1234) a = np.random.normal(6, 2.5, 160) b = np.random.normal(8, 2, 120) df = pd.DataFrame({"Group": ["a"] * 160 + ["b"] * 120, "Val"...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Adjacency Matrices Step2: A little visualization, just to double check. Step3: Steady-State Probability of Random Walker Step4: The resulting...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import networkx as nx import seaborn as sns sns.set_style('ticks') sns.set_context('poster') A_directed = np.array( [[0, 1, 0, 0, 1], [0, 0, 1, 0, 0], [1, 0, 0, 1, 1], [0, 1, 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: We'll start by generating some fake data (from a sinusoidal model) with error bars Step2: Now, we'll choose a kernel (covariance) function to m...
<ASSISTANT_TASK:> Python Code: import george george.__version__ import numpy as np import matplotlib.pyplot as pl np.random.seed(1234) x = 10 * np.sort(np.random.rand(15)) yerr = 0.2 * np.ones_like(x) y = np.sin(x) + yerr * np.random.randn(len(x)) pl.errorbar(x, y, yerr=yerr, fmt=".k", capsize=0) pl.xlim(0, 10) pl.yli...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Reading cleaned data Step2: Preparing data Step3: Regression approach Step4: Classification approach Step5: Binary solution
<ASSISTANT_TASK:> Python Code: import turicreate as tc import numpy as np import matplotlib.pyplot as plt %matplotlib inline sf = tc.SFrame.read_csv('electrodes_clean.csv') sf.explore() # in GUI # optional save to SFrame # sf = tc.SFrame('electrodes_clean.sframe') sf_reg = sf.remove_column('TPLE category') sf_class...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Compute the coronal averages for temperature and density over the whole parameter space Step2: Define a function to do the spatial averaging. S...
<ASSISTANT_TASK:> Python Code: import os import pickle import numpy as np hfRes_format = '../results/static/HYDRAD_raw/%s/HYDRAD_%d/Results/profile%d.phy' hydrad_labs = [20,40,200,500] hydrad_res = {'electron':{},'ion':{},'single':{}, 'loop_midpoint':4.5e+9, 'time':np.arange(0,5001)} int_perc = 0.9 def ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
<ASSISTANT_TASK:> Python Code: import math def Area_Parallelogram1(a , b , theta ) : area =(abs(math . tan(math . radians(theta ) ) ) / 2 ) * abs(a ** 2 - b ** 2 ) return area  def Area_Parallelogram2(a , b , gamma ) : area =(abs(math . sin(math . radians(gamma ) ) ) ) * abs(a * b ) return area  def 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: Transform data with PCA computed on the average ie evoked response Step2: Transform data with ICA computed on the raw epochs (no averaging)
<ASSISTANT_TASK:> Python Code: # Authors: Jean-Remi King <jeanremi.king@gmail.com> # Asish Panda <asishrocks95@gmail.com> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import sample from mne.decoding import UnsupervisedSpatialFilter from sklearn.dec...
<SYSTEM_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 train data Step2: Define columns Step3: Parse the weird date format of the date column Step4: Drop duplicate rows Step5: Drop duplicate...
<ASSISTANT_TASK:> Python Code: %pylab inline %load_ext autoreload %autoreload 2 from __future__ import division from collections import defaultdict, namedtuple import cPickle as pickle from datetime import datetime, timedelta import dateutil from functools import partial import inspect import json import os import re 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: <p style="font-family Step2: Let's see what is in this image. Step3: The shape of the ndarray show that it is a three layered matrix. The firs...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np from scipy import misc import matplotlib.pyplot as plt from skimage import data photo_data = misc.imread('./wifire/sd-3layers.jpg') type(photo_data) plt.figure(figsize=(15,15)) plt.imshow(photo_data) photo_data.shape #print(photo_data) photo_data.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: 이 확률 분포는 다음 식에서 보다시피 주변 확률 분포의 곱으로 표현된다. Step2: 여러 가지 Y값을 바꾸어도 조건부 확률은 변하지 않는 것을 확인할 수 있다. Step3: 이번에는 다음과 같은 결합 확률 분포를 보자. 이 경우에는 독립 조건이 성립하지...
<ASSISTANT_TASK:> Python Code: np.set_printoptions(precision=4) pmf1 = np.array([[0, 1, 2, 3, 2, 1], [0, 2, 4, 6, 4, 2], [0, 4, 8,12, 8, 4], [0, 2, 4, 6, 4, 2], [0, 1, 2, 3, 2, 1]]) pmf1 = pmf1/pmf1.sum() pmf1 sns.heatmap(pmf1) plt.xlabel("x") plt.ylab...
<SYSTEM_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="ref0"></a> Step2: Create a tensor ranging from -10 to 10 Step3: When you use sequential, you can create a sigmoid object Step4: Apply ...
<ASSISTANT_TASK:> Python Code: import torch.nn as nn import torch import torch.nn.functional as F import matplotlib.pyplot as plt torch.manual_seed(2) z=torch.arange(-10,10,0.1).view(-1, 1) sig=nn.Sigmoid() yhat=sig(z) sig(torch.tensor(-1.0)) plt.plot(z.numpy(),yhat.numpy()) plt.xlabel('z') plt.ylabel('yhat') yh...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Prep 2 Step2: Prep 3 Step3: Prep 4 Step4: UMAP Step5: Visualize 1 Step6: Fascinatingly, when Graphistry's force-directed graph layout algor...
<ASSISTANT_TASK:> Python Code: # Already installed in Graphistry & RAPIDS distros # ! pip install --user umap-learn # ! pip install --user graphistry import graphistry, pandas as pd, umap # To specify Graphistry account & server, use: # graphistry.register(api=3, username='...', password='...', protocol='https', server...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Enumerate the parameter combinations Step2: Specify the model changes Step3: Specify the result 'y' that we want to retrieve Step4: Trigger t...
<ASSISTANT_TASK:> Python Code: ## Veneer started elsewhere (probably from a command line using veneer.manager.start) ports = list(range(15004,15008)) ports bv = BulkVeneer(ports) v = bv.veneers[1] network = v.network() network.as_dataframe().plot() network.outlet_nodes() outlet_node = network.outlet_nodes()[0]['propert...