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: Statistical analysis on Allsides bias rating
Step2: from the stats page "For normally distributed data, the skewness should be about 0. A skewn... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
%matplotlib inline
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = (15, 3)
plt.rcParams['font.family'] = 'sans-serif'
pd.set_option('display.width', 5000)
pd.set_option('display.max_co... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Line plot of sunspot data
Step2: Use np.loadtxt to read the data into a NumPy array called data. Then create two new 1d NumPy arrays named year... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import os
assert os.path.isfile('yearssn.dat')
data=np.loadtxt('yearssn.dat')
years=np.array(data[::1,0])
ssc=np.array(data[::1,1])
raise NotImplementedError()
assert len(years)==315
assert years.dtype==np.dtype(float... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Sparse 2d interpolation
Step2: The following plot should show the points on the boundary and the single point in the interior
Step3: Use meshg... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set_style('white')
from scipy.interpolate import griddata
x = np.empty((1,),dtype=int)
x[0] = 0
for i in range(-4,5):
x = np.hstack((x,np.array((i,i))))
x = np.hstack((x,np.array([-5]*11))... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Next we create a DisplayPort object and configure it with the resolution and pixel format we would like.
Step2: We can now test the output by s... | <ASSISTANT_TASK:>
Python Code:
from pynq.lib.video import *
displayport = DisplayPort()
displayport.configure(VideoMode(1280, 720, 24), PIXEL_RGB)
import time
start = time.time()
for i in range(600):
frame = displayport.newframe()
frame[:,:,0] = i % 256
displayport.writeframe(frame)
end = time.time()... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Feature Exploration, Engineering and Cleaning
Step2: Well it is no surprise that our task is to somehow extract the information out of the cate... | <ASSISTANT_TASK:>
Python Code:
# Load in our libraries
import pandas as pd
import numpy as np
import re
import sklearn
import xgboost as xgb
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
import plotly.offline as py
py.init_notebook_mode(connected=True)
import plotly.graph_objs as go
import pl... |
<SYSTEM_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 a raster file representing the flow accumulation for South America. This gives an idea of the river network.
Step2: We transform the d... | <ASSISTANT_TASK:>
Python Code:
import requests
import os
from tqdm import tqdm
import zipfile
import rasterio
from affine import Affine
import numpy as np
import scipy.ndimage
from rasterio.warp import reproject, Resampling
import PIL
import matplotlib.pyplot as plt
from base64 import b64encode
try:
from StringIO i... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Train and export the model
Step2: For the example, we only trained the model for a single epoch, so it only trains to ~96% accuracy.
Step3: Us... | <ASSISTANT_TASK:>
Python Code:
! pip uninstall -y tensorflow
! pip install -U tf-nightly
import tensorflow as tf
tf.enable_eager_execution()
! git clone --depth 1 https://github.com/tensorflow/models
import sys
import os
if sys.version_info.major >= 3:
import pathlib
else:
import pathlib2 as pathlib
# Add `mode... |
<SYSTEM_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 preperation
Step2: Now, let us see a preview of what the dataset looks like.
Step3: Build the word count vector for each review
Step4: N... | <ASSISTANT_TASK:>
Python Code:
from __future__ import division
import graphlab
import math
import string
products = graphlab.SFrame('amazon_baby.gl/')
products
products[269]
def remove_punctuation(text):
import string
return text.translate(None, string.punctuation)
review_without_puctuation = products['rev... |
<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: Moving average
Step4: Trend and Seasonality
Step5: Naive Forecast
Step6: Now let's compute the mean absolute error between the forecasts and ... | <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: <br></br>
Step2: <br></br>
Step3: <br></br>
Step4: <br></br>
Step5: <br></br>
Step6: <br></br>
Step7: <br></br>
Step8: <br></br>
Step9: ... | <ASSISTANT_TASK:>
Python Code:
import warnings
import numpy as np
import pandas as pd
from time import time
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.lin... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Extract NN Features
Step2: Predicting Own Labels from Selected Images
Step3: Horizontal Striped Data
Step4: neither the svm or the logistic r... | <ASSISTANT_TASK:>
Python Code:
import sys
import os
sys.path.append(os.getcwd()+'/../')
# our lib
from lib.resnet50 import ResNet50
from lib.imagenet_utils import preprocess_input, decode_predictions
#keras
from keras.preprocessing import image
from keras.models import Model
# sklearn
import sklearn
from sklearn.line... |
<SYSTEM_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 - 1/3 + 1/5 - 1/7...的前n项的和。在主程序中,分别令n=1000及100000,打印4倍该函数的和。
Step2: 将task3中的练习1及练习4改写为函数,并进行调用
Step3: 写程序,可以求从整数m到整数n累加的和,间隔为k,求和部分需用函... | <ASSISTANT_TASK:>
Python Code:
def factorial_sum(end):
i = 0
factorial_n = 1
while i < end:
i = i + 1
factorial_n = factorial_n *i
return factorial_n
m= int(input('请输入第1个整数,以回车结束。'))
n= int(input('请输入第2个整数,以回车结束。'))
k = int(input('请输入第3个整数,以回车结束。'))
print('最终的和是:', factorial_sum(m) + fac... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: record schedules for 2 weeks, then augment count with weekly flight numbers.
Step2: good dates
Step3: Save
| <ASSISTANT_TASK:>
Python Code:
L=json.loads(file('../json/L.json','r').read())
M=json.loads(file('../json/M.json','r').read())
N=json.loads(file('../json/N.json','r').read())
import requests
AP={}
for c in M:
if c not in AP:AP[c]={}
for i in range(len(L[c])):
AP[c][N[c][i]]=L[c][i]
baseurl='https://www... |
<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: Regular Expressions
Step6: If I want, I can make the regular expression case insensitive with a COMPLIATION FLAG.
Step12: The Real Power of Re... | <ASSISTANT_TASK:>
Python Code:
import re
nameString = \
Wendy, Brian, Karen, Charlene, Jeff.
wendy, brian, Karen, charlene, jeff
r1 = re.compile(rBrian)
print (r1.findall(nameString))
r1 = re.compile(rBrian)
print (r1.findall(nameString))
r2 = re.compile(rBrian, re.IGNORECASE)
print (r2.findall(nameString))
r3 ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Built-in data structures
Step2: Note that in Python, indexing starts at 0!
Step3: Dictionaries ("Hashes")
Step4: Functions, control structure... | <ASSISTANT_TASK:>
Python Code:
print "hello world"
print "hello world", 1, 2, 1 + 2
a = 1
b = 1
print "hello world", a + b
a = 1
b = "hello"
print "hello world", a + b
b = "world"
print "hello %s" % b
T = (1, 2, 3, "hello")
print T[0]
L = [1, 2, 3, "hello"]
L[0] = "Lists are mutable"
print L[0]
L.append("goodbye")
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: 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', 'mri', 'sandbox-1', 'seaice')
# 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: The data peaks around 0 and around 6. Replacing the missing values with ~3 will be inserting values into the data set that mostly don't exist in... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import time
import pandas
import random
import numpy
import matplotlib.pyplot as plt
import seaborn; seaborn.set_style('whitegrid')
import itertools
from pomegranate import *
random.seed(0)
numpy.random.seed(0)
numpy.set_printoptions(suppress=True)
%load_ext watermark
%... |
<SYSTEM_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 some training / testing pairs
Step2: Just to check, let's print the shapes of the different train/test pairs
Step3: Let's test tr... | <ASSISTANT_TASK:>
Python Code:
# Basic imports
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
import scipy.optimize as spo
import sys
from time import time
from sklearn.metrics import r2_score, median_absolute_error
from multiprocessing import Pool
import pickle
%... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: As always, let's do imports and initialize a logger and a new Bundle. See Building a System for more details.
Step2: Relevant Parameters
Step3... | <ASSISTANT_TASK:>
Python Code:
!pip install -I "phoebe>=2.0,<2.1"
%matplotlib inline
import phoebe
from phoebe import u # units
import numpy as np
import matplotlib.pyplot as plt
logger = phoebe.logger()
b = phoebe.default_binary()
print b.get(qualifier='ecc')
print b.get(qualifier='ecosw', context='component')
print... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's play with conditional probability.
Step2: P(F) is just the probability of being 30 in this data set
Step3: And P(E) is the overall proba... | <ASSISTANT_TASK:>
Python Code:
from numpy import random
random.seed(0)
totals = {20:0, 30:0, 40:0, 50:0, 60:0, 70:0}
purchases = {20:0, 30:0, 40:0, 50:0, 60:0, 70:0}
totalPurchases = 0
for _ in range(100000):
ageDecade = random.choice([20, 30, 40, 50, 60, 70])
purchaseProbability = float(ageDecade) / 100.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: Linear Modelling
Step2: Logit model
Step3: Results indicate there is some correlation between two of the independent variables
Step4: The dat... | <ASSISTANT_TASK:>
Python Code:
# opens raw data
with open ('../data/clean_data/df_profile', 'rb') as fp:
df = pickle.load(fp)
# creates copy with non-missing observations
df_active = df.loc[df.status != 'inactive', ].copy()
# examines status of users
status = df_active['status'].value_counts()
# plots chart
status... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Fun with Turtles
Step2: Looking at documentation for tutles
Step3: Using Range
Step4: Lots of turtles
Step5: Math
Step6: Random
Step7: Cha... | <ASSISTANT_TASK:>
Python Code:
spins = input("How many times did you spin? (Enter a negative number for couter-clockwise spins) ")
# Need to ensure the direction of the spin is always correct.
# This works because of the definition of the modulo operator and what happens with
# negative numbers. Keep this in mind for... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Sadržaj
Step2: [Skica
Step3: [Skica
Step4: Osnovne mjere
Step5: Primjer
Step6: Variranje klasifikacijskog praga
Step7: Krivulja preciznost... | <ASSISTANT_TASK:>
Python Code:
# Učitaj osnovne biblioteke...
import scipy as sp
import sklearn
import pandas as pd
%pylab inline
y_test = sp.random.choice((0,1), size=10); y_test
y_pred = sp.random.choice((0,1), size=10); y_pred
def cm(y_true, y_pred):
tp = 0
fp = 0
fn = 0
tn = 0
for (t, p) in zi... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Perplexity on Each Dataset
Step2: Loss vs. Epoch
Step3: Perplexity vs. Epoch
Step4: Generations
Step5: BLEU Analysis
Step6: N-pairs BLEU An... | <ASSISTANT_TASK:>
Python Code:
report_files = ["/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing10_200_512_04drb/encdec_noing10_200_512_04drb.json", "/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing10_bow_200_512_04drb/encdec_noing10_bow_200_512_04drb.json"]
log_files... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Problem 1) Examine the Training Data
Step2: Problem 1b
Step3: We will now ignore everything in the test set until we have fully optimized the ... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
sdss_df = pd.read_hdf("sdss_training_set.h5")
sns.pairplot(sdss_df, hue = 'class', diag_kind = 'hist')
from sklearn.model_selection import train_test_split
rs = 1851
# complet... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: DataFlowKernal
Step2: Hello World App
Step3: Futures
Step4: Data Dependencies
Step5: Parallelism
| <ASSISTANT_TASK:>
Python Code:
# Import Parsl
import parsl
from parsl import *
print(parsl.__version__)
# Let's create a pool of threads to execute our functions
workers = ThreadPoolExecutor(max_workers=4)
# We pass the workers to the DataFlowKernel which will execute our Apps over the workers.
dfk = DataFlowKernel(ex... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Explanation
Step2: What loss functions best recover the curve $f$ from our dataset?
Step3: Test recovery of $f$.
| <ASSISTANT_TASK:>
Python Code:
#@title Default title text
# 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 o... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Unsupervised Clustering
Step2: First use word count to try to gauge article content
Step3: The most common words are "the", "in", etc. which a... | <ASSISTANT_TASK:>
Python Code:
import os
from urllib import urlretrieve
import graphlab
URL = 'https://d396qusza40orc.cloudfront.net/phoenixassets/people_wiki.csv'
def get_data(filename='people_wiki.csv', url=URL, force_download=False):
Download and cache the fremont data
Parameters
----------
... |
<SYSTEM_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 check how many items in the dictionary.
Step2: Yes, 7949 items is right. How about question numbers? It is continuous number or not? We m... | <ASSISTANT_TASK:>
Python Code:
import csv
import gzip
import cPickle as pickle
from collections import defaultdict
import yaml
question_reader = csv.reader(open("../data/questions.csv"))
question_header = ["answer", "group", "category", "question", "pos_token"]
questions = defaultdict(dict)
for row in question_reader:
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Loading an example geomodel
Step2: Basic plotting API
Step3: Geomodel plot
Step4: Interactive plot
Step5: Granular 3-D Visualization
Step6: ... | <ASSISTANT_TASK:>
Python Code:
# Importing GemPy
import gempy as gp
# Embedding matplotlib figures in the notebooks
%matplotlib inline
# Importing auxiliary libraries
import numpy as np
import matplotlib.pyplot as plt
data_path = 'https://raw.githubusercontent.com/cgre-aachen/gempy_data/master/'
geo_model = gp.create_... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step3: Batch Normalization using tf.layers.batch_normalization<a id="example_1"></a>
Step6: We'll use the following function to create convolutional l... | <ASSISTANT_TASK:>
Python Code:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False)
DO NOT MODIFY THIS CELL
def fully_connected(prev_layer, num_units):
Create a fully connectd layer with the given layer... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Define new workspace and project
Step2: Generate a pore network
Step3: Create a geometry
Step4: Add a phase
Step5: Add a physics
Step6: The... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import openpnm as op
np.random.seed(10)
%matplotlib inline
np.set_printoptions(precision=5)
ws = op.Workspace()
ws.settings["loglevel"] = 40
proj = ws.new_project()
net = op.network.Cubic(shape=[29, 13, 1], spacing=1e-5, project=proj)
geo = op.geometry.StickAndBall(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: Update PATH_TO_TRAIN and PATH_TO_TEST to the path for rsc15_train_full.txt and rsc15_test.txt respectively
Step2: Let's take a look to the data... | <ASSISTANT_TASK:>
Python Code:
# -*- coding: utf-8 -*-
import theano
import pickle
import sys
import os
sys.path.append('../..')
import numpy as np
import pandas as pd
import gru4rec #If this shows an error probably the notebook is not in GRU4Rec/examples/rsc15/
import evaluation
# Validate that the following assert ma... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 加载模型
Step2: 调用hanlp.load进行加载,模型会自动下载到本地缓存。
Step3: 命名实体识别
Step4: 每个四元组表示[命名实体, 类型标签, 起始下标, 终止下标],下标指的是命名实体在单词数组中的下标。
Step5: 白名单词典
Step6: 强制词... | <ASSISTANT_TASK:>
Python Code:
!pip install hanlp -U
import hanlp
hanlp.pretrained.ner.ALL # 语种见名称最后一个字段或相应语料库
ner = hanlp.load(hanlp.pretrained.ner.MSRA_NER_ELECTRA_SMALL_ZH)
print(ner([["2021年", "HanLPv2.1", "为", "生产", "环境", "带来", "次", "世代", "最", "先进", "的", "多", "语种", "NLP", "技术", "。"], ["阿婆主", "来到", "北京", "立方庭", ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Dataset
Step2: Split the Data into Training and Test
Step3: Standardizing the Data
Step4: Ok, now we have the data scaled!
Step5: Building t... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from sklearn.datasets import load_iris
iris = load_iris()
type(iris)
print(iris.DESCR)
X = iris.data
X
y = iris.target
y
from keras.utils import to_categorical
y = to_categorical(y)
y.shape
y
from sklearn.model_selection import train_test_split
X_train, X_test, y_trai... |
<SYSTEM_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: 12.2.2 - Are different groups equal or not?
Step3: Note
Step4: Figure 12.5
| <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
import theano.tensor as tt
from matplotlib import gridspec
%matplotlib inline
plt.style.use('seaborn-wh... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 使用 TensorFlow Transform 预处理数据
Step2: 安装 TensorFlow Transform
Step3: Python 检查、导入和全局
Step4: 为列命名
Step5: 定义特征和架构<br>我们根据输入中列的类型来定义一个架构。这将有助于正确... | <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: Looking at the outbreak
Step2: Plotting the data
Step3: Modeling the data
Step4: Validating the model
Step5: Projecting future data
| <ASSISTANT_TASK:>
Python Code:
ESTIMATE_DAYS = 3
data_key = 'IT'
date_limit = '2020-03-17'
import pandas as pd
import seaborn as sns
sns.set()
df = pd.read_csv(f'https://storage.googleapis.com/covid19-open-data/v3/location/{data_key}.csv').set_index('date')
def get_outbreak_mask(data: pd.DataFrame, threshold: int = 10... |
<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: Function1D is the base class for 1D spectral models and FunctionMeta is ABC class that ensures all the needed parts of a model are in the class ... | <ASSISTANT_TASK:>
Python Code:
from astromodels.functions.function import Function1D, FunctionMeta, ModelAssertionViolation
class Powerlaw(Function1D):
r
description :
A simple power-law
latex : $ K~\frac{x}{piv}^{index} $
parameters :
K :
desc : ... |
<SYSTEM_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 Iris Flower Dataset
Step2: Train A Decision Tree Model
Step3: View Feature Importance
Step4: Visualize Feature Importance
| <ASSISTANT_TASK:>
Python Code:
# Load libraries
from sklearn.ensemble import RandomForestClassifier
from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt
# Load data
iris = datasets.load_iris()
X = iris.data
y = iris.target
# Create decision tree classifer object
clf = RandomForestClassifier... |
<SYSTEM_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 calendar information so we can support any netCDF calendar.
Step4: A few calendar functions to determine the number of days in each month
... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import xarray as xr
from netCDF4 import num2date
import matplotlib.pyplot as plt
print("numpy version : ", np.__version__)
print("pandas version : ", pd.__version__)
print("xarray version : ", xr.__version__)
dpm = {'noleap': [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: Transfer Learning Using Pretrained ConvNets
Step2: Data preprocessing
Step3: Prepare training and validation cats and dogs datasets
Step4: Cr... | <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: Kernel SVMs
| <ASSISTANT_TASK:>
Python Code:
from sklearn.datasets import load_digits
from sklearn.cross_validation import train_test_split
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(digits.data / 16., digits.target % 2, random_state=2)
from sklearn.svm import LinearSVC, SVC
linear_svc = LinearSVC(los... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Get the image data
Step2: Train gaussian mixture model and save it to file
Step3: Run segmentation faster by loading model from file
Step4: T... | <ASSISTANT_TASK:>
Python Code:
from imcut import pycut
import numpy as np
import scipy.ndimage
import matplotlib.pyplot as plt
from datetime import datetime
def make_data(sz=32, offset=0, sigma=80):
seeds = np.zeros([sz, sz, sz], dtype=np.int8)
seeds[offset + 12, offset + 9 : offset + 14, offset + 10] = 1
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: 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', 'miroc', 'nicam16-8s', 'toplevel')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
| <ASSISTANT_TASK:>
Python Code:
def countOddSquares(n , m ) :
return int(m ** 0.5 ) - int(( n - 1 ) ** 0.5 )
n = 5
m = 100
print("Count ▁ is ", countOddSquares(n , m ) )
<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: La forma larga (aunque no tanto), clásica y NO pythonica
Step2: La forma pythonica y a lo numpy
| <ASSISTANT_TASK:>
Python Code:
from numpy import matrix
from numpy import empty
a=matrix(((2,5),(4,6)))
b=matrix(((1,3),(6,4)))
a
b
# shape es una tupla que indica número de filas y número de columnas
suma = empty((a.shape))
#el primer for que recorre las filas
for i in range(0, a.shape[0]):
#el segundo for recorr... |
<SYSTEM_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 server instance
Step2: Login
Step3: Access the data as usual
Step4: Logout
| <ASSISTANT_TASK:>
Python Code:
import fmrest
fms = fmrest.Server('https://10.211.55.15',
user='admin',
password='admin',
database='Contacts',
layout='Contacts',
verify_ssl=False,
data_sources=[{'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: What I like most about violin plots is that they show you the entire distribution of your data. If data inputs violate your assumptions (e.g. mu... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from fuzzywuzzy import fuzz
import numpy as np
# some settings to be used throughout the notebook
pd.set_option('max_colwidth', 70)
wf_colors = ["#C7DEB1","#9763A4"]
# make some fake data for a de... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We use a pre-existing database containing a channel library and pipeline we have established.
Step2: Calibrating Mixers
Step3: If the plot ser... | <ASSISTANT_TASK:>
Python Code:
from QGL import *
from auspex.qubit import *
cl = ChannelLibrary("my_config")
pl = PipelineManager()
spec_an = cl.new_spectrum_analzyer("SpecAn", "ASRL/dev/ttyACM0::INSTR", cl["spec_an_LO"])
cal = MixerCalibration(q2, spec_an, mixer="measure")
cal.calibrate()
cals = RabiAmpCalibration(... |
<SYSTEM_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: As we saw in the tut-events-vs-annotations tutorial, we can extract an
Step3: <div class="alert alert-info"><h4>Note</h4><p>We could a... | <ASSISTANT_TASK:>
Python Code:
import os
import mne
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False).crop(tmax=60)
ev... |
<SYSTEM_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 Python Function uN represents the expansion (2), and the printed
Step2: Differentiation
Step3: where uN1 $=u_N^{(1)}$ and uN2 $=u_N^{(2)}$... | <ASSISTANT_TASK:>
Python Code:
from shenfun import *
import sympy as sp
x = sp.Symbol('x')
ue = sp.sin(sp.pi*x)
N = 16
SN = FunctionSpace(N, 'C')
uN = Function(SN, buffer=ue)
uN
SM = FunctionSpace(0, 'C')
uM = Function(SM, buffer=ue, abstol=1e-16, reltol=1e-16)
print(uM[:N] - uN[:N])
print(len(uM))
uN1 = project(Dx(u... |
<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: Medical tests
Step4: Now we can create a Test object with parameters chosen for demonstration purposes (most medical tests are better than this... | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function, division
from thinkbayes2 import Pmf, Suite
from fractions import Fraction
class Test(Suite):
Represents beliefs about a patient based on a medical test.
def __init__(self, p, s, t, label='Test'):
# initialize the prior probabil... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Selecting parts of a tree
Step2: Fuzzy tip label matching
Step3: Get TreeNode object from node idx label
Step4: Get tip labels from a node id... | <ASSISTANT_TASK:>
Python Code:
import toytree
import toyplot
import numpy as np
# load a tree for this tutorial
tre = toytree.tree("https://eaton-lab.org/data/Cyathophora.tre")
# store a rooted copy of tre (more on this later...)
rtre = tre.root(['33588_przewalskii', '32082_przewalskii'])
rtre.draw();
# a multitree st... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Ejemplo
Step2: Shooting method
Step3: Ejemplo 2
Step4: Ejemplo 3
Step5: Ejemplo 4
| <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Un ejemplo de función solución con condiciones de borde marcadas y pendiente s
def y(x):
return np.exp(-x**2)*np.sin(x)
xx = np.linspace(0, 1, 100)
yy = y(xx)
plt.plot(xx,yy, lw=2)
plt.plot([0, 1] , [y(0), y(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:
Step2: The following function selects the columns I need.
Step3: Read data from Cycle 1.
Step4: Read data from Cycle 2.
Step5: Read data from Cycle ... | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function, division
import numpy as np
import pandas as pd
import thinkstats2
import thinkplot
import statsmodels.formula.api as smf
from iso_country_codes import COUNTRY
%matplotlib inline
def read_cycle(filename):
Reads a file containing ESS data and sel... |
<SYSTEM_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 in data.
Step2: Calculate Robinson-Foulds distance, and tree length.
Step3: Calculate RF score, pairwise over all trees in sample.
| <ASSISTANT_TASK:>
Python Code:
import dendropy
from dendropy.utility.fileutils import find_files
import numpy as np
taxa = dendropy.TaxonSet()
ours = dendropy.Tree.get_from_path('../best.phy', 'newick', taxon_set=taxa)
non_ml = dendropy.Tree.get_from_path('../Trees/MLE/ExaML_result.SquamataPyron.MLE.2b', 'newick', ta... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
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', 'cams', 'sandbox-1', 'ocean')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "emai... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Reading the rock property catalog
Step2: Plotting!
| <ASSISTANT_TASK:>
Python Code:
import requests
import pandas as pd
class RPC(object):
def __init__(self):
pass
def _query_ssw(self, filters, properties, options):
base_url = "http://www.subsurfwiki.org/api.php"
q = "action=ask&query=[[RPC:%2B]]"
q += ''.join(filters... |
<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: First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The lab... | <ASSISTANT_TASK:>
Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
%matplotlib inline
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import tarfile
from IPython.display import display,... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Measure response times and plot results
| <ASSISTANT_TASK:>
Python Code:
rc_url= 'https://v100rc2.demo.encodedcc.org/'
%%capture --no-stderr --no-display output
prod_url="https://test.encodedcc.org"
qa = qancode.QANCODE(rc_url=rc_url, prod_url=prod_url)
num_trials = 50
item_types = [
"/search/?type=Experiment&biosample_ontology.term_name=whole+organism", ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Opageve 2. De expressies uit opdracht 3 en 4 (in de slides) hebben een eigen naam,
Step2: Opageve 4. Een tautologie is een expressie die altijd... | <ASSISTANT_TASK:>
Python Code:
## Opgave 1 - uitwerking
for A in [False, True]:
for B in [False, True]:
print(A, B, not(A or B))
## Opgave 3 - uitwerking
# controle -(-A | -B) == A & B
for A in [False, True]:
for B in [False, True]:
print(A, B, not(not A or not B), A and B)
# controle door comp... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Function definitions. Here we consider a hard-coded two-layer perception with one hidden layer, using the hyperbolic tangent as activation funct... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
function_select = 5
def myfun(x):
functions = {
1: np.power(x,2), # quadratic function
2: np.sin(x), # sinus
3: np.sign(x), # signum
4: np.exp(x), # expone... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Descriptive analysis
Step2: Create the categorical variable
Step3: Looking at the distribution of countries by the new categorical variable in... | <ASSISTANT_TASK:>
Python Code:
# Import all ploting and scientific library,
# and embed figures in this file.
%pylab inline
# Package to manipulate dataframes.
import pandas as pd
# Nice looking plot functions.
import seaborn as sn
# Read the dataset.
df = pd.read_csv('data/gapminder.csv')
# Set the country name as the... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 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:
Step1: The observed magnitude of the RV variation depends crucially on the angle between the line-of-sight (LOS) and the orbit, particularly the inclin... | <ASSISTANT_TASK:>
Python Code:
# Import python modules.
from __future__ import division
from itertools import izip
import time
import datetime
import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
import astropy.table as table
import astropy.io.ascii as ascii
from PyAstronomy.pyasl import KeplerE... |
<SYSTEM_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. Download and plot the data on US CPI
Step2: 3. Fit the model with maximum likelihood
Step3: It's a good fit. We can also get the series of ... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import theano
import theano.tensor as tt
import pymc3 as pm
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
import pandas as pd
from pandas_datareader.data import DataReader
from pandas.plotting import register_matplotlib_converters
plt.s... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Init
Step2: Selecting genomes based on GC
Step3: Copying genomes
Step4: Indexing genomes
| <ASSISTANT_TASK:>
Python Code:
workDir = '/home/nick/notebook/SIPSim/dev/bac_genome3/'
SIPSimExe = '/home/nick/notebook/SIPSim/SIPSim'
genomeDir = '/home/nick/notebook/SIPSim/dev/bac_genome1210/genomes/'
#genomeTable = '/var/seq_data/ncbi_db/genome/prok-bac_filt_rand.txt'
import os,sys
import numpy as np
import pandas... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: First, let's gather some data. We use the PubMed database of medical paper.
Step2: Download a toy corpus (224 structured abstracts, 200 KB com... | <ASSISTANT_TASK:>
Python Code:
#%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py
%load_ext watermark
# for reproducibility
%watermark -a 'Paul Willot' -mvp numpy,scipy,spacy
!wget https://www.dropbox.com/s/lhqe3bls0mkbq57/pubmed_result_548899.txt.zip -P ./data/
!unzip -o ./data/pubmed... |
<SYSTEM_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', 'cnrm-cerfacs', 'sandbox-1', 'ocnbgchem')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Problem statement
Step2: Next, we need to define the bounds of the dimensions of the search space we want to explore
Step4: Optimize all the t... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import cross_val_score
boston = load_boston()
X, y = boston.data, boston.target
n_features = ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Read the survey data
Step2: Create target group 'Latin America'
Step4: Generic function to plot barchart for any categorical feature on any ta... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white")
sns.set_context("talk")
df = pd.read_csv('raw/2016-17-ClassCentral-Survey-data-noUserText.csv', decimal=',', encoding = "ISO-8859-1")
df['Which region of the world are you in?'].value_counts... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Lab Task 1
Step2: A "vector" or "rank-1" tensor is like a list of values. A vector has 1-axis
Step3: A "matrix" or "rank-2" tensor has 2-axes
... | <ASSISTANT_TASK:>
Python Code:
import tensorflow as tf
import numpy as np
print("TensorFlow version: ",tf.version.VERSION)
# This will be an int32 tensor by default; see "dtypes" below.
rank_0_tensor = tf.constant(4)
print(rank_0_tensor)
# Let's make this a float tensor.
rank_1_tensor = tf.constant([2.0, 3.0, 4.0])
p... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Below I'm plotting an example image from the MNIST dataset. These are 28x28 grayscale images of handwritten digits.
Step2: We'll train an autoe... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
img = mnist.train.images[0]
plt.imshow(img.reshape((28, 28)), cmap='... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: OK, now let's write a traitlets class that does the same thing
Step4: Roadmap
Step5: Trying it out...
Step6: Testing the result
| <ASSISTANT_TASK:>
Python Code:
import json
import jsonschema
simple_schema = {
"type": "object",
"properties": {
"foo": {"type": "string"},
"bar": {"type": "number"}
}
}
good_instance = {
"foo": "hello world",
"bar": 3.141592653,
}
bad_instance = {
"foo" : 42,
"bar" : "string... |
<SYSTEM_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 have seen how to input data from csv and xls files -- either online or from our computer and through APIs. Sometimes the data is only availab... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd # data package
import matplotlib.pyplot as plt # graphics
import datetime as dt # date tools, used to note current date
%matplotlib inline
import requests # you might have to install this
url = 'https://newyork.cra... |
<SYSTEM_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 Keras model
Step2: Next, define the feature columns. mother_age and gestation_weeks should be numeric.
Step3: We can visualize the DNN ... | <ASSISTANT_TASK:>
Python Code:
# Ensure the right version of Tensorflow is installed.
!pip freeze | grep tensorflow==2.1
# change these to try this notebook out
BUCKET = 'cloud-training-demos-ml'
PROJECT = 'cloud-training-demos'
REGION = 'us-central1'
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Vi tegner for å finne $x_0$
Step2: Vi ser en løsning nær $4$, så vi velger $x_0=4$.
Step3: Vi kan beregne det en om en
Step4: Når stopper vi?... | <ASSISTANT_TASK:>
Python Code:
def f(x):
return log(x) + cos(x) - 1
x = linspace(1,20,200)
y = f(x)
plot(x,y, lw=2)
plot([1,20],[0,0], lw=2, color='k')
ax = gca()
mpld3.display()
def fder(x):
return 1/x - sin(x)
x0=4
x1=x0- f(x0)/fder(x0)
print(x1)
x2=x1-f(x1)/fder(x1)
print(x2)
x3=x2-f(x2)/fder(x2)
print(x3... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Word Cloud from RSS feed titles
Step2: 2) HTML Parser
Step4: Modules for fetching and parsing HTML content
Step5: The get_title function shou... | <ASSISTANT_TASK:>
Python Code:
# -*-coding: utf-8 -*-
import feedparser
import re
import string
# Create the regular expressions
reg1 = re.compile(r'<br />') #Regex to replace <br /> with \n (see reg1.sub)
reg2 = re.compile(r'(<!--.*?-->|<[^>]*>)') #Regex to clean all html tags (anything with <something>)
#alternative ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Target Configuration
Step2: Experiments Configuration
Step3: Tests execution
| <ASSISTANT_TASK:>
Python Code:
import logging
from conf import LisaLogging
LisaLogging.setup()
import os
import json
from env import TestEnv
from executor import Executor
# Setup a target configuration
my_target_conf = {
# Target platform and board
"platform" : 'linux',
"board" : 'juno',
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Na sequência, dois predicados
Step2: Assim, podemos calcular a probabilidade de um novo indivíduo ser do sexo masculino.
Step3: O que $0,8$ (o... | <ASSISTANT_TASK:>
Python Code:
PDSexo = ProbDist(
Sexo_M=4,
Sexo_F=1
)
PDSexo
def sexo_m(r): return 'Sexo_M' in r
def sexo_f(r): return 'Sexo_F' in r
P(sexo_m, PDSexo)
PDIdades = ProbDist(
Idade_A=4,
Idade_B=1,
Idade_C=0,
Idade_D=0
)
PDIdades
def idade_A(r) : return 'Idade_A' in r
def idade_... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Funções de Ativação
Step2: Funções Auxiliares
Step3: Funções de Custo
Step4: Inicialização de Pesos
Step5: Exemplo 2
Step6: Gradient Checki... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import _pickle as pkl
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.datasets.samples_generator import make_blobs, make_circles, make_moons, make_classification
from sklearn.metrics import accuracy_score
from sklearn.preprocessing 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: Let's have a look at the csv files we created in the previous notebooks that we will use for training/eval.
Step2: Create TensorFlow model usin... | <ASSISTANT_TASK:>
Python Code:
PROJECT = "cloud-training-demos" # Replace with your PROJECT
BUCKET = "cloud-training-bucket" # Replace with your BUCKET
REGION = "us-central1" # Choose an available region for Cloud MLE
TFVERSION = "1.14" # TF version for CMLE to use
import os
os.environ["BUCK... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Update
Step2: Union of Dec2016 and Jan2017 version overlapping UGC's list
Step3: Total Journals in Beall's list
Step4: Jan 2017 version
Step5... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
from fuzzywuzzy import fuzz
import re
from fuzzywuzzy import process
pd.set_option('display.max_colwidth', -1)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
def clean_name(x):
## Remove things in braces such as :
## Journal ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Deep Learning activation functions examined below
Step2: 1. ReLU
Step3: 2. Leaky ReLU
Step4: 3. sigmoid
Step5: 4. tanh
| <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
#Create array of possible z values
z = np.linspace(-5,5,num=1000)
def draw_activation_plot(a,quadrants=2,y_ticks=[0],two_quad_y_lim=[0,5], four_quad_y_lim=[-1,1]):
Draws plot of activation function
Par... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Processing sample
Step2: Plotting
Step3: In the above figures, first image represents observed degree distribution of random graph $G(n, p)$ a... | <ASSISTANT_TASK:>
Python Code:
import os, sys, math
import collections as collcs
# append the path so that modules can be properly imported
sys.path.append('../src/')
import graph
import algorithms.erdos_renyi as er
import algorithms.newman_model as nm
reload(graph)
reload(er)
reload(nm)
# generate a random graph havin... |
<SYSTEM_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. Initialization of setup
Step2: 2. Initial condition
Step3: 3. Solution for the homogeneous problem
Step4: 4. Finite Volumes solution
| <ASSISTANT_TASK:>
Python Code:
# Import all necessary libraries, this is a configuration step for the exercise.
# Please run it before the simulation code!
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Show the plots in the Notebook.
plt.switch_backend("nbagg")
# Initial... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Verify CSV files exist
Step2: Create Keras model
Step5: Make dataset of features and label from CSV files.
Step7: Create input layers for raw... | <ASSISTANT_TASK:>
Python Code:
import datetime
import os
import shutil
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
print(tf.__version__)
%%bash
ls *.csv
%%bash
head -5 *.csv
# Determine CSV, label, and key columns
CSV_COLUMNS = ["weight_pounds",
"is_male",
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Read the data and get a row count. Data source
Step2: SymPy
Step3: This example was gleaned from
Step4: What is the probability that the tem... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import sys
print('Python version ' + sys.version)
print('Pandas version ' + pd.__version__)
print('Numpy version ' + np.__version__)
file_path = r'data\T100_2015.csv.gz'
df = pd.read_csv(file_path, header=0)
df.count()
df.head(n=10)
df = pd.read_csv... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 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: Sparse 2d interpolation
Step2: The following plot should show the points on the boundary and the single point in the interior
Step3: Use meshg... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set_style('white')
from scipy.interpolate import griddata
x1=np.arange(-5,6)
y1=5*np.ones(11)
f1=np.zeros(11)
x2=np.arange(-5,6)
y2=-5*np.ones(11)
f2=np.zeros(11)
y3=np.arange(-4,5)
x3=5*np.on... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Hierarchical Agglomerative Clustering - Complete Linkage Clustering
Step2: <br>
Step3: <br>
Step4: b) Condensed distance matrix (correct)
Ste... | <ASSISTANT_TASK:>
Python Code:
%load_ext watermark
%watermark -a "Sebastian Raschka" -d -v
import pandas as pd
import numpy as np
np.random.seed(123)
variables = ['X', 'Y', 'Z']
labels = ['ID_0','ID_1','ID_2','ID_3','ID_4']
X = np.random.random_sample([5,3])*10
df = pd.DataFrame(X, columns=variables, index=labels)
df
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Now lets create some lightcurves
Step2: In terms of LYRA, the server only allows you to download an entire day of data at a time. We can match ... | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function, division
import numpy as np
import sunpy
from sunpy import lightcurve as lc
import matplotlib.pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
goes_lightcurve = lc.GOESLightCurve.create('2011-06-07 06:00','2011-06-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: Enable DataFlow API for your GKE cluster
Step2: Configure the TFX pipeline example
Step3: Submit pipeline for execution on the Kubeflow cluste... | <ASSISTANT_TASK:>
Python Code:
!pip3 install 'tfx==0.15.0' --upgrade
!python3 -m pip install 'kfp>=0.1.35' --quiet
# Directory and data locations (uses Google Cloud Storage).
import os
_input_bucket = '<your gcs bucket>'
_output_bucket = '<your gcs bucket>'
_pipeline_root = os.path.join(_output_bucket, 'tfx')
# Google... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: One-hot encoding
Step2: Data argumentation
Step3: Range of image
Step4: Remove obstacle feature
Step5: Check convert image
Step6: Data shuf... | <ASSISTANT_TASK:>
Python Code:
current_dir = os.getcwd()
data_dir = os.listdir("./train/")
def image_road(data_dir):
img_matrix = []
label = []
index = 0
for data_label in data_dir:
category_list = os.listdir(os.getcwd()+"/train/"+data_label)
for data in category_list:
img = ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Checkerboard
Step2: Use vizarray to visualize a checkerboard of size=20 with a block size of 10px.
Step3: Use vizarray to visualize a checkerb... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import antipackage
import github.ellisonbg.misc.vizarray as va
def checkerboard(size):
a = np.zeros((size,size), dtype = np.float)
b = 2
if size % 2 != 0:
for element in np.ndi... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: PCA
Step2: Solving b vector
| <ASSISTANT_TASK:>
Python Code:
import pandas
df = pandas.read_csv('muct76-opencv.csv', header=0, usecols=np.arange(2,154), dtype=float)
df.head()
X = df.iloc[:, ::2].values
Y = df.iloc[:, 1::2].values
d = np.hstack((X,Y))
d.shape
import sys
threshold = 1.0e-8
def center(vec):
pivot = int(vec.shape[0]/2)
meanx =... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Sum up an array of numbers using python
Step2: Use cython, without changing the code
Step3: Does making s a local variable help?
| <ASSISTANT_TASK:>
Python Code:
%load_ext cython
import array
a = array.array('l',range(100))
s = 0
def python_sum(a):
global s
s = 0
for i in range(len(a)):
for j in range(10000):
s = s + a[i]
return s
%timeit python_sum(a)
%%cython --annotate
def cython_sum1(a):
global s
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: This map is an example of an unprojected plot
Step2: But there is a better way
Step3: For a list of projections implemented in geoplot, refer ... | <ASSISTANT_TASK:>
Python Code:
import geopandas as gpd
import geoplot as gplt
%matplotlib inline
# load the example data
contiguous_usa = gpd.read_file(gplt.datasets.get_path('contiguous_usa'))
gplt.polyplot(contiguous_usa)
boroughs = gpd.read_file(gplt.datasets.get_path('nyc_boroughs'))
gplt.polyplot(boroughs)
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 we have the weatherData object with its data variable containing four extra columns, i.e. Month, _LastYearsAvg, _LastYearsStd, and _ThisYear... | <ASSISTANT_TASK:>
Python Code:
%pylab inline
import sys
sys.path.insert(0,"../lib/")
from scipy.stats import norm
from climateData import WeatherData
weatherData = WeatherData(years=[1900,2014], optimiseFactor=True)
weatherData.data.head()
data = weatherData.data[ weatherData.data["Year"] >= 1980 ]
data = data[ np.is... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.