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: A NN plotter Step2: Generate a Network Step3: Visualize the network Step4: Visualize the Output for a few examples Step5: Training Step6: B...
<ASSISTANT_TASK:> Python Code: from matplotlib.pylab import plt from sklearn.datasets import fetch_mldata mnist = fetch_mldata('MNIST original') step = 2 train_offset = 0 features = mnist['data'][train_offset:-1:step].copy()/255 target = mnist['target'][train_offset:-1:step].copy() test_offset = 1 features_test = mnist...
<SYSTEM_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', 'ec-earth-consortium', 'ec-earth3-aerchem', 'land') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_con...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <h3> Connecting to S3 </h3> Step2: <h4>Parsing tweets</h4> Step3: If you already have a corpus and dictionary you can just load them.
<ASSISTANT_TASK:> Python Code: # some nlp tools import spacy import gensim import pyLDAvis.gensim as gensimvis import pyLDAvis # tools to get data from s3 import boto3 from io import StringIO import json import requests # would probably need these import numpy as np import pandas as pd import itertools nlp = spacy.load...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Building the model Step2: Training Step3: Plot results
<ASSISTANT_TASK:> Python Code: !wget -N https://s3.amazonaws.com/lasagne/recipes/datasets/mnist_cluttered_60x60_6distortions.npz def load_data(): data = np.load(mnist_cluttered) X_train, y_train = data['x_train'], np.argmax(data['y_train'], axis=-1) X_valid, y_valid = data['x_valid'], np.argmax(data['y_vali...
<SYSTEM_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 Network Step2: Explore Directions Step3: Interactive
<ASSISTANT_TASK:> Python Code: is_stylegan_v1 = False from pathlib import Path import matplotlib.pyplot as plt import numpy as np import sys import os from datetime import datetime from tqdm import tqdm # ffmpeg installation location, for creating videos plt.rcParams['animation.ffmpeg_path'] = str('/usr/bin/ffmpeg') im...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Initialize the Clipper cluster Step2: Define 'predict' function Step3: Deploy Keras model and 'predict' function to the Clipper cluster Step4:...
<ASSISTANT_TASK:> Python Code: from keras.applications.resnet50 import ResNet50 # https://keras.io/applications/#classify-imagenet-classes-with-resnet50 model = ResNet50(weights='imagenet') from clipper_admin import ClipperConnection, DockerContainerManager clipper_conn = ClipperConnection(DockerContainerManager()) cl...
<SYSTEM_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 a particular parameter, the corresponding function of the given family is represented as heatmap of its argument, which illustrates Step2:...
<ASSISTANT_TASK:> Python Code: import plotly.graph_objects as go import numpy as np Plotly version of the HSV colorscale, corresponding to S=1, V=1, where S is saturation and V is the value. pl_hsv = [[0.0, 'rgb(0, 255, 255)'], [0.0833, 'rgb(0, 127, 255)'], [0.1667, 'rgb(0, 0, 255)'], [0.25, 'rgb(127, 0, 255)'], [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: Sometimes you need the index of an element and the element itself while you iterate through a list. This can be achived with the enumerate funct...
<ASSISTANT_TASK:> Python Code: greek = ["Alpha", "Beta", "Gamma", "Delta"] for element in greek: print(element) for i, e in enumerate(greek): print(e + " is at index: " + str(i)) list_of_tuples = [(1,2,3),(4,5,6), (7,8,9)] for (a, b, c) in list_of_tuples: print(a + b + c) for e1, e2 in zip(greek, greek):...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data preprocessing Step2: Encoding the words Step3: Encoding the labels Step4: Okay, a couple issues here. We seem to have one review with ze...
<ASSISTANT_TASK:> Python Code: import numpy as np import tensorflow as tf with open('../sentiment-network/reviews.txt', 'r') as f: reviews = f.read() with open('../sentiment-network/labels.txt', 'r') as f: labels = f.read() reviews[:2000] from string import punctuation all_text = ''.join([c for c in reviews if...
<SYSTEM_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 construct the class containing the initial conditions of the problem Step2: New legislation changes $\lambda$ to $0.2$ Step3: Now plot sto...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from quantecon.models import LakeModel alpha = 0.012 lamb = 0.2486 b = 0.001808 d = 0.0008333 g = b-d N0 = 100. e0 = 0.92 u0 = 1-e0 T = 50 LM0 = LakeModel(lamb,alpha,b,d) x0 = LM0.find_steady_state()# initial condition...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The next thing we'll need is some data. To make for an illustrative example we'll need the data size to be fairly small so we can see what is go...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import seaborn as sns import sklearn.datasets as data %matplotlib inline sns.set_context('poster') sns.set_style('white') sns.set_color_codes() plot_kwds = {'alpha' : 0.5, 's' : 80, 'linewidths':0} moons, _ = data.make_moons(n_samples=50...
<SYSTEM_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 CoreData Step2: Compute Functional Connectivity Step3: Process Navon Step4: Process Stroop Step5: Generate Population Configuration Mat...
<ASSISTANT_TASK:> Python Code: try: %load_ext autoreload %autoreload 2 %reset except: print 'NOT IPYTHON' from __future__ import division import os import sys import glob import numpy as np import pandas as pd import seaborn as sns import scipy.stats as stats import statsmodels.api as sm import scipy.io...
<SYSTEM_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 possessives that may be acceptable behavior, but how about contractions like “didn’t” or “A’dam” (short for “Amsterdam”)? If the default tok...
<ASSISTANT_TASK:> Python Code: from collatex import * collation = Collation() collation.add_plain_witness("A", "Peter's cat.") collation.add_plain_witness("B", "Peter's dog.") table = collate(collation, segmentation=False) print(table) from collatex import * tokens_a = [ { "t": "Peter's" }, { "t": "cat" }, { "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: Configure Google Cloud environment settings Step2: Authenticate your Google Cloud account Step3: Import libraries Step4: 1. Define dataset me...
<ASSISTANT_TASK:> Python Code: !pip install -U -q google-api-python-client !pip install -U -q pandas PROJECT_ID = "sa-data-validation" MODEL_NAME = 'covertype_classifier' VERSION_NAME = 'v1' BQ_DATASET_NAME = 'prediction_logs' BQ_TABLE_NAME = 'covertype_classifier_logs' !gcloud config set project $PROJECT_ID try: ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: There are three other important Python libraries (which are bundled with the Canopy and Anaconda installations of Python) that come in quite han...
<ASSISTANT_TASK:> Python Code: import pmagpy.ipmag as ipmag import pmagpy.pmag as pmag import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_formats = {'svg',} %%capture ipmag.download_magic('magic_contribution_11087.txt', dir_path=...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: First we need to find the latitude and longitude of Syracuse, then estimate the appropriate zoom level... Step2: We get the data from the Roads...
<ASSISTANT_TASK:> Python Code: import folium import pandas as pd SYR = (43.0481, -76.1474) map = folium.Map(location=SYR, zoom_start=14) map data = pd.read_csv('https://cityofsyracuse.github.io/RoadsChallenge/data/potholes.csv') data.sample(5) # NOTE: to_dict('records') converts a pandas dataframe back to a list 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: Username Step2: First of all, let's see how many different User's we have on both datasets Step3: Unique User's in Test are close to $1$/$2$ o...
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline from fastai.imports import * from fastai.structured import * from pandas_summary import DataFrameSummary PATH = os.getcwd() train_df = pd.read_csv(f'{PATH}\\train.csv', low_memory=False) test_df = pd.read_csv(f'{PATH}\\test.csv', low_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: Open the SPI rack connection and unlock the controller. This is necessary after bootup of the controller module. If not unlocked, no communicati...
<ASSISTANT_TASK:> Python Code: # Import SPI rack and D5b module from spirack import SPI_rack, D5b_module import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) COM_port = 'COM4' # COM port of the SPI rack COM_speed = 1e6 # Baud rate, not of much importance timeout = 1 # Tim...
<SYSTEM_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 clustering model Step2: Build the optimal model and apply it Step3: Cluster Profiles
<ASSISTANT_TASK:> Python Code: def loadContributions(file, withsexe=False): contributions = pd.read_json(path_or_buf=file, orient="columns") rows = []; rindex = []; for i in range(0, contributions.shape[0]): row = {}; row['id'] = contributions['id'][i] rindex.append(contributions...
<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: If you installation was successful, you should see a version Number like '1.3.4'. Step3: Let's test our function and see the resulting output S...
<ASSISTANT_TASK:> Python Code: >>> import bokeh >>> bokeh.__version__ import numpy as np def mohrs_circle(stress_x=1,stress_y=1,shear=0): A function that calculates the critical values to build a Mohr's Circle # calculate the average stress, min stress and max stress stress_avg=(stress_x+str...
<SYSTEM_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 2 Step2: Step 3 Step3: The Expecation Maximization (EM) algorithm can also learn the parameters when we have some latent variables in the...
<ASSISTANT_TASK:> Python Code: # Use the alarm model to generate data from it. from pgmpy.utils import get_example_model from pgmpy.sampling import BayesianModelSampling alarm_model = get_example_model("alarm") samples = BayesianModelSampling(alarm_model).forward_sample(size=int(1e5)) samples.head() # Defining the Bay...
<SYSTEM_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="text-align Step2: <p style="text-align Step3: <p style="text-align Step4: <p style="text-align Step5: <p style="text-align Step6: ...
<ASSISTANT_TASK:> Python Code: def square(x): return x ** 2 type(square) ribua = square print(square(5)) print(ribua(5)) ribua is square def add(num1, num2): return num1 + num2 def subtract(num1, num2): return num1 - num2 def multiply(num1, num2): return num1 * num2 def divide(num1, num2): retur...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: README Step2: Other parameters to set Step3: Pass hits to mothur aligner Step4: Get aligned seqs that have > 50% matched to references Step5:...
<ASSISTANT_TASK:> Python Code: cd /usr/local/notebooks mkdir -p ./workdir #check seqfile files to process in data directory (make sure you still remember the data directory) !ls ./data/test/data Seqfile='./data/test/data/1c.fa' Cpu='2' # number of maxixum threads for search and alignment Hmm='./data/SSUsearch_db/Hm...
<SYSTEM_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 very simple example also shown in the wiki to simply introduce the call signature of adjust_text Step2: First a very simple example with labe...
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt from adjustText import adjust_text import numpy as np import pandas as pd np.random.seed(0) x, y = np.random.random((2,30)) fig, ax = plt.subplots() plt.plot(x, y, 'bo') texts = [plt.text(x[i], y[i], 'Text%s' %i) for i in range(len(x))] np.random.seed(0) x...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
<ASSISTANT_TASK:> Python Code:: from sklearn.linear_model import Lasso from sklearn.metrics import mean_squared_error, mean_absolute_error, max_error, explained_variance_score, mean_absolute_percentage_error # initialise & fit Lasso regression model with alpha set to 0.5 model = Lasso(alpha=0.5) model.fit(X_train, y_tr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Defining and plotting direction over a plane Step2: Variogram map
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pygslib pygslib.version.__version__ # we read the file header # use >>> print. pygslib.gslib.read_header.__doc__ for help #the data file is in the working directory mydata= pygslib.gslib.read_gslib_file('../datasets/cluster.dat') #adding elevation and a dummy ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Setp 2 Step2: Simulate using different methods Step3: MOMA and ROOM relly on a reference (wild-type) flux distribution and we can use the one ...
<ASSISTANT_TASK:> Python Code: %time fba_result = simulation.fba(model) %time pfba_result = simulation.pfba(model) model.reactions.PGI model.reactions.PGI.knock_out() model.reactions.PGI %time fba_knockout_result = simulation.fba(model) fba_knockout_result[model.objective] pfba_knockout_result = simulation.pfba(model...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Server Local Step2: Export database from dashaboard about device IoT Step3: Method
<ASSISTANT_TASK:> Python Code: -- Campainha IoT - LHC - v1.1 -- ESP Inicializa pinos, Configura e Conecta no Wifi, Cria conexão TCP -- e na resposta de um "Tocou" coloca o ESP em modo DeepSleep para economizar bateria. -- Se nenhuma resposta for recebida em 15 segundos coloca o ESP em DeepSleep. led_pin = 3 status_led ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Exoplanet properties Step2: Use np.genfromtxt with a delimiter of ',' to read the data into a NumPy array called data Step3: Make a histogram ...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np !head -n 30 open_exoplanet_catalogue.txt data = np.genfromtxt('open_exoplanet_catalogue.txt', delimiter=',') assert data.shape==(1993,24) plt.hist(data[:,2], bins=24, range=(0,12)) plt.xlabel('M_JUP') plt.ylabel('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: Import necessary libraries. Step2: Lab Task #1 Step3: The source dataset Step4: Create the training and evaluation data tables Step5: Lab Ta...
<ASSISTANT_TASK:> Python Code: %%bash sudo pip freeze | grep google-cloud-bigquery==1.6.1 || \ sudo pip install google-cloud-bigquery==1.6.1 import os from google.cloud import bigquery %%bash export PROJECT=$(gcloud config list project --format "value(core.project)") echo "Your current GCP Project Name is: "$PROJECT ...
<SYSTEM_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 use of watermark is optional. You can install this IPython extension via "pip install watermark". For more information, please see Step2: S...
<ASSISTANT_TASK:> Python Code: %load_ext watermark %watermark -a 'Sebastian Raschka' -u -d -v -p numpy,pandas,matplotlib,sklearn from IPython.display import Image %matplotlib inline # Added version check for recent scikit-learn 0.18 checks from distutils.version import LooseVersion as Version from sklearn import __ver...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Explore the data Step2: How do we know the calls in a particular training audio clip? Step3: Exercises Step4: What about the sound clips? Ste...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import bird_data as data import wav_utils from IPython.core.display import HTML # Plot in the notebook %pylab inline data.call_df.head(10) HTML(data.label_df.head(10).to_html()) data.call_df.type.unique() wavs = data.get_wav_dict() three_call_cl...
<SYSTEM_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 Step2: OPERATIONS IN DICT Step3: Add Step4: Remove Step5: Creating a dictionary from two lists Step7: Why to use dict? Because it's ...
<ASSISTANT_TASK:> Python Code: ##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 import Image #Make the notebook wider from 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: tf.data を使って NumPy データをロードする Step2: .npz ファイルからのロード Step3: tf.data.Dataset を使って NumPy 配列をロード Step4: データセットの使用 Step5: モデルの構築と訓練
<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: Data collection (2/6) Step2: Data preparation for labevents table (3/6) Step3: Data preparation for prescriptions table (4/6) Step4: Create a...
<ASSISTANT_TASK:> Python Code: # # Dash packages installation # !conda install -c conda-forge dash-renderer -y # !conda install -c conda-forge dash -y # !conda install -c conda-forge dash-html-components -y # !conda install -c conda-forge dash-core-components -y # !conda install -c conda-forge plotly -y import dash 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:
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import torch idx, B = load_data() C = B.index_select(1, idx) <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: training MultiNB & parameter tuning Step2: X_counts로 cv했을때 Step3: X_tfidf로 cv했을때 Step4: Tuning & Improvement Step5: Retraining with new para...
<ASSISTANT_TASK:> Python Code: df = pd.read_csv('../resource/final_df3.csv') sample = df.title y = df['rating(y)'].values real_X = df[['avg_rating']].values cat_X = df.text.fillna("").values from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, TfidfTransformer count_vect = CountVectorizer() 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: 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', 'miroc6', 'land') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "email")...
<SYSTEM_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 all the classifiers from their respective pickle files Step2: passing it voting class function
<ASSISTANT_TASK:> Python Code: import nltk import random from nltk.corpus import movie_reviews import pickle from nltk.classify import ClassifierI from statistics import mode ## defing the voteclassifier class class VoteClassifier(ClassifierI): def __init__(self, *classifiers): self._classifiers = classifie...
<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: Peak finding Step3: Here is a string with the first 10000 digits of $\pi$ (after the decimal). Write code to perform the following
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import seaborn as sns import numpy as np def find_peaks(a): Find the indices of the local maxima in a sequence. peaks = [] for i in range(len(a)): if i==0: if a[i]>a[i+1]: peaks.append...
<SYSTEM_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 Isochrones Step2: Build the Isochrone Library and Synthesize CMD planes Step3: Here we visualize the isochrone bins in $\log(\mathrm{...
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format='retina' # %config InlineBackend.figure_format='svg' import matplotlib as mpl import matplotlib.pyplot as plt import os import time from glob import glob import numpy as np brick = 23 STARFISH = os.getenv("STARFISH") isoc_dir = "b23ir...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Baseline evaluation Step2: Now we have a baseline score that we'll iterate towards improving. Step3: The first thing we notice is that there's...
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 import importlib import os import sys from elasticsearch import Elasticsearch from skopt.plots import plot_objective # project library sys.path.insert(0, os.path.abspath('..')) import qopt importlib.reload(qopt) from qopt.notebooks import evaluate_mrr100...
<SYSTEM_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 rbf kernel has an inverse bandwidth-parameter gamma, where large gamma mean a very localized influence for each data point, and Step2: Exer...
<ASSISTANT_TASK:> Python Code: from sklearn.metrics.pairwise import rbf_kernel line = np.linspace(-3, 3, 100)[:, np.newaxis] kernel_value = rbf_kernel(line, [[0]], gamma=1) plt.plot(line, kernel_value) from figures import plot_svm_interactive plot_svm_interactive() from sklearn import datasets digits = datasets.load_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Matrix Factorisation Step2: Let $S \in \mathbb{R}^{M \times D}, P \in \mathbb{R}^{N \times D}, Y \in \mathbb{R}^{M \times N}$ be the latent fac...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os, sys, time, gzip import pickle as pkl import numpy as np from scipy.sparse import lil_matrix, csr_matrix, issparse import matplotlib.pyplot as plt import seaborn as sns from tqdm import tqdm from tools import calc_metrics, diversity, pairwise_distance_hamming,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 这里,mnist是一个轻量级的类。它以Numpy数组的形式存储着训练、校验和测试数据集。同时提供了一个函数,用于在迭代每一小批数据,后面我们将会用到。 Step2: 计算图 Step3: 这里的x和y_并不是特定的值,相反,他们都只是一个占位符,可以在TensorFlow运行某一计算...
<ASSISTANT_TASK:> Python Code: import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) import tensorflow as tf sess = tf.InteractiveSession() x = tf.placeholder("float", shape=[None, 784]) y_ = tf.placeholder("float", shape=[None, 10]) W = tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.ze...
<SYSTEM_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 list comprehension and lambda/map function to define <b>stuff</b>. Step2: <u>Problem 2</u> Step3: <u>Problem 3</u>
<ASSISTANT_TASK:> Python Code: words = 'The quick brown fox jumps over the lazy dog'.split() print words stuff = [] for w in words: stuff.append([w.upper(), w.lower(), len(w)]) for i in stuff: print i stuff = map(lambda w: [w.upper(), w.lower(), len(w)],words) for i in stuff: print i sentence = "It's a myth 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: Run as a Python module Step2: Now, let's do it on Cloud ML Engine so we can train on GPU Step3: Monitoring training with TensorBoard Step4: H...
<ASSISTANT_TASK:> Python Code: import os 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-central1 MODEL_TYPE = "linear" # "linear", "dnn", "dnn_dropout", or "cnn" # do not...
<SYSTEM_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:共n个随机整数,整数范围在m与k之间,求西格玛log(随机整数)及西格玛1/log(随机整数) Step2: 练习 3:写函数,求s=a+aa+aaa+aaaa+aa...a的值,其中a是[1,9]之间的随机整数。例如2+22+222+2222+22222(此时共有5个数相加...
<ASSISTANT_TASK:> Python Code: n = int(input('请输入你想取的整数的个数')) m = int(input('请输入取整范围的下限')) k = int(input('请输入取整范围的上限')) import random,math def get_num(): number = random.randint(m,k) return number i = 0 total = 0 while i < n: total = total + get_num() i = i + 1 print(get_num()) average = total/...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Matching coordinates Step2: Plot $W_1-J$ vs $W_1$ Step3: W1-J < -1.7 => galaxy Step4: Collect relevant data Step5: Analysis Step6: DBSCAN S...
<ASSISTANT_TASK:> Python Code: #obj = ["3C 454.3", 343.49062, 16.14821, 1.0] obj = ["PKS J0006-0623", 1.55789, -6.39315, 1.0] #obj = ["M87", 187.705930, 12.391123, 1.0] #### name, ra, dec, radius of cone obj_name = obj[0] obj_ra = obj[1] obj_dec = obj[2] cone_radius = obj[3] obj_coord = coordinates.SkyCoord(ra=obj_...
<SYSTEM_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.2 Your first script Step2: Notice that Hello world! is printed at the bottom of the cell as an output. In general, this is how output of a py...
<ASSISTANT_TASK:> Python Code: # change this cell into a Markdown cell. Then type something here and execute it (Shift-Enter) '''Make sure you are in "edit" mode and that this cell is for Coding ( You should see the In [ ]:) on the left of the cell. ''' print("Hello world!") # print your name in this cell. # Addit...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: How are grouped operations currently handled in pandas? Step2: What about composing f_elwise and f_agg operations? Step3: Also, as noted in th...
<ASSISTANT_TASK:> Python Code: %%capture import pandas as pd pd.set_option("display.max_rows", 5) from siuba import _ from siuba.data import mtcars g_cyl = mtcars.groupby("cyl") ## Both snippets below raise an error.... :/ g_cyl.mpg + g_cyl.mpg g_cyl.add(g_cyl.mpg) # two ways to do it f_elwise ser_mpg2 = mtcars.mpg + ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Por la ecuación logística, $\mu(x)$ representa una tasa de crecimiento de la población. Por la gráfica, cuando la poblacion es pequeña esta tasa...
<ASSISTANT_TASK:> Python Code: # Numeral 1 # Importar librerías necesarias import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Definimos funcion mu def mu(x, r): return r*(1-x) # Definimos conjunto de valores en x x = np.linspace(0, 1.2, 50) # Valor del parametro solicitado r = 1 # Conjunto de v...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Let's create the distributions for the guest and the prize. Note that both distributions are independent of one another. Step2: Now let's creat...
<ASSISTANT_TASK:> Python Code: import math from pomegranate import * guest = DiscreteDistribution( { 'A': 1./3, 'B': 1./3, 'C': 1./3 } ) prize = DiscreteDistribution( { 'A': 1./3, 'B': 1./3, 'C': 1./3 } ) monty = ConditionalProbabilityTable( [[ 'A', 'A', 'A', 0.0 ], [ 'A', 'A', 'B', 0.5 ], [ 'A', 'A', 'C', 0.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: Get data from S3 Step2: Adding an RGB layer to the map Step3: To add the layer we call M.add_layer passing in a subset of the raster data set'...
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pylab as plt !curl -o /tmp/L57.Globe.month09.2010.hh09vv04.h6v1.doy247to273.NBAR.v3.0.tiff http://golden-tile-geotiffs.s3.amazonaws.com/L57.Globe.month09.2010.hh09vv04.h6v1.doy247to273.NBAR.v3.0.tiff # Set the center of the map to the location 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: [normalization.BatchNormalization.1] epsilon=1e-02, axis=-1, center=True, scale=True Step2: [normalization.BatchNormalization.2] epsilon=1e-05,...
<ASSISTANT_TASK:> Python Code: data_in_shape = (4, 3) norm = BatchNormalization(epsilon=1e-05, axis=-1, center=True, scale=True) layer_0 = Input(shape=data_in_shape) layer_1 = norm(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) weights = [] for i, w in enu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Extension types Step5: Extension types Step6: The tf.experimental.ExtensionType base class works similarly to typing.NamedTuple and @dataclass...
<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: Use the built-in library methods
<ASSISTANT_TASK:> Python Code: import pandas as pd import sklearn df = pd.read_table('https://raw.githubusercontent.com/sinanuozdemir/sfdat22/master/data/sms.tsv', sep='\t', header=None, names=['label', 'msg']) df df.label.value_counts() value_probablity = df.label.value_counts()/len(df) spam_probability = value_probab...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Al paso del tiempo Step2: Tamaños de clases de poblaciones Step3: Proporciones de tamaños de clases de poblaciones Step4: Eigenvector, eigenv...
<ASSISTANT_TASK:> Python Code: # el modelo de Leslie L = np.array([[0, 1, 2], [0.8, 0, 0], [0, 0.7, 0]]) # las cuatro clases de edad tienen 100 pobladoras al inicio poblacion_inicial = [100,100,100] # lista para contener un vector de tamaños de población por clase para # cada unid...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Locating the third reference point Step2: Now a least squares estimator is used to work out the x-y coordinates of the third reference point (x...
<ASSISTANT_TASK:> Python Code: import numpy as np from scipy.optimize import minimize x0 = [0,0] x1 = [0, 2209] d_0_2 = 2047 d_1_2 = 3020 def dist(a,b): return np.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2) def f(x): return (dist(x0, x) - d_0_2)**2 + (dist(x1, x) - d_1_2)**2 initial_guess = [2047, 0] res = minimiz...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Ignore any warnings above (I coudn't be bothered to compile audiolab with Alsa). Below you will find the method to download the Voxforge databas...
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('../python') from voxforge import * downloadVoxforgeData('../audio') f=loadFile('../audio/Joel-20080716-qoz.tgz') print f.props print f.prompts print f.data %xdel f corp=loadBySpeaker('../audio', limit=30) addPhonemesSpk(corp,'../data/lex.tgz') print corp.ke...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Some sites will block request from urlib, so we set a custom 'User-Agent' header Step2: Let's check the HTTP status and the message. Step3: We...
<ASSISTANT_TASK:> Python Code: import urllib.request url = 'https://medium.com/tag/machine-learning' req = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"}) con = urllib.request.urlopen(req) print(con.status, con.msg) con.getheader('Content-Type') text = con.read() text[:500] <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: Veja a seguir uma matriz bidimensional de dados ponto flutuante de 2 linhas e 3 colunas. Observe que a tupla do shape aumenta para a esquerda, i...
<ASSISTANT_TASK:> Python Code: import numpy as np a = np.array( [2,3,4,-1,-2,256, 270] ,'uint8') print ('Dimensões: a.shape=', a.shape) print ('Tipo dos elementos: a.dtype=', a.dtype) print ('Imprimindo o array completo:\n a=',a) m = a.max() print(m) print(m.dtype) b = a//a.max() print (b) b = np.array( [ [[1.5, 2.3, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Run the simulation, save the spectra Step2: Simulation outputs Step3: the table of simulated quasars, including redshift, luminosity, syntheti...
<ASSISTANT_TASK:> Python Code: M1450 = linspace(-30,-22,20) zz = arange(0.7,3.5,0.5) ple = bossqsos.BOSS_DR9_PLE() lede = bossqsos.BOSS_DR9_LEDE() for z in zz: if z<2.2: qlf = ple if z<2.2 else lede plot(M1450,qlf(M1450,z),label='z=%.1f'%z) legend(loc='lower left') xlim(-21.8,-30.2) xlabel("$M_{1450}$")...
<SYSTEM_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 something that doesn't work Step2: Try something that works
<ASSISTANT_TASK:> Python Code: # Create some data scores = [23,453,54,235,74,234] # Try to: try: # Add a list of integers and a string scores + 'A string of characters.' # If you get an error, set the error as 'e', except Exception as e: # print the error, e print('Error:', e) # Then, finally: # pr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: パラメータの設定 Step2: メッシュの読み込み Step3: 次のコマンドで、mに設定したメッシュをgmshのスクリプトでpng画像に打ち出し確認します。 Step4: 以下のようにipythonの機能を使用して、システムのコマンドラインでの操作を行いIpython上に画像を表...
<ASSISTANT_TASK:> Python Code: import getfem as gf import numpy as np file_msh = './mesh/tripod.mesh' E = 1e3 Nu = 0.3 Lambda = E*Nu/((1+Nu)*(1-2*Nu)) Mu = E/(2*(1+Nu)) m = gf.Mesh('load',file_msh) m.set('optimize_structure') m.export_to_pos('./pos/m.pos') %%writefile gscript Print "./png/m.png"; Exit; !gmsh ./pos/...
<SYSTEM_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: Day 5 Step2: Example Step3: Question 1 Step4: Question 2
<ASSISTANT_TASK:> Python Code: import math from matplotlib import pylab as plt %matplotlib inline def pdf(x, m, variance): sigma = math.sqrt(variance) probability density function return 1 / (sigma * math.sqrt(2 * math.pi)) * math.e ** (-1 * ((x - m)**2 / (2 * variance ** 2))) pdf(20, 20, 4) N = range(50) ...
<SYSTEM_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 = (10, 20) DON'T MODIFY ANYTHING IN THIS CELL import nu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Implementing Gates Step4: Constant Gates Step5: <hr/> Step7: For more info on broadcasting, take a look at the Theano documentation on broadc...
<ASSISTANT_TASK:> Python Code: import theano from theano import tensor import numpy as np from collections import namedtuple Gate = namedtuple("Gate", "arity module") # Theano's to_one_hot converts a numpy array # to a one-hot encoded version. In order to # know how big to make the vector, all gates # take M, the sma...
<SYSTEM_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 consistency, we will be using a random number generator with a seed for some of the iterators. Step2: Let's start by creating a small datas...
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import numpy as np import pyxis as px rng = np.random.RandomState(1234) nb_samples = 10 X = rng.rand(nb_samples, 254, 254, 3) y = np.arange(nb_samples, dtype=np.uint8) db = px.Writer(dirpath='data', map_size_limit=30, ram_gb_limit=1) db.put_samples...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: uncomment this to download the data Step2: Loading Data with Pandas Step3: Because we'll use it so much, we often import under a shortened nam...
<ASSISTANT_TASK:> Python Code: !ls # !curl -o pronto.csv https://data.seattle.gov/api/views/tw7j-dfaw/rows.csv?accessType=DOWNLOAD import pandas import pandas as pd data = pd.read_csv('pronto.csv') data.head() data.tail() data.shape data.columns data.index data.dtypes data.columns data['tripduration'] 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: <p>Equivalente a</p> Step2: $ Step3: Equivalente a Step4: Step5: $ Step6: Implementação Step7: $$
<ASSISTANT_TASK:> Python Code: L = k(X, .7) D = diag(L) M = inv(D).dot(L) # Mi,j denotes the transition probability # from the point xi to the point xj in one time step print M L/L.sum(axis=1).reshape(-1,1) Ms = (diag(D,.5)).dot(M).dot(diag(D,-.5)) Ms p = L.sum(axis=1) for i in range(0,3): a = [] for j in 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: Now try setting time range via eventTime.
<ASSISTANT_TASK:> Python Code: %matplotlib inline from owslib.sos import SensorObservationService import pdb from owslib.etree import etree import pandas as pd import datetime as dt import numpy as np url = 'http://sdf.ndbc.noaa.gov/sos/server.php?request=GetCapabilities&service=SOS&version=1.0.0' ndbc = SensorObserva...
<SYSTEM_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: Experimental PD affinity estimate Step2: Load in Data Step3: Merge experimental and model score data Step4: Examine distribution of scores fo...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt # Tuple of form: (Seq, Stringency, Kd) validated_core_seqs = [ ('TTTGGTGGATAGTAA', 1, '< 512 nM'), ('AGAGGATTTGGTGGATAGT', 0, '> 512nM'), ('AGAGGAT...
<SYSTEM_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: 패션 MNIST 데이터셋 임포트하기 Step3: load_data() 함수를 호출하면 네 개의 넘파이(NumPy) 배열이 반환됩니다 Step4: 데이터 탐색 Step5: 비슷하게 훈련 세트에는 60,000개의 레이...
<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: tf.keras를 사용한 Neural Style Transfer Step2: 이미지를 다운로드받고 스타일 참조 이미지와 콘텐츠 이미지를 선택합니다 Step3: 입력 시각화 Step4: 이미지를 출력하기 위한 간단한 함수를 정의합니다 Step5: TF-...
<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: XML example Step2: XML exercise Step3: 10 countries with the lowest infant mortality rates Step4: 10 cities with the largest population Step5...
<ASSISTANT_TASK:> Python Code: from xml.etree import ElementTree as ET document_tree = ET.parse( './data/mondial_database_less.xml' ) # print names of all countries for child in document_tree.getroot(): print (child.find('name').text) # print names of all countries and their cities for element in document_tree.ite...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Project Euler Step2: Now write a set of assert tests for your number_to_words function that verifies that it is working as expected. Step4: No...
<ASSISTANT_TASK:> Python Code: import numpy as np numbers = {0: "", 1:"one", 2:"two", 3:"three", 4:"four", 5:"five", 6:"six", 7:"seven", 8:"eight", 9:"nine", 10:"ten", 11:"eleven", 12:"twelve", 13:"thirteen", 14:"fourteen", 15:"fifteen", 16:"sixteen", 17:"seventeen", 18:"eighteen", 19:"nineteen", 20...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Using interact for animation with data Step3: To create an animation of a soliton propagating in time, we are going to precompute the soliton d...
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display def soliton(x, t, c, a): Return phi(x, t) for a soliton wave with constants c and a. phiarg = (np.sqrt(c)/2...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Loading source dataset MNIST Step2: Loading target dataset MNIST-M Step3: Naive model Step4: After training on our source dataset MNIST, we e...
<ASSISTANT_TASK:> Python Code: import numpy as np USE_SUBSET = True def get_subset(x, y): if not USE_SUBSET: return x, y subset_index = 10000 np.random.seed(1) indexes = np.random.permutation(len(x))[:subset_index] x, y = x[indexes], y[indexes] return x, y from tensorflow.keras.datasets...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Radiative efficiencies of each gas Step2: Impulse response functions (IRF) for CO<sub>2</sub>, CH<sub>4</sub>, and N<sub>2</sub>O Step4: CO<su...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np import scipy as sp import matplotlib.pyplot as plt import matplotlib as mpl from scipy.interpolate import interp1d from scipy.signal import fftconvolve from scipy.integrate import cumtrapz import seaborn as sns sns.set_palette('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: As always, let's create a dataset with MNIST data Step2: We will use the standard ResNet from the BatchFlow models. Step3: Now create pipeline...
<ASSISTANT_TASK:> Python Code: import sys import numpy as np import tensorflow as tf from tqdm import tqdm_notebook as tqn import matplotlib.pyplot as plt %matplotlib inline plt.style.use('seaborn-poster') plt.style.use('ggplot') sys.path.append('../../..') from batchflow import B, V from batchflow.opensets import MNIS...
<SYSTEM_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: Adding and Inspecting Attributes Step3: Adding Attributes for each existing node Step4: Reading in Different Representations of Gra...
<ASSISTANT_TASK:> Python Code: import csv import networkx as nx import pandas as pd import matplotlib.pyplot as plt %matplotlib inline # Create empty graph G = nx.Graph() # Add nodes G.add_node(1) G.add_nodes_from([2, 3]) G.add_node(4) G.nodes() # add edges G.add_edge(1, 2) # get graph info print(nx.info(G)) nx.dra...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Replace by your GCP project and bucket Step2: Loading the dataset in GCS Step3: It has very specialized language such as Step4: and for gcs-...
<ASSISTANT_TASK:> Python Code: #!pip freeze | grep tensorflow-hub==0.7.0 || pip install tensorflow-hub==0.7.0 import os import tensorflow as tf import tensorflow_hub as hub PROJECT = !(gcloud config get-value core/project) PROJECT = PROJECT[0] BUCKET = PROJECT REGION = "us-central1" %env PROJECT = {PROJECT} %env BUCKE...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step4: Cython -- A Transcompiler Language Step6: Now let's see the time difference between a cyfib and pyfib ... Step7: Introducing runcython !! Step...
<ASSISTANT_TASK:> Python Code: %%file ./src/helloCython.pyx import cython import sys def message(): print(" Hello World ....\n") print(" Hello Central Ohio Python User Group ...\n") print(" The 614 > 650::True") print(" Another line ") print(" The Python version is %s" % sys.version) print(" Th...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: This data is from the Council Grove gas reservoir in Southwest Kansas. The Panoma Council Grove Field is predominantly a carbonate gas reservoi...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.colors as colors from mpl_toolkits.axes_grid1 import make_axes_locatable from pandas import set_option set_option("display.max_rows", 10) pd.options.mode.ch...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
<ASSISTANT_TASK:> Python Code:: import tensorflow as tf from sklearn.model_selection import train_test_split TRAINING_FILENAMES, VALIDATION_FILENAMES = train_test_split( tf.io.gfile.glob(r'data\tfrecords\ld_train*.tfrec'), test_size=0.3, random_state=101 ) <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: First, set filename to what we want to examine and read PhSF header Step2: Checking PhSF header parameters Step3: Energy Spectrum tests Step4:...
<ASSISTANT_TASK:> Python Code: import math import matplotlib import numpy as np import matplotlib.pyplot as plt import BEAMphsf import text_loader import H1Dn import H1Du import ListTable %matplotlib inline C = 25 phsfname = "PHSF" + "." + str(C) phsfname = "../" + phsfname print ("We're reading the {1}mm phase space ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Flower power Step2: ConvNet Codes Step3: Below I'm running images through the VGG network in batches. Step4: Building the Classifier Step5: ...
<ASSISTANT_TASK:> Python Code: from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm vgg_dir = 'tensorflow_vgg/' # Make sure vgg exists if not isdir(vgg_dir): raise Exception("VGG directory doesn't exist!") class DLProgress(tqdm): last_block = 0 def hook(self, block_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: We're going to be building a model that recognizes these digits as 5, 0, and 4. Step3: Working with the images Step4: The first 10 pixels are ...
<ASSISTANT_TASK:> Python Code: from __future__ import print_function from IPython.display import Image import base64 Image(data=base64.decodestring("iVBORw0KGgoAAAANSUhEUgAAAMYAAABFCAYAAAARv5krAAAYl0lEQVR4Ae3dV4wc1bYG4D3YYJucc8455yCSSIYrBAi4EjriAZHECyAk3rAID1gCIXGRgIvASIQr8UTmgDA5imByPpicTcYGY+yrbx+tOUWpu2e6u7qnZ7qXVFP...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Q1 Step2: Q2 Step3: Q3 Step4: La méthode insere prévoit de ne rien faire dans le cas où le mot s passé en argument est égal à l'attribut m...
<ASSISTANT_TASK:> Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() class NoeudTri (object): def __init__(self,s): self.mot = s NoeudTri("a") class NoeudTri (object): def __init__(self,s): self.mot = s def __str__(self): return self.mot + "\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: Load the data into a Pandas DataFrame from a CSV file. Step2: While the coordinates for each store are contained in an X (longitude) and Y (lat...
<ASSISTANT_TASK:> Python Code: import pandas as pd import arcgis df = pd.read_csv('./store_locations.csv', index_col='OBJECTID') df.head() df['SHAPE'] = df.apply(lambda row: arcgis.geometry.Point({'x': row.X, 'y': row.Y, 'spatialReference': {'wkid': 4326}}), axis=1) df = df.drop(['X', 'Y'], axis=1) df.head() sdf = 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: Step2: Next, a function that extracts the net rating for a team. Step3: The Pistons Step4: As experienced as a fan this year, we are a bit bi-modal, ...
<ASSISTANT_TASK:> Python Code: import csv import numpy as np import matplotlib.pyplot as plt import os import itertools %matplotlib inline %config InlineBackend.figure_format = 'retina' nba_games = [] fname = 'nba-games.csv' with open(fname,"r") as f: # game_id,game_date,team_id,team_name,net_rating reader = cs...
<SYSTEM_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 do a lil bit better Step2: Linear regression example Step3: Using the Normal Equation Step4: Batch gradient descent with manually comp...
<ASSISTANT_TASK:> Python Code: tf.reset_default_graph()#important for tensorboard when using jupyter notebook students = tf.Variable(13, name="students") coffee = tf.Variable(-10, name="coffee") lees_checking = students*coffee #one way to do it but pretty verbose sess = tf.Session() sess.run(students.initializer) 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: 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: Create the signal Step2: Listen to the signal Step3: Plot the signal Step4: Segmentation Using Python List Comprehensions Step5: Define a he...
<ASSISTANT_TASK:> Python Code: T = 3.0 # duration in seconds sr = 22050 # sampling rate in Hertz amplitude = numpy.logspace(-3, 0, int(T*sr), endpoint=False, base=10.0) # time-varying amplitude print(amplitude.min(), amplitude.max()) # starts at 110 Hz, ends at 880 Hz t = numpy.linspace(0, T, int(T*sr), endpoin...
<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: As we can see from the cross-validation results above, the performance of the three models is almost equal. Step6: <br> Step8: <br>
<ASSISTANT_TASK:> Python Code: from sklearn import datasets iris = datasets.load_iris() X, y = iris.data[:, 1:3], iris.target from sklearn import cross_validation from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier import nu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: TensorBoard Scalars Step2: 配置数据用来训练回归 Step3: 训练模型和记录损失 (loss) Step4: 使用 TensorBoard 检查损失 (loss) Step5: <img class="tfo-display-only-on-site"...
<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: Read and preprocess the data. Preprocessing consists of Step2: Define a function that runs ICA on the raw MEG data and plots the components Ste...
<ASSISTANT_TASK:> Python Code: # Authors: Pierre Ablin <pierreablin@gmail.com> # # License: BSD-3-Clause from time import time import mne from mne.preprocessing import ICA from mne.datasets import sample print(__doc__) data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'...