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: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 2... | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ipsl', 'sandbox-3', 'seaice')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "ema... |
<SYSTEM_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 モデルから Estimator を作成する
Step2: 単純な Keras モデルを作成する。
Step3: モデルをコンパイルして要約を取得します。
Step4: 入力関数を作成する
Step5: input_fn をテストします。
Step6: tf.kera... | <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: Dans les séquences de travail, vous rencontrerez certains logos
Step2: On peut aussi mêler texte et variables, de la façon suivante
Step3: O... | <ASSISTANT_TASK:>
Python Code:
# Exécutez cette cellule !
from IPython.core.display import HTML
styles = "<style>\n.travail {\n background-size: 30px;\n background-image: url('https://cdn.pixabay.com/photo/2018/01/04/16/53/building-3061124_960_720.png');\n background-position: left top;\n background-repeat:... |
<SYSTEM_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 representation
Step2: Preprocess text
Step3: Cluster the talks
| <ASSISTANT_TASK:>
Python Code:
from bs4 import BeautifulSoup
import requests
import pandas as pd
website_to_parse = "https://csvconf.com/speakers/"
# Save HTML to soup
html_data = requests.get(website_to_parse).text
soup = BeautifulSoup(html_data, "html5lib")
doc = soup.find_all("table", attrs={"class", "speakers"})[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: Import data of politicians by country
Step2: Import population by country
Step3: Combined data
Step4: ORES article quality data
Step5: Impor... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import requests
import json
%matplotlib notebook
politicianFile = 'PolbyCountry_data.csv'
politicianNames = pd.read_csv(politicianFile)
# rename variables
politicianNames.rename(columns = {'page':'article_name'}, inpl... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <center><h3>2. Mając dane w takiej postaci, gdzie pierwszy index to numer strony, a drugi to numer zawartości.</center></h3>
Step2: Stwórz list... | <ASSISTANT_TASK:>
Python Code:
max_num("9512983", 1) # "9"
max_num("9512983", 3) # "998"
max_num("9512983", 7) # "9512983"
POST = {
u"page[1][1]['id']": [u'baloes_bd_8_1'],
u"page[0][1]['text']": [u'Mum, dad! Look, the school email. '],
u"page[1][0]['id']": [u'baloes_bd_9_1'],
u"page[0][1]['id']": [u'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:
Step2: The tweet enricher
Step3: Enrichment classes
Step5: Convenience and simplification
Step6: The problem
Step8: commentary
Step10: commentary
... | <ASSISTANT_TASK:>
Python Code:
DT_FORMAT_STR = "%Y-%m-%dT%H:%M:%S.%f"
def stream_of_tweets(n=10):
# generator function to generate sequential tweets
for i in range(n):
time.sleep(0.01)
tweet = {
'body':'I am tweet #' + str(i),
'postedTime':datetime.datetime.now().strftime... |
<SYSTEM_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: 이 값은 5% 보다는 작고 1% 보다는 크기 때문에 유의 수준이 5% 라면 기각할 수 있으며(즉 공정한 동전이 아니라고 말할 ... | <ASSISTANT_TASK:>
Python Code:
xx1 = np.linspace(-4, 4, 100)
xx2 = np.linspace(-4, -2, 100)
xx3 = np.linspace(2, 4, 100)
plt.subplot(3, 1, 1)
plt.fill_between(xx1, sp.stats.norm.pdf(xx1), facecolor='green', alpha=0.1)
plt.fill_between(xx2, sp.stats.norm.pdf(xx2), facecolor='blue', alpha=0.35)
plt.fill_between(xx3, sp.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: Données
Step2: On extrait les données de la base et on les écrit dans un fichiers plat.
Step3: On sépare ce fichier plat en 50 morceaux.
Step... | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
import pyensae.datasource
pyensae.datasource.download_data("twitter_for_network_100000.db.zip")
import cytoolz as ct # import groupby, valmap, compose
import cytoolz.curried as ctc ## pipe, map, filter, get
import sqlite3
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: Download brownian trajectory from here, and read the latter by using trajectory from COSSIO generator.
Step3: Trajectory analysis and assignmen... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%load_ext autoreload
%autoreload 2
import time
import numpy as np
import scipy.stats
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="ticks", color_codes=True, font_scale=1.5)
sns.set_style({"xtick.direction": "in", "ytick.direction": "in"})
from 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: Make training set
Step2: It means that user 0 tried to solve question number 1 which has 77 tokens for question and he or she answered at 61st ... | <ASSISTANT_TASK:>
Python Code:
import gzip
import cPickle as pickle
with gzip.open("../data/train.pklz", "rb") as train_file:
train_set = pickle.load(train_file)
with gzip.open("../data/test.pklz", "rb") as test_file:
test_set = pickle.load(test_file)
with gzip.open("../data/questions.pklz", "rb") as questions_... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: This is what the data looks like
Step2: Corpus
Step3: Biagram
Step4: Vectorizer
| <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
legislatorsData = pd.read_csv("../data/legislators.csv")
legislatorsData.head()
legislatorsData.columns
legislators = pd.DataFrame(legislatorsData)
legislators.head()
from urllib2 import Request, urlopen
import json
from pandas.io.json import json_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 in house sales data
Step2: If we want to do any "feature engineering" like creating new features or adjusting existing ones we should do t... | <ASSISTANT_TASK:>
Python Code:
import graphlab
sales = graphlab.SFrame('../Data/kc_house_data.gl/')
import numpy as np # note this allows us to refer to numpy as np instead
def get_numpy_data(data_sframe, features, output):
data_sframe['constant'] = 1 # this is how you add a constant column to an SFrame
# 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: IMF notes
Step2: The total number of stars $N_{tot}$ is then
Step3: With a yield ejected of $0.1 Msun$, the total amount ejected is
Step4: co... | <ASSISTANT_TASK:>
Python Code:
#from imp import *
#s=load_source('sygma','/home/nugrid/nugrid/SYGMA/SYGMA_online/SYGMA_dev/sygma.py')
#%pylab nbagg
import sys
import sygma as s
print s.__file__
reload(s)
s.__file__
#import matplotlib
#matplotlib.use('nbagg')
import matplotlib.pyplot as plt
#matplotlib.use('nbagg')
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: 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', 'nasa-giss', 'sandbox-3', 'ocnbgchem')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("nam... |
<SYSTEM_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 you can see, the training_corpus is a list with all words extracted from English articles, together with their POS tag.
Step2: The Testing C... | <ASSISTANT_TASK:>
Python Code:
# load in the training corpus
with open("../datasets/WSJ_02-21.pos", 'r') as f:
training_corpus = f.readlines() # list
print("A few items of the training corpus list: ")
print(training_corpus[0:5])
len(training_corpus)
# load in the test corpus
with open("../datasets/WSJ_24.pos", 'r... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 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', 'bcc', 'sandbox-2', 'atmoschem')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "e... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step12: Module is an abstract class which defines fundamental methods necessary for a training a neural network. You do not need to change anything her... | <ASSISTANT_TASK:>
Python Code:
class Module(object):
def __init__ (self):
self.output = None
self.gradInput = None
self.training = True
Basically, you can think of a module as of a something (black box)
which can process `input` data and produce `ouput` data.
This is like 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: Problem Beschreibung
Step2: <h3>Beschreibende Statistik</h3>
Step3: <h3>Visualisierung der Daten</h3>
Step4: <h3>Univariate Feature Selektion... | <ASSISTANT_TASK:>
Python Code:
# Laden der entsprechenden Module (kann etwas dauern !)
# Wir laden die Module offen, damit man einmal sieht, was da alles benötigt wird
# Allerdings aufpassen, dann werden die Module anderst angesprochen wie beim Standard
# zum Beispiel pyplot und nicht plt
from matplotlib import pyplot
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Sampling and taking the z-transform of the step-response
| <ASSISTANT_TASK:>
Python Code:
h, lam = sy.symbols('h, lambda', real=True, positive=True)
s, z = sy.symbols('s, z', real=False)
G = 1/(s-lam)
Y = G/s
Yp = sy.apart(Y, s)
Yp
from sympy.integrals.transforms import inverse_laplace_transform
from sympy.abc import t
inverse_laplace_transform(Yp, s, t)
lam = -0.5
h = 0.1
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: By far, we'll use the plt object from the second import the most; that contains the main plotting library.
Step2: Note that you do NOT need to ... | <ASSISTANT_TASK:>
Python Code:
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
x = np.random.random(10)
y = np.random.random(10)
plt.plot(x, y)
fig = plt.figure()
fig.canvas.get_supported_filetypes()
%matplotlib inline
import numpy as np
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: <a href="https
Step3: Now that we've got a copy of the TS client we need to get to the sketch.
Step4: OK, sketch nr 6 is the one that we are a... | <ASSISTANT_TASK:>
Python Code:
# @markdown Only execute if not already installed and running a cloud runtime
!pip install -q timesketch_api_client
!pip install -q vt-py nest_asyncio pandas
!pip install -q picatrix
# @title Import libraries
# @markdown This cell will import all the libraries needed for the running of 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: Level 0
| <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.append('/home/pi/minecraft-programming')
import mini_game as pepgame
game = pepgame.ShapeGame("TETRAHEDRON")
game.startGame()
<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: Quick Start
Step2: Suppose one has a calibrated spectrum and wants to compute the vega magnitude throug the HST WFC3 F110W passband,
| <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pylab as plt
import numpy as np
import sys
sys.path.append('../')
from pyphot import astropy as pyphot
from pyphot.svo import get_pyphot_astropy_filter as get_filter_from_svo
lst = ["2MASS/2MASS.J", "2MASS/2MASS.H", "2MASS/2MASS.Ks",
"HST/ACS_WFC.F475W", ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: You'll work with a dataset from the US Environmental Protection Agency (EPA) that tracks releases of toxic chemicals in Philadelphia, Pennsylvan... | <ASSISTANT_TASK:>
Python Code:
#$HIDE_INPUT$
import folium
from folium import Marker, GeoJson
from folium.plugins import HeatMap
import pandas as pd
import geopandas as gpd
releases = gpd.read_file("../input/geospatial-learn-course-data/toxic_release_pennsylvania/toxic_release_pennsylvania/toxic_release_pennsylvania.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: Image Classification
Step2: Explore the Data
Step5: Implement Preprocess Functions
Step8: One-hot encode
Step10: Randomize Data
Step12: Che... | <ASSISTANT_TASK:>
Python Code:
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile
cifar10_dataset_folder_path = 'cifar-10-batches-py'
# Use Floyd's cifar-10 dataset 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:
Step3: Here are some of the functions from Chapter 5.
Step4: Read the GSS data again.
Step5: Most variables use special codes to indicate missing dat... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='white')
from utils import decorate
from thinkstats2 import Pmf, Cdf
import thinkstats2
import thinkplot
def MakeNormalModel(values, label=''):
Plots a CDF wi... |
<SYSTEM_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 block creates a model and populates it with parameters.
Step2: Training
Step3: To use the trainer, we need to
Step4: The optimizati... | <ASSISTANT_TASK:>
Python Code:
# create a model and add the parameters.
m = Model()
m.add_parameters("W", (8,2))
m.add_parameters("V", (1,8))
m.add_parameters("b", (8))
renew_cg() # new computation graph. not strictly needed here, but good practice.
# associate the parameters with cg Expressions
W = parameter(m["W"])
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: 1. Let's start with a showcase
Step2: Starting from reading this dataset, to answering questions about this data in a few lines of code
Step3: ... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
pd.options.display.max_rows = 8
df = pd.read_csv("data/titanic.csv")
df.head()
df['Age'].hist()
df.groupby('Sex')[['Survived']].aggregate(lambda x: x.sum() / len(x))
df.groupby('Pclass')['Survive... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: erode
Step2: dilate
Step3: open
Step4: close
Step5: sobel
Step6: watershed
Step7: mahotas vs skimage vs opencv
| <ASSISTANT_TASK:>
Python Code:
import os
import numpy as np
import timeit
import cv2, mahotas, skimage, skimage.morphology
from pylab import imshow, show
import matplotlib.pyplot as plt
%matplotlib inline
lena_path = 'pershoot/lena.jpeg'
def pyplots(f1, f2, f3, f4, cmap='gray', scatter=False):
plt.figure(figsize=(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: Open and visually inspect the data
Step2: View the first 5 rows of the data frame
Step3: Examine the data for issues. Some things to look for
... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
sns.set_context("poster")
sns.set(style="ticks",font="Arial",font_scale=2)
os.getcwd()
os.listdir()
subjects = pd.read_table("Study2_Subjects.csv", sep=",")
subjects.head()
subjects["... |
<SYSTEM_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 includes the whole module and makes it available for use later in the program.
Step2: Alternatively, we can chose to import all symbols (... | <ASSISTANT_TASK:>
Python Code:
import math
import math
x = math.cos(2 * math.pi)
print(x)
from math import cos, pi
x = cos(2 * pi)
print(x)
from math import cos as cosine # Now the `cos` function can be referenced as `cosine`
cosine(pi/2)
from math import *
print("Cosine Function: ", cos(pi))
print("Sin Function: ... |
<SYSTEM_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 Chainladder Method
Step2: We can now use the basic Chainladder estimator to estimate ultimate_ values of our Triangle.
Step3: We can also ... | <ASSISTANT_TASK:>
Python Code:
# Black linter, optional
%load_ext lab_black
import pandas as pd
import numpy as np
import chainladder as cl
import matplotlib.pyplot as plt
import os
%matplotlib inline
print("pandas: " + pd.__version__)
print("numpy: " + np.__version__)
print("chainladder: " + cl.__version__)
genins = ... |
<SYSTEM_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 MNIST dataset, flatten the images, convert the class labels, and scale the data.
Step2: Next, we construct a tokenizer object, initial... | <ASSISTANT_TASK:>
Python Code:
%pylab inline
import copy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sys
import os
import re
from keras.datasets import imdb, reuters
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.optimiz... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step3: Word counting
Step5: Write a function count_words that takes a list of words and returns a dictionary where the keys in the dictionary are the ... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
def tokenize(s, stop_words=None, punctuation='`~!@#$%^&*()_-+={[}]|\:;"<,>.?/}\t'):
Split a string into a list of words, removing punctuation and stop words.
# the following functions were influenced ... |
<SYSTEM_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', 'messy-consortium', 'sandbox-3', 'atmoschem')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contribut... |
<SYSTEM_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 Normal Incidence Seismogram
Step2: 1.2 Depth to Time conversion
Step3: 1.3 Constructing the ideal seismogram
Step4: 1.4 Vertical Resolution... | <ASSISTANT_TASK:>
Python Code:
# Import the necessary packages
%matplotlib inline
from SimPEG.utils import download
from geoscilabs.seismic.syntheticSeismogram import InteractLogs, InteractDtoT, InteractWconvR, InteractSeismogram
from geoscilabs.seismic.NMOwidget import ViewWiggle, InteractClean, InteractNosiy, NMOs... |
<SYSTEM_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: y (actual value)
Step3: Building an ANN
Step4: Making predictions and evaluating the model
Step5: Evaluating, Impr... | <ASSISTANT_TASK:>
Python Code:
# Installing Theano
# pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
# Installing Tensorflow
# pip install tensorflow
# Installing Keras
# pip install --upgrade keras
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step8: 1. PCFG
Step9: Let's try out the classes by initializing some terminal an nonterminal symbols
Step10: The methods __eq__ and __ne__ make it po... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from collections import Counter, defaultdict
import math
import nltk
from nltk.tree import Tree
class Symbol:
A symbol in a grammar.
This class will be used as parent class for Terminal, Nonterminal.
This way both will be a type of Symbol.
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:
Step1: In order to be able to use the Data Observatory via CARTOframes, you need to set your CARTO account credentials first.
Step2: 1. Load data
Step... | <ASSISTANT_TASK:>
Python Code:
import geopandas as gpd
import ipywidgets as widgets
import numpy as np
import pandas as pd
import pyproj
from cartoframes.auth import set_default_credentials
from cartoframes.data.observatory import *
from cartoframes.data.services import Geocoding, Isolines
from cartoframes.viz import *... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <font color='midnightblue'> Example
Step2: <font color='midnightblue'> Example
Step3: <font color='mediumblue'> Tuples
Step4: <font color='mi... | <ASSISTANT_TASK:>
Python Code:
list1 = [10, 12, 14, 16, 18]
print(list1[0]) # Index starts at 0
print(list1[-1]) # Last index at -1
print(list1[0:3]) # Slicing: exclusive of end value
# i.e. get i=(0, 1, .. n-1)
print(list1[3:]) # "slice from i=3 to end"
list1.append(20)
print(li... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Raw DDSM images
Step2: Threshold Images
| <ASSISTANT_TASK:>
Python Code:
import datetime
import gc
import numpy as np
import os
import random
from scipy import misc
import string
import time
import sys
import sklearn.metrics as skm
import collections
from sklearn.svm import SVC
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from 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: Load software and filenames definitions
Step2: Data folder
Step3: List of data files
Step4: Data load
Step5: Laser alternation selection
Ste... | <ASSISTANT_TASK:>
Python Code:
ph_sel_name = "Dex"
data_id = "17d"
# ph_sel_name = "all-ph"
# data_id = "7d"
from fretbursts import *
init_notebook()
from IPython.display import display
data_dir = './data/singlespot/'
import os
data_dir = os.path.abspath(data_dir) + '/'
assert os.path.exists(data_dir), "Path '%s' doe... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Unit Test
| <ASSISTANT_TASK:>
Python Code:
%run ../bst/bst.py
%load ../bst/bst.py
def bfs(self, visit_func):
# TODO: Implement me
pass
%run ../utils/results.py
# %load test_bfs.py
from nose.tools import assert_equal
class TestBfs(object):
def __init__(self):
self.results = Results()
def test_bfs(self):
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: フェデレーテッドラーニングリサーチの TFF
Step2: TFF が動作していることを確認します。
Step4: 入力データを準備する
Step6: モデルを定義する
Step7: モデルのトレーニングとトレーニングメトリックの出力
Step11: では、フェデレーテッドアベ... | <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:
Step2: Create initial box of water
Step4: Create OpenMM System classes for a variety of long-range correction schemes
Step5: Here we perform the actu... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *
from sys import stdout
import matplotlib, matplotlib.pyplot as plt
import pandas as pd
from io import StringIO
import numpy as np, os
matplotlib.rcParams.update({'font.size': 12})
# simul... |
<SYSTEM_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 columns are the instances and rows the features so we need to transpose the dataset.
Step2: Read in the labels...
Step3: We are using the ... | <ASSISTANT_TASK:>
Python Code:
data = pd.read_csv('/Users/Frankie/Documents/Dissertation/Data/pancreatic/24hProbeExpressionValues.csv')
data[:5]
data = data.T
label = pd.read_csv('/Users/Frankie/Documents/Dissertation/Data/pancreatic/24hTargets.csv')
label[:5]
label = label[['FileName', 'OAC']]
label[:5]
joined_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: Data
Step2: Array of desired pressure levels
Step3: Interpolate The Data
Step4: Plotting the Data for 700 hPa.
| <ASSISTANT_TASK:>
Python Code:
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
from netCDF4 import Dataset, num2date
from metpy.cbook import get_test_data
from metpy.interpolate import log_interpolate_1d
from metpy.plots import add_metpy_logo, add_timestamp
from metpy.units... |
<SYSTEM_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 load an image from scikit-image's collection, stored in the data module. These come back as regular numpy arrays
Step3: Let's make a litt... | <ASSISTANT_TASK:>
Python Code:
# Stdlib imports
from io import BytesIO
# Third-party libraries
from IPython.display import Image
from ipywidgets import interact, interactive, fixed
import matplotlib as mpl
from skimage import data, filters, io, img_as_float
import numpy as np
i = img_as_float(data.coffee())
i.shape
d... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Create Unnormalized Data
Step2: Normalize The Column
| <ASSISTANT_TASK:>
Python Code:
# Import required modules
import pandas as pd
from sklearn import preprocessing
# Set charts to view inline
%matplotlib inline
# Create an example dataframe with a column of unnormalized data
data = {'score': [234,24,14,27,-74,46,73,-18,59,160]}
df = pd.DataFrame(data)
df
# View the unno... |
<SYSTEM_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 assign uniform priors to the parameters of the powerlaw function. The function uniform_prior is defined like this
Step2: We can use i... | <ASSISTANT_TASK:>
Python Code:
from astromodels import *
# Create a point source named "pts1"
pts1 = PointSource('pts1',ra=125.23, dec=17.98, spectral_shape=powerlaw())
# Create the model
my_model = Model(pts1)
uniform_prior.info()
# Set 'lower_bound' to -10, 'upper bound' to 10, and leave the 'value' parameter
# to... |
<SYSTEM_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', 'test-institute-1', 'sandbox-2', 'land')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("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: 2. Identify influential friends using 'Page Rank' formulation
Step2: Initialize PageRank vector, such that all the nodes have equal PageRank sc... | <ASSISTANT_TASK:>
Python Code:
from collections import Counter, defaultdict
from datetime import datetime
from sklearn.decomposition import PCA
import csv
import matplotlib.pyplot as plt
import numpy as np
import os.path
import pandas as pd
import re
import seaborn as sns; sns.set()
import time
import twitter
% matplo... |
<SYSTEM_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 3 Encodings
| <ASSISTANT_TASK:>
Python Code:
rootdir = "C:\\Users\\Shantnu\\Desktop\\Data Sources\\Enron Spam"
# Loop through all the directories, sub directories and files in the above folder, and print them.
# For files, print number of files.
for directories, subdirs, files in os.walk(rootdir):
print(directories, subdirs, len... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Useful references
Step2: Useful references
| <ASSISTANT_TASK:>
Python Code:
# Imports the functionality that we need to display YouTube videos in a Jupyter Notebook.
# You need to run this cell before you run ANY of the YouTube videos.
from IPython.display import YouTubeVideo
# Display a specific YouTube video, with a given width and height.
# WE STRONGLY R... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: I plot the error of the filtered wave. I use the absulte values of the difference between sine wave and median filtered wave and calculate the m... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
% matplotlib inline
def ErrorPlot( wavenumber,windowLength ):
data = np.fromfunction( lambda x: np.sin((x-windowLength / 2)/128 * 2 * np.pi * waveNumber), (128 + windowLength /... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Your guess
Step2: Your guess
Step3: Your guess
Step4: Your guess
Step5: Your guess
Step6: Your guess
Step7: Your guess
Step8: Your guess
... | <ASSISTANT_TASK:>
Python Code:
for i in range(1, 10, 2):
print i
for i in range (5, 1, -1):
print i
count = 0
while (count < 5):
print count
count = count + 1
total = 0
for i in range(4):
total = total + i
print total
name = "Mits"
for i in name:
print i
name = "Wilfred"
newName = ""
for le... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load data
Step2: Linear model 1
Step3: Linear model 2
Step4: Linear model 3. Predicting Yelp ratings
| <ASSISTANT_TASK:>
Python Code:
%config InlineBackend.figure_format = 'retina'
%matplotlib inline
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import pandas as pd
import statsmodels.api as sm
import seaborn as sns
sns.set_style("white")
import util
df = util.load_burritos()
N = df.shape[0]
# D... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 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', 'ipsl', 'sandbox-3', '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: Icons as categorical mappings + glyph types
Step2: Icons as continuous mappings and text
Step3: Special continuous bins
Step4: Flag inference... | <ASSISTANT_TASK:>
Python Code:
# ! pip install --user graphistry
import graphistry
# To specify Graphistry account & server, use:
# graphistry.register(api=3, username='...', password='...', protocol='https', server='hub.graphistry.com')
# For more options, see https://github.com/graphistry/pygraphistry#configure
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: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the ship
Step3: The very same sample of th... | <ASSISTANT_TASK:>
Python Code:
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
%matplotlib inlin... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Binary
Step2: 1024 byte = 1 kilobyte
Step3: Binary
Step4: Denary to Binary and Binary to Denary
Step5: Exercise
| <ASSISTANT_TASK:>
Python Code:
13 % 5 == 3
12 ** 2 == 144
146 % 67 == 12
19 % 8.5 == 2
4 ** (3 % 11)
1024 `megabytes` = 1 `??`
1024 `gigabyte` = 1 `??`
1024 `terabyte` = 1 `??`
movies_per_gb = 1024.0/650.0
print(movies_per_gb) #number of videos I can store in 1GB
movies_per_tb = float(movies_per_gb * 1024)
print(movi... |
<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: Data collection
Step3: Word2Vec
Step4: Testing Word2Vec Model
Step5: Saving the features
Step6: Training Classifier Model
Step7: Evaluating... | <ASSISTANT_TASK:>
Python Code:
# Importing all the required modules and the helper functions
import numpy as np
import urllib.request
from bs4 import BeautifulSoup
from nltk import sent_tokenize
from nltk import word_tokenize
import re
from gensim.models import Word2Vec
import pickle
# the following two modules are ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
| <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.DataFrame({'a':[12,13,23,22,23,24,30,35,55], 'b':[1,1,1,2,2,2,3,3,3]})
import numpy as np
def g(df):
return df.groupby("b")["a"].agg([np.mean, np.std])
result = g(df.copy())
<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: 6.1.2 パイプラインで変換器と推定器を結合する
Step2: 6.2 k分割交差検証を使ったモデルの性能の評価
Step3: 6.3 学習曲線と検証曲線によるアルゴリズムの診断
Step4: 6.3.2 検証曲線を使って過学習と学習不足を明らかにする
Step5: 6.4 グ... | <ASSISTANT_TASK:>
Python Code:
from IPython.core.display import display
from distutils.version import LooseVersion as Version
from sklearn import __version__ as sklearn_version
# データセットを読み込む
import pandas as pd
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.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: Measurement of $T_1$
Step2: The last calibration of $T_1$ was measured to be
Step3: Measurement of $T_2^*$
Step4: Measurement of $T_2$ Echo
S... | <ASSISTANT_TASK:>
Python Code:
import qiskit as qk
import numpy as np
from scipy.optimize import curve_fit
from qiskit.tools.qcvv.fitters import exp_fit_fun, osc_fit_fun, plot_coherence
from qiskit.wrapper.jupyter import *
# Load saved IBMQ accounts
qk.IBMQ.load_accounts()
# backend and token settings
backend = qk.IBMQ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Bagwell (1993) pointed out that the usual story of Stackelberg commitment to an action depends critically on the observability of the commitment... | <ASSISTANT_TASK:>
Python Code:
import gambit
import numpy
L = numpy.array([[5,3], [6,4]])
L
F = numpy.array([[2,1], [3,4]])
F
g = gambit.Game.from_arrays(L, F)
g.players[0].label = "Leader"
g.players[0].strategies[0].label = "S"
g.players[0].strategies[1].label = "C"
g.players[1].label = "Follower"
g.players[1].stra... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: This is an extra layer of convenience compared to PyMC. Any variables created within a given Model's context will be automatically assigned to t... | <ASSISTANT_TASK:>
Python Code:
import pymc3 as pm
with pm.Model() as model:
parameter = pm.Exponential("poisson_param", 1.0)
data_generator = pm.Poisson("data_generator", parameter)
with model:
data_plus_one = data_generator + 1
parameter.tag.test_value
with pm.Model() as model:
theta = pm.Exponentia... |
<SYSTEM_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', 'ipsl', 'sandbox-1', 'atmos')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "emai... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set parameters
Step2: Compute statistic
Step3: Visualize the clusters
| <ASSISTANT_TASK:>
Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Eric Larson <larson.eric.d@gmail.com>
# License: BSD (3-clause)
import os.path as op
import numpy as np
from scipy import stats as stats
import mne
from mne import spatial_src_adjacency
from mne.stats import spatio_tem... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step7: 4T_Pandas로 배우는 SQL 시작하기 (4) - HAVING, SUB QUERY
Step9: HAVING
Step10: 실습)
Step13: film_df => film_id, title
Step15: 실습 추가)
Step17: 영화를 흥행시킨... | <ASSISTANT_TASK:>
Python Code:
import pymysql
import curl
db = pymysql.connect(
"db.fastcamp.us",
"root",
"dkstncks",
"sakila",
charset = "utf8",
)
customer_df = pd.read_sql("SELECT * FROM customer;", db)
rental_df = pd.read_sql("SELECT * FROM rental;", db)
df = rental_df.merge(customer_df, on="cust... |
<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: Examine a single patient
Step4: Above we can see a patient is admitted on (or quickly administered after admission) two drugs
| <ASSISTANT_TASK:>
Python Code:
# Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import psycopg2
import getpass
import pdvega
# for configuring connection
from configobj import ConfigObj
import os
%matplotlib inline
# Create a database connection using settings from config 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: In previous weeks we have covered preprocessing our data, dimensionality reduction, clustering, regression and classification. This week we will... | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model, decomposition, datasets
from sklearn.metrics import accuracy_score
digits = datasets.load_digits()
X_digits = dig... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Simple 3D Visualizations of a neuron
Step2: Simple 1D visualizations
| <ASSISTANT_TASK:>
Python Code:
# Imports
import numpy as np
import tensorflow as tf
import scipy.ndimage as nd
import time
import imageio
import matplotlib
import matplotlib.pyplot as plt
import lucid.modelzoo.vision_models as models
from lucid.misc.io import show
import lucid.optvis.objectives as objectives
import luc... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the ship
Step3: The very same sample of th... | <ASSISTANT_TASK:>
Python Code:
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
%matplotlib inlin... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Archive objects have a method that reports for each user how many emails they sent each day.
Step2: This plot will show when each sender sent t... | <ASSISTANT_TASK:>
Python Code:
url = "scipy-user"
arx = Archive(url,archive_dir="../archives")
arx.data[:1]
act = arx.get_activity()
fig = plt.figure(figsize=(12.5, 7.5))
#act.idxmax().order().T.plot()
(act > 0).idxmax().order().plot()
fig.axes[0].yaxis_date()
fig = plt.figure(figsize=(12.5, 7.5))
(act > 0).idxmax()... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Contents
Step2: Function time dependence
Step3: If you need something more complex, such as a state with memory or to build a parametrised set... | <ASSISTANT_TASK:>
Python Code:
# Basic setup
import qutip
import numpy as np
size = 4
t = 1.0
a = qutip.destroy(size)
ad = qutip.create(size)
n = qutip.num(size)
I = qutip.qeye(size)
constant_form = qutip.QobjEvo([n])
def cos_t(t, args):
return np.cos(t)
function_form = qutip.QobjEvo([n, [a+ad, cos_t]])
class ca... |
<SYSTEM_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 matrix rank
Step2: So, small perturbations might crucially affect the rank.
Step3: Separation of variables for 2D functions
Step4: ... | <ASSISTANT_TASK:>
Python Code:
#A fast matrix-by-vector product demo
import numpy as np
n = 1000
r = 10
u = np.random.randn(n, r)
v = np.random.randn(n, r)
a = u.dot(v.T)
x = np.random.randn(n)
%timeit a.dot(x)
%timeit u.dot(v.T.dot(x))
#Computing matrix rank
import numpy as np
n = 50
a = np.ones((n, n))
print 'Rank ... |
<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: トレーニングのチェックポイント
Step3: tf.kerasトレーニング API から保存する
Step5: チェックポイントを記述する
Step6: チェックポイントオブジェクトを作成する
Step7: モデルをトレーニングおよびチェックポイントする
Step8: 復元して... | <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: Unit Test
| <ASSISTANT_TASK:>
Python Code:
%run ../stack/stack.py
%load ../stack/stack.py
import sys
class MyStack(Stack):
def __init__(self, top=None):
# TODO: Implement me
pass
def min(self):
# TODO: Implement me
pass
def push(self, data):
# TODO: Implement me
pass
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: ... and export it directly export it into the active gephi workspace. After executing the following code, the graph should be available in the f... | <ASSISTANT_TASK:>
Python Code:
G = generators.ErdosRenyiGenerator(300, 0.2).generate()
G.addEdge(0, 1) #We want to make sure this specific edge exists, for usage in an example later.
client = gephi.streaming.GephiStreamingClient()
client.exportGraph(G)
communities = community.detectCommunities(G)
client.exportNodeVal... |
<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: Vectors
Step7: The dot product measures how far the vector v extends in the w direction.
Step11: Using lists as vectors
Step12: Matrices wi... | <ASSISTANT_TASK:>
Python Code:
import re, math, random # regexes, math functions, random numbers
import matplotlib.pyplot as plt # pyplot
from collections import defaultdict, Counter
from functools import partial, reduce
v = [1, 2]
w = [2, 1]
vectors = [v, w]
def vector_add(v, w):
adds two vectors componentwise
... |
<SYSTEM_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 models
Step2: Internally, the list objects are converted to NumPy arrays. Notice that when we are defining $G_4$, we skipped the $D$ m... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from harold import *
import matplotlib.pyplot as plt
G1 = Transfer([1, -1],[1, -2, 1, 0], dt=0.1) # discrete
G2 = Transfer([[1, [1, 3]],[0, [1, 2]]], [[[1, 2], [1, 0, -4]],[1, [1, -3]]])
G3 = State([[0, 1], [-0.1, -0.5]], [[0], [1]], [0, 3.5], 1, dt=0.1) # discrete
G4 ... |
<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: Spacy Documentation
Step3: Download and load the model. SpaCy has an excellent English NLP processor. It has the following features which we sh... | <ASSISTANT_TASK:>
Python Code:
!pip install spacy nltk
text = 'Please would you tell me,' said Alice, a little timidly, for she was not quite sure whether it was good manners for her to speak first, 'why your cat grins like that?'
'It's a Cheshire cat,' said the Duchess, 'and that's why. Pig!'
She said the last word w... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 베이지안 변환점(switchpoint) 분석
Step2: 데이터세트
Step3: 확률 모델
Step4: 위의 코드는 JointDistributionSequential 분포를 통해 모델을 정의합니다. disaster_rate 함수는 [0, ..., len... | <ASSISTANT_TASK:>
Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# 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 l... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: Character counting and entropy
Step4: The entropy is a quantiative measure of the disorder of a probability distribution. It is used extensivel... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact
def char_probs(s):
l = len(s)
dic = {l}
for i in l:
prob = i/l
Find the probabilities of the unique characters in the string 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: Start by finding structures using online databases (or cached local results). This uses an InChI for a known structure that will be added if not... | <ASSISTANT_TASK:>
Python Code:
import openchemistry as oc
mol = oc.find_structure('InChI=1S/C6H6/c1-2-4-6-5-3-1/h1-6H')
mol.structure.show()
image_name = 'openchemistry/chemml:0.6.0'
input_parameters = {}
result = mol.calculate(image_name, input_parameters)
result.properties.show()
<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: 이미지 분할
Step2: Oxford-IIIT Pets 데이터 세트를 다운로드 하기
Step3: 다음 코드는 이미지를 뒤집는 간단한 확장을 수행합니다. 또한, 영상이 [0,1]로 정규화됩니다. 마지막으로, 위에서 언급한 것처럼 분할 마스크의 픽셀에 {1,... | <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 cv2
import numpy as np
array_of_image = np.array(image)
image_rgb = cv2.cvtColor(array_of_image, cv2.COLOR_BGR2RGB)
cv2.imshow('image', image_rgb)
<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:
Step2: Unsupervised Anomaly Detection based on Forecasts
Step3: Download raw dataset and load into dataframe
Step4: Below are some example records of... | <ASSISTANT_TASK:>
Python Code:
def get_result_df(y_true_unscale, y_pred_unscale, ano_index, look_back,target_col='cpu_usage'):
Add prediction and anomaly value to dataframe.
result_df = pd.DataFrame({"y_true": y_true_unscale.squeeze(), "y_pred": y_pred_unscale.squeeze()})
result_df['anomalies'] = ... |
<SYSTEM_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 print a value to the screen, we use the function print()
Step2: Jupyter notebooks will always print the value of the last line so you don't ... | <ASSISTANT_TASK:>
Python Code:
type('I am amazing!')
type(145)
type(2.5)
print("Hello World")
"Hello World"
"Hello World";
WHALE = 'Orca'
number_of_whales = 10
weight_of_1_whale = 5003.2
print(number_of_whales)
1 + 2
fish = 15
fish_left = fish - 3
print(fish_left)
print(3 * 2.1)
number_of_whales ** 2
print(5 / 2)
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The consumer's optimum
Step2: The expenditure function
Step3: Interactive plot with sliders (visible if if running on a notebook server)
Step4... | <ASSISTANT_TASK:>
Python Code:
consume_plot()
interact(consume_plot,p1=(pmin,pmax,0.1),p2=(pmin,pmax,0.1), I=(Imin,Imax,10),alpha=(0.05,0.95,0.05));
consume_plot2(r, delta, rho, y1, y2)
interact(consume_plot2, r=(rmin,rmax,0.1), rho=fixed(rho), delta=(0.5,1,0.1), y1=(10,100,1), y2=(10,100,1));
c1e, c2e, uebar = find... |
<SYSTEM_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 LendingClub Dataset
Step2: As before, we reassign the labels to have +1 for a safe loan, and -1 for a risky (bad) loan.
Step3: We will be... | <ASSISTANT_TASK:>
Python Code:
import graphlab
loans = graphlab.SFrame('lending-club-data.gl/')
loans['safe_loans'] = loans['bad_loans'].apply(lambda x : +1 if x==0 else -1)
loans = loans.remove_column('bad_loans')
features = ['grade', # grade of the loan
'term', # the term 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:
Step2: ServerSim Tutorial
Step3: Printing the simulation results
Step4: Mini-batching, plotting, and comparison of results
Step5: Random number gene... | <ASSISTANT_TASK:>
Python Code:
# %load simulate_deployment_scenario.py
from __future__ import print_function
from typing import List, Tuple, Sequence
from collections import namedtuple
import random
import simpy
from serversim import *
def simulate_deployment_scenario(num_users, weight1, weight2, server_range1,
... |
<SYSTEM_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 complexity, overfitting, underfitting
Step2: Scoring metrics
Step3: Data Wrangling
| <ASSISTANT_TASK:>
Python Code:
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import cross_val_score
digits = load_digits()
X, y = digits.data / 16., digits.target
cross_val_score(LogisticRegression(), X, y, cv=5)
from sklearn.grid_search 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: Now that we see how the data is organized, let's use a MLP, with an architecture as the one taught in "Machine Learning" from Stanford in course... | <ASSISTANT_TASK:>
Python Code:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd #... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Rotating Log Files
Step2: The most current file is always logging_rotatingfile_example.out, and each time it reaches the size limit it is renam... | <ASSISTANT_TASK:>
Python Code:
import logging
LOG_FILENAME = 'logging_example.log'
logging.basicConfig(
filename=LOG_FILENAME,
level=logging.DEBUG,
)
logging.debug('This message should go to the log file')
with open(LOG_FILENAME, 'rt') as f:
body = f.read()
print('FILE:')
print(body)
import glob
import log... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Picking at the message structure
Step2: Header
Step3: 'SS' Size bytes.
Step4: three 'ZZ' running total bytes.
Step5: the 'KK' checksum and e... | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function, division
import itertools
import re
# numpy imports
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def hexbyte(x):
return "{:02X}".format(x)
def binbyte(x):
return "{:08b}".format(x)
def tohex(by, sep=" "):
return 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: Checking predictive power using the test set
Step2: Regularization parameter
Step3: Summary
| <ASSISTANT_TASK:>
Python Code:
# Load the data again. Keep air quality data, drop the index column
# and any missing data columns.
df = pd.read_csv(
'https://vincentarelbundock.github.io/Rdatasets/csv/ISLR/Default.csv'
).iloc[:,1:].dropna()
# Recode strings to numeric.
df['default'] = np.where(df['default']=='Yes',... |
<SYSTEM_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: adapt()メソッドは、Numpy 配列またはtf.data.Datasetオブジェクトのいずれかを取ります。StringLookupおよびTextVectorizationの場合、文字列のリストを渡すこともできます。
Step3: さらに、... | <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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.