Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
400 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import sys
# Add a new path with needed .py files.
sys.path.insert(0, 'C:\Users\Dominik\Documents\GitRep\kt-2015-DSPHandsOn\MedianFilter\Python')
import functions
import gitInformation
%matplotlib inline
gitInformation.printInformation()... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Visualization of the Error rate with different window lengths and a sine with wave number 5 (128 samples)
Step2: As you can see, the error is h... |
401 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
import re
import math
from sys import argv
sns.set_style("whitegrid")
sns.set_style("ticks")
sns.set_context("poster")
def read_clusters_tsv(path):
df = pd.read_csv(path, ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Seaborn settings
Step2: Function to read tsv of clusters and fix cluster size column
Step3: Function to plot histograms of cluster size
Step4:... |
402 | <ASSISTANT_TASK:>
Python Code:
from sklearn.datasets import make_classification
X, y = make_classification()
from reskit.core import Pipeliner
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Setting steps for our pipelines and parameters for grid search
Step2: Setting a cross-validation for grid searching of hyperparameters and for ... |
403 | <ASSISTANT_TASK:>
Python Code:
import george
george.__version__
import numpy as np
import matplotlib.pyplot as plt
def objective(theta):
return -0.5 * np.exp(-0.5*(theta - 2)**2) - 0.5 * np.exp(-0.5 * (theta + 2.1)**2 / 5) + 0.3
t = np.linspace(-5, 5, 5000)
plt.figure(figsize=(8, 5))
plt.plot(t, objective(t))
plt.... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: In this tutorial, we'll show a very simple example of implementing "Bayesian optimization" using george.
Step2: Now, for the "Bayesian" optimiz... |
404 | <ASSISTANT_TASK:>
Python Code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# We'll also import a few standard python libraries
from matplotlib import pyplot
import numpy as np
import time
# These are the droids you ... | <SYSTEM_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 might see a warning saying that caffe2 does not have GPU support. That means you are running a CPU-only build. Don't be alarmed - anything C... |
405 | <ASSISTANT_TASK:>
Python Code:
# Make sure the base overlay is loaded
from pynq import Overlay
Overlay("base.bit").download()
from pynq.iop import Arduino_Analog
from pynq.iop import ARDUINO
from pynq.iop import ARDUINO_GROVE_A1
from pynq.iop import ARDUINO_GROVE_A4
analog1 = Arduino_Analog(ARDUINO,ARDUINO_GROVE_A1)
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 1. Instantiate individual analog controller
Step2: 2. Read voltage value out
Step3: 3. Read raw value out
Step4: 4. Logging multiple sample v... |
406 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.read_csv('./input.gtf', sep='\t', header = None)
df
replace_dict = {0 : 'reference', 1 : 'source', 2 : 'feature', 3 : 'start', 4 : 'end', 5 : 'score', 6 : 'strand', 7 : 'frame', 8 : 'attributes'}
df.rename(columns = replace_dict, inplace = True)
df
df.drop([... | <SYSTEM_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) Leggere il file GTF
Step2: NB
Step3: 4) Eliminare le colonne source e score e sostituire l'identificatore ENm006 con l'identificatore ENCOD... |
407 | <ASSISTANT_TASK:>
Python Code:
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
%pylab inline
import matplotlib.pylab as plt
import numpy as np
from distutils.version import StrictVersion
import sklearn
print(sklearn.__version__)
assert StrictVersion(sklearn.__version__ ) >= StrictVersion('0.18.1')
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Iris mit Neuronalen Netzwerken
Step2: Wir probieren unser Modell mit dem Iris Dataset
Step3: Wie sollen wir das interpretieren? Damit können w... |
408 | <ASSISTANT_TASK:>
Python Code:
# Učitaj osnovne biblioteke...
import sklearn
import mlutils
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
%pylab inline
from collections import Counter
class VotingClassifierDIY(object):
SCHEME_COUNTING = "counting"
SCHEME_AVERAGING = "averaging"
... | <SYSTEM_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. Ansambli (glasovanje)
Step2: (b)
Step3: Q
Step4: Razred koji implementira stablo odluke jest tree.DecisionTreeClassifier. Prvo naučite sta... |
409 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import scipy as sp
from scipy import linalg as la
import scipy.sparse.linalg as spla
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib as mpl
mpl.rcParams['font.size'] = 14
mpl.rcParams['axes.labelsize'] = 20
mpl.rcParams['xtick.labelsize'] = 14
mpl.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: <div id='intro' />
Step2: Using a Jacobi/Gauss-Seidel iterative solver
Step3: Using GMRes of SciPy
Step4: Computing the relative residues
Ste... |
410 | <ASSISTANT_TASK:>
Python Code:
def first_order(t,A,k):
First-order kinetics model.
return A*(1 - np.exp(-k*t))
def first_order_r(param,t,obs):
Residuals function for first-order model.
return first_order(t,param[0],param[1]) - obs
def fit_model(t,obs,param_guesses=(1,1)):
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step3: Parameter uncertainty
Step4: Generate 1,000 simulated data sets where each experimental point is drawn from a normal distribution with a mean o... |
411 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import YouTubeVideo
# WATCH THE VIDEO IN FULL-SCREEN MODE
YouTubeVideo("JXJQYpgFAyc",width=640,height=360) # Numerical integration
# Put your code here
import math
Nstep = 10
begin = 0.0
end = 3.1415926
dx = (end-begin)/Nstep
sum = 0.0
xpos = 0.0
for i in range(Nst... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Question 1
Step2: Question 2
|
412 | <ASSISTANT_TASK:>
Python Code:
import pyautogui
# Writes to the cell right below (70 pixels down)
pyautogui.moveRel(0,70)
pyautogui.click()
pyautogui.typewrite('Hello world!')
# Writes to the cell right below (70 pixels down)
pyautogui.moveRel(0,70)
pyautogui.click()
pyautogui.typewrite('Hello world!', interval=0.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: This lesson will control all the keyboard controlling functions in the module.
Step2: Again, to simulate more human interaction, we can an inte... |
413 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from pylab import *
np.random.seed(2)
pageSpeeds = np.random.normal(3.0, 1.0, 1000)
purchaseAmount = np.random.normal(50.0, 10.0, 1000) / pageSpeeds
scatter(pageSpeeds, purchaseAmount)
x = np.array(pageSpeeds)
y = np.array(purchaseAmount)
p4 = np.poly1d(np.polyfit(x, y... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: numpy has a handy polyfit function we can use, to let us construct an nth-degree polynomial model of our data that minimizes squared error. Let'... |
414 | <ASSISTANT_TASK:>
Python Code:
import pyisc;
import visisc;
import numpy as np
import datetime
from scipy.stats import poisson, norm, multivariate_normal
%matplotlib wx
from pylab import plot, figure
n_sources = 10
n_events = 20
num_of_normal_days = 200
num_of_anomalous_days = 10
data = None
days_list = [num_of_normal... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Event Frequency Data
Step2: Flat Event Data Model
Step3: Second we transform numpy array to a pyisc data object. The data object consists of t... |
415 | <ASSISTANT_TASK:>
Python Code:
print "Hello World!"
print 'Hello World!'
# This is a comment.
print 'This is not a comment.'
'Something smells funny.'
print 2 + 2
# Spaces between characters don't matter
print 2+2
2 + 2
print "2 + 2"
print 2.1 + 2 # The most precise value is a float.
(3.*10. - 26.)/5.
(3*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:
Step1: Python as a calculator
Step2: Defining and using variables
Step3: Some more mathy operators
Step4: Comparisons
Step5: Truthiness
Step6: 0j ... |
416 | <ASSISTANT_TASK:>
Python Code:
# Some imports we will need below
import numpy as np
from devito import *
import matplotlib.pyplot as plt
%matplotlib inline
nx, ny = 100, 100
grid = Grid(shape=(nx, ny))
u = TimeFunction(name='u', grid=grid, space_order=2, save=200)
c = Constant(name='c')
eqn = Eq(u.dt, c * u.laplace... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Solver implementation
Step2: To represent the density, we use a TimeFunction -- a scalar, discrete function encapsulating space- and time-varyi... |
417 | <ASSISTANT_TASK:>
Python Code:
'''
The code in this cell opens up the file skydiver_time_velocities.csv
and extracts two 1D numpy arrays of equal length. One array is
of the velocity data taken by the radar gun, and the second is
the times that the data is taken.
'''
import numpy as np
skydiver_time, skydiver_velocit... | <SYSTEM_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 second part of the challenge
Step3: Assignment wrapup
|
418 | <ASSISTANT_TASK:>
Python Code:
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from time import time
from IPython.display import display # Allows the use of display() for DataFrames
# Import supplementary visualization code visuals.py
import visuals as vs
# Pretty display for notebo... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Implementation
Step2: Featureset Exploration
Step3: For highly-skewed feature distributions such as 'capital-gain' and 'capital-loss', it is ... |
419 | <ASSISTANT_TASK:>
Python Code:
2 #Integer yani tam sayı
2.0 #Float yani ondalıklı sayı
1.67 #Yine bir float
4 #Yine bir int(Integer)
'Bu bir string'
"Bu da bir string"
True #Boolean
False #Boolean
print('test')
print('test2')
print("deneme123")
print(1)
print(2.55)
print(1, 2, 'Hello World!')
print('\n')
print(1, '\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: print Fonksiyonu, Özel Karakterler ve str Fonksiyonu
Step2: Mantıksal İşlemler
Step3: Matematiksel İşlemler
Step4: Yönü Yok kavramını açacağı... |
420 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas import Series, DataFrame
from numpy.random import randint
dices = randint(1,7,(5,2))
dices
diceroll = DataFrame(dices, columns=['dice1','dice2'])
diceroll
city = Series(['Tokyo','Osaka','Nagoya','Okinawa... | <SYSTEM_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次元の array を DataFrame に変換する例です。
Step2: columns オプションで、各列の column 名を指定します。
Step3: Series オブジェクトから DataFrame を作成する例です。
Step4: 各列の column 名と対応す... |
421 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import pandas.io.data as pdd
from urllib import urlretrieve
%matplotlib inline
try:
index = pdd.DataReader('^GDAXI', data_source='yahoo', start='2007/3/30')
# e.g. the EURO STOXX 50 ticker symbol -- ^SX5E
except:
index = pd.read_cs... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The convenience function DataReader makes it easy to read historical stock price data from Yahoo! Finance (http
Step2: pandas strength is the h... |
422 | <ASSISTANT_TASK:>
Python Code:
import csv
import re
import googlemaps
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
db_password = 'somestring'
gapi_key = 'anotherstring'
points = []
positions = []
project_no = False
while project_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: Setting initial variables
Step2: User input for Project ID
Step4: SQLAlchemy code
Step5: Looping through the data of each Location ID
Step6: ... |
423 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
reviews = pd.read_csv('reviews.txt', header=None)
labels = pd.read_csv('labels.txt', header=None)
from collections import Counter
total_counts = # bag of words her... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Preparing the data
Step2: Counting word frequency
Step3: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in... |
424 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
from scipy import linalg as la
def KDparams(F):
u, s, v = svd(F)
Rxy = s[0]/s[1]
Ryz = s[1]/s[2]
K = (Rxy-1)/(Ryz-1)
D = sqrt((Rxy-1)**2 + (Ryz-1)**2)
return K, D
yearsec = 365.25*24*3600
sr = 3e-15
times = linspace(0.00000001,10,20)
alphas = linsp... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Here we will examine strain evolution during transpression deformation. Transpression (Sanderson and Marchini, 1984) is considered as a wrench o... |
425 | <ASSISTANT_TASK:>
Python Code:
import pprint
def primes():
generate successive prime numbers (trial by division)
candidate = 1
_primes_so_far = [2] # first prime, only even prime
yield _primes_so_far[0] # share it!
while True:
candidate += 2 # check odds only from now on
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: Silicon Forest Math Series<br/>Oregon Curriculum Network
Step2: The above algorithm is known as "trial by division".
Step3: How does Euclid'... |
426 | <ASSISTANT_TASK:>
Python Code:
from torchvision import utils
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import torch, torch.nn as nn
import torch.nn.functional as F
from itertools import count
from IPython import display
import warnings
import time
plt.rcParams.update({'axes.titlesize': 'smal... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Generative adversarial nets 101
Step2: Discriminator
Step5: Training
Step6: Auxilary functions
Step7: Training
Step8: Evaluation
|
427 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import matplotlib as plt
# draw plots in notebook
%matplotlib inline
# make plots SVG (higher quality)
%config InlineBackend.figure_format = 'svg'
# more time/compute intensive to parse dates. but we know we definitely have/need them
df = pd.read_csv('data/sf_listings.... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Star Schema (facts vs. dimensions)
Step2:
Step3: Pandas Resample String convention
Step4: Correlation vs. Regression
Step5: R-squared
Step6... |
428 | <ASSISTANT_TASK:>
Python Code:
import warnings
warnings.filterwarnings("ignore")
import os
import numpy as np
import xarray as xr
import dask
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
%matplotlib inline
import holoviews as hv
hv.notebook_extension("matplotlib")
from landlab import RasterMo... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Part 1
Step2: Next we make our layer elevations. We will make 20 layers that are 5 meters thick. Note that here, as with most Landlab component... |
429 | <ASSISTANT_TASK:>
Python Code:
%run "../Functions/1. Game sessions.ipynb"
import unidecode
accented_string = "Enormément"
# accented_string is of type 'unicode'
unaccented_string = unidecode.unidecode(accented_string)
unaccented_string
# unaccented_string contains 'Malaga'and is of type 'str'
_rmDF = rmdf1522
userId ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Tests
Step2: getUserSessions tinkering
Step3: getTranslatedForm tinkering - from 0.4 GF correct answers
Step4: print("part100="+str(part100.h... |
430 | <ASSISTANT_TASK:>
Python Code:
with open('data/inflammation-01.csv', 'r') as f:
snippet = f.readlines()[:3]
print(*snippet)
import numpy as np
data = np.loadtxt(fname='data/inflammation-01.csv', delimiter=',') # Comma-separated...
print(data)
type(data)
data.shape
", ".join(dir(data))
print(data * 2)
data[0:3... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: This construct, a with statement, addresses the age-old problem of cleaning up file descriptors. In general, a with context expects the object b... |
431 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from parcels import FieldSet, ParticleSet, JITParticle, AdvectionRK4
from datetime import timedelta, datetime
filenames = {'U': "GlobCurrent_example_data/20*.nc",
'V': "GlobCurrent_example_data/20*.nc"}
variables = {'U': 'eastward_eulerian_current_velocity... | <SYSTEM_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 then instatiate a FieldSet with the velocity field data from GlobCurrent dataset.
Step2: Next, we instantiate a ParticeSet composed of JITPa... |
432 | <ASSISTANT_TASK:>
Python Code:
# Examples are given for numpy. This code also setups ipython/jupyter
# so that numpy arrays in the output are displayed as images
import numpy
from utils import display_np_arrays_as_images
display_np_arrays_as_images()
ims = numpy.load('./resources/test_images.npy', allow_pickle=False)
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load a batch of images to play with
Step2: Composition of axes
Step3: Decomposition of axis
Step4: Order of axes matters
Step5: Meet einops.... |
433 | <ASSISTANT_TASK:>
Python Code:
PATH='data/aclImdb/'
TRN_PATH = 'train/all/'
VAL_PATH = 'test/all/'
TRN = f'{PATH}{TRN_PATH}'
VAL = f'{PATH}{VAL_PATH}'
%ls {PATH}
trn_files = !ls {TRN}
trn_files[:10]
review = !cat {TRN}{trn_files[6]}
review[0]
!find {TRN} -name '*.txt' | xargs cat | wc -w
!find {VAL} -name '*.txt' | ... | <SYSTEM_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 look inside the training folder...
Step2: ...and at an example review.
Step3: Sounds like I'd really enjoy Zombiegeddon...
Step4: Befor... |
434 | <ASSISTANT_TASK:>
Python Code:
%load_ext autoreload
%autoreload 2
import lxmls.readers.sentiment_reader as srs
scr = srs.SentimentCorpus("books")
import lxmls.classifiers.multinomial_naive_bayes as mnbb
mnb = mnbb.MultinomialNaiveBayes()
params_nb_sc = mnb.train(scr.train_X,scr.train_y)
y_pred_train = mnb.test(scr.tra... | <SYSTEM_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 will load the data in a bag-of-words representation where rare words (occurring less than 5 times in the training data) are removed.
Step2:... |
435 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
import IPython
import sys
from music21 import *
import numpy as np
from grammar import *
from qa import *
from preprocess import *
from music_utils import *
from data_utils import *
from keras.models import load_model, Model
from keras.layers 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: 1 - Problem statement
Step2: We have taken care of the preprocessing of the musical data to render it in terms of musical "values." You can inf... |
436 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from parcels import Variable, Field, FieldSet, ParticleSet, ScipyParticle, AdvectionRK4, plotTrajectoriesFile
import numpy as np
from datetime import timedelta as delta
import netCDF4
import matplotlib.pyplot as plt
# Velocity fields
fname = r'GlobCurrent_example_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: In this specific example, particles will be advected by surface ocean velocities stored in netCDF files in the folder GlobCurrent_example_data. ... |
437 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler, ... | <SYSTEM_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 Model
Step2: Note that for your own datasets you can use our utility function gen_category_map to create the category map
Step3: Define ... |
438 | <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: Using DTensors with Keras
Step2: Next, import tensorflow and tensorflow.experimental.dtensor, and configure TensorFlow to use 8 virtual CPUs.
S... |
439 | <ASSISTANT_TASK:>
Python Code:
import rockbag as rb
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
mpl.rcParams["figure.facecolor"] = "white"
mpl.rcParams["axes.facecolor"] = "white"
mpl.rcParams["savefig.facecolor"] = "white"
import numpy as np
# stub list of files for 2012 09
def get_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: any missing data in the set?
Step2: total points different by more than .5
|
440 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
titanic=pd.read_csv('./titanic_clean_data.csv')
cols_to_norm=['Age','Fare']
col_norms=['Age_z','Fare_z']
titanic[col_norms]=titanic[cols_to_norm].apply(lambda x: (x-x.mean())/x.std())
#titanic['cabin_clean']=(pd.notnull(titanic.Cabin))
from sklearn.c... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Our key parameters here are the penalty term, and the best k features from the univariate analysis
Step2: 22
Step3: Prep the Kaggle test data,... |
441 | <ASSISTANT_TASK:>
Python Code:
def swap(a, b):
a, b = b, a
x, y = 1, 2
print("Before swap, x = %d and y = %d." % (x, y))
swap(x, y)
print("After swap, x = %d and y = %d." % (x, y))
def add_function_of_integers(func, upto):
total = 0
for n in range(upto + 1):
total = total + func(n)
return total... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Moral
Step2: Anonymous functions
Step3: List comprehensions
Step4: Example
Step5: Now we form a new list with the sum and the actual tuples ... |
442 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.datasets import load_linnerud
linnerud = load_linnerud()
chinups = linnerud.data[:,0]
plt.hist(chinups, histtype = "step", lw = 3)
plt.hist(chinups, bins = 5, histtype="step", lw = 3)
plt.hist(chinups, a... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Problem 1) Density Estimation
Step2: Problem 1a
Step3: Already with this simple plot we see a problem - the choice of bin centers and number ... |
443 | <ASSISTANT_TASK:>
Python Code:
%%bash
cd ~/Downloads
wget https://s3.amazonaws.com/ed-college-choice-public/CollegeScorecard_Raw_Data.zip
unzip CollegeScorecard_Raw_Data.zip
!ls ~/Downloads/CollegeScorecard_Raw_Data
import pandas as pd
df = pd.read_csv('~/Downloads/CollegeScorecard_Raw_Data/MERGED2011_PP.csv', na_val... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: lets explore
Step2: for some reason 2011 was the last year for which there is earning information
Step3: the number of schools covered
Step4: ... |
444 | <ASSISTANT_TASK:>
Python Code:
# Answer
# Answer
# Answer
# Answer
<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: Visualize the data
Step2: Well.. Train the model
Step3: Show some quantitative results
|
445 | <ASSISTANT_TASK:>
Python Code:
!pip install -q amplpy ampltools pandas bokeh
MODULES=['ampl', 'gurobi']
from ampltools import cloud_platform_name, ampl_notebook
from amplpy import AMPL, register_magics
if cloud_platform_name() is None:
ampl = AMPL() # Use local installation of AMPL
else:
ampl = ampl_notebook(m... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Google Colab & Kaggle interagration
Step2: Quick start
Step 1
Step3: Import Bokeh (do not run if you do not have Bokeh installed)
Step4: For ... |
446 | <ASSISTANT_TASK:>
Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
with open('anna.txt', 'r') as f:
text=f.read()
vocab = set(text)
vocab_to_int = {c: i for i, c in enumerate(vocab)}
int_to_vocab = dict(enumerate(vocab))
encoded = np.array([vocab_to_int[c] 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: First we'll load the text file and convert it into integers for our network to use. Here I'm creating a couple dictionaries to convert the chara... |
447 | <ASSISTANT_TASK:>
Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Chris Holdgraf <choldgraf@berkeley.edu>
#
# License: BSD (3-clause)
import matplotlib.pyplot as plt
import mne
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
fname = data_path + '/MEG/sam... | <SYSTEM_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 events
Step2: Events objects are essentially numpy arrays with three columns
Step3: Plotting events
Step4: Writing events
|
448 | <ASSISTANT_TASK:>
Python Code:
products = pd.read_csv('amazon_baby_subset.csv')
products = products.fillna({'review':''}) # fill in N/A's in the review column
def remove_punctuation(text):
import string
return text.translate(None, string.punctuation)
products['review_clean'] = products['review'].apply(remove... | <SYSTEM_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. data transformations
Step2: 3. Compute word counts (only for important_words)
Step3: 4. Show 'perfect' word counts
Step4: Train-Validation... |
449 | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
from pyensae.datasource import download_data
files = download_data("td2a_eco_exercices_de_manipulation_de_donnees.zip",
url="https://github.com/sdpython/ensae_teaching_cs/raw/master/_doc/notebooks/td2a_... | <SYSTEM_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
|
450 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import math
import numpy as np
import matplotlib.pyplot as plt
##import seaborn as sbn
##from scipy import *
x = .5
print x
x_vector = np.array([1,2,3])
print x_vector
print type(x_vector)
c_list = [1,2]
print "The list:",c_list
print "Has length:", len(c_list)
c_vec... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: This code sets up Ipython Notebook environments (lines beginning with %), and loads several libraries and functions. The core scientific stack ... |
451 | <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.append('C:\Anaconda2\envs\dato-env\Lib\site-packages')
import graphlab
sales = graphlab.SFrame('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... | <SYSTEM_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... |
452 | <ASSISTANT_TASK:>
Python Code:
!ls *fits
import astropy.io.fits as afits
from astropy.wcs import WCS
from astropy.visualization import ZScaleInterval
import matplotlib
%matplotlib notebook
%pylab
f1 = afits.open('wdd7.040920_0452.051_6.fits')
f2 = afits.open('wdd7.080104_0214.1025_6.fits')
f1wcs = WCS(f1[0].header)
f2... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: While the images have been de-trended, they still have the original WCS from the telescope. They aren't aligned. You could use ds9 to check this... |
453 | <ASSISTANT_TASK:>
Python Code:
import re, os, sys, shutil
import shlex, subprocess
import glob
import pandas as pd
import panedr
import numpy as np
import MDAnalysis as mda
import nglview
import matplotlib.pyplot as plt
import parmed as pmd
import py
import scipy
from scipy import stats
from importlib import reload
fro... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step4: Common functions
Step5: Get charges
Step6: Parameterize molecule in GAFF with ANTECHAMBER and ACPYPE
Step7: Move molecules
Step8: Minimize
S... |
454 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import h5py
import matplotlib.pyplot as plt
from testCases_v2 import *
from dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] ... | <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: 2 - Outline of the Assignment
Step4: Expected output
Step6: Expected output
Step8: Expected output
Step10: Expected output
Step12: <table s... |
455 | <ASSISTANT_TASK:>
Python Code:
import hashlib
import os
import pickle
from urllib.request import urlretrieve
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils import resample
from tqdm import tqdm
from zipfil... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step3: The notMNIST dataset is too large for many computers to handle. It contains 500,000 images for just training. You'll be using a subset of this... |
456 | <ASSISTANT_TASK:>
Python Code:
# 检查你的Python版本
from sys import version_info
if version_info.major != 2 and version_info.minor != 7:
raise Exception('请使用Python 2.7来完成此项目')
# 引入这个项目需要的库
import numpy as np
import pandas as pd
import visuals as vs
from IPython.display import display # 使得我们可以对DataFrame使用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: 分析数据
Step2: 练习
Step3: 问题 1
Step4: 问题 2
Step5: 问题 3
Step6: 观察
Step7: 练习
Step8: 问题 4
Step9: 问题 5
Step10: 练习:降维
Step11: 观察
Step12: 可视化一个... |
457 | <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:
Step3: Batch Normalization using tf.layers.batch_normalization<a id="example_1"></a>
Step6: We'll use the following function to create convolutional l... |
458 | <ASSISTANT_TASK:>
Python Code:
# Import necessary libraries
import matplotlib.pyplot as plt
import os
import re
import shutil
import string
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras import losses
# Print the TensorFlow version
print(tf.__version__)
# Download the IMDB dataset
ur... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Sentiment analysis
Step2: The aclImdb/train/pos and aclImdb/train/neg directories contain many text files, each of which is a single movie revi... |
459 | <ASSISTANT_TASK:>
Python Code:
from lsst.cwfs.instrument import Instrument
from lsst.cwfs.algorithm import Algorithm
from lsst.cwfs.image import Image, readFile
import lsst.cwfs.plots as plots
fieldXY = [1.185,1.185]
I1 = Image(readFile('../tests/testImages/LSST_NE_SN25/z11_0.25_intra.txt'), fieldXY, Image.INTRA)
I2 =... | <SYSTEM_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 the image objects. Input arguments
Step2: Define the instrument. Input arguments
Step3: Define the algorithm being used. Input argument... |
460 | <ASSISTANT_TASK:>
Python Code:
# Authors: Chris Holdgraf <choldgraf@gmail.com>
# Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)
# sphinx_gallery_thumbnail_number = 7
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.decoding import ReceptiveField, TimeDelayingRidge
from ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load audio data
Step2: Create a receptive field
Step3: Simulate a neural response
Step4: Fit a model to recover this receptive field
Step5: ... |
461 | <ASSISTANT_TASK:>
Python Code:
import sys, os
spark_home = os.environ.get("SPARK_HOME", None)
# Add the spark python sub-directory to the path
sys.path.insert(0, spark_home + "/python")
# Add the py4j to the path.
# You may need to change the version number to match your install
sys.path.insert(0, os.path.join(spark_ho... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 3. Logistic Regression Application
Step2: HW accelerated vs SW-only
Step3: Instantiate a Logistic Regression model
Step4: Train the LR model
... |
462 | <ASSISTANT_TASK:>
Python Code:
def reverse_words (S):
#TODO: implement me
pass
from nose.tools import assert_equal
class UnitTest (object):
def testReverseWords(self):
assert_equal(func('the sun is hot'), 'eht nus si toh')
assert_equal(func(''), None)
assert_equal(func(... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Unit Test
|
463 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.cm as cm
import matplotlib
matplotlib.rcParams.update({'font.size':18})
matplotlib.rcParams.update({'font.family':'serif'})
Alpha = 3./2.
ab_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: The idea is simple
Step2: a simple 3D model
Step3: OK, so our toy model works... but how do we actually detect these beacons among the noise o... |
464 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%config InlineBackend.figure_format='retina'
from __future__ import absolute_import, division, print_function
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib.pyplot import GridSpec
import seaborn as sns
import numpy as np
import pandas as 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: About the Data
Step2: Tidy Dyads and Starting Joins
Step3: Remove records that come from players who don't have a skintone rating
Step4: Disa... |
465 | <ASSISTANT_TASK:>
Python Code:
import scipy as sp
import openpnm as op
import matplotlib.pyplot as plt
%matplotlib inline
wrk = op.Workspace() # Initialize a workspace object
wrk.loglevel=50
net = op.network.CubicDual(shape=[6, 6, 6])
from openpnm.topotools import plot_connections, plot_coordinates
fig1 = plot_coord... | <SYSTEM_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 a CubicDual and visualize it in Paraview
Step2: The resulting network has two sets of pores, labelled as blue and red in the image... |
466 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
a = np.array([1, 2, 3])
print(repr(a), a.shape, end="\n\n")
b = np.array([(1, 2, 3), (4, 5, 6)])
print(repr(b), b.shape)
print(b.T, end="\n\n") # transpoe uma matriz
print(a + b, end="\n\n") # soma um vetor linha/coluna a todas as linhas/colunas de uma matriz
print(b ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: A base de seu funcionamento é o np.array, que retorna o objeto array sobre o qual todas as funções estão implementadas
Step2: O array traz cons... |
467 | <ASSISTANT_TASK:>
Python Code:
try:
# Use the Colab's preinstalled TensorFlow 2.x
%tensorflow_version 2.x
except:
pass
# Install the required packages
!pip install fastavro
!pip install tensorflow-io==0.9.0
# Install the specified package
!pip install google-cloud-bigquery-storage
PROJECT_ID = "<YOUR PROJECT>"... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Please ignore the incompatible errors.
Step2: Set your PROJECT ID
Step3: Import Python libraries, define constants
Step4: Import census data ... |
468 | <ASSISTANT_TASK:>
Python Code:
# Importing numpy for math, and matplotlib for plots
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
class Arm:
def __init__(self, mu=None, sigma=None):
if mu is None:
self.mu = np.absolute(np.random.uniform())
else:
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: Arms
Step2: Agents
Step3: Example agents
Step4: Beta-Softmax
Step5: Upper Confidence Bound (UCB1)
Step6: Metrics
Step7: Test
Step8: Exper... |
469 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
from scipy.integrate import odeint
from math import sqrt, atan
# Constants
g = 9.8 # Accelaration of gravity
p = 1.2 # Density of air
# Caracteristics of the problem
m = 0.100 # A 100 g ball
r = 0.10 # 10 cm radi... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We now define the initial conditions and constants of the problem.
Step2: As said, let's define a system of ordinary differential equations in ... |
470 | <ASSISTANT_TASK:>
Python Code:
from pprint import pprint
import urllib.request
import os
# print date & versions
import datetime
print("Date & time:",datetime.datetime.now())
import sys
print("Python version:", sys.version)
import pbxplore as pbx
print("PBxplore version:", pbx.__version__)
names = []
pb_sequences = []... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Fasta files
Step2: Sequences can be written once at a time using the pbxplore.io.write_fasta_entry() function.
Step3: By default, the lines in... |
471 | <ASSISTANT_TASK:>
Python Code:
# install Pint if necessary
try:
import pint
except ImportError:
!pip install pint
# download modsim.py if necessary
from os.path import exists
filename = 'modsim.py'
if not exists(filename):
from urllib.request import urlretrieve
url = 'https://raw.githubusercontent.com/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: In the previous chapter we developed a quadratic model of world
Step2: And here's the code that reads table2, which contains world populations ... |
472 | <ASSISTANT_TASK:>
Python Code:
import theano
import os, sys
sys.path.insert(1, os.path.join('utils'))
from __future__ import print_function, division
path = 'data/statefarm/'
import utils; reload(utils)
from utils import *
batch_size=16
vgg = Vgg16()
model = vgg.model
last_conv_idx = [i for i, l in enumerate(model.laye... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Manual iteration through test image to generate convolutional test features. Saves each batch to disk insetad of loading in memory.
Step2: I th... |
473 | <ASSISTANT_TASK:>
Python Code:
all_crime_tipos.head(10)
all_crime_tipos_top10 = all_crime_tipos.head(10)
all_crime_tipos_top10.plot(kind='barh', figsize=(12,6), color='#3f3fff')
plt.title('Top 10 crimes por tipo (Mar 2017)')
plt.xlabel('Número de crimes')
plt.ylabel('Crime')
plt.tight_layout()
ax = plt.gca()
ax.xaxis.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: Todas as ocorrências criminais de março
Step2: Quantidade de crimes por região
Step3: As 5 regiões com mais ocorrências
Step4: Acima podemos ... |
474 | <ASSISTANT_TASK:>
Python Code:
import csv
import json
import os
import ujson
import urllib2
from riotwatcher import RiotWatcher
config = {
'key': 'API_key',
}
class RiotCrawler:
def __init__(self, key):
self.key = key
self.w = RiotWatcher(key)
self.tiers = {
'bronze': [],
... | <SYSTEM_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 use the Riot api, one more important thing to do is to get your own API key. API key can be obtained from here. Note that normal developr API... |
475 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import scipy.stats
# Create two lists of random values
x = [1,2,3,4,5,6,7,8,9]
y = [2,1,2,4.5,7,6.5,6,9,9.5]
# Create a function that takes in x's and y's
def spearmans_rank_correlation(xs, ys):
# Calculate the rank of x's
xranks = 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: Create Data
Step2: Calculate Spearman's Rank Correlation
Step3: Calculate Spearman's Correlation Using SciPy
|
476 | <ASSISTANT_TASK:>
Python Code:
from sklearn.datasets import load_digits
digits = load_digits()
%matplotlib inline
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(6, 6)) # figure size in inches
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
# plot the digits: each image is 8x... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We'll re-use some of our code from before to visualize the data and remind us what
Step2: Visualizing the Data
Step3: Here we see that the dig... |
477 | <ASSISTANT_TASK:>
Python Code:
import torch
from torch import nn
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.figure(figsize=(8,5))
# how many time steps/data pts are in one batch of data
seq_length = 20
# generate evenly spaced data pts
time_steps = np.linspace(0, np.pi, seq_length + 1)
da... | <SYSTEM_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 the RNN
Step2: Check the input and output dimensions
Step3: Training the RNN
Step4: Loss and Optimization
Step5: Defining the trainin... |
478 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
xpoints=512 #nr of grid points in 1 direction
xmax=1 #extension of grid [m]
pref=9e9 # 1/(4pi eps0)
x=np.linspace(-xmax,xmax,xpoints)
y=x
[x2d,y2d]=np.meshgrid(x,y,indexing='ij') #2D matrices holding x or y coordinate for each point on t... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: create grid to plot (choose 2D plane for visualisation cutting through charge centers , but calculation is correct for 3D)
Step2: calculate the... |
479 | <ASSISTANT_TASK:>
Python Code:
!wget https://d17h27t6h515a5.cloudfront.net/topher/2016/December/584f6edd_data/data.zip -O data.zip
!unzip -q data.zip
!mv data udacity_data
!rm -rf __MACOSX/
!unzip -q data_val.zip
!unzip -q data_test.zip
DATA_TRAIN_FOLDER = 'udacity_data/'
DATA_VAL_FOLDER = 'data_val/'
DATA_TEST_FOLDER... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Unzip prepared validation and training sets
Step2: Step 1 -- load data and visualize
Step3: Step 2 data generators
Step4: Step 2 -- define th... |
480 | <ASSISTANT_TASK:>
Python Code:
np.random.seed(0)
X0 = sp.stats.norm(-2, 1).rvs(40)
X1 = sp.stats.norm(+2, 1).rvs(60)
X = np.hstack([X0, X1])[:, np.newaxis]
y0 = np.zeros(40)
y1 = np.ones(60)
y = np.hstack([y0, y1])
sns.distplot(X0, rug=True, kde=False, norm_hist=True, label="class 0")
sns.distplot(X1, rug=True, kde=Fal... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 베르누이 분포 나이브 베이즈 모형
Step2: 다항 분포 나이브 베이즈 모형
Step3: 예 1
Step4: 감성 분석 Sentiment Analysis
Step5: CountVectorize 사용
Step6: TfidfVectorizer 사용
St... |
481 | <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:
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... |
482 | <ASSISTANT_TASK:>
Python Code:
import theano
import theano.tensor as T
import numpy as np
vector1 = T.vector('vector1')
vector2 = T.vector('vector2')
output, updates = theano.scan(fn=lambda a, b : a * b,
sequences=[vector1, vector2])
f = theano.function(inputs=[vector1, vector2],
... | <SYSTEM_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 call the scan() function. It has many parameters but, because our use case is simple, we only need two of them. We'll introduce other p... |
483 | <ASSISTANT_TASK:>
Python Code:
from IPython.core.display import HTML
css_file = 'pynoddy.css'
HTML(open(css_file, "r").read())
%matplotlib inline
# here the usual imports. If any of the imports fails,
# make sure that pynoddy is installed
# properly, ideally with 'python setup.py develop'
# or 'python setup.py instal... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Defining an experiment
Step2: For simpler visualisation in this notebook, we will analyse the following steps in a section view of the model.
S... |
484 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from __future__ import absolute_import
from __future__ import print_function
# import local library
import tools
import nnlstm
# import library to build the neural network
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's gather the datas from the previous notebook
Step2: and pad each vector to a regular size (necessary for the sequence processing)
Step3: ... |
485 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
from datetime import timedelta
from obspy.core import read
from obspy.core.utcdatetime import UTCDateTime
from obspy.core.invent... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Getting Started with the Apollo Passive Seismic Data Archive
Step3: Notice that the raw seismogram is
Step5: In the next section, we will mak... |
486 | <ASSISTANT_TASK:>
Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
import collections
import math
import numpy as np
import os
import random
import tensorflow as tf
import urllib
import zipfile
from matplotlib import pylab
from sklearn.manifold 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:
Step2: Download the data from the source website if necessary.
Step3: Read the data into a string.
Step4: Build the dictionary and replace rare words... |
487 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.DataFrame.from_dict({'id': ['A', 'B', 'A', 'C', 'D', 'B', 'C'],
'val': [1,2,-3,1,5,6,-2],
'stuff':['12','23232','13','1234','3235','3236','732323']})
def g(df):
df['cummax'] = df.groupby('id')['val']... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
488 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
import mne
import os.path as op
import numpy as np
from matplotlib import pyplot as plt
# Load an example dataset, the preload flag loads the data into memory now
data_path = op.join(mne.datasets.sample.data_path(), 'MEG',
'sample... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: It is often necessary to modify data once you have loaded it into memory.
Step2: Signal processing
Step3: In addition, there are functions for... |
489 | <ASSISTANT_TASK:>
Python Code:
# import feedforward neural net
from mlnn import neural_net
# Visualize tanh and its derivative
x = np.linspace(-np.pi, np.pi, 120)
plt.figure(figsize=(8, 3))
plt.subplot(1, 2, 1)
plt.plot(x, np.tanh(x))
plt.title("tanh(x)")
plt.xlim(-3, 3)
plt.subplot(1, 2, 2)
plt.plot(x, 1 - np.square... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <script type="text/javascript" src="https
Step2: It can be seen from the above figure that as we increase our input the our activation starts t... |
490 | <ASSISTANT_TASK:>
Python Code:
class Test:
pass
a = Test()
a
type(a)
type(Test)
type(type)
type?
TestWithType = type('TestWithType', (object,), {})
type(TestWithType)
ins1 = TestWithType()
type(ins1)
type('TestWithType', (object,), {})()
class TestClass:
def __new__(cls, *args, **kwargs):
print('new m... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Classes - Nothing but instances of types. Class technically is a sugar over the native 'type'
Step2: 'type' is an important native structure u... |
491 | <ASSISTANT_TASK:>
Python Code:
# Loading modules
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1,2,3,5,6,7,8,10],dtype=float)
x
y = np.arange(10)
y
z = np.linspace(0,100,50)
z
h = np.random.randn(100)
h
print('Min X: {0:.3f} \t Max X: {1:.3f}'.format(np.min(x), np.max(x)) )
zz =... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Review
Step2: Handling arrays
Step3: Apply mathematical functions
Step4: Conditionals
Step5: Manipulating Arrays
Step6: We can get the over... |
492 | <ASSISTANT_TASK:>
Python Code:
import hashlib
import os
import pickle
from urllib.request import urlretrieve
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils import resample
from tqdm import tqdm
from zipfil... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step3: The notMNIST data is a large dataset to handle for most computers. It contains 500 thousands images for just training. You'll be using a subse... |
493 | <ASSISTANT_TASK:>
Python Code:
import random
elements = list(range(1, 11)) * 2 + [25, 50, 75, 100]
game = random.sample(elements, 6)
goal = random.randint(100, 999)
print goal, ':', game
# the DNA is just the calcul in a string
def random_dna(game):
# we want random links to node, so we need to shuffle the game
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Now, we need to generate our population, this means for each candidate we will generate random DNA
Step2: Now, we would like to score our popu... |
494 | <ASSISTANT_TASK:>
Python Code:
%%capture
!python -m pip install iree-compiler iree-runtime iree-tools-tflite -f https://github.com/google/iree/releases/latest
!pip3 install --extra-index-url https://google-coral.github.io/py-repo/ tflite_runtime
import numpy as np
import urllib.request
import pathlib
import tempfile
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: Load the TFLite model
Step2: Run using TFLite
Step3: Run using IREE
|
495 | <ASSISTANT_TASK:>
Python Code:
!pip install praatio --upgrade
from praatio import textgrid
# Textgrids take no arguments--it gets all of its necessary attributes from the tiers that it contains.
tg = textgrid.Textgrid()
# IntervalTiers and PointTiers take four arguments: the tier name, a list of intervals or points,
#... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <hr>
Step2: <a id="example_create_blank_textgrids">
Step3: Bravo! You've saved your colleagues the tedium of creating empty textgrids for eac... |
496 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'mohc', 'hadgem3-gc31-hh', 'aerosol')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
497 | <ASSISTANT_TASK:>
Python Code:
# define base values and measurements
v1_s = 0.500
v1_sb1 = 1.800
v1_sb2 = 1.640
v1_m = np.mean([0.47, 0.46, 0.46, 0.46, 0.46, 0.47, 0.46, 0.46, 0.46, 0.46, 4.65 / 10]) * 1e-3
v1_T = np.mean([28.68 / 10, 28.91 / 10])
v1_cw = 0.75
v1_cw_u = 0.08
v1_A = 4*1e-6
v1_pl = 1.2041
def air_resista... | <SYSTEM_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>
Step2: Es resultiert in Grafik \ref{fig
Step3: Vergleich der Messmethoden
Step4: Streuung der Mündungsgeschwindigkeit
Step5: Vergle... |
498 | <ASSISTANT_TASK:>
Python Code:
import datetime
import os
import shutil
import matplotlib.pyplot as plt
import tensorflow as tf
print(tf.__version__)
%%bash
ls *.csv
%%bash
head -5 *.csv
# Determine CSV, label, and key columns
# TODO: Create list of string column headers, make sure order matches.
CSV_COLUMNS = [""]
# ... | <SYSTEM_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: Lab Task #2
Step7: Lab Task #3
Step9: Lab Task #4
Step11: Lab Task #5
Step13: Lab ... |
499 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
# Create a random array with a lot of zeros
X = np.random.random((10, 5))
print(X)
X[X < 0.7] = 0 # note: fancy indexing
print(X)
from scipy import sparse
# turn X into a csr (Compressed-Sparse-Row) matrix
X_csr = sparse.csr_matrix(X)
print(X_csr)
# convert the sparse ... | <SYSTEM_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 CSR representation can be very efficient for computations, but it is not as good for adding elements.
Step2: Often, once an LIL matrix is... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.