Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
2,400 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using the PyTorch JIT Compiler with Pyro
This tutorial shows how to use the PyTorch jit compiler in Pyro models.
Summary
Step1: Introduction
PyTorch 1.0 includes a jit compiler to speed up ... | Python Code:
import os
import torch
import pyro
import pyro.distributions as dist
from torch.distributions import constraints
from pyro import poutine
from pyro.distributions.util import broadcast_shape
from pyro.infer import Trace_ELBO, JitTrace_ELBO, TraceEnum_ELBO, JitTraceEnum_ELBO, SVI
from pyro.infer.mcmc import ... |
2,401 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 Google Inc.
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 Licen... | Python Code:
%%bash
pip3 install git+https://github.com/GoogleCloudPlatform/healthcare.git#subdirectory=imaging/ml/toolkit
pip3 install dicomweb-client
pip3 install pydicom
Explanation: Copyright 2018 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in complia... |
2,402 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>The BurnMan Tutorial</h1>
Part 2
Step1: After initialization, the "print" method can be used to directly print molar, weight or atomic amounts. Optional variables control the print prec... | Python Code:
from burnman import Composition
olivine_composition = Composition({'MgO': 1.8,
'FeO': 0.2,
'SiO2': 1.}, 'weight')
Explanation: <h1>The BurnMan Tutorial</h1>
Part 2: The Composition Class
This file is part of BurnMan - a thermoelastic and... |
2,403 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression based on Iris dataset
We ll use the Iris dataset in the regression setup
- not use the target variable (typicall classification case)
- use petal width (cm) as dependent variable... | Python Code:
import sklearn.datasets as datasets
import pandas as pd
iris=datasets.load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df.head(2)
Explanation: Regression based on Iris dataset
We ll use the Iris dataset in the regression setup
- not use the target variable (typicall classification case... |
2,404 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step 1
Step1: Each row represents a different person and each column is on of many physical measurments lke the position of their arm, or forearm and each person gets one of 5 labels (class... | Python Code:
dataframe_all = pd.read_csv("https://d396qusza40orc.cloudfront.net/predmachlearn/pml-training.csv")
num_rows = dataframe_all.shape[0]
print('No. of rows:', num_rows)
dataframe_all.head()
Explanation: Step 1: download the data
End of explanation
#List all fators from our response variable
dataframe_all.clas... |
2,405 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to select a classifier
This document will guide you through the process of selecting a classifier for your problem.
Note that there is no established, scientifically proven rule-set for ... | Python Code:
from skmultilearn.dataset import load_dataset
X_train, y_train, feature_names, label_names = load_dataset('emotions', 'train')
X_test, y_test, _, _ =load_dataset('emotions', 'test')
Explanation: How to select a classifier
This document will guide you through the process of selecting a classifier for your p... |
2,406 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
how to save a trained machine learning or deep learning model
| Python Code::
model.save('filename')
|
2,407 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exponentials, Radicals, and Logs
Up to this point, all of our equations have included standard arithmetic operations, such as division, multiplication, addition, and subtraction. Many real-w... | Python Code:
x = 5**3
print(x)
Explanation: Exponentials, Radicals, and Logs
Up to this point, all of our equations have included standard arithmetic operations, such as division, multiplication, addition, and subtraction. Many real-world calculations involve exponential values in which numbers are raised by a specific... |
2,408 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Let's look at a traditional logistic regression model for some mildly complicated data.
Step1: Another pair of metrics
Step2: F1 is the harmonic mean of precision and recall | Python Code:
# synthetic data
X, y = make_classification(n_samples=10000, n_features=50, n_informative=12,
n_redundant=2, n_classes=2, random_state=0)
# statsmodels uses logit, not logistic
lm = sm.Logit(y, X).fit()
results = lm.summary()
print(results)
# hard problem
lm = sm.Logit(y, X).fit(... |
2,409 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How does the current Game2048 class work?
In this short notebook, we introduce how the class method should be called in our experiment code.
Step1: A game round demo
Step2: Let's check whe... | Python Code:
from game import Game2048
Explanation: How does the current Game2048 class work?
In this short notebook, we introduce how the class method should be called in our experiment code.
End of explanation
g = Game2048(game_mode=False) # False means AI mode
g.print_game()
g.active_player
moves = g.moves_available... |
2,410 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
En pandas tenemos varias posibilidades para leer datos y similares posibilidades para escribirlos.
Leamos unos datos de viento
En la carpeta Datos tenemos un fichero que se llama mast.txt co... | Python Code:
# primero hacemos los imports de turno
import os
import datetime as dt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display
np.random.seed(19760812)
%matplotlib inline
ipath = os.path.join('Datos', 'mast.txt')
wind = pd.read_csv(ipath)
wind.head(3)
wind... |
2,411 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Python for System Administrator
Author
Step2: Basic Arithmetic
Step3: Variable assignment
Step4: Formatting numbers
Step5: Formatting
Step6: Formatting with names | Python Code:
# Importing_new_features
# ..is easy. Features are collected
# in packages or modules. Just
import telnetlib # to use a
telnetlib.Telnet # client
# We can even import single classes
# from a module, like
from telnetlib import Telnet
# And read the module or class docs
help(telnetlib)
help(Telnet)
# you ... |
2,412 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'sandbox-3', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: EC-EARTH-CONSORTIUM
Source ID: SANDBOX-3
Topic: Atmosc... |
2,413 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python for Bioinformatics
This Jupyter notebook is intented to be used alongside the book Python for Bioinformatics
Chapter 18
Step1: Listing 18.1
Step2: Listing 18.2 | Python Code:
!pip install biopython
!curl https://raw.githubusercontent.com/Serulab/Py4Bio/master/samples/samples.tar.bz2 -o samples.tar.bz2
!mkdir samples
!tar xvfj samples.tar.bz2 -C samples
Explanation: Python for Bioinformatics
This Jupyter notebook is intented to be used alongside the book Python for Bioinformatic... |
2,414 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocean
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'inm', 'inm-cm5-0', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: INM
Source ID: INM-CM5-0
Topic: Ocean
Sub-Topics: Timestepping Framework, Adve... |
2,415 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Introduction to the TensorFlow Models NLP library
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
S... | 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 writing, software
# dist... |
2,416 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
本章将讨论继承和子类化,重点是说明对 Python 而言尤为重要的两个细节:
子类化内置类型的缺点
多重继承的方法和解析顺序
我们将通过两个重要的 Python 项目探讨多重继承,这两个项目是 GUI 工具包 Tkinter 和 Web 框架 Django
我们将首先分析子类化内置类型的问题,然后讨论多重继承,通过案例讨论类层次结构方面好的做法和不好的
子类化内置类型很麻烦
在... | Python Code:
class DoppelDict(dict):
def __setitem__(self, key, value):
super().__setitem__(key, [value] * 2)
dd = DoppelDict(one=1)
dd # 继承 dict 的 __init__ 方法忽略了我们覆盖的 __setitem__方法,'one' 值没有重复
dd['two'] = 2 # `[]` 运算符会调用我们覆盖的 __setitem__ 方法
dd
dd.update(three=3) #继承自 dict 的 update 方法也不会调用我们覆盖的 __setitem__ ... |
2,417 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kaggle Titanic Competition
This Jupyter Notebook examines how to use Python's scikit-learn module to create and train Decision Tree machine learning models. It does so specifically within t... | Python Code:
# import os and urllib
import os
# For Python 3.x the import should be urllib.request, but for Python 2.x it should just be urllib
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
# Make sure data directory exists
data_dir = 'data/kaggle/titanic'
if not... |
2,418 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Introduction to Document Similarity with Elasticsearch
In a text analytics context, document similarity relies on reimagining texts as points in space that can be close (similar) or d... | Python Code:
import os
from sklearn.datasets.base import Bunch
from yellowbrick.download import download_all
## The path to the test data sets
FIXTURES = os.path.join(os.getcwd(), "data")
## Dataset loading mechanisms
datasets = {
"hobbies": os.path.join(FIXTURES, "hobbies")
}
def load_data(name, download=True):
... |
2,419 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Understanding masking & padding
Authors
Step1: Introduction
Masking is a way to tell sequence-processing layers that certain timesteps
in an input are missing, and thus should be skipped wh... | Python Code:
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
Explanation: Understanding masking & padding
Authors: Scott Zhu, Francois Chollet<br>
Date created: 2019/07/16<br>
Last modified: 2020/04/14<br>
Description: Complete guide to using mask-aware sequen... |
2,420 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modifying the Variational Strategy/Variational Distribution
The predictive distribution for approximate GPs is given by
$$
p( \mathbf f(\mathbf x^) ) = \int_{\mathbf u} p( f(\mathbf x^) \mid... | Python Code:
import urllib.request
import os
from scipy.io import loadmat
from math import floor
# this is for running the notebook in our testing framework
smoke_test = ('CI' in os.environ)
if not smoke_test and not os.path.isfile('../elevators.mat'):
print('Downloading \'elevators\' UCI dataset...')
urllib.re... |
2,421 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The AdaNet Authors.
Step1: Customizing AdaNet With TensorFlow Hub Modules
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: ... | 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 writing, software
# dist... |
2,422 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook shows how BigBang can help you explore a mailing list archive.
First, use this IPython magic to tell the notebook to display matplotlib graphics inline. This is a nice way to d... | Python Code:
%matplotlib inline
Explanation: This notebook shows how BigBang can help you explore a mailing list archive.
First, use this IPython magic to tell the notebook to display matplotlib graphics inline. This is a nice way to display results.
End of explanation
import bigbang.mailman as mailman
import bigbang.g... |
2,423 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
If we had wanted to manage the same result using the StatsModels.formula.api, we should have typed the following
Step1: 第ä¸ä¸ªåæ°æ¯y0å¼ï¼å³x=0æ¶ï¼yè½´ä¸çå¼ã
第äºä¸ªæ¯æ... | Python Code:
fitted_model.summary()
print (fitted_model.params)
betas = np.array(fitted_model.params)
fitted_values = fitted_model.predict(X)
Explanation: If we had wanted to manage the same result using the StatsModels.formula.api, we should have typed the following:
linear_regression = smf.ols(formula='target ~ R... |
2,424 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
OpenPIV tutorial 1
In this tutorial we read a pair of images and perform the PIV using a standard algorithm. At the end, the velocity vector field is plotted.
Step1: Reading images
Step2: ... | Python Code:
from openpiv import tools, pyprocess, validation, filters, scaling
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import imageio
Explanation: OpenPIV tutorial 1
In this tutorial we read a pair of images and perform the PIV using a standard algorithm. At the end, the velocity vector ... |
2,425 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this post, we will build a couple different quiver plots using Python and matplotlib. A quiver plot is a type of 2D plot that shows vector lines as arrows. Quiver plots are useful in elec... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
#add %matplotlib inline if using a Jupyter notebook, remove if using a .py script
%matplotlib inline
Explanation: In this post, we will build a couple different quiver plots using Python and matplotlib. A quiver plot is a type of 2D plot that shows vector ... |
2,426 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Understand Data
Step1: 1.1 Conclusion
We have 10 886 observations and 12 features.
We don't have missing value.
Most value is integer, few of them float and object (should be a date).
Le... | Python Code:
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
train.info()
Explanation: 1. Understand Data
End of explanation
train.describe()
Explanation: 1.1 Conclusion
We have 10 886 observations and 12 features.
We don't have missing value.
Most value is integer, few of them float and object (should ... |
2,427 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EuroSciPy 2018
Step1: Use slicing to produce the following outputs
Step2: Get the second row by slicing twice
Try to get the second column by slicing. Do not use a list comprehension!
Gett... | Python Code:
mylist = list(range(10))
print(mylist)
Explanation: EuroSciPy 2018: NumPy tutorial
Let's do some slicing
End of explanation
matrix = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]
Explanation: Use slicing to produce the following outputs:
[2, 3, 4, 5]
[0, 1, 2, 3, 4]
[6, 7, 8, 9]
[0, 2, 4, 6, 8]
[9,... |
2,428 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Project
Step1: Step 1
Step2: Step 2
Step3: Step 3
Step4: Step 4
Step5: Repeat above process with new tweets from API in March 2017 | Python Code:
# imports
import pandas as pd
import nltk
from sklearn.cluster import KMeans
import re
import requests
from requests_oauthlib import OAuth1
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.stem import WordNetLemmatizer
from textblob import TextBlob
from nltk.stem.porter import PorterSt... |
2,429 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bolometric Corrections
Details about the bolometric correction package can be found in the GitHub repository starspot.
Step1: Before requesting bolometric corrections, we need to first init... | Python Code:
# change directory
%cd ../../../Projects/starspot/starspot/
from color import bolcor as bc
Explanation: Bolometric Corrections
Details about the bolometric correction package can be found in the GitHub repository starspot.
End of explanation
bc.utils.log_init('table_limits.log') # initialize bolometric co... |
2,430 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Parameter exploration
Purpose
Step1: This tutorial will introduce you to the "psyrun" tool for parameter space exploration and serial farming step by step. It also integrates well with "ctn... | Python Code:
from __future__ import print_function
from pprint import pprint
Explanation: Parameter exploration
Purpose: Run the simulation with varying parameters and characterize the effects of those parameters
Parameter exploration can either be done as grid search where a multidimensional "regular" grid of paramete... |
2,431 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
VIZBI Tutorial Session
Part 2
Step1: Don't forget to update this line! This should be your host machine's IP address.
Step2:
Step3: 2. Test Cytoscape REST API
Check the status of server... | Python Code:
# HTTP Client for Python
import requests
# Standard JSON library
import json
# Basic Setup
PORT_NUMBER = 1234 # This is the default port number of CyREST
Explanation: VIZBI Tutorial Session
Part 2: Cytoscape, IPython, Docker, and reproducible network data visualization workflows
Tuesday, 3/24/2015
Lesson 1... |
2,432 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | 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)
Explanation: Language Translation
In this project, you’re going ... |
2,433 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Control-Flow" data-toc-modified-id="Control-Flow-1"><span class="toc-item-num">1 </span>Control Flow</a></div><div class=... | Python Code:
collection = [1,2,3,4,5]
len(collection)
if len(collection) == 5:
print("Woohoo!")
collection[1]
if collection[0] % 2 == 0:
print("Divisible")
else:
print("Not Divisible")
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Control-Flow" data-toc-modified-id="Control-Flow-1">... |
2,434 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Embeddings for Weather Data
An embedding is a low-dimensional, vector representation of a (typically) high-dimensional feature which maintains the semantic meaning of the feature in a such a... | Python Code:
!sudo apt-get -y --quiet install libeccodes0
%pip install -q cfgrib xarray pydot
import apache_beam as beam
print(beam.__version__)
PROJECT='ai-analytics-solutions'
BUCKET='{}-kfpdemo'.format(PROJECT)
Explanation: Embeddings for Weather Data
An embedding is a low-dimensional, vector representation of a (ty... |
2,435 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First Steps with Python
Source
Step1: Variable amount of parameters
Step2: Variable amount of named parameters
Step3: Regular expressions
Step4: Sets
Step5: JSON/Pickle serialization
Us... | Python Code:
sentence = 'the quick brown fox jumps over the lazy dog'
words = sentence.split()
word_lengths = [len(word) for word in words if 'the' != word]
print(word_lengths)
Explanation: First Steps with Python
Source: learnpython.org
List comprehensions
End of explanation
def foo(first, second, third, *therest):
... |
2,436 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Examples
The core function of this package is design_matrices(). It returns an object of class DesignMatrices that contains information about the response, common effects and group specific ... | Python Code:
import pandas as pd
import numpy as np
from formulae import design_matrices
np.random.seed(1234)
SIZE = 20
CNT = 20
data = pd.DataFrame(
{
'x': np.random.normal(size=SIZE),
'y': np.random.normal(size=SIZE),
'z': np.random.normal(size=SIZE),
'$2#abc': np.random.normal(si... |
2,437 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Common Error Messages
Hi guys, in this lecture we shall be looking at a couple of Python's error messages you are likely to see when writing scripts. We shall also cover a few fixes for sai... | Python Code:
3ds = 100 # cannot start names with numbers. To fix: three_d_s = 100, or nintendo3ds = 100
list = [1,2,3] # "list" is a special keyword in Python, cannot use it as a name. To fix: a_list = [1,2,3]
Explanation: Common Error Messages
Hi guys, in this lecture we shall be looking at a couple of Python's error... |
2,438 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Point collocation
Point collection method is a broad term, as it covers multiple variation, but
in a nutshell all consist of the following steps
Step1: The number of Sobol samples to use at... | Python Code:
from pseudo_spectral_projection import gauss_quads
gauss_nodes = [nodes for nodes, _ in gauss_quads]
Explanation: Point collocation
Point collection method is a broad term, as it covers multiple variation, but
in a nutshell all consist of the following steps:
Generate samples $Q_1=(\alpha_1, \beta_1), \dot... |
2,439 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Named Entity Recognition and Classifiers to Extract Entities from Peer-Reviewed Journals
The overwhelming amount of unstructured text data available today from traditional media source... | Python Code:
##############################################
# Administrative code: Import what we need
##############################################
import os
import time
from os import walk
###############################################
# Set the Path
##############################################
path = os.p... |
2,440 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PR
Step2: Current Darknet, and Proposed Changes
Step3: 1. fastai Darknet Loss Function
Darknet without LogSoftmax layer and with NLL loss
Step4: fastai.conv_learner logic sets criterion t... | Python Code:
%matplotlib inline
%reload_ext autoreload
%autoreload 2
from pathlib import Path
from fastai.conv_learner import *
# from fastai.models import darknet
Explanation: PR: Adding LogSoftmax layer to Darknet for Cross Entropy Loss
Wayne Nixalo - 2018/4/24
0. Proposed Change; Setup
Dataset is the fast.ai ImageNe... |
2,441 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Storage command-line tool
The Google Cloud SDK provides a set of commands for working with data stored in Cloud Storage. This notebook introduces several gsutil commands for interacting with... | Python Code:
!gsutil help
Explanation: Storage command-line tool
The Google Cloud SDK provides a set of commands for working with data stored in Cloud Storage. This notebook introduces several gsutil commands for interacting with Cloud Storage. Note that shell commands in a notebook must be prepended with a !.
List ava... |
2,442 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What Do We Need From Slides 📑
Easy to create.
Easy to share.
Step1: Our Data 📉 | Python Code:
import pandas as pd
import numpy as np
import janitor
import pandas_flavor as pf
import janitor
def load_data():
return pd.read_csv('https://github.com/Kokkalo4/Kaggle-SF-Salaries/raw/master/Salaries.csv')\
.replace('Not Provided', np.nan)\
.astype({"BasePay":float, "OtherPay"... |
2,443 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Electric Machinery Fundamentals 5th edition
Chapter 1 (Code examples)
Example 1-10
Calculate and plot the velocity of a linear motor as a function of load.
Import the PyLab namespace (provid... | Python Code:
%pylab notebook
Explanation: Electric Machinery Fundamentals 5th edition
Chapter 1 (Code examples)
Example 1-10
Calculate and plot the velocity of a linear motor as a function of load.
Import the PyLab namespace (provides set of useful commands and constants like $\pi$)
End of explanation
VB = 120.0 # B... |
2,444 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic vectorization
Vectorizing text is a fundamental concept in applying both supervised and unsupervised learning to documents. Basically, you can think of it as turning the words in a giv... | Python Code:
bill_titles = ['An act to amend Section 44277 of the Education Code, relating to teachers.']
vectorizer = CountVectorizer()
features = vectorizer.fit_transform(bill_titles).toarray()
print features
print vectorizer.get_feature_names()
Explanation: Basic vectorization
Vectorizing text is a fundamental conce... |
2,445 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Figure 1
Start by loading some boiler plate
Step1: And some more specialized dependencies
Step2: Configuration for this figure.
Step3: Open a chest located on a remote globus endpoint and... | Python Code:
%matplotlib inline
import matplotlib
matplotlib.rcParams['figure.figsize'] = (10.0, 16.0)
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp1d, InterpolatedUnivariateSpline
from scipy.optimize import bisect
import json
from functools import partial
class Foo: pass
Expla... |
2,446 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Random Walks
In many situations, it is very useful to think of some sort of process that you wish to model as a succession of random steps. This can describe a wide variety of phenomena - t... | Python Code:
# put your code for Part 1 here. Add extra cells as necessary!
Explanation: Random Walks
In many situations, it is very useful to think of some sort of process that you wish to model as a succession of random steps. This can describe a wide variety of phenomena - the behavior of the stock market, models ... |
2,447 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transfer Learning
Most of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instea... | Python Code:
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
vgg_dir = 'tensorflow_vgg/'
# Make sure vgg exists
if not isdir(vgg_dir):
raise Exception("VGG directory doesn't exist!")
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=... |
2,448 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data validation using TFX Pipeline and TensorFlow Data Validation
Learning Objectives
Understand the data types, distributions, and other information (e.g., mean value, or number of uniques)... | Python Code:
# Install the TensorFlow Extended library
!pip install -U tfx
Explanation: Data validation using TFX Pipeline and TensorFlow Data Validation
Learning Objectives
Understand the data types, distributions, and other information (e.g., mean value, or number of uniques) about each feature.
Generate a preliminar... |
2,449 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
E2E ML on GCP
Step1: Restart the kernel
Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages.
Step2: Before you begin
Set up y... | Python Code:
import os
# The Vertex AI Workbench Notebook product has specific requirements
IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME")
IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(
"/opt/deeplearning/metadata/env_version"
)
# Vertex AI Notebook requires dependencies to be installed with '--user'
U... |
2,450 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reproducing the COHERENT results - and New Physics constraints
Code for reproducing the CEvNS signal observed by COHERENT - see arXiv
Step1: Import the CEvNS module (for calculating the sig... | Python Code:
from __future__ import print_function
%matplotlib inline
import numpy as np
import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as pl
from scipy.integrate import quad
from scipy.interpolate import interp1d, UnivariateSpline,InterpolatedUnivariateSpline
from scipy.optimize import minimize
from... |
2,451 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Counting Colonies with scikit-image
Step1: Load in the plate image
Step2: Construct a mask to remove the plate itself
Step3: Creates a mask that is False if pixel is inside the plate and ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from skimage.feature import blob_dog, blob_log, blob_doh
from skimage.color import rgb2gray
from skimage.draw import circle
Explanation: Counting Colonies with scikit-image
End of explanation
image = np.array(Image.... |
2,452 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Higgs Boson Analysis with ATLAS Open Data
This is an example analysis of the Higgs boson detection via the decay channel H → ZZ* → 4l
From the decay products measured at the ATLAS ... | Python Code:
# Run this if you need to install Apache Spark (PySpark)
# !pip install pyspark
# Install sparkhistogram
# Note: if you cannot install the package, create the computeHistogram
# function as detailed at the end of this notebook.
!pip install sparkhistogram
# Run this to download the dataset
# It is a small... |
2,453 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
make the train_pivot, duplicate exist when index = ['Cliente','Producto']
for each cliente & producto, first find its most common Agencia_ID, Canal_ID, Ruta_SAK
Step1: make pivot table of t... | Python Code:
agencia_for_cliente_producto = train_dataset[['Cliente_ID','Producto_ID'
,'Agencia_ID']].groupby(['Cliente_ID',
'Producto_ID']).agg(lambda x:x.value_counts().index[0]).reset_index()
canal_f... |
2,454 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression diagnostics
This example file shows how to use a few of the statsmodels regression diagnostic tests in a real-life context. You can learn about more tests and find out more inform... | Python Code:
%matplotlib inline
from __future__ import print_function
from statsmodels.compat import lzip
import statsmodels
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
import statsmodels.stats.api as sms
import matplotlib.pyplot as plt
# Load data
url = 'http://vincentarelbundock.githu... |
2,455 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Least squares fitting using linfit.py
This notebook demonstrates the function linfit, which I propose adding to the SciPy library.
linfit is designed to be a fast, lightweight function, wr... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec # for unequal plot boxes
from linfit import linfit
Explanation: Least squares fitting using linfit.py
This notebook demonstrates the function linfit, which I propose adding to the SciPy library.
linfit is designed ... |
2,456 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: KD-trees
Question 1
<img src="images/Screen Shot 2016-07-03 at 12.14.16 AM.png">
Screenshot taken from Coursera
<!--TEASER_END-->
Question 2
<img src="images/Screen Shot 2016-07-02 at... | Python Code:
import numpy as np
x1 = np.array([-1.58, 0.91, -0.73, -4.22, 4.19, -0.33])
x2 = np.array([-2.01, 3.98, 4.00, 1.16, -2.02, 2.15])
x = np.vstack((x1, x2)).T
x
# Mid range of x1
x1_midrange = (x1.max() + x1.min())/2
x1_midrange
def get_mid_range(data, column=0):
Get midrange of data by column
- x1: c... |
2,457 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NWB use-case pvc-7
--- Data courtesy of Aleena Garner, Allen Institute for Brain Sciences ---
Here we demonstrate how data from the NWB pvc-7 use-case can be stored in NIX files.
Context
Ste... | Python Code:
from nixio import *
import numpy as np
import matplotlib.pylab as plt
%matplotlib inline
from utils.notebook import print_stats
from utils.plotting import Plotter
Explanation: NWB use-case pvc-7
--- Data courtesy of Aleena Garner, Allen Institute for Brain Sciences ---
Here we demonstrate how data from the... |
2,458 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Seaice
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify ... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'sandbox-3', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: EC-EARTH-CONSORTIUM
Source ID: SANDBOX-3
Topic: Seaice
Sub-T... |
2,459 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Algorithms Exercise 1
Imports
Step3: Word counting
Write a function tokenize that takes a string of English text returns a list of words. It should also remove stop words, which are common ... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
Explanation: Algorithms Exercise 1
Imports
End of explanation
def tokenize(s, stop_words=None, punctuation='`~!@#$%^&*()_-+={[}]|\:;"<,>.?/}\t'):
Split a string into a list of words, removing punctuation and stop words.
s = ... |
2,460 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<small><i>The PCA section of this notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small>
Dimensionality Reduction
Step1: Introducing Principal Compo... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
# use seaborn plotting style defaults
import seaborn as sns; sns.set()
Explanation: <small><i>The PCA section of this notebook was put together by Jake Vanderplas. S... |
2,461 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Z-Stage" data-toc-modified-id="Z-Stage-1"><span class="toc-item-num">1 </span>Z-Stage</a></div><div class="lev1 toc-item"... | Python Code:
import logging; logging.basicConfig(level=logging.DEBUG)
import time
import mr_box_peripheral_board as mrbox
import serial
reload(mrbox)
# Try to connect to MR-Box control board.
retry_count = 2
for i in xrange(retry_count):
try:
proxy.close()
except NameError:
pass
try:
... |
2,462 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Eye Drops Analysis for NIRS and Pulse Ox
Writing a new notebook to analyze eye drops only
Initialize and Select ROP Subject Number
Step1: Baseline Average Calculation
Step2: First Eye Drop... | Python Code:
from ROPini import *
#Takes a little bit, wait a while.
Hour1, Minute1, Hour2, Minute2, Hour3,
Minute3 = [int(x) for x in raw_input("Enter times for eye drops here: ").split()]
#Syntax should be "HH MM HH MM HH MM" First time, second time, third time all in one line.
#No commas or colons.
W1 = datetime(Y... |
2,463 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GAMES OR ADVERSARIAL SEARCH
This notebook serves as supporting material for topics covered in Chapter 5 - Adversarial Search in the book Artificial Intelligence
Step1: GAME REPRESENTATION
T... | Python Code:
from games import *
from notebook import psource, pseudocode
Explanation: GAMES OR ADVERSARIAL SEARCH
This notebook serves as supporting material for topics covered in Chapter 5 - Adversarial Search in the book Artificial Intelligence: A Modern Approach. This notebook uses implementations from games.py mod... |
2,464 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ncar', 'sandbox-1', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: NCAR
Source ID: SANDBOX-1
Sub-Topics: Radiative Forcings.
Properties: ... |
2,465 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Inference in Discrete Bayesian Network
In this notebook, we show a simple example for doing Exact inference in Bayesian Networks using pgmpy. We will be using the Asia network (http
Step1: ... | Python Code:
# Fetch the asia model from the bnlearn repository
from pgmpy.utils import get_example_model
asia_model = get_example_model("asia")
print("Nodes: ", asia_model.nodes())
print("Edges: ", asia_model.edges())
asia_model.get_cpds()
Explanation: Inference in Discrete Bayesian Network
In this notebook, we show a... |
2,466 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time-energy fit
3ML allows the possibility to model a time-varying source by explicitly fitting the time-dependent part of the model. Let's see this with an example.
First we import what we ... | Python Code:
from threeML import *
import matplotlib.pyplot as plt
from jupyterthemes import jtplot
%matplotlib inline
jtplot.style(context="talk", fscale=1, ticks=True, grid=False)
plt.style.use("mike")
Explanation: Time-energy fit
3ML allows the possibility to model a time-varying source by explicitly fitting the tim... |
2,467 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create evoked objects in delayed SSP mode
This script shows how to apply SSP projectors delayed, that is,
at the evoked stage. This is particularly useful to support decisions
related to the... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
Explanation: C... |
2,468 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step5: Skripta za generiranje kolokvija
Skripta generira $\LaTeX$ dokument s slučajno generiranim kolokvijima. Studenti se učitavaju iz datoteke.
Najprije definiramo stringove koji sadrže za... | Python Code:
header1 = r\documentclass[a4paper,11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[croatian]{babel}
\usepackage{minted}
\usepackage{amsmath,amsfonts}
\usepackage{graphicx}
\usepackage{booktabs}
\usepackage[hmargin=1.5cm,vmargin=1cm]{geometry}
\pagestyle{empty}
\begin{document... |
2,469 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
나이브 베이즈 분류 모형
나이브 베이즈 분류 모형(Naive Bayes classification model)은 대표적인 확률적 생성 모형이다.
타겟 변수 $y$의 각 클래스 ${C_1,\cdots,C_K}$ 에 대한 독립 변수 $x$의 조건부 확률 분포 정보 $p(x \mid y = C_k)$ 를 사용하여 주어진 새로운 독립 변수 값 ... | Python Code:
np.random.seed(0)
X0 = sp.stats.norm(-2, 1).rvs(40)
X1 = sp.stats.norm(+2, 1).rvs(60)
X = np.hstack([X0, X1])[:, np.newaxis]
y0 = np.zeros(40)
y1 = np.ones(60)
y = np.hstack([y0, y1])
sns.distplot(X0, rug=True, kde=False, norm_hist=True, label="class 0")
sns.distplot(X1, rug=True, kde=False, norm_hist=True... |
2,470 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fitting Models Exercise 1
Imports
Step1: Fitting a quadratic curve
For this problem we are going to work with the following model
Step2: First, generate a dataset using this model using th... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
Explanation: Fitting Models Exercise 1
Imports
End of explanation
a_true = 0.5
b_true = 2.0
c_true = -4.0
Explanation: Fitting a quadratic curve
For this problem we are going to work with the following model:... |
2,471 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using wrappers for Gensim models for working with Keras
This tutorial is about using gensim models as a part of your Keras models.
The wrappers available (as of now) are
Step1: Next we cre... | Python Code:
from gensim.models import word2vec
Explanation: Using wrappers for Gensim models for working with Keras
This tutorial is about using gensim models as a part of your Keras models.
The wrappers available (as of now) are :
* Word2Vec (uses the function get_embedding_layer defined in gensim.models.keyedvector... |
2,472 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Statistical Data Modeling
Some or most of you have probably taken some undergraduate- or graduate-level statistics courses. Unfortunately, the curricula for most introductory statisics cours... | Python Code:
import numpy as np
import pandas as pd
# Set some Pandas options
pd.set_option('display.notebook_repr_html', False)
pd.set_option('display.max_columns', 20)
pd.set_option('display.max_rows', 25)
Explanation: Statistical Data Modeling
Some or most of you have probably taken some undergraduate- or graduate-l... |
2,473 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Autoregressions
This notebook introduces autoregression modeling using the AutoReg model. It also covers aspects of ar_select_order assists in selecting models that minimize an information c... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import pandas_datareader as pdr
import seaborn as sns
from statsmodels.tsa.api import acf, graphics, pacf
from statsmodels.tsa.ar_model import AutoReg, ar_select_order
Explanation: Autoregressions
This notebook introduces autoregression... |
2,474 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
final_df 완성하기
Step1: 1. 이동진 평점 및 코멘트만 불러오기 (new_df3)
Step2: 최종적으로 뽑고 싶은 features(dataframe보여주기위한)
y값 | Python Code:
import pandas as pd
df1 = pd.read_csv('../resource/raw_df1.csv')
df2 = pd.read_csv('../resource/raw_df2.csv')
df3 = pd.read_csv('../resource/lee_df.csv')
df1.tail(1)
df2.tail(1)
df3.tail(1)
Explanation: final_df 완성하기
End of explanation
lee = df3['name'] == '이동진 평론가'
lee
lee_df = df3[lee]
new_df3 = pd.conca... |
2,475 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Part of Speech Tagging
Part of speech tagging task aims to assign every word/token in plain text a category that identifies the syntactic functionality of the word occurrence.
Polyglot recog... | Python Code:
from polyglot.downloader import downloader
print(downloader.supported_languages_table("pos2"))
Explanation: Part of Speech Tagging
Part of speech tagging task aims to assign every word/token in plain text a category that identifies the syntactic functionality of the word occurrence.
Polyglot recognizes 17 ... |
2,476 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'thu', 'ciesm', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: THU
Source ID: CIESM
Sub-Topics: Radiative Forcings.
Properties: 85 (42 req... |
2,477 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<header class="w3-container w3-teal">
<img src="images/utfsm.png" alt="" align="left"/>
<img src="images/inf.png" alt="" align="right"/>
</header>
<br/><br/><br/><br/><br/>
IWI131
Programaci... | Python Code:
r = 0.2
area = 3.14*r**2
print "Circulo de radio", r, "[m] tiene area", area, "[m2]"
r = 1.0
area = 3.14*r**2
print "Circulo de radio", r, "[m] tiene area", area, "[m2]"
r = 42.0
area = 3.14*r**2
print "Circulo de radio", r, "[m] tiene area", area, "[m2]"
Explanation: <header class="w3-container w3-teal">
... |
2,478 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
You are trying to measure a difference in the $K_{D}$ of two proteins binding to a ligand. From previous experiments, you know that the values of replicate measurements of $K_{D}$ follow a ... | Python Code:
%matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
Explanation: You are trying to measure a difference in the $K_{D}$ of two proteins binding to a ligand. From previous experiments, you know that the values of replicate measurements of $K_{D}$ follow a normal distribution with $\si... |
2,479 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Say, I have an array: | Problem:
import numpy as np
a = np.array([0, 1, 2, 5, 6, 7, 8, 8, 8, 10, 29, 32, 45])
result = (a.mean()-3*a.std(), a.mean()+3*a.std()) |
2,480 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Non-Personalized Recommenders Assignment
Overview
This assignment will explore non-personalized recommendations. You will be given a 20x20 matrix where columns represent movies, rows represe... | Python Code:
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('darkgrid')
%matplotlib inline
Explanation: Non-Personalized Recommenders Assignment
Overview
This assignment will explore non-personalized recommendations. You will be given ... |
2,481 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework 2 - Classification Dataset
Two datasets are included, related to red and white vinho verde wine samples, from the north of Portugal. The goal is to model wine quality based on physi... | Python Code:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
Explanation: Homework 2 - Classification Dataset
Two datasets are included, related to red and white vinho verde wine samples, from the north of Portugal. The goal is to model wine quality based on physicochemical t... |
2,482 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Healpix pixelization of DR72 SDSS Database
First import all the modules such as healpy and astropy needed for analyzing the structure
Step1: Read the data file
Sorted and reduced column set... | Python Code:
import healpix_util as hu
import astropy as ap
import numpy as np
from astropy.io import fits
from astropy.table import Table
import astropy.io.ascii as ascii
from astropy.constants import c
import matplotlib.pyplot as plt
import math
import scipy.special as sp
Explanation: Healpix pixelization of DR72 SDS... |
2,483 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
how to plot confusion matrix using python
| Python Code::
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import normalize
import seaborn as sns
cm = confusion_matrix(target, pred)
normed_confusion_matrix = normalize(cm, axis = 1, norm = 'l1')
cm_df = pd.DataFrame(normed_confusion_matrix,index, columns)
sns.heatmap(cm_df, annot=True)
|
2,484 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercises for Chapter 1
Training Machine Learning Algorithms for Classification
Question 1. In the file algos/perceptron.py, implement Rosenblatt's perceptron algorithm by fleshing out the c... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from algos.perceptron import Perceptron
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)
y = df.iloc[0:100, 4].values
y = np.where(y == 'Iris-setosa', 1, -1)
X ... |
2,485 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | 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)
Explanation: Language Translation
In this project, you’re going ... |
2,486 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Water Classification and Analysis of Lake Chad
The previous tutorial introduced Landsat 7 imagery. The Lake Chad dataset was split into pre and post rainy season data-sets. The datasets wer... | Python Code:
import xarray as xr
Explanation: Water Classification and Analysis of Lake Chad
The previous tutorial introduced Landsat 7 imagery. The Lake Chad dataset was split into pre and post rainy season data-sets. The datasets were then cleaned up to produce a cloud-free and SLC-gap-free composite.
This tutori... |
2,487 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Autoregressive Moving Average (ARMA)
Step1: Sunpots Data
Step2: Does our model obey the theory?
Step3: This indicates a lack of fit.
In-sample dynamic prediction. How good does our model ... | Python Code:
%matplotlib inline
from __future__ import print_function
import numpy as np
from scipy import stats
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.graphics.api import qqplot
Explanation: Autoregressive Moving Average (ARMA): Sunspots data
End of explanatio... |
2,488 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generating Weak Labels for Image Datasets (e.g. Person Riding Bike)
Note
Step1: Note
Step2: 1. Load and Visualize Dataset
First, we load the dataset and associated bounding box objects and... | Python Code:
%load_ext autoreload
%autoreload 2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import os
Explanation: Generating Weak Labels for Image Datasets (e.g. Person Riding Bike)
Note: This notebook assumes that Snorkel is installed. If not, see the Quick Start guide in the Snorkel README.... |
2,489 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualizing the stock market structure
This example employs several unsupervised learning techniques to extract
the stock market structure from variations in historical quotes.
The quantity ... | Python Code:
print(__doc__)
# Author: Gael Varoquaux gael.varoquaux@normalesup.org
# License: BSD 3 clause
import datetime
import numpy as np
import matplotlib.pyplot as plt
try:
from matplotlib.finance import quotes_historical_yahoo_ochl
except ImportError:
# quotes_historical_yahoo_ochl was named quotes_histo... |
2,490 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Conversão de tipo
Step2: Operações com String (texto)
Step3: Faça um programa que leia o nome, a qtde e o valor de um produto qualquer, apresente os dados do produto... | Python Code:
nome1 = "Maria" # criando uma variável texto
idade1 = 42
nome2 = input("Digite seu nome: ") # pedindo dados ao usuário
idade2 = int(input("Digite sua idade: "))
print(type(idade2)) # verificando o tipo da variá... |
2,491 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--
17/11
Introducción a la de programación orientada a objetos. Uso de objetos dados.
-->
Programación Orientada a Objetos (POO)
¿Qué es un objeto?
Comencemos por definir ¿qué es un objeto... | Python Code:
class Mesa(object):
cantidad_de_patas = None
color = None
material = None
mi_mesa = Mesa()
mi_mesa.cantidad_de_patas = 4
mi_mesa.color = 'Marrón'
mi_mesa.material = 'Madera'
print 'Tendo una mesa de {0.cantidad_de_patas} patas de color {0.color} y esta hecha de {0.material}'.format(mi_mesa... |
2,492 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below ... | Python Code:
#Set up the sum of multiples and reset to zero
multiples_sum = 0
#Create the function that divides all the numbers from 1-1000 by 3 or 5 and add them
for i in range(1, 1000):
if (i % 3 == 0 or i % 5 == 0):
multiples_sum = multiples_sum + i
#Print results
print (multiples_sum)
Explanation: Probl... |
2,493 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute source power using DICS beamfomer
Compute a Dynamic Imaging of Coherent Sources (DICS) [1]_ filter from
single-trial activity to estimate source power for two frequencies of
interest... | Python Code:
# Author: Roman Goj <roman.goj@gmail.com>
# Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne.datasets import sample
from mne.time_frequency import csd_epochs
from mne.beamformer import dics_source_power
print(__doc__)
data_path = sample.data_path()
raw_fname... |
2,494 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create a training set, a test set and a set to predict for
Step1: Inspect the features, I know these features (at leasr spectral indices) are correlated but also have high variance, I could... | Python Code:
features=list(hst3d.columns)
features.remove('name')
Explanation: Create a training set, a test set and a set to predict for
End of explanation
import seaborn as sns
#plt.xscale('log')
sns.pairplot(spex[features], hue=None)
good_features=['H_2O-1/J-Cont', 'CH_4/H-Cont', 'H_2O-2/J-Cont']
from sklearn.decomp... |
2,495 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This code is taken from the TensorFlow tutorial expert example. The purpose here is to create an MNIST classifier. I tried to remove all the magic numbers in the example.
Step1: Below, we... | Python Code:
import tensorflow.examples.tutorials.mnist.input_data as id
mnist = id.read_data_sets('MNIST_data', one_hot=True)
import tensorflow as tf
sess = tf.InteractiveSession()
Explanation: This code is taken from the TensorFlow tutorial expert example. The purpose here is to create an MNIST classifier. I tried ... |
2,496 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Weather and Motor Vehicle Collisions
Step1: Download weather data
Step2: Cleaning the weather dataset
Convert weather DateUTC to local time
Step3: Merge weather and NYPD MVC datasets
Step... | Python Code:
import pandas as pd
import numpy as np
import datetime
from datetime import date
from dateutil.rrule import rrule, DAILY
from __future__ import division
import geoplotlib as glp
from geoplotlib.utils import BoundingBox, DataAccessObject
pd.set_option('display.max_columns', None)
%matplotlib inline
Explan... |
2,497 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Instructions
Work on a copy of this notebook
Step1: Now, let's create and test a pipeline
Step2: Let's first create a simple CUDA kernel within Bifrost.
We will generate 1000 integers, fee... | Python Code:
# @title Install C++ deps
%%shell
sudo apt-get -qq install exuberant-ctags libopenblas-dev software-properties-common build-essential
# @title Install python deps
%%shell
pip install -q contextlib2 pint simplejson ctypesgen==1.0.2
# @title Build and Install Bifrost
%%shell
cd "${HOME}"
if [ -d "${HOME}/bif... |
2,498 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
K-Nearest Neighbors (KNN)
by Chiyuan Zhang and Sören Sonnenburg
This notebook illustrates the <a href="http
Step1: Let us plot the first five examples of the train data (first row) and... | Python Code:
import numpy as np
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
from scipy.io import loadmat, savemat
from numpy import random
from os import path
mat = loadmat(os.path.join(SHOGUN_DATA_DIR, 'multiclass/usps.mat'))
Xall = mat['data']
Yall = np.array(mat['label'].squeeze... |
2,499 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Here, we construct a simple neural network transform with the ability to add layers and change the optimizer while training. Note that this code is largely identical to the Keras example, an... | Python Code:
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD
class SimpleNN(ContinuousTransform):
def init_func(self,target_df,X_train_df,y_train_df,X_test_df,y_test_df):
model=Sequential()
model.add(Dense(64, input_dim=78... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.