Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
12,600 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
n = 5 # Toplam nesne sayısı
ust_ag = 30 # Olabilecek en yüksek ağırlık
x_degerleri = np.random.rand(n)
y_degerleri = np.random.rand(n)
agirliklar = ust_ag*np.random.rand(n) #
print x_degerleri
print y_degerleri
print a... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: İlk işimiz nesnelerin ağırlıklarını ve koordinatlarını rassal olarak üretmek olsun.
Step2: Her noktanın koordinatlarını rassal olarak ürettik. ... |
12,601 | <ASSISTANT_TASK:>
Python Code:
import imapclient
import email
conn = imapclient.IMAPClient('imap.gmail.com', ssl=True)
# Real values were used in testing, and removed for Github
# Due to the nature of Gmail's security, you may have to allow access from 'less secure apps' (like this script)
# The setting can be change... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The first step in setting up email is creating a connection object again to interact with an email, but this time for the IMAP server.
Step2: W... |
12,602 | <ASSISTANT_TASK:>
Python Code:
breakfast = ["sausage", "eggs", "bacon", "spam"]
for item in breakfast:
print(item)
squares = []
for i in range(1, 10, 2):
squares.append(i**2)
print(squares)
fruits = {'banana' : 5, 'strawberry' : 7, 'pineapple' : 3}
for fruit in fruits:
print(fruit)
sum = 0
for price in f... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Write then a for which loop determines the squares of the odd
Step2: Looping through a dictionary
Step3: Next, write a loop that sums up the p... |
12,603 | <ASSISTANT_TASK:>
Python Code:
from arcgis.gis import GIS
from getpass import getpass
from IPython.display import display
# Get username and password
username = input('Username: ')
password = getpass(prompt='Password: ')
# Connect to portal
gis = GIS("https://arcgis.com/", username, password)
user = gis.users.get(use... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Create the GIS object and point it to AGOL
Step2: Test the connection
Step3: Get the item that you want to update
Step4: Update the metadata
|
12,604 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
%matplotlib inline
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
from cycler import cycler
# import all shogun classes
from shogun import *
slope = 3
X_train = rand(30)*10
y_train = slope*(X_train)+random.randn(30)*2+2
y_true = slope*(X_train)+2
X_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: Training and generating weights
Step2: This value of $\text w$ is pretty close to 3, which certifies a pretty good fit for the training data. N... |
12,605 | <ASSISTANT_TASK:>
Python Code:
import requests
from bs4 import BeautifulSoup
from IPython.display import Pretty
import pprint
pp = pprint.PrettyPrinter(indent=4)
url = 'http://seclists.org/fulldisclosure/2017/Jan'
r = requests.get(url)
raw = r.text
Pretty(raw)
raw = raw.replace('<a name="begin">', '<a name="begin"></a... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The generated code from seclists.org contains an unterminated anchor tag, so to make things easier for BeautifulSoup's parser, we'll just replac... |
12,606 | <ASSISTANT_TASK:>
Python Code:
import openpnm as op
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(10)
from ipywidgets import interact, IntSlider
%matplotlib inline
ws = op.Workspace()
ws.settings["loglevel"] = 40
N = 100
net = op.network.Cubic(shape=[N, N, 1], spacing=2.5e-5)
geom = op.geometry.Sti... | <SYSTEM_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 2D Cubic network with standard PSD and define the phase as Water and use Standard physics which implements the washburn capillary press... |
12,607 | <ASSISTANT_TASK:>
Python Code:
import sys
import logging
# Import the GEM-PRO class
from ssbio.pipeline.gempro import GEMPRO
# Printing multiple outputs per cell
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
# Create logger
logger = logging.getLogger()
logge... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Logging
Step2: Initialization
Step3: Mapping gene ID --> sequence
Step4: Mapping representative sequence --> structure
Step5: Homology model... |
12,608 | <ASSISTANT_TASK:>
Python Code:
data['Outcomes'] = 'plural'
data['Outcomes'][1] = 'singular'
data
W = ndl.rw(data,M=10)
A = activation(W)
A
pd.DataFrame([data['Outcomes'], A.idxmax(1), A.idxmax(1) == data['Outcomes']], index = ['Truth', 'Prediction', 'Accurate?']).T
np.mean(A.idxmax(1) == data['Outcomes'])
float(sum(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: With these associations, how many of the 15 items will the learner correctly label?
Step2: How often are they correct (using relative item freq... |
12,609 | <ASSISTANT_TASK:>
Python Code:
from scipy.signal import convolve2d
img = color.rgb2gray(io.imread('../images/snakes.png'))
# Reduce all lines to one pixel thickness
snakes = morphology.skeletonize(img < 1)
# Find pixels with only one neighbor
corners = convolve2d(snakes, [[1, 1, 1],
[1, 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: Parameters of a pill
Step2: Viscous fingers
Step3: Counting coins
Step4: Color wheel
Step5: Hand-coin
Step6: <div style="height
|
12,610 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
a = np.array([1, 2, 3, 4])
c = np.array([[1, 2, 3, 4],[4, 5, 6, 7], [7, 8, 9, 10]])
c
c.shape
d = a.reshape((2,2))
d
a
a[1] = 100
d
a.dtype
b=np.array([[1, 2, 3, 4],[4, 5, 6, 7], [7, 8, 9, 10]], dtype=np.float)
b
np.arange(0, 1, 0.1)
np.linspace(0, 1, 12)
np.log... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 数组的大小可以通过其shape属性获得:
Step2: 使用数组的reshape方法,可以创建一个改变了尺寸的新数组,原数组的shape保持不变:
Step3: 数组a和d其实共享数据存储内存区域,因此修改其中任意一个数组的元素都会同时修改另外一个数组的内容:
Step4: 数组的... |
12,611 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
# RMS Titanic data visualization code
from titanic_visualizations import survival_stats
from IPython.display import display
%matplotlib inline
# Load the dataset
in_file = 'titanic_data.csv'
full_data = pd.read_csv(in_file)
# Print the first few ent... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the ship
Step3: The very same sample of th... |
12,612 | <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: コピュラ入門
Step3: [copula](https
Step4: しかし、このようなモデルの力は、確率積分変換を使用して任意の R.V. にコピュラを使用するところにあります。こうすることで、任意の周辺分布を指定し、コピュラを使って接合することができます。
Step6: 異な... |
12,613 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
pd.plotting.register_matplotlib_converters()
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
print("Setup Complete")
# Set up code checking
import os
if not os.path.exists("../input/candy.csv"):
os.symlink("../input/data-for-datavis/candy.... | <SYSTEM_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 questions below will give you feedback on your work. Run the following cell to set up our feedback system.
Step2: Step 1
Step3: Step 2
Ste... |
12,614 | <ASSISTANT_TASK:>
Python Code:
path = get_file('nietzsche.txt', origin="https://s3.amazonaws.com/text-datasets/nietzsche.txt")
text = open(path).read()
print('corpus length:', len(text))
chars = sorted(list(set(text)))
vocab_size = len(chars)+1
print('total chars:', vocab_size)
chars.insert(0, "\0")
''.join(chars[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: Sometimes it's useful to have a zero value in the dataset, e.g. for padding
Step2: Map from chars to indices and back again
Step3: idx will be... |
12,615 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import os
import pandas as pd
habilitando plots no notebook
%matplotlib inline
plot libs
import matplotlib.pyplot as plt
import seaborn as sns
Configurando o Matplotlib para o modo manual
plt.interactive(False)
DataFrame contendo 5 Séries com Distribuições Norma... | <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: Módulo 3
Step5: Dataset
Step10: Histogram Plot
Step11: Observação
Step15: Usando Pandas
Step17: Usando Seaborn
Step21: Observação
Step24: ... |
12,616 | <ASSISTANT_TASK:>
Python Code:
import dx
import datetime as dt
import pandas as pd
from pylab import plt
plt.style.use('seaborn')
r = dx.constant_short_rate('r', 0.01)
me_1 = dx.market_environment('me', dt.datetime(2016, 1, 1))
me_1.add_constant('initial_value', 100.)
# starting value of simulated processes
me_1.ad... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Risk Factor Models
Step2: We then define a market environment containing the major parameter specifications needed,
Step3: Next, the model obj... |
12,617 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%qtconsole --colors=linux
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import optimize
import pymc3 as pm
import theano as thno
import theano.tensor as T
# conf... | <SYSTEM_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 Prepare Data
Step2: Observe
Step3: Sample
Step4: View Traces
Step5: NOTE
Step6: Sample
Step7: View Traces
Step8: Observe
Step9: ... |
12,618 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
from time import time
import datetime
import lightgbm as lgb
import gc, warnings
gc.collect()
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import precision_score, recall_score... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Above we notice that the number of frauds per day seems to stay pretty stable throughout the trainset
Step2: Correlation to daily isFraud.sum()... |
12,619 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import random as rnd
import pandas as pd
import numpy as np
import time
import datetime
import calendar
# fix what is missing with the datetime/time/calendar package
def add_months(sourcedate,months):
month = sourcedate.month - 1 + mo... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: classes buyers and sellers
Step2: Construct the market
Step3: Observer
Step4: Example Market
Step5: run the model
Step6: Operations Researc... |
12,620 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, recall_score
df = pd.read_table('data/preprocessed.tsv',... | <SYSTEM_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 Training & Prediction pipeline
Step2: Text Vectorization & The TD Matrix
Step3: Dimensionality Reduction
Step4: Training the Classifier
S... |
12,621 | <ASSISTANT_TASK:>
Python Code:
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import iris
import matplotlib.pyplot as plt
import numpy as np
import os
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
iris.FUTURE.netcdf_promote = True
filepath ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Don't bother me with warnings!
Step2: Read the NetCDF data file
Step3: Use the simplest loading method to open a NetCDF file as a iris.cube.Cu... |
12,622 | <ASSISTANT_TASK:>
Python Code:
#The ibmseti package contains some useful tools to faciliate reading the data.
#The `ibmseti` package version 1.0.5 works on Python 2.7.
# !pip install --user ibmseti
#A development version runs on Python 3.5.
# !pip install --user ibmseti==2.0.0.dev5
# If running on DSX, YOU WILL NEE... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: No Spark Here
Step2: Assume you have the data in a local folder
Step3: Use ibmseti for convenience
Step4: The Goal
Step5: 2. Build the spect... |
12,623 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
from urllib2 import Request, urlopen, URLError
from lxml import html
import time
from netCDF4 import Dataset
import datetime
import calendar
from collections import OrderedDict
from bokeh.plotting import figure, ColumnDataSource
from bokeh.models 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: In case, the output wants to be seen within the jupyter notebook, this line must be un-commented. However, since the generated HTML file will be... |
12,624 | <ASSISTANT_TASK:>
Python Code:
# importing
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
# showing figures inline
%matplotlib inline
# plotting options
font = {'size' : 20}
plt.rc('font', **font)
plt.rc('text', usetex=matplotlib.checkdep_usetex(True))
matplotlib.rc('figure', figsize=(18, 6) )... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Function for determining the impulse response of an RC filter
Step2: Parameters
Step3: Get QPSK and OQPSK signal
Step4: Plotting
|
12,625 | <ASSISTANT_TASK:>
Python Code:
import os
import numpy as np
import nibabel
import matplotlib.pyplot as plt
import matplotlib.patheffects as path_effects
import mne
from mne.transforms import apply_trans
from mne.io.constants import FIFF
data_path = mne.datasets.sample.data_path()
subjects_dir = os.path.join(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: MRI coordinate frames
Step2: Notice that the axes in the
Step3: These data are voxel intensity values. Here they are unsigned integers in the
... |
12,626 | <ASSISTANT_TASK:>
Python Code:
import os
path_to_file = os.path.join(os.pardir, 'data', 'new.nc')
from __future__ import division, print_function # py2to3 compatibility
import netCDF4 as nc
import numpy as np
print('NetCDF package version: {}'.format(nc.__version__))
try:
ncfile.close()
except:
pass
# anothe... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: mode='r' is the default.
Step2: Just to be safe, make sure dataset is not already open
Step3: Creating dimensions
Step4: Creating attributes
... |
12,627 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
cookbook_df = pd.DataFrame({'AAA' : [4,5,6,7], 'BBB' : [10,20,30,40],'CCC' : [100,50,-30,-50]})
cookbook_df['BBB']
<END_TASK> | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: dictionary like operations
|
12,628 | <ASSISTANT_TASK:>
Python Code:
# Here we'll import data processing libraries like Numpy and Tensorflow
import numpy as np
import tensorflow as tf
# Use matplotlib for visualizing the model
from matplotlib import pyplot as plt
# Here we'll show the currently installed version of TensorFlow
print(tf.__version__)
# Creat... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Operations on Tensors
Step2: Point-wise operations
Step3: NumPy Interoperability
Step4: Linear Regression
Step5: Let's also create a test da... |
12,629 | <ASSISTANT_TASK:>
Python Code:
%matplotlib nbagg
import matplotlib.pyplot as plt
import sys
import matplotlib
import numpy as np
from NuPyCEE import sygma as s
from NuPyCEE import omega as o
from NuPyCEE import stellab
from NuPyCEE import read_yields as ry
table='yield_tables/agb_and_massive_stars_nugrid_MESAonly_fryer... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Default setup - total yields
Step2: Setup with total yields as input but net yields are calculated in the code and then applied
|
12,630 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
matplotlib.style.use('ggplot')
%matplotlib inline
data = pd.read_csv('data.csv')
data.shape
X = data.drop('Grant.Status', 1)
y = data['Grant.Status']
data.head()
numeric_cols = ['RFCD.Percent... | <SYSTEM_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: Выделим из датасета целевую переменную Grant.Status и обозначим её за y
Step3: Теория по логистической регрессии
Step... |
12,631 | <ASSISTANT_TASK:>
Python Code:
# This model training code is directly from:
# https://github.com/keras-team/keras/blob/master/examples/imdb_lstm.py
'''Trains an LSTM model on the IMDB sentiment classification task.
The dataset is actually too small for LSTM to be of any advantage
compared to simpler, much faster method... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Explain the model with DeepExplainer and visualize the first prediction
|
12,632 | <ASSISTANT_TASK:>
Python Code:
# Set Path
import sys
sys.path.append('../../src/')
%autoreload 2
# Import Libraries
from fem import Function
from fem import QuadFE
from fem import DofHandler
from fem import Kernel
from fem import Basis
from fem import Form
from fem import Assembler
from fem import LinearSystem
from plo... | <SYSTEM_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 test the system
Step2: Since we have already tested the assembly, we focus here on the linear system. In particular
Step3: To test extract... |
12,633 | <ASSISTANT_TASK:>
Python Code:
# Run this cell to set up the notebook.
import numpy as np
import pandas as pd
import seaborn as sns
import scipy as sci
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib import patches, cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Today's lab reviews Maximum Likelihood Estimation, and introduces interctive plotting in the jupyter notebook.
Step2: Question 2
Step3: Questi... |
12,634 | <ASSISTANT_TASK:>
Python Code:
X, y = puzzleData(puzzle=0, n=25)
residualPuzzle1D(X, y, hint=True)
x, y = puzzleData(puzzle=1, n=25)
X = x
# Add a new feature as a column of X
# with X = np.column_stack((x, #TODO))
residualPuzzle1D(X, y, hint=False)
x, y = puzzleData(puzzle=2, n=25)
X = x
# Add a new feature as a co... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Q
Step2: Q
Step3: <br><br>
Step4: Each row in the data matrix $X$ contains advertising budgets for a particular market. The first through thir... |
12,635 | <ASSISTANT_TASK:>
Python Code:
# Creating a class called Bike
class Bike:
pass
# An 'instance' of a bike
my_bike = Bike()
type(my_bike)
class Bike:
def __init__(self, speed, wheel, weight):
self.speed = speed
self.wheel = wheel
self.weight = weight
# Instantiating a Bike Object
woo = ... | <SYSTEM_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 you do not already know, the word "instantiation" means to create a version of an object. Here is how we would instantiate a bike.
Step2: No... |
12,636 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import statsmodels.api as sm
from scipy import stats
from statsmodels.iolib.table import SimpleTable, default_txt_fmt
np.random.seed(1024)
nsample = 50
x = np.linspace(0, 20, nsample)
X = np.column_stack((x, (x - 5) **... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: WLS Estimation
Step2: WLS knowing the true variance ratio of heteroscedasticity
Step3: OLS vs. WLS
Step4: Compare the WLS standard errors to ... |
12,637 | <ASSISTANT_TASK:>
Python Code:
!wget https://raw.githubusercontent.com/rodluger/tutorials/master/gps/data/sample_transit.txt
!mv *.txt data/
import numpy as np
from scipy.linalg import cho_factor
def ExpSquaredKernel(t1, t2=None, A=1.0, l=1.0):
Return the ``N x M`` exponential squared
covariance matrix be... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step5: Benchmarking our implementation
Step6: <div style="background-color
|
12,638 | <ASSISTANT_TASK:>
Python Code:
# YOUR ACTION REQUIRED:
# Execute this cell first using <CTRL-ENTER> and then using <SHIFT-ENTER>.
# Note the difference in which cell is selected after execution.
print('Hello world!')
# YOUR ACTION REQUIRED:
# Execute only the first print statement by selecting the first line and press... | <SYSTEM_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 also only execute one single statement in a cell.
Step2: What to do if you get stuck
Step3: Importing TensorFlow
Step4: Running shell... |
12,639 | <ASSISTANT_TASK:>
Python Code:
%%bash
pip freeze | grep tensor
!pip3 install tensorflow-hub==0.7.0
!pip3 install --upgrade tensorflow==1.15.3
!pip3 install google-cloud-bigquery==1.10
import os
import tensorflow as tf
import numpy as np
import tensorflow_hub as hub
import shutil
PROJECT = 'cloud-training-demos' # REP... | <SYSTEM_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 make sure we install the necessary version of tensorflow-hub. After doing the pip install below, click "Restart the kernel" on the noteboo... |
12,640 | <ASSISTANT_TASK:>
Python Code:
# Install CLU & Flax.
!pip install -q clu flax
example_directory = 'examples/seq2seq'
editor_relpaths = ('train.py', 'input_pipeline.py', 'models.py')
repo, branch = 'https://github.com/google/flax', 'main'
# (If you run this code in Jupyter[lab], then you're already in the
# example dir... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Imports
Step2: Dataset
Step3: Training
Step4: Inference
|
12,641 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'noaa-gfdl', 'gfdl-esm4', 'ocnbgchem')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("nam... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
12,642 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import StringIO
import zipfile
import urllib
from __future__ import division, print_function
matplotlib.style.use('fivethirtyeight')
%matplotlib inline
# Download and extract the 2015 FARS file
output... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Motor Vehicles Are Third-Leading Cause of Death Due to Injury
Step2: There were 35,092 traffic fatalities in the U.S. in 2015, or a little more... |
12,643 | <ASSISTANT_TASK:>
Python Code:
import pints
import pints.toy as toy
import pints.plot
import numpy as np
import matplotlib.pyplot as plt
# Load a forward model
model = toy.LogisticModel()
# Create some toy data
real_parameters = [0.015, 500]
times = np.linspace(0, 1000, 1000)
org_values = model.simulate(real_parameter... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: ARMA errors
Step2: Perform Bayesian inference using statsmodels' ARIMA Kalman filter
Step3: Look at results.
Step4: Look at results. Note tha... |
12,644 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import climlab
import xarray as xr
import scipy.integrate as sp #Gives access to the ODE integration package
from climlab.utils.thermo import pseudoadiabat
def generate_idealized_temp_profile(SST, plevs, Tstrat=200):
... | <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: Set up idealized atmospheric profiles of temperature and humidity
Step3: Now, compute specific humidity profile using climlab.radiation.water_v... |
12,645 | <ASSISTANT_TASK:>
Python Code:
import graphlab
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
wiki = graphlab.SFrame('people_wiki.gl')
wiki
wiki['URI'][1]
wiki['word_count'] = graphlab.text_analytics.count_words(wiki['text'])
wiki
model = graphlab.nearest_neighbors.create(wiki, label='name', f... | <SYSTEM_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 Wikipedia dataset
Step2: Extract word count vectors
Step3: Find nearest neighbors
Step4: Let's look at the top 10 nearest neighbors by p... |
12,646 | <ASSISTANT_TASK:>
Python Code:
import sys
try:
import cplex
except:
if hasattr(sys, 'real_prefix'):
#we are in a virtual env.
!pip install cplex
else:
!pip install --user cplex
import sys
try:
import docplex.mp
except:
if hasattr(sys, 'real_prefix'):
#we are in a vir... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Installs DOcplexif needed
Step2: If either CPLEX or docplex where installed in the steps above, you will need to restart your jupyter kernel fo... |
12,647 | <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.append("../python/")
import pentoref.IO as IO
import sqlite3 as sqlite
# Create databases if required
if False: # make True if you need to create the databases from the derived data
for corpus_name in ["TAKE", "TAKECV", "PENTOCV"]:
data_dir = "../../../pe... | <SYSTEM_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 utterances from certain time periods in each experiment or for certain episodes
Step2: Get mutual information between words used in referri... |
12,648 | <ASSISTANT_TASK:>
Python Code:
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.evaluation import RegressionEvaluator, MulticlassClassificationEvaluator
from pyspark.ml import Pipeline
from pyspark.mllib.regression import LabeledPoint
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Funções
Step2: Convertendo a saída de categórica para numérica
Step3: Definição do Modelo Logístico
Step4: Cross-Validation - TrainValidation... |
12,649 | <ASSISTANT_TASK:>
Python Code:
import sys
print("Python %d.%d.%d" % (sys.version_info.major, \
sys.version_info.minor, \
sys.version_info.micro))
import numpy as np
print("NumPy %s" % np.__version__)
import scipy
import scipy.io as sio
from scipy.optimize import fmi... | <SYSTEM_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 Modules
Step2: Display Settings
Step3: Collaborative Filtering[1]
Step4: Based on movie_ids.txt file, Toy Story (1995) movie is on the... |
12,650 | <ASSISTANT_TASK:>
Python Code:
import os
import sys
import logging
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
sys.path.append(module_path)
import hurraypy as hurray
import numpy as np
hurray.__version__
logger = logging.getLogger('hurraypy')
# console = logging.StreamHandler(... | <SYSTEM_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, make sure all logging messages are sent to stdout
Step2: Connecting to a hurray server
Step3: Working with files
Step4: Note that Hurr... |
12,651 | <ASSISTANT_TASK:>
Python Code:
# numpy provides python tools to easily load comma separated files.
import numpy as np
# use numpy to load disease #1 data
d1 = np.loadtxt(open("../30_Data_ML-III/D1.csv", "rb"), delimiter=",")
# features are all rows for columns before 200
# The canonical way to name this is that X is ou... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Implement an SVM!
Step2: The parts inside the parentheses give us the ability to set or change parameters. Anything with an equals sign after i... |
12,652 | <ASSISTANT_TASK:>
Python Code:
PATH_NEWS_ARTICLES="/home/phoenix/Documents/HandsOn/Final/news_articles.csv"
ARTICLES_READ=[2,7]
NUM_RECOMMENDED_ARTICLES=5
try:
import numpy
import pandas as pd
import pickle as pk
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwi... | <SYSTEM_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. Represent articles in terms of bag of words
Step2: 2. Represent user in terms of read articles associated words
Step3: 3. Generate TF-IDF m... |
12,653 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
# Code Under Test
def entropy(ps):
items = ps * np.log(ps)
if any(np.isnan(items)):
raise ValueError("Cannot compute log of ps!")
return -np.sum(items)
np.isnan([.1, .9])
# Smoke test
entropy([0.5, 0.5])
# One-shot test. Need to know the correct ans... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Suppose that all of the probability of a distribution is at one point. An example of this is a coin with two heads. Whenever you flip it, you al... |
12,654 | <ASSISTANT_TASK:>
Python Code:
%tensorflow_version 1.x
!curl -Lo deepchem_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py
import deepchem_installer
%time deepchem_installer.install(version='2.3.0')
import deepchem as dc
import os
from deepchem.utils import download_url
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: Training the Model
|
12,655 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import re
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import cross_val_score
from os.path import join
from bs4 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: If you are missing bs4 or nltk you can install them via
Step2: Let's take a quick look at the data
Step3: In particular note that the review c... |
12,656 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import locale
import matplotlib.pyplot as plt
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, HoverTool
%matplotlib inline
from bokeh.plotting import output_notebook
output_notebook()
_ = locale.setlocale(locale.LC_... | <SYSTEM_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 csv
Step2: Address nan column values
Step3: Change column types and drop unused columns
Step4: Cleanup amounts
Step5: Outlier data
Step... |
12,657 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.api as sm
np.random.seed(9876789)
nsample = 100
x = np.linspace(0, 10, 100)
X = np.column_stack((x, x ** 2))
beta = np.array([1, 0.1, 10])
e = np.random.normal(size=nsample)
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: OLS estimation
Step2: Our model needs an intercept so we add a column of 1s
Step3: Fit and summary
Step4: Quantities of interest can be extra... |
12,658 | <ASSISTANT_TASK:>
Python Code:
import getpass
APIKEY = getpass.getpass()
from googleapiclient.discovery import build
speech_service = build('speech', 'v1p1beta1', developerKey=APIKEY)
#@title このセルを実行して record_audio を定義
# Install required libraries and packages
!pip install -qq pydub
!apt-get -qq update
!apt-get -qq 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: Cloud Speech-to-Text API を使ってみよう !
Step2: 音声データの準備
Step3: record_audio を実行して音声を録音しましょう。
Step4: 録音結果を確認しましょう。
Step5: 音声認識の実行
Step6: 入力する音声デー... |
12,659 | <ASSISTANT_TASK:>
Python Code:
pm_df = pd.read_hdf('pm_objid_stars.h5')
len(missing_is_pm_star)
len(np.where(missing_is_pm_star == 1)[0])
len(tmp_tbl)
len(np.unique(tmp_tbl.objid))
tmp_tbl
pm_objid = np.empty(0).astype(np.int64)
for mf in missing_files:
tstart = time.time()
tmp_tbl = fits.getdata(mf)
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: Read in RF classifications and replace Gaia stars with score = 1
|
12,660 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib as mpl # used sparingly
import matplotlib.pyplot as plt
pd.set_option("notebook_repr_html", False)
pd.set_option("max_rows", 10)
%matplotlib inline
from matplotlib import matplotlib_fname
matplotlib_fname()
from matplotlib impor... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Landscape of Plotting Libraries
Step2: Backends
Step3: This has a popular one
Step4: You can also use the rc_context context manager
Step5: ... |
12,661 | <ASSISTANT_TASK:>
Python Code:
### BEGIN SOLUTION
import sympy as sym
a, b, c = sym.Symbol("a"), sym.Symbol("b"), sym.Symbol("c")
sym.expand((9 * a ** 2 * b * c ** 4) ** (sym.S(1) / 2) / (6 * a * b ** (sym.S(3) / 2) * c))
### END SOLUTION
### BEGIN SOLUTION
sym.expand((sym.S(2) ** (sym.S(1) / 2) + 2) ** 2 - 2 ** (sym.... | <SYSTEM_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. \((2 ^ {\frac{1}{2}} + 2) ^ 2 - 2 ^ {\frac{5}{2}}\)
Step2: \((\frac{1}{8}) ^ {\frac{4}{3}}\)
Step4: Question 2
Step5: Question 3
Step6: b... |
12,662 | <ASSISTANT_TASK:>
Python Code:
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("https://en.wikipedia.org/wiki/Python_(programming_language)")
bsObj = BeautifulSoup(html.read(), "html.parser")
for link in bsObj.findAll("a"):
if 'href' in link.attrs:
print(link.attrs['href'])
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 可以发现,所有指向Wikipedia词条的链接都是/wiki/开头,所以我们可以用正则表达式来过滤出这些词条,就像这样
Step2: 上面的函数还不太能用于实际抓取,我们稍作改进,变成下面这个样子,就可以初步用于抓取页面的所有链接了。因为我们不能无限制地抓取下去,我便设置了10个链接的... |
12,663 | <ASSISTANT_TASK:>
Python Code:
# CHANGE the following settings
BASE_IMAGE='gcr.io/your-image-name'
MODEL_STORAGE = 'gs://your-bucket-name/folder-name' #Must include a folder in the bucket, otherwise, model export will fail
BQ_DATASET_NAME="hotel_recommendations" #This is the name of the target dataset where you model a... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: Create BigQuery function
Step5: Creating the model
Step8: Creating embedding features for users and hotels
Step10: Function below combines al... |
12,664 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
!wget http://www.cs.colostate.edu/~anderson/cs480/notebooks/oldfaithful.csv
data = np.loadtxt('oldfaithful.csv')
data.shape
plt.scatter(data[:,0],data[:,1]);
plt.xlabel('Duration');
plt.ylabel('Interval');
clusters = [... | <SYSTEM_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 represent clusters as a list of sample matrices, each matrix containing samples from one cluster. Initially, all samples are in their own... |
12,665 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
#Imports for solution
import numpy as np
import scipy.stats as sp
from matplotlib.pyplot import *
#Setting Distribution variables
##All rates are in per Minute.
#Everything will me modeled as a Poisson Process
SIM_TIME = 180
QUEUE_ARRIVAL_RATE = 15
N_SCANNERS =4
SCANNE... | <SYSTEM_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 this simulation, we'll be using numpy and scipy for their statistical and matrix math prowess and matplotlib as our primary plotting tool
St... |
12,666 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import re, pickle, collections, bcolz, numpy as np, keras, sklearn, math, operator
from gensim.models import word2vec
import torch, torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
path='/data/datasets/fr-en-109-... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Prepare corpus
Step2: To make this problem a little simpler so we can train our model more quickly, we'll just learn to translate questions tha... |
12,667 | <ASSISTANT_TASK:>
Python Code:
__AUTHORS__ = {'am': ("Andrea Marino",
"andrea.marino@unifi.it",),
'mn': ("Massimo Nocentini",
"massimo.nocentini@unifi.it",
"https://github.com/massimo-nocentini/",)}
__KEYWORDS__ = ['Python', 'Jupyter', ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <center><img src="https
Step2: we want to build an object that denotes a Bernoulli random variable.
|
12,668 | <ASSISTANT_TASK:>
Python Code:
# Install the SDK
#!pip3 install 'kfp>=0.1.31.2' --quiet
import kfp
import kfp.components as comp
#Define a Python function
def add(a: float, b: float) -> float:
'''Calculates sum of two arguments'''
return a + b
add_op = comp.func_to_container_op(add)
#Advanced function
#Demonst... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Simple function that just add two numbers
Step2: Convert the function to a pipeline operation
Step3: A bit more advanced function which demons... |
12,669 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
%matplotlib qt
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6*8,3), np.float32)
objp[:,:2] = np.mgrid[0:8, 0:6].T.reshape(-1,2)
# Arrays to store object points and image poin... | <SYSTEM_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 the above cell ran sucessfully, you should now have objpoints and imgpoints needed for camera calibration. Run the cell below to calibrate, ... |
12,670 | <ASSISTANT_TASK:>
Python Code:
from keras.layers import Conv2D, MaxPooling2D, Input, Dense, Flatten, Activation, add, Lambda
from keras.layers.normalization import BatchNormalization
from keras.layers.pooling import GlobalAveragePooling2D
from keras.optimizers import RMSprop
from keras.backend import tf as ktf
from ker... | <SYSTEM_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 MNIST data. Notice that we assume that it's 'kaggle-DigitRecognizer/data/train.csv', and we use helper function to read into a dictiona... |
12,671 | <ASSISTANT_TASK:>
Python Code:
import veneer
v = veneer.Veneer()
%matplotlib inline
v.network().plot()
set(v.model.catchment.runoff.get_models())
v.model.find_states('TIME.Models.RainfallRunoff.AWBM.AWBM')
v.model.catchment.runoff.create_modelled_variable?
# Save the result!
variables = v.model.catchment.runoff.creat... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Demonstration model
Step2: NOTE
Step3: The result of the function call is very important. It tells us what was created and the names.
Step4: ... |
12,672 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
data = pd.read_csv("train.csv", index_col="Loan_ID")
# test = pd.read_csv("test.csv", index_col="PassengerID")
print data.shape
data.columns
data.loc[(data["Gender"]=="Female") & (data["Education"]=="Not Graduate") & (data["Loan_Status"]=="Y"), ["Ge... | <SYSTEM_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. Boolean Indexing
Step2: More
Step3: Here we see that Credit_History is a nominal variable but appearing as float. A good way to tackle this... |
12,673 | <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: How to solve a problem on Kaggle with TF-Hub
Step2: Since this tutorial will be using a dataset from Kaggle, it requires creating an API Token ... |
12,674 | <ASSISTANT_TASK:>
Python Code:
%%writefile game_of_life_utils.py
import numpy as np
from scipy.signal import convolve2d
def life_step_1(X):
Game of life step using generator expressions
nbrs_count = sum(np.roll(np.roll(X, i, 0), j, 1)
for i in (-1, 0, 1) for j in (-1, 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:
Step2: Game of life - serial version
Step3: Initial conditions
Step4: Different example
Step5: Visualization
Step6: Parallel game of life
Step7: s... |
12,675 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
rand_1kx = np.random.randint(0,100,1000)
x_mean = np.mean(rand_1kx)
x_sd = np.std(rand_1kx)
x_mean
pop_intercept = 30
pop_slop... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Synthesize the dataset
Step2: Make a scatter plot of X and y variables.
Step3: X and y follow uniform distribution, but the error $\epsilon$ i... |
12,676 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.read_csv('data/human_body_temperature.csv')
# Your work here.
# Load Matplotlib + Seaborn and SciPy libraries
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy import stats
from scipy.stats import norm
from statsmodels.stats.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: Questions and Answers
Step2: 2. Is the sample size large? Are the observations independent?
Step3: What we know about population and what we g... |
12,677 | <ASSISTANT_TASK:>
Python Code:
import tensorflow as tf
x = tf.constant(35, name='x')
y = tf.Variable(x + 5, name='y')
print(y)
x = tf.constant(35, name='x')
y = tf.Variable(x + 5, name='y')
model = tf.initialize_all_variables()
with tf.Session() as session:
session.run(model)
print(session.run(y))
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: Exercise
Step2: 2.
Step3: tensorboard
|
12,678 | <ASSISTANT_TASK:>
Python Code:
import wget
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
# Import the dataset
data_url = 'https://raw.githubusercontent.com/nslatysheva/data_science_blogging/master/datasets/wine/winequality-red.csv'
dataset = wget.download(data_url)
dataset... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Build models
Step2: 4) Majority vote on classifications
Step3: And we could assess the performance of the majority voted predictions like so
S... |
12,679 | <ASSISTANT_TASK:>
Python Code:
class PlanetaryObject():
A simple class used to store pertinant information about the plantary object
def __init__(self, date, L, e, SMA, i, peri, asc, r, v, anom, fp, mu):
self.date = date # Event Date
self.L = L # Longitude
self.e = 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: SIE 552 HW #3
Step9: There are also a few fundamental equations we need to know. These are captured below as python functions.
Step10: We'll ... |
12,680 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from ttim import *
import pandas as pd
b = 10 #aquifer thickness in m
Q = 172.8 #constant discharge rate in m^3/d
rw = 0.1 #well radius in m
rc = 0.1 #casing radius in m
r1 = 3.16
r2 = 31.6
data0 = np.loadtxt('data/m... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set basic parameters
Step2: Load datasets of observation wells
Step3: Check how well TTim can simulate drawdowns in a vertically anisotropic w... |
12,681 | <ASSISTANT_TASK:>
Python Code:
# TODO: You Must Change the setting bellow
MYSQL = {
'user': 'root',
'passwd': '',
'db': 'coupon_purchase',
'host': '127.0.0.1',
'port': 3306,
'local_infile': True,
'charset': 'utf8',
}
DATA_DIR = '/home/nasuno/recruit_kaggle_datasets' # ディレクトリの名前に日本語(マルチバイト文... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 3. モデリング対象の設定
Step2: ランダム推定・MAP@10の評価
Step3: 2. 抽出したクーポン群から各ユーザが購買するクーポンをランダムに10個選び、予測結果とする。
Step4: 3. 実際に購買したクーポンと照らし合わせ、MAP@10を算出する。
Step5:... |
12,682 | <ASSISTANT_TASK:>
Python Code:
bayarea.find().count()
bayarea.find({"type": "node"}).count()
bayarea.find({"type": "way"}).count()
pipeline = [{"$match": {"amenity": {"$ne": None}}},
{"$group": {"_id": "$amenity",
"count": {"$sum": 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: Number of nodes
Step2: Number of ways
Step3: Top 10 types of amenities
Step4: Top 10 fast food chains
Step5: Top 10 types of leisurely activ... |
12,683 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from sklearn.datasets import load_sample_image
china = load_sample_image("china.jpg")
fig = plt.figure(1)
ax = fig.add_subplot(1,1,1)
ax.imshow(china)
iso = china.reshape(-1,3)
print(iso.shape)
print(iso.nbytes)
fig =... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Queremos comprimir esta imagen para reducir el tamaño que cuesta almacenarlo en memoria. Una de las estrategias de compresión es reducir la pale... |
12,684 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.datasets import load_boston
boston = load_boston()
print("Keys of boston: {}".format(boston.keys()))
# The value of the key DESCR is a short description of the dataset. Here we show 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: A First Application
Step2: Measuring Success
Step3: First things first
Step4: From the plots, we can see RM has a strong positive linear rela... |
12,685 | <ASSISTANT_TASK:>
Python Code:
# Python standard-library
from urllib.parse import urlencode
from urllib.request import urlretrieve
# Third-party dependencies
from astropy import units as u
from astropy.coordinates import SkyCoord
from IPython.display import Image
# initialize a SkyCood object named hcg7_center at the ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Describing on-sky locations with coordinates
Step2: <div class="alert alert-info">
Step3: Show the available methods and attributes of the Sky... |
12,686 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import tensorflow as tf
# initial parameters can be learned on training data
# theory reference https://web.stanford.edu/~jurafsky/slp3/8.pdf
# code reference https://phvu.net/2013/12/06/sweet-implementation-of-viterbi-in-python/
class HMM(object):
def __init__(sel... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Create the same HMM model as before. This time, we'll include a couple additional functions.
Step2: Define the forward algorithm from Concept01... |
12,687 | <ASSISTANT_TASK:>
Python Code:
# If we're running on Colab, install modsimpy
# https://pypi.org/project/modsimpy/
import sys
IN_COLAB = 'google.colab' in sys.modules
if IN_COLAB:
!pip install pint==0.9
!pip install modsimpy
!mkdir figs
# Configure Jupyter so figures appear in the notebook
%matplotlib inline... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Bungee jumping
Step3: Now here's a version of make_system that takes a Params object as a parameter.
Step4: Let's make a System
Step6: drag_f... |
12,688 | <ASSISTANT_TASK:>
Python Code:
print("Missing values")
titanic_data.isnull().any(axis=1).sum()
titanic_data.isnull().sum()
treated_data = titanic_data.drop(['Cabin','Name', 'PassengerId', 'Ticket'], axis=1)
treated_data = treated_data.dropna()
treated_data.isnull().any(axis=1).sum()
treated_data['Age'].hist()
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: That's a lot of missing values, let's see how they are distributed
Step2: We can just drop the cabin column as it isn't important, we will also... |
12,689 | <ASSISTANT_TASK:>
Python Code:
#basic imports and ipython setup
import matplotlib.pyplot as plt
import numpy as np
#import solver related modules
from MCEq.core import MCEqRun
#import primary model choices
import crflux.models as pm
mceq_run = MCEqRun(
#provide the string of the interaction model
interaction_model='SIB... | <SYSTEM_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 everything succeeds than the last message should be something like
Step2: Calculate average flux
Step3: Plot with matplotlib
Step4: Save a... |
12,690 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
from ipywidgets import widget
from IPython.display import display
from math import pi, sin
import numpy as np
from matplotlib import pyplot as plt
from sklearn.linear_model import Ri... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Underfit
Step2: Overfit
Step3: Just right
Step4: Regularization -- More Data
Step5: You can see above, just be sampling 90 more data points ... |
12,691 | <ASSISTANT_TASK:>
Python Code:
path = "./pydata-book/ch02/usagov_bitly_data2012-03-16-1331923249.txt"
open(path).readline()
print(path)
print(type(path))
import json
datach02= [json.loads(line) for line in open(path)]
import json
path = "./pydata-book/ch02/usagov_bitly_data2012-03-16-1331923249.txt"
records = [json.lo... | <SYSTEM_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有许多内置或第三方模块可以将JSON字符转换成python字典对象。这里,我将使用json模块及其loads函数逐行加载已经下载好的数据文件:
Step2: 上面最后一行表达式,叫做“列表推导式 list comprehension”。这是一种在一组字符串(或一组别的对象)... |
12,692 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data_path = 'Bike-Sharing-Dataset/hour.csv'
rides = pd.read_csv(data_path)
rides.head()
rides[:24*10].plot(x='dteday', y='cnt')
dummy_fields = ['seas... | <SYSTEM_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 prepare the data
Step2: Checking out the data
Step3: Dummy variables
Step4: Scaling target variables
Step5: Splitting the data into... |
12,693 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
from IPython.display import display, HTML
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
CSS =
.output {
flex-direction: row;
}
complete_data = pd.read_csv("../data/Exercises_Summary_Statistics_Data.csv")
complete_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: Summary Statistics - Examples
Step2: The dimensions of the dataset are
Step3: Let's take a look
Step4: For those without biological backgroun... |
12,694 | <ASSISTANT_TASK:>
Python Code:
# 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 writing, sof... | <SYSTEM_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 Meta-Dataset Data Pipeline
Step2: Primers
Step3: Reading datasets
Step4: (1) Episodic Mode
Step5: Using Dataset
Step6: Visualizin... |
12,695 | <ASSISTANT_TASK:>
Python Code:
# !pip install cloudmlmagic
%load_ext cloudmlmagic
%%ml_init -projectId PROJECTID -bucket BUCKET -scaleTier BASIC_GPU -region asia-east1 -runtimeVersion 1.2
{'install_requires': ['keras', 'h5py', 'Pillow']}
%%ml_code
from keras.applications.inception_v3 import InceptionV3
model = Incep... | <SYSTEM_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 cloudmlmagic extension
Step2: Initialize and setup ML Engine parameters.
Step3: Load InceptionV3 model
Step4: Load dataset
Step5: Split... |
12,696 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
np.random.seed(0)
data = np.random.randint(40, 100, size=(5, 5))
data
data.mean()
data.std()
# X - mean
dev_arr = data - data.mean()
dev_arr
# ( X - mean )^2
dev_arr ** 2
# sum( ( X - mean )^2 ) / N
a = (dev_arr ** 2 ).sum() / 25
a
np.sqrt(a)
<END_TASK> | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 평균
Step2: 표준편차
|
12,697 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
symbols = [np.exp(1j * np.pi * (2*k+1) / 4) for k in range(4)]
sigma = 1/3
size = 10000 # Anzahl Symbole in Simulation
# Sendesignal
s = np.random.choice(symbols, size)
# Rauschen
n = np.random.normal(0, sigma, 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: Sendesymbole und Rauschen
Step2: Empfangssignal
Step3: Ergebnisse
Step4: Übertragungsfehler
|
12,698 | <ASSISTANT_TASK:>
Python Code:
%load_ext autoreload
%autoreload 1
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
pd.options.display.max_rows = 1000
pd.options.display.max_columns = 60
#utils.py is where all our custom functions live is we set an autoreloa... | <SYSTEM_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 the data
Step2: Preparing a test sample
Step3: Plotting the data
Step4: Session with range and extrapolated range
Step5: Testing
Ste... |
12,699 | <ASSISTANT_TASK:>
Python Code:
import em1ds as zpic
electrons = zpic.Species( "electrons", -1.0, ppc = 64, uth=[0.005,0.005,0.005])
sim = zpic.Simulation( nx = 1000, box = 100.0, dt = 0.05, species = electrons )
#Bz0 = 0.5
Bz0 = 1.0
#Bz0 = 4.0
sim.emf.set_ext_fld('uniform', B0= [0.0, 0.0, Bz0])
import numpy as np
nite... | <SYSTEM_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 run the simulation up to a fixed number of iterations, controlled by the variable niter, storing the value of the EM fields $E_y$ (X-wave) an... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.