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: iris為一個dict型別資料,我們可以用以下指令來看一下資料的內容。
Step2: | 顯示 | 說明 |
Step3: 而接下來為了產生一個包含絕大部份可能的測試矩陣,我們會用到以下指令。
Step4: (三) 測試分類器以及畫出機率分佈圖的選擇
| <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data[:, 0:2] # 僅使用前兩個特徵,方便視覺化呈現
y = iris.target
n_features = X.shape[1]
for key,value in 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: Consumption in Europe is led by Germany followed by France and the United Kingdom. Spain is in the 5th place with a household consumption during... | <ASSISTANT_TASK:>
Python Code:
#Europe
df5 = df4.loc[df4.index.isin(['Austria', 'Belgium', 'Bulgaria','Croatia', 'Cyprus', 'Czechia','Denmark', 'Estonia','Finland','France','Germany','Greece','Hungary','Ireland','Italy','Latvia','Lithuania','Luxembourg','Malta','Netherlands','Poland','Portugal','Romania','Slovakia', '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: <div id='intro' />
Step2: The other algorithm we will use is implemented in the function np.linalg.solve of NumPy.
Step3: The following code c... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
# This function solves a linear system of equation
# in a NOT recomended way, we just include it here
# for comparison purposes. Please DON'T do this!
def solve_inverse(A,b):
B = np.linalg.inv(A) # FORBIDDEN!!
x = np.dot(B,b)
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load the data
Step2: Calculate chromosome properties and classify
Step3: 2. Calculate chromosomal properties
Step4: 3. Summarize chromosome c... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
# import matplotlib.gridspec as gridspec
import seaborn as sns
import pathlib
import PaSDqc
%matplotlib inline
sns.set_context('poster')
sns.set_style("ticks", {'ytick.minor.size': 0.0, 'xtick.... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: "echo" に修正して実行してみましょう。
Step2: Jupyter-LC_wrapper
Step3: Jupyter-multi_outputs
Step4: 上の例では、タブをクリックすると以前の出力結果を参照することができます。
Step5: 以前の出力結果を選択表... | <ASSISTANT_TASK:>
Python Code:
! echo "This is 1st step" > foo; cat foo
! echo ".. 2nd step..." >> foo && cat foo
!echooooo ".. 3rd step... will fail" >> foo && cat foo
! cat foo
%env lc_wrapper 8:8:10:10
# lc_wrapper s:h:e:f
#
# s : Summary starts when # of output lines exceed 's' (default s=1)
# h : Summary 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: Set parameters and read data
Step2: Loop through frequencies, apply classifier and save scores
Step3: Plot frequency results
Step4: Loop thro... | <ASSISTANT_TASK:>
Python Code:
# Authors: Laura Gwilliams <laura.gwilliams@nyu.edu>
# Jean-Remi King <jeanremi.king@gmail.com>
# Alex Barachant <alexandre.barachant@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
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: Step 2
Step2: Step 3
Step3: Step 4
Step4: Step 5
Step5: Step 6
Step6: Step 7
Step7: Step 8
Step8: Step 9
Step9: Step 10
Step10: Step 11... | <ASSISTANT_TASK:>
Python Code:
import os, re
# Provide the directory for your index and read files (you can do multiple independently in one go)
bioblitz = '/home/roli/BioBlitz.2017/SV_based/'
# Prepare an object with the name of the library, the name of the directory object (created above), and the metadatafile 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: Create a linear stream of 10million points between -50 and 50.
Step2: Create random noise of same dimension
Step3: Define the function
Step4: ... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
x = np.arange(-50,50,0.00001)
x.shape
bias = np.random.standard_normal(x.shape)
y2 = np.cos(x)**3 * (x**2/max(x)) + ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step4: Plotting functions
Step14: Restricted Boltzmann Machines
Step15: Load MNIST
Step17: Training with optax
Step18: Evaluating Training
Step20: ... | <ASSISTANT_TASK:>
Python Code:
!pip install optax
import numpy as np
import jax
from jax import numpy as jnp
from jax import grad, jit, vmap, random
import optax
import tensorflow_datasets as tfds
from sklearn.linear_model import LogisticRegression
from matplotlib import pyplot as plt
import matplotlib.gridspec as grid... |
<SYSTEM_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: Погрешность измерения барабана 12 градусов. Отсюда находим погрешность измерения длин волн
Step4: Определе... | <ASSISTANT_TASK:>
Python Code:
import numpy as np; import scipy as sps; import matplotlib.pyplot as plt; import pandas as pd
%matplotlib inline
table_1 = pd.read_excel('lab-4-1.xlsx', '1'); table_1.iloc[:, :4]
table_2 = pd.read_excel('lab-4-1.xlsx', '2'); table_2.iloc[:, :]
degrees = table_1.values[:, 0].tolist()[::-... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Numeric widgets
Step2: FloatSlider
Step3: An example of sliders displayed vertically.
Step4: FloatLogSlider
Step5: IntRangeSlider
Step6: Fl... | <ASSISTANT_TASK:>
Python Code:
import ipywidgets as widgets
widgets.IntSlider(
value=7,
min=0,
max=10,
step=1,
description='Test:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='d'
)
widgets.FloatSlider(
value=7.5,
min=... |
<SYSTEM_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 Hyperbolic Orbits into REBOUND
Step2: We want to add these comits to a REBOUND simulation(s). The first thing to do is set the units,... | <ASSISTANT_TASK:>
Python Code:
from io import StringIO
import numpy as np
import rebound
epoch_of_elements = 53371.0 # [MJD, days]
c = StringIO(u
# id e q[AU] i[deg] Omega[deg] argperi[deg] t_peri[MJD, days] epoch_of_observation[MJD, days]
168026 12.181214 15.346358 136.782470 37.581438 ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Display mode
Step2: Display mode
Step3: Recognized Formats
Step4: Programmable Table Actions
Step5: Set index to DataFrame
Step6: Update ce... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
from beakerx import *
from beakerx.object import beakerx
pd.read_csv('../resources/data/interest-rates.csv')
table = TableDisplay(pd.read_csv('../resources/data/interest-rates.csv'))
table.setAlignmentProviderForColumn('m3', TableDisplayAlignmentProvider.CENTER_ALIGNME... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Then import the Codon Table for standard genetic code, with the slight modification - add STOP codon * as a fully-fledged member of the table
St... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import os
import sys
from Bio import SeqRecord
from Bio import AlignIO
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from Bio.Data import CodonTable
genetic_code = CodonTable.standard_dna_table.forward_table
stop_codons = dict([ (codon,'*') 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: Load the lending club dataset
Step2: Like the previous assignment, we reassign the labels to have +1 for a safe loan, and -1 for a risky (bad) ... | <ASSISTANT_TASK:>
Python Code:
import graphlab
loans = graphlab.SFrame('lending-club-data.gl/')
loans['safe_loans'] = loans['bad_loans'].apply(lambda x : +1 if x==0 else -1)
loans = loans.remove_column('bad_loans')
features = ['grade', # grade of the loan
'term', # the term of ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Stochastical estimation of ELBO
Step2: Minibatches speed up computation
Step3: Running stochastic optimization
| <ASSISTANT_TASK:>
Python Code:
import sys, os
import numpy
import time
sys.path.append(os.path.join(os.getcwd(),'..'))
import candlegp
from matplotlib import pyplot
import torch
from torch.autograd import Variable
%matplotlib inline
pyplot.style.use('ggplot')
import IPython
M = 50
def func(x):
return torch.sin(x * ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2 About the data
Step2: For convenience, we will rename all columns to upper case, so we don't have to remember what is upper or lower case in ... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
% matplotlib inline
from matplotlib import pyplot as plt
from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
data = pd.read_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: So we had to just put the parentheses
Step2: Time taken to execute a cell
| <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
# importing the dataset we prepared and saved using Baseline 1 Notebook
ricep = pd.read_csv("/Users/macbook/Documents/BTP/Notebook/BTP/ricep.csv")
ricep.head()
ricep = ricep.drop(["Unnamed: 0"],axis=1)
ricep["phosphorus"] = ricep["phosphorus"]*10
ric... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Code from the previous chapter
Step2: System objects
Step4: And we can encapsulate the code that runs the model in a function.
Step6: We can ... | <ASSISTANT_TASK:>
Python Code:
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import functions from the modsim.py module
from modsim import *
from panda... |
<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: Let me work through CSS Tutorial, while consulting Cascading Style Sheets - Wikipedia, the free encyclopedia.
Step6: Box model
Step7: Basic ex... | <ASSISTANT_TASK:>
Python Code:
from nbfiddle import Fiddle
# http://www.w3schools.com/css/tryit.asp?filename=trycss_default
Fiddle(
div_css =
background-color: #d0e4fe;
h1 {
color: orange;
text-align: center;
}
p {
font-family: "Times New Roman";
font-size: 20px;
}
,
html =
<h1>My First CSS Examp... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nasa-giss', 'sandbox-1', 'ocean')
# 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: First tell PyPSA that links can have multiple outputs by overriding the component_attrs. This can be done for as many buses as you need with for... | <ASSISTANT_TASK:>
Python Code:
import pypsa
import numpy as np
import matplotlib.pyplot as plt
override_component_attrs = pypsa.descriptors.Dict(
{k: v.copy() for k, v in pypsa.components.component_attrs.items()}
)
override_component_attrs["Link"].loc["bus2"] = [
"string",
np.nan,
np.nan,
"2nd bus"... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Tirer des points aléatoirement et les afficher
Step2: Distance d'un chemin
Step3: Visualisation
Step4: Parcourir toutes les permutations
Step... | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
import numpy
points = numpy.random.random((6, 2))
points
def distance_chemin(points, chemin):
dist = 0
for i in range(1, len(points)):
dx, dy = points[chemin[i], :] - points[chemin[i-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: Advanced example
Step2: Progress monitoring and control using callback argument of fit method
Step3: Counting total iterations that will be us... | <ASSISTANT_TASK:>
Python Code:
from skopt import BayesSearchCV
from sklearn.datasets import load_digits
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
X, y = load_digits(10, True)
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, test_size=.25, random_state=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:
Step2: 2 - Outline of the Assignment
Step4: Expected Output
Step6: Expected Output
Step8: Expected Output
Step10: Expected Output
Step12: Expected... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import h5py
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
%load_ext autoreload
%autoreload 2
np.random.seed(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: Data preprocessing
Step2: Encoding the words
Step3: Encoding the labels
Step4: If you built labels correctly, you should see the next output.... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import tensorflow as tf
with open('../sentiment-network/reviews.txt', 'r') as f:
reviews = f.read()
with open('../sentiment-network/labels.txt', 'r') as f:
labels = f.read()
reviews[:2000]
from string import punctuation
all_text = ''.join([c for c in reviews if... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Are we underfitting?
Step2: py
Step3: ```py
Step5: ...and load our fine-tuned weights.
Step6: We're going to be training a number of iterati... | <ASSISTANT_TASK:>
Python Code:
from theano.sandbox import cuda
%matplotlib inline
from importlib import reload
import utils; reload(utils)
from utils import *
from __future__ import division, print_function
#path = "data/dogscats/sample/"
path = "data/dogscats/"
model_path = path + 'models/'
if not os.path.exists(model... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Exercise 1
Step2: Exercise 2
Step3: Exercise 3
| <ASSISTANT_TASK:>
Python Code:
# This is a configuration step for the exercise. Please run it before calculating the derivative!
import numpy as np
import matplotlib.pyplot as plt
# Show the plots in the Notebook.
plt.switch_backend("nbagg")
#################################################################
# IMPLEMENT... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Start from a simple linear regression
Step2: As it is metioned before, the command in Sklearn for LinearRegression can be used except that the ... | <ASSISTANT_TASK:>
Python Code:
from importlib import reload
import sklearn.linear_model
import pandas as pd
import numpy as np
from poodle import linear_model
reload( linear_model)
ml = linear_model.LinearRegression()
ml.fit('sheet/xy_pdl.csv')
ml.predict( 'sheet/x_pdl.csv', 'sheet/yp_pdl.csv')
linear_model.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:
Step3: Download block_events and blocked_users
Step5: Download NPA warnings
Step7: Download Long term Users
Step9: Download Gender
Step10: Onionize... | <ASSISTANT_TASK:>
Python Code:
def cf_helper(path, cols, k = 5):
df = pd.read_csv(path, sep = '\t', quoting = 3, encoding = 'utf-8', header = None, usecols=range(len(cols)))
if df.shape[0] ==0:
return pd.DataFrame(columns = cols)
if df.shape[1] != len(cols):
print(path)
print(df.shap... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: TSNE
| <ASSISTANT_TASK:>
Python Code:
df_train = sessions_to_dataframe(training_sessions)
df_val = sessions_to_dataframe(validation_sessions)
df_train.head()
df_train = preprocess_data(df_train)
df_val = preprocess_data(df_val)
#### SPECIAL CASE #####
# There isnt any XButton data in the validation set so we better drop this ... |
<SYSTEM_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 shape of the 4D tensor corresponding to the weight matrix W is
Step2: Note that we use the same weight initialization formula as with the M... | <ASSISTANT_TASK:>
Python Code:
import cPickle
import gzip
import os
import sys
import timeit
import numpy
import theano
import theano.tensor as T
from theano.tensor.signal import downsample
from theano.tensor.nnet import conv
rng = numpy.random.RandomState(23455)
# instantiate 4D tensor for input
input = T.tensor4(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: Data preprocessing
Step2: Compute covariance matrices, fit and apply spatial filter.
Step3: Plot source space activity
Step4: Now let's plot... | <ASSISTANT_TASK:>
Python Code:
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import mne
from mne.datasets import sample
from mne.beamformer import make_lcmv, apply_lcmv
print(__doc__)
data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
raw_fname = data_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: Let's restrict the number of conditions to speed up computation
Step2: Define stimulus - trigger mapping
Step3: Let's make the event_id dictio... | <ASSISTANT_TASK:>
Python Code:
# Authors: Jean-Remi King <jeanremi.king@gmail.com>
# Jaakko Leppakangas <jaeilepp@student.jyu.fi>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
from pandas import read_csv
import matplo... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: For a test case, we generate 10 random points and observations, where the
Step2: Using the circumcenter and circumcircle radius information fro... | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial import ConvexHull, Delaunay, delaunay_plot_2d, Voronoi, voronoi_plot_2d
from scipy.spatial.distance import euclidean
from metpy.gridding import polygons, triangles
from metpy.gridding.interpolation import nn_point
np.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: Next, we instantiate a main compiler engine using the IBM Q back-end and the predefined compiler engines which take care of the qubit placement,... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import projectq.setups.ibm
from projectq.backends import IBMBackend
from projectq.ops import Measure, Entangle, All
from projectq import MainEngine
eng = MainEngine(IBMBackend(use_hardware=True, num_runs=1024,
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Tuples, lists, sets, dicts, strings and numpy arrays are the hard core of the objects just to handle data in phython. In this notebook we learn ... | <ASSISTANT_TASK:>
Python Code:
from pprint import pprint
import numpy as np
myTuple = ('This', 'is', 'our', 'tuple', 'number', 1)
print("This tuple contains {} itmes.".format(len(myTuple)))
print("Here you see that the object is a tuple: {}".format(type(myTuple)))
print("If you ask if this is a tuple, this is the answ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1
Step1: To get the monthly traffic data on English Wikipedia from January 2008 through September 2017, we need to use 2 API endpoints, the Pagecou... | <ASSISTANT_TASK:>
Python Code:
# Import packages that will be used in this assignment
import requests
import json
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
# Collect desktop traffic data from January 2008 through July 2016 using the Pagecounts API
endpoint_pagecounts... |
<SYSTEM_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 you can invoke f and pass the input values, i.e. f(1,1), f(10,-3) and the result for this operation is returned.
Step2: Printing of the gra... | <ASSISTANT_TASK:>
Python Code:
import theano
import theano.tensor as T
#Put your code here
print f(1,1)
print f(10,-3)
#Graph for z
theano.printing.pydotprint(z, outfile="pics/z_graph.png", var_with_name_simple=True)
#Graph for function f (after optimization)
theano.printing.pydotprint(f, outfile="pics/f_graph.png"... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Hamilton (1989) switching model of GNP
Step2: We plot the filtered and smoothed probabilities of a recession. Filtered refers to an estimate of... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
import requests
from io import BytesIO
# NBER recessions
from pandas_datareader.data import DataReader
from datetime import datetime
usrec = DataReader('USREC', 'fred', 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: Data - Sinus + linear function
Step2: The is how it looks like
Step10: The Fitting class
| <ASSISTANT_TASK:>
Python Code:
# == Basic import == #
# plot within the notebook
%matplotlib inline
# No annoying warnings
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import matplotlib.pyplot as mpl
x = np.linspace(0,20,100)
dy = np.random.normal(0,7,100)
y = 10*np.sin(x) + 4*x + dy
mpl.plot... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <span id="plat_prod">Choose Platforms and Products ▴</span>
Step2: <span id="extents">Get the Extents of the Cube ▴</span>
Step3: ... | <ASSISTANT_TASK:>
Python Code:
import sys
import os
sys.path.append(os.environ.get('NOTEBOOK_ROOT'))
import warnings
# Supress Warning
warnings.filterwarnings('ignore')
from datacube.utils.aws import configure_s3_access
configure_s3_access(requester_pays=True)
import utils.data_cube_utilities.data_access_api as dc_api... |
<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... | <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:
Step1: 2. Linear Regression
Step2: The orange line on the plot above is the number of page views in blue and the orange line is the CPU load that view... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (13.0, 8.0)
%matplotlib inline
import pickle
import sklearn
import sklearn.linear_model
import sklearn.preprocessing
import sklearn.gaussian_process
import sklearn.ensemble
import pickle # Pickle files al... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <p style="font-family
Step2: <p style="font-family
Step3: <p style="font-family
Step4: <p style="font-family
Step5: <p style="font-family
St... | <ASSISTANT_TASK:>
Python Code:
import sqlite3
import pandas as pd
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from math import sqrt
# Create your connection.
cnx = 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: visiulization the steering dataset, and we can see there only have 8000 labeld data, and this data is only labed the center image, so we can lab... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
driving_log = pd.read_csv(PATH+data_csv, names = None)
print(driving_log.shape)
driving_log.head()
import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline
plt.figure(figsize=(20,10));
driving_log['steering'].plot()
#nb_epoch... |
<SYSTEM_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 strategy to choose a change point is to pick a point which has a low pvalue and also has a large enough effect size. Note that a changepoint... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from changepoint.mean_shift_model import MeanShiftModel
ts = np.concatenate([np.random.normal(0, 0.1, 10), np.random.normal(1, 0.1, 10)])
model = MeanShiftModel()
stats_ts, pvals, nums = model.detect_mean_shift(ts, B=10000)
%matplotlib inline
import pylab as pl
pl.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: Relative intensity
Step2: Fold-change
| <ASSISTANT_TASK:>
Python Code:
# First, we must perform the incantations.
%pylab inline
import pandas as pd
# Parse data file.
proteins = pd.read_table('data/pubs2015/proteinGroups.txt', low_memory=False)
# Find mass spec intensity columns.
intensity_cols = [c for c in proteins.columns if 'intensity '
in 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: Apoi se importa modulul astfel
Step2: Orice functie din acest modul se apeleaza apoi ca plt.NumeFunctie.
Step3: O alta solutie este sa diviza... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
a=0
b=6*np.pi
n=300
x=np.linspace(a, b,n)
y=np.exp(-x/8)*np.cos(x)
plt.plot(x,y, 'r')
plt.title('Grafic de functie')
plt.xlabel('x')
plt.ylabel('y=f(x)')
a=-5
b=7
h=0.01
X=np.arange(a,b, h)
Y=-2*X*X+X+1
plt.plot(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: IV.1 Particle Metropolis-Hastings
Step2: Bootstrap particle filter giving an estimate $\widehat{z}\theta$ of the joint likelihood $p(y{1
Step3:... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from scipy import stats
from tqdm import tqdm_notebook
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style()
T = 50
xs_sim = np.zeros((T + 1,))
ys_sim = np.zeros((T,))
# Initial state
xs_sim[0] = 0.
for t in range(T):
xs_sim[t + 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: Observe que na linha acima aplicamos o método split diretamente a uma string, sem precisarmos nomear uma variável com o conteúdo da string!
Step... | <ASSISTANT_TASK:>
Python Code:
minhalista = "Como fazer uma list comprehension".split()
minhalista
minhalista = [x.capitalize() for x in minhalista]
minhalista
x
linguadope = ["Pe"+palavra for palavra in minhalista]
linguadope
" ".join(linguadope)
numeros = [n for n in range(0,10)]
print(numeros)
numeros = [2*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: Explore data
Step2: From scratch
Step3: With sklearn
| <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
from IPython.core.display import display, HTML
display(HTML('''
<style>
.dataframe td, .dataframe th {
border: 1px solid black;
background: white;
}
.dataframe td {
text-align: left;
}
</style>
'''))
df = pd.DataFrame({
'Outlook': ['sunny',... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Summarize
Step2: Summarize
Step3: Setting values in lists
Step4: Predict what this code does.
Step5: Predict what this code does.
Step6: Su... | <ASSISTANT_TASK:>
Python Code:
some_list = [10,20,30]
print(some_list[2])
some_list = [10,20,30]
print(some_list[0])
some_list = [10,20,30]
print(some_list[-1])
some_list = [10,20,30,40]
print(some_list[1:3])
some_list = [10,20,30]
print(some_list[:3])
some_list = [0,10,20,30,40,50,60,70]
print(some_list[2:4])
some_... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Contents
Step2: Facility generation and CO2 emissions
Step3: EIA Facility level emissions (consolidate fuels/prime movers)
Step4: Total EIA g... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from __future__ import division
import matplotlib.pyplot as plt
import seaborn as sns
# import plotly.plotly as py
# import plotly.graph_objs as go
# from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import pandas as pd
import os
import numpy... |
<SYSTEM_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 workshop we will code up a genetic algorithm for a simple mathematical optimization problem.
Step11: The optimization problem
Step12: ... | <ASSISTANT_TASK:>
Python Code:
# All the imports
from __future__ import print_function, division
from math import *
import random
import sys
import matplotlib.pyplot as plt
# TODO 1: Enter your unity ID here
__author__ = "dndesai"
class O:
Basic Class which
- Helps dynamic updates
- Pretty 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: tf.dataを使って画像をロードする
Step2: データセットのダウンロードと検査
Step3: 218MBをダウンロードすると、花の画像のコピーが使えるようになっているはずです。
Step4: 画像の検査
Step5: 各画像のラベルの決定
Step6: ラベルにインデッ... | <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: Now we use a model atmosphere with a lower alpha enhancement
Step2: And a model atmosphere with a higher alpha enhancement
Step3: Compare
| <ASSISTANT_TASK:>
Python Code:
atm= atlas9.Atlas9Atmosphere(teff=3500.,logg=2.5,metals=0.,am=0.,cm=0.)
synspec_correct= apogee.modelspec.turbospec.synth(modelatm=atm,
linelist='20150714',
lsf='all',cont='true',vmacro=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: 1. Set source and destination paths
Step2: 2. Instantiate a BatchGenerator
Step3: 3. Set the processing parameters and start the processing
| <ASSISTANT_TASK:>
Python Code:
from batch_generator import BatchGenerator
from cityscapesscripts.helpers.labels import IDS_TO_TRAINIDS_ARRAY
# The directories that contain the train, val, and test images
train_images = '../../datasets/Cityscapes/leftImg8bit/train/'
train_extra_images = '../../datasets/Cityscapes/leftI... |
<SYSTEM_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. Carregar, examinar e fazer plot dos dados
Step2: 3. Ajustar (sobrepor ?) uma reta qualquer
| <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
# O arquivo de dados é um txt no qual cada linha
# contém dois números, separados por vírgula.
# A primeira coluna representa x e a segunda coluna y
fname = 'data1.txt'
data = np.loadtxt(fname, delimiter = ',')
N = data.shape[0] # númer... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Plot the different time series and PSDs
| <ASSISTANT_TASK:>
Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
import mne
from mne.time_frequency import fit_iir_model_raw
from mne.datasets import sample
print(__doc__)
data_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: Get layer data
Step2: Get $p, T, \rho$
Step3: Note that the geopotential height can be provided as a numpy array
Step4: If height is provided... | <ASSISTANT_TASK:>
Python Code:
# Import isa library
from pyturb.gas_models import isa
import numpy as np
from matplotlib import pyplot as plt
height = [0, 11000, 20000, 32000, 47000, 51000, 71000, 84852]
for i_layer, h in enumerate(height):
lapse_rate, Tbase, pbase, dbase, heightbase, layer_name = isa.get_atmosdat... |
<SYSTEM_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 the cell function, we can create Cell widgets that are directly added to the current sheet.
Step2: Events
Step3: Cell ranges
Step4: Cal... | <ASSISTANT_TASK:>
Python Code:
import ipysheet
sheet = ipysheet.sheet()
sheet
sheet = ipysheet.sheet(rows=3, columns=4)
cell1 = ipysheet.cell(0, 0, 'Hello')
cell2 = ipysheet.cell(2, 0, 'World')
cell_value = ipysheet.cell(2,2, 42.)
sheet
import ipywidgets as widgets
sheet = ipysheet.sheet(rows=3, columns=2, column_hea... |
<SYSTEM_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 Structure for Recurrent Neural Networks
Step2: This is essentially building a CSV file from scratch, to see it as a data frame, use the fo... | <ASSISTANT_TASK:>
Python Code:
from sklearn import preprocessing
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Encode text values to dummy variables(i.e. [1,0,0],[0,1,0],[0,0,1] for red,green,blue)
def encode_text_dummy(df,name):
dummies = pd.get_dummies(df[name])
for x in dummies.col... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: if clauses and embedded lists
Step2: dictionary and set comprehensions
Step3: <a id='exercise_1_1'></a>
Step4: <a id="string_formatting"></a>... | <ASSISTANT_TASK:>
Python Code:
N_SQUARES = 10
# Don't do this!!!
ugly_list = []
for i in range(N_SQUARES):
ugly_list.append(i**2)
print('ugly list = {}'.format(ugly_list))
# You can do the same in one line
wonderful_list = [ i**2 for i in range(N_SQUARES) ]
print('wonderful list = {}'.format(wonderful_list))
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Run the next cell to load the "SIGNS" dataset you are going to use.
Step2: As a reminder, the SIGNS dataset is a collection of 6 signs represen... | <ASSISTANT_TASK:>
Python Code:
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
import tensorflow as tf
from tensorflow.python.framework import ops
from cnn_utils import *
%matplotlib inline
np.random.seed(1)
# Loading the data (sig... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Bayesian Solution
Step2: Short Cut #1
Step3: Short Cut #2
Step4: How does the outcome depend on all those parameter?
Step5: Observation
Step... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from straightline_utils import *
%matplotlib inline
from matplotlib import rcParams
rcParams['savefig.dpi'] = 100
(x,y,sigmay) = get_data_no_outliers()
plot_yerr(x, y, sigmay)
def straight_line_log_likelihood(x, y, sigmay, m, b):
'''
Returns the log-likelihood ... |
<SYSTEM_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 process is quite simple and only requires the user to store the .qasm file in an appropriate location and maintain the absolute path of the ... | <ASSISTANT_TASK:>
Python Code:
from qutip_qip.qasm import read_qasm
from qutip import rand_ket, tensor, basis
from qutip_qip.circuit import Measurement
import numpy as np
path = "qasm_files/swap.qasm"
qasm_file = open(path, "r")
print(qasm_file.read())
from qutip_qip.operations.gates import gate_sequence_product
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: In Python, models should not be saved with pickle; the Stan backend attached to the model object will not pickle well, and will produce issues u... | <ASSISTANT_TASK:>
Python Code:
%%R
saveRDS(m, file="model.RDS") # Save model
m <- readRDS(file="model.RDS") # Load model
import json
from prophet.serialize import model_to_json, model_from_json
with open('serialized_model.json', 'w') as fout:
json.dump(model_to_json(m), fout) # Save model
with open('serialized_... |
<SYSTEM_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 fetching and preprocessing
Step2: We can see from this example that the textual data are not very cleaned
Step3: Textual data preprocessi... | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
#get raw data
import xml.etree.ElementTree as ET
tree = ET.parse('../dataset/nysk.xml')
root = tree.getroot()
root1 = root.getchildren()[150].getchildren()
texts=[]
for document in root.iter('document'):
text = docum... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Recall that tables in relational databases are linked through primary keys and sometimes other fields that are common to multiple tables (as is ... | <ASSISTANT_TASK:>
Python Code:
%load_ext sql
%sql mysql://studentuser:studentpw@mysqlserver/dognitiondb
%sql USE dognitiondb
%config SqlMagic.displaylimit=25
%%sql
SELECT d.dog_guid AS DogID, d.user_guid AS UserID, AVG(r.rating) AS AvgRating,
COUNT(r.rating) AS NumRatings, d.breed, d.breed_group, d.breed_type
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: Calculate the mean
Step2: Calculate the median
Step3: Calculate the mode
Step4: Calculate the standard deviation
Step5: Alternatively, we ca... | <ASSISTANT_TASK:>
Python Code:
from statistics import mean, median, mode, stdev
test_scores = [60 , 83, 83, 91, 100]
mean(test_scores)
median(test_scores)
83
mode(test_scores)
stdev(test_scores)
import statistics
test_scores = [60 , 83, 83, 91, 100]
statistics.mean(test_scores)
statistics.median(test_scores)
stati... |
<SYSTEM_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) local histogram equilization
Step2: 3) Filter out the noise in the image to get only the points we actually want
Step3: 4) Now that you've ... | <ASSISTANT_TASK:>
Python Code:
from clarityviz import claritybase
token = 'Fear199'
source_directory = '/cis/home/alee/claritycontrol/code/data/raw'
# Initialize the claritybase object, the initial basis for all operations.
# After you initialize with a token and source directory, a folder will be created in your curre... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Note pairs of clusters with similar mean densities and y-values.
Step2: This clustering result is more along the lines of what we expected, as ... | <ASSISTANT_TASK:>
Python Code:
from sklearn import cluster
kmeans1 = cluster.KMeans(4)
kmeans1.fit_predict(data)
print kmeans1.cluster_centers_
data_yd = data[:, (1, 3)]
kmeans2 = cluster.KMeans(4)
kmeans2.fit_predict(data_yd)
print kmeans2.cluster_centers_
colors = ['b', 'g', 'r', 'c', 'm']
for i, c in zip(range(4),... |
<SYSTEM_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 would now like to classify the test data with the kNN classifier. Recall that we can break down this process into two steps
Step2: Inline Qu... | <ASSISTANT_TASK:>
Python Code:
# Run some setup code for this notebook.
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
# This is a bit of magic to make matplotlib figures appear inline in the notebook
# rather than in a new window.
%matplotlib inline
plt.rcPa... |
<SYSTEM_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 raw data
Step2: Use tf.data to read the CSV files
Step3: Build a simple keras DNN model
Step4: Next, we can call the build_model to crea... | <ASSISTANT_TASK:>
Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
import datetime
import os
import shutil
import pandas as pd
import tensorflow as tf
from matplotlib import pyplot as plt
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.lay... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Benchmarking
Step2: Parallelism
| <ASSISTANT_TASK:>
Python Code:
import pescador
import numpy as np
np.set_printoptions(precision=4)
import sklearn
import sklearn.datasets
import sklearn.linear_model
import sklearn.metrics
import sklearn.model_selection
def batch_sampler(X, Y, batch_size=20, scale = 1e-1):
'''A gaussian noise generator for data
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load & Read Datasets
Step2: Extracting features
Step3: Convert Occurrence to Frequency
Step4: In the above code, we first used the fit() meth... | <ASSISTANT_TASK:>
Python Code:
import nltk
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.ensemble import RandomForestClassifier
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:
Step1: The Rise and Fall of the US Employment-Population Ratio
Step2: Source
Step3: Source
Step4: Source
| <ASSISTANT_TASK:>
Python Code:
Creates a figure using FRED data
Uses pandas Remote Data Access API
Documentation can be found at http://pandas.pydata.org/pandas-docs/stable/remote_data.html
%matplotlib inline
import pandas as pd
import pandas.io.data as web
import matplotlib.pyplot as plt
import numpy as np
import date... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Optimizer -
Step2: Initializing an Optimizer
Step3: cbs is a list of functions that will be composed when applying the step. For instance, you... | <ASSISTANT_TASK:>
Python Code:
#|export
class _BaseOptimizer():
"Common functionality between `Optimizer` and `OptimWrapper`"
def all_params(self,
n:(slice, int)=slice(None), # Extended slicing over the optimizer `param_lists`
with_grad:bool=False # Get all param tuples. If `True` select only th... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Inspecting unique values in each columns
Step2: Selecting only relevant columns
Step3: still needs to be done
Step4: Saving selection
Step5:... | <ASSISTANT_TASK:>
Python Code:
with open('d3/mapHemicycle/data/scrutins.json', 'r') as f:
json_data = json.load(f)
json_data.keys()
json_data['scrutins'].keys()
df = pd.io.json.json_normalize(json_data['scrutins']['scrutin'])
for col in df.columns:
print ('____________________')
print (col)
try:
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's start again with our text-classification problem, but for now we will only use a reduced number of instances. We will work only with 3,000... | <ASSISTANT_TASK:>
Python Code:
%pylab inline
import IPython
import sklearn as sk
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
print 'IPython version:', IPython.__version__
print 'numpy version:', np.__version__
print 'scikit-learn version:', sk.__version__
print 'matplotlib version:', matplotlib... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: BNU 1
Step2: HNU Dataset
Step3: DC1 Dataset
Step4: NKI 1
| <ASSISTANT_TASK:>
Python Code:
%%script false
## disklog.sh
#!/bin/bash -e
# run this in the background with nohup ./disklog.sh > disk.txt &
#
while true; do
echo "$(du -s $1 | awk '{print $1}')"
sleep 30
done
##cpulog.sh
import psutil
import time
import argparse
def cpulog(outfile):
with open(outfile, 'w'... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Bootstrap Comparisons
Step2: TOST Equivalence Tests
| <ASSISTANT_TASK:>
Python Code:
# Import numpy and set random number generator
import numpy as np
np.random.seed(10)
# Import stats functions
from pymer4.stats import perm_test
# Generate two samples of data: X (M~2, SD~10, N=100) and Y (M~2.5, SD~1, N=100)
x = np.random.normal(loc=2, size=100)
y = np.random.normal(loc=... |
<SYSTEM_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 time series data
Step2: There are a few supported file formats. AT2 files can be loaded as follows
Step3: Create site profile
Step4: Cre... | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
import pysra
%matplotlib inline
# Increased figure sizes
plt.rcParams["figure.dpi"] = 120
fname = "data/NIS090.AT2"
with open(fname) as fp:
next(fp)
description = next(fp).strip()
next(fp)
parts = next(fp).split()
tim... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 1. Series
Step2: También podemos crear una Series a partir de un diccionario de Python. Como no le especificamos índices, se genera a partir de... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
# Este notebook fue elaborado con la versión 1.0.3 de Pandas
pd.__version__
s= pd.Series(np.random.randn(5), index=['a','b','c','d','e'])
s
d = pd.Series({'b': 1, 'a': 0, 'c': 2})
d
s[s > s.median()] # Seleccionamos los valores mayores a la median... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Exercise 1
Step2: Exercise 2
Step3: Exercise 3
| <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
emails = ['alawrence0@prlog.org',
'blynch1@businessweek.com',
'mdixon2@cmu.edu',
'rvasquez3@1688.com',
'astone4@creativecommons.org',
'mcarter5@chicagotribune.com',
'dcole6@vinaora.com',
'kpeterson7@topsy.com',
'ewebb... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Locally and Remote
Step2: Plot a Histogram of x
Step3: Customizable
Step4: Other Languages
Step5: Keep it all together
Step6: NBconvert exa... | <ASSISTANT_TASK:>
Python Code:
2+4
print("hello")
print("Hello world!")
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(10000)
print(x)
plt.hist(x, bins=50)
plt.show()
%lsmagic
%timeit y = np.random.randn(100000)
%ll
%%bash
ls -l
files = !ls # But glob is a better way
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: Sample Code
Step2: Compile Model
Step3: Fit Model
| <ASSISTANT_TASK:>
Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo('mPFq5KMxKVw', width=800, height=450)
from tensorflow.python.keras.applications import ResNet50
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, Flatten, GlobalAveragePooling2D
nu... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: We're going to be building a model that recognizes these digits as 5, 0, and 4.
Step3: Working with the images
Step4: The first 10 pixels are ... | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
from IPython.display import Image
import base64
Image(data=base64.decodestring("iVBORw0KGgoAAAANSUhEUgAAAMYAAABFCAYAAAARv5krAAAYl0lEQVR4Ae3dV4wc1bYG4D3YYJucc8455yCSSIYrBAi4EjriAZHECyAk3rAID1gCIXGRgIvASIQr8UTmgDA5imByPpicTcYGY+yrbx+tOUWpu2e6u7qnZ7qXVFP... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Re-arrange classes to 2 separate directories
Step2: Training configs
Step3: Setup generators to provide with train and validation batches
Step... | <ASSISTANT_TASK:>
Python Code:
!pip install kaggle
api_token = {"username":"xxxxx","key":"xxxxxxxxxxxxxxxxxxxxxxxx"}
import json
import zipfile
import os
os.mkdir('/root/.kaggle')
with open('/root/.kaggle/kaggle.json', 'w') as file:
json.dump(api_token, file)
!chmod 600 /root/.kaggle/kaggle.json
# !kaggle config pa... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Read raw data
Step2: Time-frequency beamforming based on DICS
| <ASSISTANT_TASK:>
Python Code:
# Author: Roman Goj <roman.goj@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne.event import make_fixed_length_events
from mne.datasets import sample
from mne.time_frequency import csd_fourier
from mne.beamformer import tf_dics
from mne.viz import plot_source_spectrogram
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: アテンションを用いたニューラル機械翻訳
Step2: データセットのダウンロードと準備
Step3: 実験を速くするためデータセットのサイズを制限(オプション)
Step4: tf.data データセットの作成
Step5: エンコーダー・デコーダーモデルの記述
Step6: ... | <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: The shape of an ndarray gives us the dimensions. b is a 1-by-4 matrix, or a row vector. c is a 2-by-2 vector, or a column vector. d is a 2-by-2 ... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([[1, 2, 3, 4]])
c = np.array([[1], [2], [3], [4]])
d = np.array([[1, 2], [3, 4]])
print(a)
print('shape of a: {}'.format(a.shape))
print()
print(b)
print('shape of b: {}'.format(b.shape))
print()
print(c)
print('shape of c: {}'.fo... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Questão 01
Step2: Questão 02
Step3: Questão 03
Step4: Questão 04
Step5: Questão 05
Step6: Questão 06
Step7: Questão 07
Step8: Questão 08
| <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
% matplotlib inline
def f(x):
return (x**4 - 10 * x ** 3 - x**2 + 5 * x) / (x**4 + 1)
A = 8.00
B = 12.00
xa = A
xb = B
ga = f(xa)
gb = f(xb)
for i in range(10):
xmed = (xa + xb) / 2
gmed = f(xmed)
if gmed < 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: A number of Pandas functions are useful when cleaning up raw data and converting it to a data set ready for analysis and visualisation. In this ... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
countries = pd.DataFrame({'county name': ['Belgium', 'Flance', 'Germany', 'Netherlands', ['United Kingdom', 'Germany']],
'population': [11.3, 64.3, 81.3, 16.9, 64.9],
... |
<SYSTEM_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. Get data (cAFM and SKPM images of a P3HT/PMMA blend) for this tutorial
Step2: 3. Import relevant packages and data into the notebook.
Step3:... | <ASSISTANT_TASK:>
Python Code:
#for igor files:
!curl -o util.py https://raw.githubusercontent.com/kongjy/hyperAFM/master/hyperAFM/util.py
#for image alignment:
!curl -o imagealignment.py https://raw.githubusercontent.com/kongjy/hyperAFM/master/hyperAFM/imagealignment.py
#the above will download the files at the spec... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set parameters
Step2: Define adjacency for statistics
Step3: Compute statistic
Step4: View time-frequency plots
| <ASSISTANT_TASK:>
Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.time_frequency import tfr_morlet
from mne.stats import permutation_cluster_1samp_test
from mne.datasets import sample
print(__doc_... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Process our simulated raw data (taking into account head movements)
| <ASSISTANT_TASK:>
Python Code:
# Authors: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)
from os import path as op
import mne
from mne.preprocessing import maxwell_filter
print(__doc__)
data_path = op.join(mne.datasets.misc.data_path(verbose=True), 'movement')
pos = mne.chpi.read_head_pos(op.join(dat... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <h3>Display Sequence logo of unaligned motives</h3>
Step2: <h3>Multiple Sequence Alignment of motives with Muscle</h3>
Step3: <h3>Display sequ... | <ASSISTANT_TASK:>
Python Code:
#printing motives as lists
for motif in glam2.motives_list:
for m in motif:
print m
print
glam2.display_logo(do_alignment=False)
glam2.display_logo(motif_num=1)
glam2.align_motives() #MSA with Muscle
motives1=glam2.aligned_motives_list
for m in motives1:
for i in ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Creating a SEA model
Step2: We are only interested in a limited frequency range, e.g. the third octave bands ranging from 1000 to 4000 Hz.
Step... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
pd.set_option('float_format', '{:.2e}'.format)
import matplotlib
%matplotlib inline
from seapy import System
from acoustics.signal import OctaveBand
f = OctaveBand(fstart=20.0, fstop=4000.0, fraction=1)
system1 = System(f)
air = system1.add_materia... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.