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: Linear Regression
Step2: Again, we start by splitting our dataset into a training (75%) and a test set (25%)
Step3: Next, we use the learning ... | <ASSISTANT_TASK:>
Python Code:
x = np.linspace(-3, 3, 100)
print(x)
rng = np.random.RandomState(42)
y = np.sin(4 * x) + x + rng.uniform(size=len(x))
plt.plot(x, y, 'o');
print('Before: ', x.shape)
X = x[:, np.newaxis]
print('After: ', X.shape)
from sklearn.model_selection import train_test_split
X_train, X_test, y_tr... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Récupérer les données
| <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
from pyensae.datasource import download_data
data_train = download_data("off_train_all.zip",
url="https://raw.githubusercontent.com/sdpython/data/master/OpenFoodFacts/")
data_test = download_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: SHARING VARIABLES FROM PYTHON TO R
Step2: GETTING STOCK DATA FROM R INTO PYTHON
Step3: PANDAS IS AWESOME
Step4: STACKING UP DATA IN PANELS
St... | <ASSISTANT_TASK:>
Python Code:
#Invoke numPy and matplotlib in one command
%pylab inline
#IMPORTING STOCK DATA USING PANDAS
from pandas.io.data import DataReader
from datetime import datetime
goog = DataReader("GOOG", "yahoo", datetime(2014,4,1), datetime(2015,3,31))
stkp = goog["Adj Close"]
print stkp
goog.head()
goo... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Считаем данные по росту и весу (weights_heights.csv, приложенный в задании) в объект Pandas DataFrame
Step2: Чаще всего первое, что надо надо с... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
data = pd.read_csv('weights_heights.csv', index_col='Index')
data.plot(y='Height', kind='hist',
color='red', title='Height (inch.) distribution')
# Ваш код здесь... |
<SYSTEM_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 will use scipy from the Anaconda distribution to read the WAV sample files
Step2: We define the length we want to record in seconds and the ... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from scipy.io import wavfile
# Let's start with the first sample corresponding to the lower string E2
rate, myrecording = wavfile.read("samples/guitar_E2_very-long_forte_normal.wav")
print(rate, np_... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load the data
Step2: Extract 30s events from annotations
Step3: Create Epochs from the data based on the events found in the annotations
Step4... | <ASSISTANT_TASK:>
Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Stanislas Chambon <stan.chambon@gmail.com>
# Joan Massich <mailsik@gmail.com>
#
# License: BSD Style.
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets.sleep_physionet.age 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: Language Translation
Step3: Explore the Data
Step6: Implement Preprocessing Function
Step8: Preprocess all the data and save it
Step10: Chec... | <ASSISTANT_TASK:>
Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
view_sentence_range = (1, 10)
DON'T MODIFY AN... |
<SYSTEM_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 treats mystring as an instance of a string object. One then has access to a long list of attributes and methods associated with this obj... | <ASSISTANT_TASK:>
Python Code:
mystring = 'economics'
# return the string capitalized
mystring.upper()
# count the number of occurunces of the letter 'o'
mystring.count('o')
# tell me if the string ends with the letter 'M'
mystring.endswith('M')
import numpy as np
from geqfarm import *
myeconomy= Economy(20)
myecon... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Librerias
Step2: El panorama!
Step3: Los datos como X y Y
Step4: A visualizar! (Solo para recordar como son los datos)
Step5: Algoritmo-del-... | <ASSISTANT_TASK:>
Python Code:
def grafica_KMeans(X1,X2,Y,clf):
X1=X[:, 0]
X2=X[:, 1]
# Plot the decision boundary. For that, we will assign a color to each
x_min, x_max = X1.min()-1, X1.max() +1
y_min, y_max = X2.min()-1, X2.max() +1
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 200), np.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: Polynomial regression, revisited
Step2: Let's use matplotlib to visualize what a polynomial regression looks like on the house data.
Step3: As... | <ASSISTANT_TASK:>
Python Code:
import graphlab
import numpy as np
def polynomial_sframe(feature, degree):
poly_dataset = graphlab.SFrame()
poly_dataset['power_1'] = feature
if degree > 1:
for power in range(2, degree + 1):
column = 'power_' + str(power)
poly_dataset[column] ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Shell Info
Step2: You can interact with the widget produced in output above (which may not be visible) like this
| <ASSISTANT_TASK:>
Python Code:
# Import the tardis widgets module
import tardis.widgets as tw
# Create a Simulation object by running tardis
from tardis import run_tardis
sim = run_tardis('tardis_example.yml')
# Now use it to create a shell info widget
shell_info = tw.shell_info_from_simulation(sim)
# Call display met... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Raw data
Step2: Plotting
Step3: Do calculations with the data
Step4: Here's an example of calculating the difference between the values in co... | <ASSISTANT_TASK:>
Python Code:
# import software packages
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
inline_rc = dict(mpl.rcParams)
# enter column labels and raw data (with same # of values)
table1 = pd.DataFrame.from_items([
('column1', [... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Model Inputs
Step2: Generator network
Step3: Discriminator
Step4: Hyperparameters
Step5: Build network
Step6: Discriminator and Generator L... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data')
def model_inputs(real_dim, z_dim):
inputs_real = tf.placeholde... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: File Reading
Step2: Scatter Plots
Step3: Plot properties
Step4: Multiple plots
Step5: Save figure
| <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
x = np.arange(-np.pi,np.pi,0.01) # Create an array of x values from -pi to pi with 0.01 interval
y = np.sin(x) # Apply sin function on all x
plt.plot(x,y)
plt.plot(y)
x = np.arange(0,10,1) # x = 1,2,3,4,5...
y = x*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: Step 1
Step2: Step 2
Step3: They are pretty similar to full data when I print the descriptive stats for test and train data.
Step 3
Step4: M... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import matplotlib.pyplot as plt
# Read CSV data into df
df = pd.read_csv('./theAwesome_EnsModel.csv')
# delete id column no need
df.drop('Id',axis=1,inplace=True)
df.head()
# Learn the unique values in diagnosis column
print("Classification labels: ", df.Species.unique... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Make an artificial case where we expect to not go to any of the houses (too much candy from each home, as each home gives more than the maximum ... | <ASSISTANT_TASK:>
Python Code:
sample_input_arr = np.array([5,10,2,4,3,2,1],dtype=np.int32)
f = np.savetxt("sample_input.txt", sample_input_arr, fmt='%i',delimiter="\n")
N_H = 10 # <= 10000
C_max = 5 # <= 1000
c_low = 0
c_high = 10
filename = "sample_input_1.txt"
homes = np.random.randint(low=c_low,high=c_high, size=... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Read the RIRE data and generate a larger point set as a reference
Step2: Initial Alignment
Step3: Registration
Step4: In some cases visual co... | <ASSISTANT_TASK:>
Python Code:
import SimpleITK as sitk
# Utility method that either downloads data from the network or
# if already downloaded returns the file name for reading from disk (cached data).
from downloaddata import fetch_data as fdata
# Always write output to a separate directory, we don't want to pollute ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: UMAP vs T-SNE
Step2: Writing a Function to quickly Visualize Corpus
Step3: Quickly Comparing Plots by Controlling
| <ASSISTANT_TASK:>
Python Code:
##### Import all the necessary Libraries
from yellowbrick.text import TSNEVisualizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from yellowbrick.text import UMAPVisualizer
from yellowbrick.datasets import load_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: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 2... | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ipsl', 'sandbox-2', 'toplevel')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "e... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Interact basics
Step2: Use the interact function to interact with the print_sum function.
Step3: Write a function named print_string that prin... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
from IPython.html import widgets
def print_sum(a, b):
c = a + b
print c
interact(print_sum, a = (-10., 10.... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: Import hooks typically take the form of two objects
Step5: Notebook Loader
Step7: The Module Finder
Step8: Register the hook
Step9: After th... | <ASSISTANT_TASK:>
Python Code:
import io, os, sys, types
import nbformat
from IPython import get_ipython
from IPython.core.interactiveshell import InteractiveShell
def find_notebook(fullname, path=None):
find a notebook, given its fully qualified name and an optional path
This turns "foo.bar" into "foo/ba... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Language Translation
Step3: Explore the Data
Step6: Implement Preprocessing Function
Step8: Preprocess all the data and save it
Step10: Chec... | <ASSISTANT_TASK:>
Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
view_sentence_range = (0, 10)
DON'T MODIFY AN... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Evolution
Step2: Selection-Mutation
Step3: Multiple species.
Step4: Genomes are Sequences
Step5: Fitness Landscape
Step6: Evolutionary Game... | <ASSISTANT_TASK:>
Python Code:
%%html
<div >
<iframe type="text/html" width="336" height="550" frameborder="0" allowfullscreen style="max-width:100%;float: left" src="https://lesen.amazon.de/kp/card?asin=B003UV8TC2&preview=inline&linkCode=kpe&ref_=cm_sw_r_kb_dp_MamPyb1NWT7A8" ></iframe>
</div>
<div >
<iframe type="text... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Initialization
Step2: Reading the sample tube file and creating a sample spatial object group object
Step3: Reading the sample image file and ... | <ASSISTANT_TASK:>
Python Code:
import os
import sys
import numpy
# Path for TubeTK libs and bin
#Values takend from TubeTK launcher
sys.path.append("C:/src/TubeTK_Python_ITK/TubeTK-build/lib/")
sys.path.append("C:/src/TubeTK_Python_ITK/TubeTK-build/lib/Release")
# Setting TubeTK Build Directory
TubeTK_BUILD_DIR=None
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: Foreword
Step2: Not bad for less than ten lines of code!
Step3: Now, instead of a single string label as our output (prediction), we have a 3x... | <ASSISTANT_TASK:>
Python Code:
from IPython.display import Image
Image(data="img/mr-t.jpg")
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
seed = 1234; np.random.seed(seed)
import seaborn as sns
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from sklearn.cros... |
<SYSTEM_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 some test histograms
Step4: Calculate global p-value based on maximum local significance and several toy likelihood scans
Step5: The co... | <ASSISTANT_TASK:>
Python Code:
%pylab inline --no-import-all
from lee2d import *
from create_test_histograms import *
create_test_histograms()
#check to make sure test_hists.root exists
!ls *root
# Specify the necessary info
max_local_significance = 4.
# choose u1, u2 thresholds for doing the scan.
# these are arbit... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Como los datos son bidimensionales, podemos representar cada punto en un sistema de coordenadas (ejes x e y).
Step2: La clasificación es una ta... | <ASSISTANT_TASK:>
Python Code:
from sklearn.datasets import make_blobs
X, y = make_blobs(centers=2, random_state=0)
print('X ~ n_samples x n_features:', X.shape)
print('y ~ n_samples:', y.shape)
print('\n5 primeros ejemplos:\n', X[:5, :])
print('\n5 primeras etiquetas:', y[:5])
plt.scatter(X[y == 0, 0], X[y == 0, 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: TF Lattice 집계 함수 모델
Step2: 필수 패키지 가져오기
Step3: 퍼즐 데이터세트 다운로드하기
Step4: 특성과 레이블 추출하기 및 변환하기
Step5: 이 가이드에서 훈련에 사용되는 기본값 설정하기
Step6: 특성 구성
Step... | <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 toy data created above consists of 4 gaussian blobs, having 200 points each, centered around the vertices of a rectancle. Let's plot it for ... | <ASSISTANT_TASK:>
Python Code:
from numpy import concatenate, array
from numpy.random import randn
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
num = 200
d1 = concatenate((randn(1,num),10.*randn(1,num)),0)
d2 = concatenate((randn(1,num),10.*randn(1,num)),0)+array([[10.],[0.]])
d3 = concatenat... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 위의 코드에서 우리는 함수 'ex_func'이 함수 내에서 입력받은 변수를 잘 출력해주는 것을 확인했습니다.
Step2: 언뜻보면 지정한 값이 잘 대입된듯합니다.
Step3: 그럼 함수 ex_func이 값을 가지게 하려면 어떻게 해야할까요?
Step4: ... | <ASSISTANT_TASK:>
Python Code:
def ex_func(ltr):
ltr = 1
print ltr # 변수 ltr을 print로 출력했습니다.
ex_func('a') # 입력된 변수가 잘 출력되었습니다.
def ex_func(ltr):
ltr = 1
print ltr
var = ex_func('a')
def ex_func(ltr):
ltr = 1
print ltr
var = ex_func('a')
print var # None이 출력됩니다. 실제로는 var에 아무런 값도 없... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Dataset
Step2: Prior, Likelihood, and True Posterior
Step3: HMC using Blackjax
Step4: Density of samples and True posterior
Step5: Trace plo... | <ASSISTANT_TASK:>
Python Code:
import jax
import jax.numpy as jnp
from jax import lax
try:
from probml_utils import latexify, savefig
except:
%pip install git+https://github.com/probml/probml-utils.git
from probml_utils import latexify, savefig
try:
import blackjax
except:
%pip install blackjax
... |
<SYSTEM_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 go over the columns
Step2: Now suppose we want a DataFrame of all earnings releases with revenue over 30 billion dollars. For those earni... | <ASSISTANT_TASK:>
Python Code:
# import the dataset
from quantopian.interactive.data.eventvestor import earnings_releases
# or if you want to import the free dataset, use:
# from quantopian.interactivedata.eventvestor import earnings_releases_free
# import data operations
from odo import odo
# import other libraries we... |
<SYSTEM_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 prompt messagges with the priority level of "information".
Step2: Maximum information (aka 'Information overload')
Step3: Adjusting ... | <ASSISTANT_TASK:>
Python Code:
import logging
logging.basicConfig(level=logging.INFO)
import warnings
import logging
warnings.simplefilter('default', DeprecationWarning)
logging.captureWarnings(True)
logging.basicConfig(level=logging.INFO)
import warnings
import logging
warnings.simplefilter('always', DeprecationWarn... |
<SYSTEM_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 there are 8 folders present inside the train folder, one for each species.
Step2: So the number of files for species ALB (Albacore tuna) is ... | <ASSISTANT_TASK:>
Python Code:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd #... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: TensorFlow Addons Layers
Step2: Build Models
Step3: Load Data
Step4: Train Models
| <ASSISTANT_TASK:>
Python Code:
#@title Licensed under the Apache License, Version 2.0
# 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 writing, software
# dis... |
<SYSTEM_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 visualize this vector
Step2: Our first scoring function will score a single annotation (encoder hidden state), which looks like this
Step... | <ASSISTANT_TASK:>
Python Code:
dec_hidden_state = [5,1,20]
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Let's visualize our decoder hidden state
plt.figure(figsize=(1.5, 4.5))
sns.heatmap(np.transpose(np.matrix(dec_hidden_state)), annot=True, cmap=sns.light_palette("pur... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Import section specific modules
Step2: 1.10 The Limits of Single Dish Astronomy
Step3: Figure 1.10.1
Step4: Figure 1.10.2
Step6: Figure 1.10... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import HTML
HTML('../style/course.css') #apply general CSS
import ipywidgets
from IPython.display import Image
HTML('../style/code_toggle.html')
Image(filename='figures/hart_26m_15m_2012-09-11_08... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Sparse 2d interpolation
Step2: The following plot should show the points on the boundary and the single point in the interior
Step3: Use meshg... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set_style('white')
from scipy.interpolate import griddata
x = np.hstack((np.linspace(-4,4,9), np.full(11, -5), np.linspace(-4,4,9), np.full(11, 5), [0]))
y = np.hstack((np.full(9,-5), np.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: Problem Statement
Step3: Each dot corresponds to a position on the football field where a football player has hit the ball with his/her head af... | <ASSISTANT_TASK:>
Python Code:
# import packages
import numpy as np
import matplotlib.pyplot as plt
from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec
from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters
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: Task 2
Step2: Task 3
Step3: Task 4
Step4: Task 5
Step6: Assignment wrapup
| <ASSISTANT_TASK:>
Python Code:
# Put your code here!
# Put your code here!
# Put your code here!
# Put your code here!
# Put your code here!
from IPython.display import HTML
HTML(
<iframe
src="https://goo.gl/forms/VwY5ods4ugnwidnG2?embedded=true"
width="80%"
height="1200px"
frameborder="0"
marginheight="... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Linear Mixed Effects Models
Step2: Make things Fast!
Step4: Note
Step5: We load and preprocess the data set. We hold out 20% of the data so w... | <ASSISTANT_TASK:>
Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Make sure you have pycocotools installed
Step2: Get tensorflow/models or cd to parent directory of the repository.
Step3: Compile protobufs an... | <ASSISTANT_TASK:>
Python Code:
!pip install -U --pre tensorflow=="2.*"
!pip install tf_slim
!pip install pycocotools
import os
import pathlib
if "models" in pathlib.Path.cwd().parts:
while "models" in pathlib.Path.cwd().parts:
os.chdir('..')
elif not pathlib.Path('models').exists():
!git clone --depth 1 https... |
<SYSTEM_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. Ensuring Your Changes Stick
Step2: Hrm, it looks like the DataFrame is updated, but is it? I think not!
Step3: What the heck?! The missing ... | <ASSISTANT_TASK:>
Python Code:
# Import the Python libraries we need
import pandas as pd
# Define a variable for the accidents data file
f = './data/accidents1k.csv'
# Use read_csv() to import the data
accidents = pd.read_csv(f,
sep=',',
header=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: As always, let's do imports and initialize a logger and a new Bundle. See Building a System for more details.
Step2: Now let's add a light cur... | <ASSISTANT_TASK:>
Python Code:
!pip install -I "phoebe>=2.2,<2.3"
%matplotlib inline
import phoebe
from phoebe import u # units
import numpy as np
import matplotlib.pyplot as plt
logger = phoebe.logger('error')
b = phoebe.default_binary()
b.add_dataset('lc', times=phoebe.linspace(-0.05, 0.05, 51), dataset='lc01')
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: Customization basics
Step2: Import TensorFlow
Step3: Tensors
Step4: Each tf.Tensor has a shape and a datatype
Step5: The most obvious differ... | <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: You can then run the sample script in the examples folder to run the gaussian example on e.g. 16 processors using
Step2: An additional flag whi... | <ASSISTANT_TASK:>
Python Code:
prop={'dfunc':dist_metric, 'outfile':"gaussian_example.txt", 'verbose':1, 'adapt_t': True, 'mpi': True}
prop={'dfunc':dist_metric, 'outfile':"gaussian_example.txt", 'verbose':1, 'adapt_t': True, 'pert_kernel':2,\
'mpi':True,'mpi_splitcomm': True, 'num_abc': 4}
#to run on 4 threads... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Seznam zdrojů
Step2: Základní vizualizace dat
Step3: Knihovna seaborn je nadstavba nad knihovou matplotlib, která poskytuje graficky přehledně... | <ASSISTANT_TASK:>
Python Code:
MY_VERSION = 1,0
import sys
import datetime
import numpy as np
import pandas as pd
import pandas_datareader as pdr
import pandas_datareader.data as pdr_web
import quandl as ql
from matplotlib import __version__ as matplotlib_version
from seaborn import __version__ as seaborn_version
# Loa... |
<SYSTEM_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: 単純化するため、見出しのテキストのみを維持し、発行日は削除します。
Step5: TF-Hub モジュールを読... | <ASSISTANT_TASK:>
Python Code:
# Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved.
#
# 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
#
# http://www.apache.org/licenses/LICENSE... |
<SYSTEM_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 data
Step2: Artificially inducing missing values
Step3: Perform UNCURL for imputation
Step5: Imputation with MW
Step6: Imputation te... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import random
import numpy as np
import matplotlib.pyplot as plt
import scipy
import scipy.io
from scipy import sparse
import uncurl
data_z = scipy.io.loadmat('../data/GSE60361_dat.mat')
data_10x = scipy.io.loadmat('../data/10x_pooled_400.mat')
data_z_mat = data_z['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: Load Iris Dataset
Step2: Create Logistic Regression
Step3: Create Hyperparameter Search Space
Step4: Create Grid Search
Step5: Conduct Grid ... | <ASSISTANT_TASK:>
Python Code:
# Load libraries
import numpy as np
from sklearn import linear_model, datasets
from sklearn.model_selection import GridSearchCV
# Load data
iris = datasets.load_iris()
X = iris.data
y = iris.target
# Create logistic regression
logistic = linear_model.LogisticRegression()
# Create regul... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 4.1 Introduction
Step2: 4.2 Basic Visualizations
Step3: 4.2.1.1 Labeling Data Points
Step4: 4.2.1.2 Points and Lines
Step5: 4.2.2 Visualizin... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from matplotlib import pylab as plt
plt.rcParams['figure.figsize'] = (15.0, 10.0)
import pandas as pd
import seaborn as sns
data = pd.read_csv("978-3-319-12065-2/chapter-4/teams.csv")
data.head()
data.plot(kind='scatter',x="payroll",y="wins")
sns.regplot("payroll","wi... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 행렬
Step2: 특수한 행렬
Step3: 대각 행렬 중에서도 모든 대각 성분의 값이 1인 대각 행렬을 단위 행렬(identity matrix)이라고 한다. 단위 행렬은 보통 알파벳 대문자 $I$로 표기하는 경우가 많다.
Step4: 연산
Step5: ... | <ASSISTANT_TASK:>
Python Code:
x = np.array([1, 2, 3, 4])
x, np.shape(x)
x = np.array([[1], [2], [3], [4]])
x, np.shape(x)
X = np.array([[11,12,13],[21,22,23]])
X
np.diag([3, 4, 1])
np.identity(3)
np.eye(5)
X = np.array([[11,12,13],[21,22,23]])
X
X.T
x = np.array([10, 11, 12, 13, 14])
x
y = np.array([0, 1, 2, 3, 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: Load and run strategy
Step2: Display the trade details
Step3: Load existing objects into a Jupyter notebook
Step4: Load live trading results ... | <ASSISTANT_TASK:>
Python Code:
from pathlib import Path
from freqtrade.configuration import Configuration
# Customize these according to your needs.
# Initialize empty configuration object
config = Configuration.from_files([])
# Optionally, use existing configuration file
# config = Configuration.from_files(["config.js... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Fully-Connected Neural Nets
Step4: Affine layer
Step5: Affine layer
Step6: ReLU layer
Step7: ReLU layer
Step8: "Sandwich" layers
Step9: Lo... | <ASSISTANT_TASK:>
Python Code:
# As usual, a bit of setup
from __future__ import print_function
import time
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.fc_net import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_... |
<SYSTEM_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: 使用pct_change()计算收益率,使用dropna去除缺失值,使用distplot... | <ASSISTANT_TASK:>
Python Code:
#导入需要的程序包
import pandas as pd
import seaborn as sns
# 获取600196.XSHG的2015年01月的日级数据, 只获取open+close字段
df = get_price('600196.XSHG', start_date='2014-01-01', end_date='2015-01-31', frequency='daily', fields=['open','close'])
returns = df.pct_change().dropna()
sns.distplot(returns.iloc[:,0: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: Load the RECS dataset into the memory.
Step2: Preliminary analysis of dataset
Step3: 'TOTALBTU' column represents the total energy consumption... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
from operator import itemgetter
import math
%matplotlib inline
f= open('recs2009_public.csv','r')
datanames = np.genfromtxt(f,delimiter=',', names=True,dtype=None)
data1 = np.genfromtxt('recs2009_public.csv',delimit... |
<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: Fitting a model to data with outliers using MCMC
Step3: Now we'll actually generate the fake data. The cell below contains tunable parameters -... | <ASSISTANT_TASK:>
Python Code:
def sinusoid(t, amp, period, phase):
A generic sinusoidal curve. 'period' and 't' should have
the same units (e.g., days), and phase should be in
radians.
Parameters
----------
t : array_like
Array of times.
amp :... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Natural Frequency, Damped Frequency
Step2: Computation
Step3: We initialize a time variable
Step4: We compute the load, the sines and the cos... | <ASSISTANT_TASK:>
Python Code:
M = 600000
T = 0.6
z = 0.10
p0 = 400000
t0, t1, t2, t3 = 0.0, 1.0, 3.0, 6.0
wn = 2*np.pi/T
wd = wn*np.sqrt(1-z**2)
dt = 0.05
edt = np.exp(-z*wn*dt)
fac = dt/(2*M*wd)
t = dt*np.arange(1+int(t3/dt))
p = np.where(t<=t1, p0*(t-t0)/(t1-t0), np.where(t<t2, p0*(1-(t-t1)/(t2-t1)), 0))
s = np.... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <div style="background
Step2: <div style="background
Step3: <div style="background
Step4: <div style="background
Step5: <div style="backgrou... | <ASSISTANT_TASK:>
Python Code:
from IPython.display import Javascript,display
from corticalmapping.ipython_lizard.html_widgets import raw_code_toggle
raw_code_toggle()
display(Javascript(var nb = IPython.notebook;
//var is_code_cell = (nb.get_selected_cell().cell_type == 'code')
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: El vocabulario se utiliza en la fase transform para construir la matriz de ocurrencias
Step2: Vamos a realizar un nuevo fit con un corpus algo ... | <ASSISTANT_TASK:>
Python Code:
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(min_df=1)
vectorizer.fit([
"The cat sat on the mat.",
])
vectorizer.vocabulary_
X = vectorizer.transform([
"The cat sat on the mat.",
"This cat is a nice cat.",
]).toarray()
print(len(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: Minimal imports
Step2: Read data
Step3: Recommend articles
| <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.append('../..')
from bestPy import RecoBasedOn
from bestPy.datastructures import Transactions
file = '../tests/data/data50.csv' # Enter the path to and name of your data file here!
data = Transactions.from_csv(file)
customer = '7' # Specify the ID of the customer ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Higher order shape functions result from the (renormalized to 1) iterated convolution of the top hat shape function with itself
Step2: They're ... | <ASSISTANT_TASK:>
Python Code:
x, dx = np.linspace(-2, 2, 1000, retstep=True)
S = np.where(np.abs(x) < 0.5, 1, 0)
Sm = [S]
for i in range(1, 5):
Si = np.convolve(Sm[-1], Sm[0], mode='same').astype(float)
Si_value = integrate.trapz(Si, x)
Si /= Si_value
Sm.append(Si)
fig, ax = plt.subplots()
# ax.vlines... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Move code into python package
Step2: To use hyperparameter tuning in your training job you must perform the following steps
Step3: Modify task... | <ASSISTANT_TASK:>
Python Code:
PROJECT = <YOUR PROJECT>
BUCKET = <YOUR BUCKET>
REGION = <YOUR REGION>
TFVERSION = "2.1" # TF version for AI Platform to use
import os
os.environ["PROJECT"] = PROJECT
os.environ["BUCKET"] = BUCKET
os.environ["REGION"] = REGION
os.environ["TFVERSION"] = TFVERSION
!ls -la ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Real Robots
Step2: Get Real (aka Measured) Poses
Step3: Split Calibration and Validation Measures
Step4: Get Nominal Position Errors
Step5: ... | <ASSISTANT_TASK:>
Python Code:
from pybotics.robot import Robot
from pybotics.predefined_models import ur10
nominal_robot = Robot.from_parameters(ur10())
import pandas as pd
def display_robot_kinematics(robot: Robot):
df = pd.DataFrame(robot.kinematic_chain.matrix)
df.columns = ["alpha", "a", "theta", "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: Actually classify (here, we depart from public script)
Step2: Now, start the real hacking, so that it let's us interact
| <ASSISTANT_TASK:>
Python Code:
import csv
sports = [] # This is a python "list" data structure (it is "mutable")
# The file has a list of sports, one per line.
# There are spaces in some names, but no commas or weird punctuation
with open('../data/SportsDataset_ListOfSports.csv','r') as csvfile:
myreader = csv.rea... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: TFLite Authoring Tool
Step2: TensorFlow to TensorFlow Lite compatibility issue
Step3: Simple Target Aware Authoring usage
Step4: If any Tenso... | <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: First, dividing everything up into trials.
Step2: Again, plot some single trials to see what's up.
| <ASSISTANT_TASK:>
Python Code:
parameters = ho.read_session_data(alias, 'parameters')
parameters.head(5)
trial_phases = ho.read_session_data(alias, 'trial_phases')
trial_phases.head(5)
trials = ho.read_session_data(alias, 'trials')
trials.head(5)
screen_dims = ho.screen_dimensions_during_trial(alias=alias,trial_nr=0)
p... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: BigQuery TensorFlow 리더의 엔드 투 엔드 예제
Step2: 인증합니다.
Step3: 프로젝트 ID를 설정합니다.
Step4: Python 라이브러리를 가져오고 상수를 정의합니다.
Step5: BigQuery로 인구 조사 데이터 가져오기... | <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: Load in the desired scene, in this case, containing an instance of the Baxter robot.
Step2: Cameras
Step3: Grab a Snapshot from the Cameras
St... | <ASSISTANT_TASK:>
Python Code:
from ipywidgets import interact, interact_manual
import ipywidgets
from matplotlib import pyplot as plt
%matplotlib inline
import cv2
import numpy as np
import math
%run 'Set-up.ipynb'
%run 'Loading scenes.ipynb'
loadSceneRelativeToClient('../scenes/Baxter_demo.ttt')
from pyrep.vrep.vrep... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Class attributes
Step2: Also you can get all the specs. This is the dictionary with a lot of parameters.
Step3: Getting info
Step4: If you wa... | <ASSISTANT_TASK:>
Python Code:
am = Hero(1)
# You can use attributes to get some hero properties which depends on lvl, examples:
print('Anti-Mage stats on lvl {}'.format(am.lvl))
print('\tstrength = {}'.format(am.str))
print('\tagility = {}'.format(am.agi))
print('\tintellect = {}'.format(am.int))
print('\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: Now let's set up REBOUNDx and add radiation_forces. We also have to set the speed of light in the units we want to use.
Step2: By default, the... | <ASSISTANT_TASK:>
Python Code:
import rebound
import reboundx
import numpy as np
sim = rebound.Simulation()
sim.G = 6.674e-11 # SI units
sim.dt = 1.e4 # Initial timestep in sec.
sim.N_active = 2 # Make it so dust particles don't interact with one another gravitationally
sim.add(m=1.99e30, hash="Sun") # add Sun with mas... |
<SYSTEM_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. What are truncated distributions?
Step2: Let's now check that we can use this model in a typical MCMC workflow.
Step3: Inference
Step4: Re... | <ASSISTANT_TASK:>
Python Code:
!pip install -q git+https://github.com/pyro-ppl/numpyro.git
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
import numpyro
import numpyro.distributions as dist
from jax import lax, random
from jax.scipy.special import ndtr, ndtri
from jax.scipy.stats ... |
<SYSTEM_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... | <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 = Counter([i for idx... |
<SYSTEM_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, load the data for the EBTEL and HYDRAD results.
Step2: We'll some very basic curve fitting on a couple of our $\mathrm{EM}$ distribution... | <ASSISTANT_TASK:>
Python Code:
import os
import sys
import pickle
import numpy as np
from scipy.optimize import curve_fit
import seaborn.apionly as sns
import matplotlib.pyplot as plt
from matplotlib import ticker
sys.path.append(os.path.join(os.environ['EXP_DIR'],'EBTEL_analysis/src'))
import em_binner as emb
%matplot... |
<SYSTEM_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) Setup the Request
Step2: Where is the downloaded file getting stored?
Step3: What's the S3 Location (Unique Bucket Name + Key)?
Step4: Bui... | <ASSISTANT_TASK:>
Python Code:
# Setup the Sci-pype environment
import sys, os
# Only redis is needed for this notebook:
os.environ["ENV_DEPLOYMENT_TYPE"] = "JustRedis"
# Load the Sci-pype PyCore as a named-object called "core" and environment variables
from src.common.load_ipython_env import *
ds_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: We will remove the approval year information in order to make the model useful for future years (not included in the data).
Step2: Target varia... | <ASSISTANT_TASK:>
Python Code:
#Import necessary Python packages
#data analysis tools
import numpy as np
import pandas as pd
import datetime
from dateutil.relativedelta import relativedelta
#plotting tools
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
import graphviz
#classification
from s... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We load the variables and initilize the parameters we need
Step2: We run the filter
Step3: We can see a slight offset, we would expect that to... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
from numpy.linalg import inv
%matplotlib inline
data = loadmat('data_files/Tut7_file1.mat')
locals().update(data)
data.keys()
p, T = z.shape
mu = np.zeros(z.shape)
K = np.zeros((4, 4, T))
V = np.zeros((4, 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: Nota
Step2: Imágenes por clase en datos de entrenamiento
Step3: Observar algunas de las imágenes
Step4: Análisis de componentes principales (... | <ASSISTANT_TASK:>
Python Code:
import os
import random
from tqdm import tqdm
import matplotlib.pyplot as plt
from skimage import io #Para leer las imágenes
from skimage import img_as_float
%matplotlib inline
ROOT_DIR = os.getcwd()
DATA_DIR = os.path.join(ROOT_DIR, 'german-traffic-signs')
TRAIN_DIR = os.path.join(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: B-DNA Model
Step2: <img src="figures/DNA1.png" style="width
Step3: Function to plot the dye position
Step4: FRET as a function of $R$ and $R_... | <ASSISTANT_TASK:>
Python Code:
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from cycler import cycler
import seaborn as sns
%matplotlib inline
%config InlineBackend.figure_format='retina' # for hi-dpi displays
from mpl_toolkits.mplot3d import Axes3D
from num... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Question
Step2: Refresher
Step3: Interpretation
Step4: Predicting a Categorical Response
Step5: Let's change our task, so that we're predict... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import zipfile
with zipfile.ZipFile('../datasets/glass.csv.zip', 'r') as z:
f = z.open('glass.csv')
glass = pd.read_csv(f, sep=',', index_col=0)
glass.head()
%matplotlib inline
import matplotlib.pyplot as plt
# scatter plot using Pandas
glass.plot(kind='scatte... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Object Detection with TensorFlow Lite Model Maker
Step2: Import the required packages.
Step3: Prepare the dataset
Step4: Step 2. Load the dat... | <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 Metapack system allows for packaging data, long with all of the metadata, and the open_package function can be used to load packages off the... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import metapack as mp
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import geopandas as gpd
regions = mp.open_package('http://library.metatab.org/sandiego.gov-police_regions-1.csv')
regions
calls_p = mp.open_package('http://library.metatab... |
<SYSTEM_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 see the distribution of the Profit using a histogram plot and see if there is any outliers in the data using bosplot.
Step2: Profit has o... | <ASSISTANT_TASK:>
Python Code:
df_null_idx = df[df.isnull().sum(axis = 1) > 0].index
df.iloc[df_null_idx]
median_values = df.groupby("State")[["R&D Spend", "Marketing Spend"]].median()
median_values
df["R&D Spend"] = df.apply(lambda row: median_values.loc[row["State"], "R&D Spend"] if np.isnan(row["R&D Spend"]) else 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: ENDF
Step2: We can access the parameters contained within File 32 in a similar manner to the File 2 parameters from before.
Step3: The newly c... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import os
from pprint import pprint
import shutil
import subprocess
import urllib.request
import h5py
import numpy as np
import matplotlib.pyplot as plt
import openmc.data
# Download ENDF file
url = 'https://t2.lanl.gov/nis/data/data/ENDFB-VII.1-neutron/Gd/157'
filenam... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: I. Background
Step2: C. Data Exploration
Step3: D. Labeling Function Metrics
Step4: Viewing Error Buckets
Step5: Other Search Contexts
Step6... | <ASSISTANT_TASK:>
Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import re
import sys
import numpy as np
# Connect to the database backend and initalize a Snorkel session
from lib.init import *
from lib.scoring import *
from lib.lf_factories import *
from snorkel.lf_helpers import test_LF
from snork... |
<SYSTEM_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
Step2: 3
Step3: 3a
Step4: 4
| <ASSISTANT_TASK:>
Python Code:
from cellpy.utils import easyplot
files = [
# "./data/raw/20160805_test001_45_cc_01.res",
# "./data/raw/20160805_test001_45_cc_01_copy.res"# ,
# "./data/20210430_seam10_01_01_cc_01_Channel_48_Wb_1.xlsx.csv# ",
# "./data/20210430_seam10_01_02_cc_01_Channel_49_Wb_1.xlsx.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: <i class="fa fa-diamond"></i> Primero pimpea tu libreta!
Step2: Introduccion a Machine Learning
Step3: El panorama!
Step4: A visualizar!
Step... | <ASSISTANT_TASK:>
Python Code:
from IPython.core.display import HTML
import os
def css_styling():
Load default custom.css file from ipython profile
base = os.getcwd()
styles = "<style>\n%s\n</style>" % (open(os.path.join(base,'files/custom.css'),'r').read())
return HTML(styles)
css_styling()
import num... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
| <ASSISTANT_TASK:>
Python Code:
import numpy as np
arr = (np.random.rand(100, 50)-0.5) * 50
result = arr.copy()
arr[np.where(result < -10)] = 0
arr[np.where(result >= 15)] = 30
arr[np.logical_and(result >= -10, result < 15)] += 5
<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:
| <ASSISTANT_TASK:>
Python Code:
def countDiv(arr ) :
rem0 = 0
rem1 = 0
rem2 = 0
for i in arr :
digitSum = 0
for digit in str(i ) :
digitSum += int(digit )
if digitSum % 3 == 0 :
rem0 += 1
elif digitSum % 3 == 1 :
rem1 += 1
else :
rem2 += 1
return(rem0 // 2 + min(rem1 , rem2 ) ... |
<SYSTEM_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 1
Step2: Check out the data
Step3: Step 2
Step4: Design the single function to get the key tree information
Step5: Decision Tree 0 (Fir... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.datasets import load_breast_cancer
import numpy as np
from functools import reduce
# Import our custom utilities
from imp import reload
from utils import irf_jupyter_utils
from utils imp... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Formatting the data
Step2: Create rating matrix
Step3: Finally, let's transform the rating matrix into a Compressed Sparse Row (CSR) format,... | <ASSISTANT_TASK:>
Python Code:
# Import some libraries
import numpy as np
import math
from test_helper import Test
from scipy import sparse
# Define data file
ratingsFilename = 'u.data'
f = open(ratingsFilename)
rawRatings = f.readlines()
# Check file format
print rawRatings[: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: Load sample glass data.
Step2: Read SDSS data, preprocessed by colour indices and reddenning correction
Step3: Use the same features as report... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.neighbors.kde import KernelDensity
%matplotlib inline
data = pd.read_csv("../data/glass.csv", index_col=False,names=["class"] + list(range(8)))
data_features = [x for x in ran... |
<SYSTEM_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 interactive interface is handy for exploration but we usually need to download "mechanically" in order to use them in our analysis, plots, o... | <ASSISTANT_TASK:>
Python Code:
from IPython.display import HTML
url = (
"https://cordc.ucsd.edu/projects/mapping/maps/fullpage.php?"
"ll=29.061888,-87.373643&"
"zm=7&"
"mt=&"
"rng=0.00,50.00&"
"us=1&"
"cs=4&"
"res=6km_h&"
"ol=3&"
"cp=1"
)
iframe = (
'<iframe src="{src}" width... |
<SYSTEM_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. Optimization & GIS
Step2: PySAL.Network
Step3: Gurobi 6.5
Step4: "Traditional" Conceptual Model
Step5: <b>So why ... | <ASSISTANT_TASK:>
Python Code:
import datetime as dt
import gurobipy as gbp
import IPython.display as IPd
import os
import platform
import pysal as ps
import sys
import time
# Local path on user's machine
path = '/Users/jgaboardi/SHRUG__15/'
print dir(ps)
print dir(ps.Network)
print dir(gbp)
# Manual Conceptual Mod... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: BERT Preprocessing with TF Text
Step2: Our data contains two text features and we can create a example tf.data.Dataset. Our goal is to create a... | <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: Y yo para que quiero eso? De que sirve pandas?
Step2: No nos sirve nada vacio, entonces agreguemos le informacion!
Step3: Jugando con el Dataf... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np # modulo de computo numerico
import matplotlib.pyplot as plt # modulo de graficas
# esta linea hace que las graficas salgan en el notebook
%matplotlib inline
df = pd.DataFrame()
df['Pastor']=np.random.randint(100, size=7)
df['Tripas']=np.random.ran... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Notice something about $b$?
Step2: In Class Exercise
| <ASSISTANT_TASK:>
Python Code:
from astropy import constants as const
import numpy as np
import matplotlib.pyplot as plt
#This just needed for the Notebook to show plots inline.
%matplotlib inline
print(const.e.value)
print(const.e)
#Atomic Number of Gold
Z = 72
e = const.e.value
E = 7.7e6*e
eps0 = const.eps0.value
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: Y copiando la función para generar matrices de transformación homogéneas a partir de los parametros DH
Step2: He guardado todas las matrices de... | <ASSISTANT_TASK:>
Python Code:
from sympy.physics.mechanics import mechanics_printing
mechanics_printing()
from sympy import var, Function, pi
var("l1:4")
var("m1:4")
var("g t")
q1 = Function("q1")(t)
q2 = Function("q2")(t)
q3 = Function("q3")(t)
def DH(params):
from sympy import Matrix, sin, cos
a, 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: 阅读文献
Step2: The SVD algorithm factorizes a matrix into one matrix with orthogonal columns and one with orthogonal rows (along with a diagonal m... | <ASSISTANT_TASK:>
Python Code:
# 多行结果输出支持
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
import numpy as np
np.set_printoptions(precision=4)
# 导入视频
# from IPython.display import YouTubeVideo
# YouTubeVideo("8iGzBMboA0I")
# 制作切片(tuple 形式)
dims = np.index_exp[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: Below I'm plotting an example image from the MNIST dataset. These are 28x28 grayscale images of handwritten digits.
Step2: We'll train an autoe... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
img = mnist.train.images[2]
plt.imshow(img.reshape((28, 28)), cmap='... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.