Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
1,900 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CrowdTruth for Recognizing Textual Entailment Annotation
This analysis uses the data gathered in the "Recognizing Textual Entailment" crowdsourcing experiment published in Rion Snow, Brendan... | Python Code:
import pandas as pd
test_data = pd.read_csv("../data/rte.standardized.csv")
test_data.head()
Explanation: CrowdTruth for Recognizing Textual Entailment Annotation
This analysis uses the data gathered in the "Recognizing Textual Entailment" crowdsourcing experiment published in Rion Snow, Brendan O’Connor, ... |
1,901 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
VHSE-Based Prediction of Proteasomal Cleavage Sites
Xie J, Xu Z, Zhou S, Pan X, Cai S, Yang L, et al. (2013) The VHSE-Based Prediction of Proteasomal Cleavage Sites. PLoS ONE 8(9)
Step1: Th... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, metrics
from sklearn.preprocessing import MinMaxScaler
Explanation: VHSE-Based Prediction of Proteasomal Cleavage Sites
Xie J, Xu Z, Zhou S, Pan X, Cai S, Yang L, et al. (2013) The VHSE-Based Prediction of Prote... |
1,902 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Q-learning
In this notebook, we'll build a neural network that can learn to play games through reinforcement learning. More specifically, we'll use Q-learning to train an agent to play ... | Python Code:
import gym
import tensorflow as tf
import numpy as np
Explanation: Deep Q-learning
In this notebook, we'll build a neural network that can learn to play games through reinforcement learning. More specifically, we'll use Q-learning to train an agent to play a game called Cart-Pole. In this game, a freely sw... |
1,903 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
"or" operator
This presentation is inspired by
Neil Ludban's use
of the "or" operator in
Test-Driven Development with Python at
last month's technical meeting.
split diff view of code on g... | Python Code:
# meld is a great visual difference program
# http://meldmerge.org/
# the following command relies on the directory structure on my computer
# tdd-demo comes from https://github.com/james-prior/tdd-demo/
!cd ~/projects/tdd-demo;git difftool -t meld -y 389df2a^ 389df2a
Explanation: "or" operator
This presen... |
1,904 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Superposed epoch analysis in the presence of high internal variability
We will be using a 4000yr pre-industrial time series of monthly-mean NINO3.4 SST from the GFDL CM2.1, described in
Ste... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import LMRt
import os
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats.mstats import mquantiles
import xarray as xr
from matplotlib import gridspec
from scipy.signal import find_peaks
import pandas as pd
import p... |
1,905 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generative Adversarial Network
In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d... | Python Code:
%matplotlib inline
import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data')
Explanation: Generative Adversarial Network
In this notebook, we'll be building a gen... |
1,906 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
05 - Continuous Training
After testing, compiling, and uploading the pipeline definition to Cloud Storage, the pipeline is executed with respect to a trigger. We use Cloud Functions and Clou... | Python Code:
import json
import os
import logging
import tensorflow as tf
import tfx
import IPython
logging.getLogger().setLevel(logging.INFO)
print("Tensorflow Version:", tfx.__version__)
Explanation: 05 - Continuous Training
After testing, compiling, and uploading the pipeline definition to Cloud Storage, the pipeli... |
1,907 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CesiumWidget together with CZML library
This notebook shows how to use the CesiumWidget together with the CZML library from https
Step1: Some data for the viewer to display
Step2: Create w... | Python Code:
from CesiumWidget import CesiumWidget
import czml
Explanation: CesiumWidget together with CZML library
This notebook shows how to use the CesiumWidget together with the CZML library from https://github.com/cleder/czml
If the CesiumWidget is installed correctly, Cesium should be accessable at:
http://localh... |
1,908 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Probability Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Linear Mixed Effects Models
<table class="tfo-notebook-buttons" ali... | 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 law or agreed to in... |
1,909 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Named Entity Recognition
Author
Step1: Let's take a paragraph from the Wikipedia page of Ada Lovelace as an example. We need to put the text in triple quotes since the text itself contains ... | Python Code:
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize
# Adapt those lines to your installation
jar_location = '/Users/sech/stanford-ner-2018-10-16/stanford-ner.jar'
model_location_3classes = '/Users/sech/stanford-ner-2018-10-16/classifiers/english.all.3class.distsim.crf.ser.gz'
mod... |
1,910 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Feature
Step1: NLTK tools
Step2: Config
Automatically discover the paths to various data folders and compose the project structure.
Step3: Identifier for storing these features on disk an... | Python Code:
from pygoose import *
Explanation: Feature: "Jaccard with WHQ" (@dasolmar)
Based on the kernel XGB with whq jaccard by David Solis.
Imports
This utility package imports numpy, pandas, matplotlib and a helper kg module into the root namespace.
End of explanation
import nltk
from collections import Counter
f... |
1,911 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reinforcement Learning with Policy Gradients using PyTorch
Agenda
What reinforcement learning is all about?
Introduction
Deep Reinforcement Learning
Methods to solve reinforcement learning p... | Python Code:
import gym
env = gym.make('Pong-v0').unwrapped
observation = env.reset()
while True:
env.render()
observation, reward, done, _ = env.step(action)
# Record reward for future training
policy.rewards.append(reward)
reward_sum += reward
Explanation: Reinforcement Learning with Policy G... |
1,912 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Debug Models Using tfdbg
Open a Terminal through Jupyter Notebook
(Menu Bar -> Terminal -> New Terminal)
Run the Next Cell to Display the Code
Find the DebugWrapper around the tf.Session
ses... | Python Code:
%%bash
cat /root/src/main/python/debug/debug_model_cpu.py
Explanation: Debug Models Using tfdbg
Open a Terminal through Jupyter Notebook
(Menu Bar -> Terminal -> New Terminal)
Run the Next Cell to Display the Code
Find the DebugWrapper around the tf.Session
sess = tf.Session(config=config)
sess = tf_debug.... |
1,913 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have a data frame with one (string) column and I'd like to split it into two (string) columns, with one column header as 'fips' and the other 'row' | Problem:
import pandas as pd
df = pd.DataFrame({'row': ['00000 UNITED STATES', '01000 ALABAMA',
'01001 Autauga County, AL', '01003 Baldwin County, AL',
'01005 Barbour County, AL']})
def g(df):
return pd.DataFrame(df.row.str.split(' ', 1).tolist(), columns=['fips... |
1,914 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: I wanted to implement a GAN but my derivatives didn't work after a lot of try, so I gave up. If you are available in Monday or Tuesday can we have a look at them?
Generative Adverseri... | Python Code:
# As usual, a bit of setup
import time, os, json
import numpy as np
import matplotlib.pyplot as plt
from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interp... |
1,915 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Get Started
Here are some sample queries. See what BQX can do.
Initialization
Step1: 1. Simple examples
1.1 Make simple query.
Step2: 1.2 Get rid of quotes using Aliases.
Step3: 1.3 You'l... | Python Code:
from bqx.query import Query as Q
from bqx.parts import Table as T, Column as C
from bqx.func import SUM
Explanation: Get Started
Here are some sample queries. See what BQX can do.
Initialization
End of explanation
q = Q().SELECT('name').FROM('sample_table')
print(q.getq())
Explanation: 1. Simple examples
1... |
1,916 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SPLAT Tutorials
Step1: Reading in and visualizing spectra
SPLAT contains a built-in library of published SpeX prism spectra of ultracool dwarfs. It is also possible to download additional s... | Python Code:
# main splat import
import splat
import splat.plot as splot
import splat.photometry as sphot
import splat.empirical as spem
# other useful imports
import matplotlib.pyplot as plt
import numpy as np
import pandas
import astropy.units as u
from astropy.io import fits
from astropy.utils.data import download_f... |
1,917 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Model-Free Reinforcement Learning
Remember how in last Notebook we felt like cheating by using directions calculated from the map of the environment?? Well, model-free reinforcement learning... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tempfile
import pprint
import math
import json
import sys
import gym
from gym import wrappers
from subprocess import check_output
from IPython.display import HTML
Explanation: Model-Free Reinforcement Learning
Remember how in las... |
1,918 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DirectLiNGAM by Kernel Method
Import and settings
In this example, we need to import numpy, pandas, and graphviz in addition to lingam.
Step1: Test data
We create test data consisting of 6 ... | Python Code:
import numpy as np
import pandas as pd
import graphviz
import lingam
from lingam.utils import make_dot
print([np.__version__, pd.__version__, graphviz.__version__, lingam.__version__])
np.set_printoptions(precision=3, suppress=True)
np.random.seed(0)
Explanation: DirectLiNGAM by Kernel Method
Import and se... |
1,919 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Estimating Precession Frequencies
Introduction
This Notebook demonstrates how to use QInfer to estimate a single precession frequency, for example in a Rabi or Ramsey experiment.
Setup
First... | Python Code:
from __future__ import division, print_function
Explanation: Estimating Precession Frequencies
Introduction
This Notebook demonstrates how to use QInfer to estimate a single precession frequency, for example in a Rabi or Ramsey experiment.
Setup
First, to make sure that this example works in both Python 2 ... |
1,920 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
======================================================================
Time-frequency on simulated data (Multitaper vs. Morlet vs. Stockwell)
================================================... | Python Code:
# Authors: Hari Bharadwaj <hari@nmr.mgh.harvard.edu>
# Denis Engemann <denis.engemann@gmail.com>
# Chris Holdgraf <choldgraf@berkeley.edu>
#
# License: BSD (3-clause)
import numpy as np
from matplotlib import pyplot as plt
from mne import create_info, EpochsArray
from mne.baseline import ... |
1,921 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id='top'> </a>
Author
Step1: Cosmic-ray composition effective area analysis
Table of contents
Load simulation DataFrame and apply quality cuts
Define functions to be fit to effective are... | Python Code:
%load_ext watermark
%watermark -u -d -v -p numpy,matplotlib,scipy,pandas,sklearn,mlxtend
Explanation: <a id='top'> </a>
Author: James Bourbeau
End of explanation
%matplotlib inline
from __future__ import division, print_function
from collections import defaultdict
import os
import numpy as np
from scipy im... |
1,922 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tyler Jensen
Recursive Backtracking || Brute Force Solutions
Why use recursion?
You now have a couple tools to solve programming, namely iteration and recursion. Both can be used in many sit... | Python Code:
def pathTo(x, y, path):
#basecase
if x == 0 and y == 0:
print path
#recursive case
#this is an elif because we don't want to recurse forever once we are too far to the right, or too high up
elif x >= 0 and y >= 0:
pathTo(x - 1, y, path + "Right ") #choose right... |
1,923 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Real Life Example
Step1: Loading and Preparing Data
Step3: Big Kudos to Waleed Abdulla for providing the initial idea and many of the functions used to prepare and display the images
Step4... | Python Code:
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
%pylab inline
import matplotlib.pylab as plt
import numpy as np
from distutils.version import StrictVersion
import sklearn
print(sklearn.__version__)
assert StrictVersion(sklearn.__version__ ) >= StrictVersion('0.18.1')
import tensorflow ... |
1,924 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
UAT for NbAgg backend.
The first line simply reloads matplotlib, uses the nbagg backend and then reloads the backend, just to ensure we have the latest modification to the backend code. Note... | Python Code:
import matplotlib
reload(matplotlib)
matplotlib.use('nbagg')
import matplotlib.backends.backend_nbagg
reload(matplotlib.backends.backend_nbagg)
Explanation: UAT for NbAgg backend.
The first line simply reloads matplotlib, uses the nbagg backend and then reloads the backend, just to ensure we have the lates... |
1,925 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Equation for Neuron Paper
A dendritic segment can robustly classify a pattern by subsampling a small number of cells from a larger population. Assuming a random distribution of patterns, ... | Python Code:
oxp = Symbol("Omega_x'")
b = Symbol("b")
n = Symbol("n")
theta = Symbol("theta")
w = Symbol("w")
s = Symbol("s")
a = Symbol("a")
subsampledOmega = (binomial(s, b) * binomial(n - s, a - b)) / binomial(n, a)
subsampledFpF = Sum(subsampledOmega, (b, theta, s))
subsampledOmegaSlow = (binomial(s, b) * binomial(... |
1,926 | 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', 'nerc', 'sandbox-1', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: NERC
Source ID: SANDBOX-1
Topic: Atmoschem
Sub-Topics: Transport, Emi... |
1,927 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Name
Data preparation using PySpark on Cloud Dataproc
Label
Cloud Dataproc, GCP, Cloud Storage,PySpark, Kubeflow, pipelines, components
Summary
A Kubeflow Pipeline component to prepare data ... | Python Code:
%%capture --no-stderr
!pip3 install kfp --upgrade
Explanation: Name
Data preparation using PySpark on Cloud Dataproc
Label
Cloud Dataproc, GCP, Cloud Storage,PySpark, Kubeflow, pipelines, components
Summary
A Kubeflow Pipeline component to prepare data by submitting a PySpark job to Cloud Dataproc.
Details... |
1,928 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
model 03 linear_model with dictVectorizer
Load train, test, questions data from pklz
First of all, we need to read those three data set.
Step1: Make training set
For training model, we migh... | Python Code:
import gzip
import cPickle as pickle
with gzip.open("../data/train.pklz", "rb") as train_file:
train_set = pickle.load(train_file)
with gzip.open("../data/test.pklz", "rb") as test_file:
test_set = pickle.load(test_file)
with gzip.open("../data/questions.pklz", "rb") as questions_file:
question... |
1,929 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: TensorBoard.dev を使う
TensorBoard.dev は、無料で提供されている一般向けの TensorBoard サービスです。機械学習の実験をアップロードし、あらゆるユーザーと共有することができます。
このノートブックでは、簡単なモデルをトレーニングし、Tensor... | 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... |
1,930 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
write a small code snippet for edge detection for an image using python
| Python Code::
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import convolve2d
image = Image.open('image.jpg')
gray = np.mean(image, axis = 2)
h_x = [[1,0,-1], [2,0,-2], [1,0,-1]]
h_y = [[1,2,1], [0,0,0], [-1,-2,-1]]
g_x = convolve2d(gray, h_x)
g_y = convolve2d(gray, h_y)
a =... |
1,931 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
markdown test, i can write normal text here and it will not run as code!
Step1: strings yoiu can use the %s to format strings into your print statements | Python Code:
# this is a comment and will not run in the code
'''this is just a mulit line comment'''
pwd
#addition
2+1
# substraction
2-1
1-2
2*2
3/2
3.0/2
float(3)/2
3/float(2)
from __future__ import division
3/2
1/2
2/3
root(2)
sqrt(2)
4^2
4^.5
4**.5
a=5
a=6
a+a
a
0.1+0.2-0.3
'hello'
'this entire thing can be a stri... |
1,932 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create TensorFlow Wide and Deep Model
Learning Objective
- Create a Wide and Deep model using the high-level Estimator API
- Determine which features to use as wide columns and which to use... | Python Code:
PROJECT = "cloud-training-demos" # Replace with your PROJECT
BUCKET = "cloud-training-bucket" # Replace with your BUCKET
REGION = "us-central1" # Choose an available region for Cloud MLE
TFVERSION = "1.14" # TF version for CMLE to use
import os
os.environ["BUCKET"] = BUCKET
os.e... |
1,933 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
L-BFGS vs GD
Curiously, the original L-BFGS convergence proof essentially reduces the L-BFGS iteration to GD. This establishes L-BFGS converges globally for sufficiently regular functions an... | Python Code:
from numpy_ringbuffer import RingBuffer
import numpy as np
from scipy.stats import special_ortho_group
from scipy import linalg as sla
%matplotlib inline
from matplotlib import pyplot as plt
from scipy.optimize import line_search
class LBFGS:
def __init__(self, m, d, x0, g0):
self.s = RingBuffe... |
1,934 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Resources
For further information and tutorials see
Step1: Variables
Step2: Lists
Python has two array-like things. The first is called a "list", which can hold any data types.
Step3: Th... | Python Code:
# you can type math directly into Python (IPython, command line)
2+2
4**2 # this is "4 to the power of 2"
1./2 # converts 1 to a float
4*3; # The semicolon suppresses the output in IPython - this is similar to Matlab or Oracle
Explanation: Resources
For further information and tutorials see:
Software Carp... |
1,935 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generate large frames for testing
Step1: On Flex 5
Step2: On Flex 5 | Python Code:
from Frame2D import Frame2D
from Tables import Table, DataSource
import numpy as np
import pandas as pd
## NOTE: all units are kN and m
FD = {'storey_heights': [6.5] + [5.5]*20 + [7.0], # m
'bay_widths': [10.5,10,10,10,10,10.5], # m
'frame_spacing':8, # m, us... |
1,936 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Skip-gram word2vec
In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about emb... | Python Code:
import time
import numpy as np
import tensorflow as tf
import utils
Explanation: Skip-gram word2vec
In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural lang... |
1,937 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quasi-binomial regression
This notebook demonstrates using custom variance functions and non-binary data
with the quasi-binomial GLM family to perform a regression analysis using
a dependent... | Python Code:
import statsmodels.api as sm
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from io import StringIO
Explanation: Quasi-binomial regression
This notebook demonstrates using custom variance functions and non-binary data
with the quasi-binomial GLM family to perform a regression analys... |
1,938 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setup
Step1: Tweet activity
Let's explore counts by hour, day of the week, and weekday versus weekend hourly trends.
Step2: Hmmm, what's this created_at attribute?
Step3: Hourly counts
St... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('fivethirtyeight')
import tweepy
import numpy as np
import pandas as pd
from collections import Counter
from datetime import datetime
# Turn on retina mode for high-quality inline plot resolution
from IPython.display imp... |
1,939 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analysing tabular data
we are going to use a LIBRARY called numpy
Step1: Variables
Step2: Tasks
* Produce maximum and minimum plots of this data
* What do you think? | Python Code:
import numpy
numpy.loadtxt(fname='data/weather-01.csv', delimiter = ',')
Explanation: Analysing tabular data
we are going to use a LIBRARY called numpy
End of explanation
Weight_kg = 55
print (Weight_kg)
print('Weight in pounds:', Weight_kg * 2.2)
Weight_kg = 57.5
print ('New weight: ', Weight_kg * 2.2)
%w... |
1,940 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Jupyter notebook for interactive development
url
Step1: PYTRAJ
Step2: Compute multiple dihedrals
Step3: get help?
Step4: Protein/DNA/RNA viewer in notebook
Written in Python/Javasc... | Python Code:
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", category=UserWarning)
import parmed as pmd
x = pmd.load_file('tz2.pdb')
[res.name for res in x.residues]
[atom.name for atom in x.residues[0]]
Explanation: Using Jupyter notebook for interacti... |
1,941 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have my data in a pandas DataFrame, and it looks like the following: | Problem:
import pandas as pd
df = pd.DataFrame({'cat': ['A', 'B', 'C'],
'val1': [7, 10, 5],
'val2': [10, 2, 15],
'val3': [0, 1, 6],
'val4': [19, 14, 16]})
def g(df):
df = df.set_index('cat')
res = df.div(df.sum(axis=0), axis=1)
retu... |
1,942 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Scipy
Python's favorite library for scientific computing.
Scipy modules are viewed as the equivalent of Matlab's standard toolboxes
Scikit modules are viewed as the equivalent of Matlab's ex... | Python Code:
from sklearn.datasets import load_iris
iris = load_iris()
print(iris.feature_names, iris.target_names)
print(iris.data.shape)
#print(iris.DESCR)
from scipy import linalg
# perform SVD
A = iris.data
U, s, V = linalg.svd(A)
print("U.shape, V.shape, s.shape: ", U.shape, V.shape, s.shape)
print("Singular value... |
1,943 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Running Code
First and foremost, the Jupyter Notebook is an interactive environment for writing and running code. The notebook is capable of running code in a wide range of languages. Howeve... | Python Code:
a = 10
print(a)
Explanation: Running Code
First and foremost, the Jupyter Notebook is an interactive environment for writing and running code. The notebook is capable of running code in a wide range of languages. However, each notebook is associated with a single kernel. This notebook is associated with t... |
1,944 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Session 3
Step1: The functions in np.random return one dimensional arrays. You can check this with .shape and change it with .reshape()
Step2: You can perform basic arithmetic on arrays, u... | Python Code:
import numpy as np
random = np.random.normal(size=100)
random
Explanation: Session 3: Python Data Analysis World
Python has a very strong community in the data analytics and scientific computing world. There are a lot of great Python packages to support different analyses, but there are a few very key pack... |
1,945 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Astronomy I & II sessions
[Astropy Basics]
Constants and units
Celestial Coordinates
Time and dates
FITS files
FITS Tables (and other common formats)
Spectra
Images & WCS
[Astroquery]
Query ... | Python Code:
%matplotlib inline
import numpy as np
import math
import matplotlib.pyplot as plt
import seaborn
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 14
plt.rcParams['lines.linewidth'] = 2
plt.rcParams['xtick.labelsize'] = 13
plt.rcParams['ytick.labelsize'] = 13
plt.rcParams['axes.titlesize... |
1,946 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Object Detection Demo
Welcome to the object detection inference walkthrough! This notebook will walk you step by step through the process of using a pre-trained model to detect objects in a... | Python Code:
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
Explanation: Object Detection Demo
Welcome to the object det... |
1,947 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Preprocessing and Pipelines
<img src="figures/pipeline.svg" width=60%>
Step1: Cross-validated pipelines including scaling, we need to estimate mean and standard deviation separately for eac... | Python Code:
from sklearn.datasets import load_digits
from sklearn.cross_validation import train_test_split
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target)
Explanation: Preprocessing and Pipelines
<img src="figures/pipeline.svg" width=60%>
End of explanation
from s... |
1,948 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What's the terminal velocity of a skydiver?
Names of group members
// put your names here!
Goals of this assignment
The main goal of this assignment is to use numerical integration and diffe... | Python Code:
'''
The code in this cell opens up the file skydiver_time_velocities.csv
and extracts two 1D numpy arrays of equal length. One array is
of the velocity data taken by the radar gun, and the second is
the times that the data is taken.
'''
import numpy as np
skydiver_time, skydiver_velocity = np.loadtxt("sk... |
1,949 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
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', 'dwd', 'sandbox-3', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: DWD
Source ID: SANDBOX-3
Topic: Ocnbgchem
Sub-Topics: Tracers.
Proper... |
1,950 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is the client!!
Step1: Above is the output I'm getting- still need to discuss interpolation and also adding in the parameter for number of timeseries to find | Python Code:
import MessageFormatting
import importlib
importlib.reload(MessageFormatting)
from MessageFormatting import *
from timeseries.ArrayTimeSeries import ArrayTimeSeries as ts
import numpy as np
from scipy.stats import norm
t = np.arange(0.0, 1.0, 0.01)
v = norm.pdf(t, 100, 100) + 1000*np.random.randn(100)
ts_t... |
1,951 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Python 2
Creating Functions
<section class="objectives panel panel-warning">
<div class="panel-heading">
<h3><span class="fa fa-certificate"></span> Learning Objectives
Step1... | Python Code:
# Let's get our import statements out of the way first
from __future__ import division, print_function
import numpy as np
import glob
import matplotlib.pyplot as plt
%matplotlib inline
def kelvin_to_celsius(temp):
return temp - 273.15
Explanation: Introduction to Python 2
Creating Functions
<section cl... |
1,952 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Crib dragging
following http
Step1: To demonstrate the OTP, we can decrypt the CTs by XOR'ing with the key (k)
Step2: The assignment asks us to examine what happens when we a space charact... | Python Code:
m1 = "hello world!!".encode('hex')
m2 = "other message".encode('hex')
key = "secretkey123!".encode('hex')
print 'm1: {}\nm2: {}\nkey: {}'.format(m1, m2, key)
print len(m1), len(m2), len(key)
ct1 = hex(int(m1, 16) ^ int(key, 16))[2:-1]
ct2 = hex(int(m2, 16) ^ int(key, 16))[2:-1]
print 'ct1: {}\nct2: {}'.for... |
1,953 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ALMA Cycle 0
https
Step1: Creation of Dictionary
We create the words necessary to fit a sparse coding model to the observed spectra in the previous created cube.
It returns a DataFrame with... | Python Code:
file_path = '../data/2011.0.00419.S/sg_ouss_id/group_ouss_id/member_ouss_2013-03-06_id/product/IRAS16547-4247_Jet_CH3OH7-6.clean.fits'
noise_pixel = (15, 4)
train_pixels = [(133, 135),(134, 135),(133, 136),(134, 136)]
img = fits.open(file_path)
meta = img[0].data
hdr = img[0].header
# V axis
naxisv = hdr['... |
1,954 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
得益于 Python 数据模型,自定义类型行为可以像内置类型那样自然。实现如此自然的行为,靠的不是继承,而是鸭子类型,我们只需要按照预定行为实现对象所需方法即可
这一章我们定义自己的类,而且让类的行为跟真正的 Python 对象一样,这一章延续第一章,说明如何实现在很多 Python 类型中常见的特殊方法。
本章包含以下话题:
支持用于生成对象其他表示形式的内置函数(如 rep... | Python Code:
v1 = Vector2d(3, 4)
print(v1.x, v1.y) # 可以直接通过属性访问
x, y = v1 # 可以拆包成元祖
x, y
v1
v1_clone = eval(repr(v1)) # repr 函数调用 Vector2d 实例,结果类似于构建实例的源码
v1 == v1_clone # 支持 == 比较
print(v1) # 会调用 str 函数,对 Vector2d 来说,输出的是一个有序对
octets = bytes(v1) # 调用 __bytes__ 方法,生成实例的二进制表示形式
octets
abs(v1) # 会调用 __abs__ 方法,返回 Vector2... |
1,955 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<html><head><meta content="text/html; charset=UTF-8" http-equiv="content-type"><style type="text/css">ol</style></head><body class="c5"><p class="c0 c4"><span class="c3"></span></p><p class=... | Python Code:
import bokeh.plotting as bpl
import cv2
import glob
import logging
import matplotlib.pyplot as plt
import numpy as np
import os
try:
cv2.setNumThreads(0)
except():
pass
try:
if __IPYTHON__:
# this is used for debugging purposes only. allows to reload classes
# when changed
... |
1,956 | Given the following text description, write Python code to implement the functionality described.
Description:
Print all safe primes below N
Python 3 implementation of the approach ; Function to print first n safe primes ; Initialize all entries of integer array as 1. A value in prime [ i ] will finally be 0 if i is No... | Python Code:
from math import sqrt
def printSafePrimes(n ) :
prime =[0 for i in range(n + 1 ) ]
for i in range(2 , n + 1 ) :
prime[i ] = 1
prime[0 ] = prime[1 ] = 0
for p in range(2 , int(sqrt(n ) ) + 1 , 1 ) :
if(prime[p ] == 1 ) :
for i in range(p * 2 , n + 1 , p ) :
prime[i ] = 0
for... |
1,957 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
New function to make a list and to select calibrator
I add a function to retrieve all the flux from the ALMA Calibrator list with its frequency and observing date, and to retrieve redshift (... | Python Code:
file_listcal = "alma_sourcecat_searchresults_20180419.csv"
q = databaseQuery()
Explanation: New function to make a list and to select calibrator
I add a function to retrieve all the flux from the ALMA Calibrator list with its frequency and observing date, and to retrieve redshift (z) from NED.
End of expla... |
1,958 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
H2O Tutorial
Step1: If you already have an H2O cluster running that you'd like to connect to (for example, in a multi-node Hadoop environment), then you can specify the IP and port of that ... | Python Code:
import h2o
# Start an H2O Cluster on your local machine
h2o.init()
Explanation: H2O Tutorial: Breast Cancer Classification
Author: Erin LeDell
Contact: erin@h2o.ai
This tutorial steps through a quick introduction to H2O's Python API. The goal of this tutorial is to introduce through a complete example H2O'... |
1,959 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Neural Network for Image Classification
Step1: 2 - Dataset
You will use the same "Cat vs non-Cat" dataset as in "Logistic Regression as a Neural Network" (Assignment 2). The model you ... | Python Code:
import time
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
from dnn_app_utils_v2 import *
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
p... |
1,960 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualization 1
Step1: Scatter plots
Learn how to use Matplotlib's plt.scatter function to make a 2d scatter plot.
Generate random data using np.random.randn.
Style the markers (color, size... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Visualization 1: Matplotlib Basics Exercises
End of explanation
x=np.random.randn(22)
y=np.random.randn(22)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Scatter')
plt.scatter(x,y,s=22.0,c='g',marker='x',alpha=.7,linewidths=2.2... |
1,961 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bangladesh Medical Association(BMA) member data extraction
Version
Step2: We need a function to parse the HTML data after extracting the result.
Step3: Now we extract the result pages aga... | Python Code:
#Load the necessary modules
from mechanize import Browser
import pandas as pd
from IPython.core.display import HTML
import requests
Explanation: Bangladesh Medical Association(BMA) member data extraction
Version : 1.0<br>
Date : 2015-05-21
This notebook will illustrate the approach undertaken to extract th... |
1,962 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step4: Вопросы
Какие есть два способа создать поток, используя модуль threading?
Что такое кооперативная многозадачность? Что такое Future?
В чем основные отличия между асинхронными и синхро... | Python Code:
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute(
CREATE TABLE employees (
id int unsigned NOT NULL,
first_name string NOT NULL,
last_name string NOT NULL,
department_id int unsigned,
PRIMARY KEY (id)
))
c.execute(
CREATE TABLE departments (
id int unsigned NOT NU... |
1,963 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This module provides tools to simulate scattering intensities detected by POPS as a function of particle size, refractive index, and some more less obvious parameters. Simulatio... | Python Code:
from atmPy.aerosols.instruments.POPS import mie
%matplotlib inline
import matplotlib.pylab as plt
plt.rcParams['figure.dpi'] = 200
Explanation: Introduction
This module provides tools to simulate scattering intensities detected by POPS as a function of particle size, refractive index, and some more less ob... |
1,964 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This world is far from Normal(ly distributed)
Step1: Create some toy data but also add some outliers.
Step2: Plot the data together with the true regression line (the three points in the u... | Python Code:
%matplotlib inline
import pymc3 as pm
import matplotlib.pyplot as plt
import numpy as np
import theano
Explanation: This world is far from Normal(ly distributed): Bayesian Robust Regression in PyMC3
Author: Thomas Wiecki
This tutorial first appeard as a post in small series on Bayesian GLMs on my blog:
The... |
1,965 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TF-DNNRegressor - ReLU - Spitzer Calibration Data
This script show a simple example of using tf.contrib.learn library to create our model.
The code is divided in following steps
Step1: Load... | Python Code:
import pandas as pd
import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
import warnings
warnings.filterwarnings("ignore")
%matplotlib inline
from matplotlib import pyplot as plt
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import Standar... |
1,966 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyEmma Featurizer Support
Step1: Import a PyEmma Coordinates Module
Using of pyemma featurizers or general other complex code requires a little trick to be storable. Since storing of code o... | Python Code:
import openpathsampling as paths
import numpy as np
from __future__ import print_function
#! lazy
import pyemma.coordinates as coor
#! lazy
ref_storage = paths.Storage('engine_store_test.nc', mode='r')
#! lazy
storage = paths.Storage('delete.nc', 'w')
storage.trajectories.save(ref_storage.trajectories[0])
... |
1,967 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a part-of-speech tagger with transformers (BERT)
This example shows how to use Thinc and Hugging Face's transformers library to implement and train a part-of-speech tagger on the Un... | Python Code:
!pip install "thinc>=8.0.0a0" transformers torch "ml_datasets>=0.2.0a0" "tqdm>=4.41"
Explanation: Training a part-of-speech tagger with transformers (BERT)
This example shows how to use Thinc and Hugging Face's transformers library to implement and train a part-of-speech tagger on the Universal Dependencie... |
1,968 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p><font size="6"><b> CASE - air quality data of European monitoring stations (AirBase)</b></font></p>
© 2021, Joris Van den Bossche and Stijn Van Hoey (jorisv... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
Explanation: <p><font size="6"><b> CASE - air quality data of European monitoring stations (AirBase)</b></font></p>
© 2021, Joris Van den Bossche and Stijn Van Hoey (jorisvandenb... |
1,969 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Face recognition
The goal of this seminar is to build two simple (anv very similar) face recognition pipelines using scikit-learn package. Overall, we'd like to explore different representat... | Python Code:
import scipy.io
image_h, image_w = 32, 32
data = scipy.io.loadmat('faces_data.mat')
X_train = data['train_faces'].reshape((image_w, image_h, -1)).transpose((2, 1, 0)).reshape((-1, image_h * image_w))
y_train = (data['train_labels'] - 1).reshape((-1,))
X_test = data['test_faces'].reshape((image_w, image_h, ... |
1,970 | Given the following text description, write Python code to implement the functionality described.
Description:
Count ways to form minimum product triplets
function to calculate number of triples ; Sort the array ; Count occurrences of third element ; If all three elements are same ( minimum element appears at l east 3 ... | Python Code:
def noOfTriples(arr , n ) :
arr . sort()
count = 0
for i in range(n ) :
if arr[i ] == arr[2 ] :
count += 1
if arr[0 ] == arr[2 ] :
return(count - 2 ) *(count - 1 ) *(count ) / 6
elif arr[1 ] == arr[2 ] :
return(count - 1 ) *(count ) / 2
return count
arr =[1 , 3 , 3 , 4 ... |
1,971 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to plot topomaps the way EEGLAB does
If you have previous EEGLAB experience you may have noticed that topomaps
(topoplots) generated using MNE-Python look a little different from those
c... | Python Code:
# Authors: Mikołaj Magnuski <mmagnuski@swps.edu.pl>
#
# License: BSD (3-clause)
import numpy as np
from matplotlib import pyplot as plt
import mne
print(__doc__)
Explanation: How to plot topomaps the way EEGLAB does
If you have previous EEGLAB experience you may have noticed that topomaps
(topoplots) gener... |
1,972 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Replication for results in Davidson et al. 2017. "Automated Hate Speech Detection and the Problem of Offensive Language"
Step1: Loading the data
Step2: Columns key
Step3: This histogram s... | Python Code:
import pandas as pd
import numpy as np
import pickle
import sys
from sklearn.feature_extraction.text import TfidfVectorizer
import nltk
from nltk.stem.porter import *
import string
import re
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer as VS
from textstat.textstat import *
from skle... |
1,973 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Loading and parsing XML files from the file system
Our XML files are in a subdirectory called 'partonopeus'. We load the os library and use its listdir() method to verify the contents of tha... | Python Code:
import os
os.listdir('partonopeus')
Explanation: Loading and parsing XML files from the file system
Our XML files are in a subdirectory called 'partonopeus'. We load the os library and use its listdir() method to verify the contents of that directory.
End of explanation
inputFiles = {}
for inputFile in os.... |
1,974 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
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', 'test-institute-3', 'sandbox-3', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: TEST-INSTITUTE-3
Source ID: SANDBOX-3
Topic: Ocnbgchem
Su... |
1,975 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sudden Landslide Identification Product (SLIP)
What to expect from this notebook
Introduction to the SLIP algorithm
describing change detection in the context of datacube
Detailed band math... | Python Code:
import sys
import os
sys.path.append(os.environ.get('NOTEBOOK_ROOT'))
import numpy as np
import xarray as xr
import pandas as pd
import matplotlib.pyplot as plt
from utils.data_cube_utilities.dc_display_map import display_map
from utils.data_cube_utilities.clean_mask import landsat_clean_mask_full
# la... |
1,976 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ArangoDB with Graphistry
We explore Game of Thrones data in ArangoDB to show how Arango's graph support interops with Graphistry pretty quickly.
This tutorial shares two sample transforms
S... | Python Code:
!pip install python-arango --user -q
from arango import ArangoClient
import pandas as pd
import graphistry
def paths_to_graph(paths, source='_from', destination='_to', node='_id'):
nodes_df = pd.DataFrame()
edges_df = pd.DataFrame()
for graph in paths:
nodes_df = pd.concat([ nodes_df, p... |
1,977 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p><font size="6"><b>CASE - Observation data</b></font></p>
© 2021, Joris Van den Bossche and Stijn Van Hoey (jorisvandenbo... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn-whitegrid')
Explanation: <p><font size="6"><b>CASE - Observation data</b></font></p>
© 2021, Joris Van den Bossche and Stijn Van Hoey (jorisv... |
1,978 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--BOOK_INFORMATION-->
<img align="left" style="padding-right
Step1: Or if you try an operation that's not defined
Step2: Or you might be trying to compute a mathematically ill-defined re... | Python Code:
print(Q)
Explanation: <!--BOOK_INFORMATION-->
<img align="left" style="padding-right:10px;" src="fig/cover-small.jpg">
This notebook contains an excerpt from the Whirlwind Tour of Python by Jake VanderPlas; the content is available on GitHub.
The text and code are released under the CC0 license; see also t... |
1,979 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Voyager 2
Example data taken on 2018-10-22 during MARS receiver testing, using the Breakthrough Listen backend.
Data recorded over full bandwidth of MARS receiver, here we have extracted a s... | Python Code:
%matplotlib inline
import blimpy as bl
import pylab as plt
import numpy as np
plt.rcParams['font.size'] = 12
Explanation: Voyager 2
Example data taken on 2018-10-22 during MARS receiver testing, using the Breakthrough Listen backend.
Data recorded over full bandwidth of MARS receiver, here we have extracte... |
1,980 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling of Qubit Chain
Simulation of few steps of quantum walk
<img src="images/line_qubits_site1.png" alt="Qubit Chain">
<img src="images/line_qubits_site.png" alt="Qubit Chain Shift">
Con... | Python Code:
from pprint import pprint
import math
import numpy as np
# importing the Qiskit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import Aer, execute
# import state tomography functions
from qiskit.tools.visualization import plot_histogram, plot_state
# Definition of matchga... |
1,981 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Independent confirmation of ACA offsets
As part of the verification of the dynamic offsets process, SOT/ACA ops has independently confirmed the FOT aimpoint offsets for the JUL0415O test wee... | Python Code:
import os
import sys
from glob import glob
import json
import numpy as np
from astropy.table import Table
from Chandra.Time import DateTime
from Ska.Matplotlib import plot_cxctime
from chandra_aca import drift
import parse_cm
Explanation: Independent confirmation of ACA offsets
As part of the verification ... |
1,982 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Initial planning steps
Step1: Targeting and master list design
Latest cuts
Step2: Test round with Ody
Step3: Sky Fiber positions
For some hosts we already have sky positions from the last... | Python Code:
#if online
ufo = urllib2.urlopen('https://docs.google.com/spreadsheet/ccc?key=1b3k2eyFjHFDtmHce1xi6JKuj3ATOWYduTBFftx5oPp8&output=csv')
hosttab = QTable.read(ufo.read(), format='csv')
ufo.close()
#if offline
hosttab = Table.read('SAGADropbox/hosts/host_catalog_flag0.csv')
hostscs = SkyCoord(u.Quantity(host... |
1,983 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nearest Neighbors
author
Step1: Load Wikipedia dataset
We will be using the same dataset of Wikipedia pages that we used in the Machine Learning Foundations course (Course 1). Each element ... | Python Code:
import graphlab
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
Explanation: Nearest Neighbors
author: 申恒恒
When exploring a large set of documents -- such as Wikipedia, news articles, StackOverflow, etc. -- it can be useful to get a list of related material. To find relevant documents... |
1,984 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CMS Autoencoder Development
Joeri R. Hermans
Departement of Data Science & Knowledge Engineering
Maastricht University, The Netherlands
In this notebook ... | Python Code:
%matplotlib inline
import numpy as np
import os
from pyspark import SparkContext
from pyspark import SparkConf
from pyspark.sql.types import *
from pyspark.storagelevel import StorageLevel
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from distkeras.trainers import *
from distkeras.utils i... |
1,985 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Webscraping with Beautiful Soup
Intro
In this tutorial, we'll be scraping information on the state senators of Illinois, available here, as well as the list of bills each senator has sponsor... | Python Code:
# import required modules
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import time
import re
import sys
Explanation: Webscraping with Beautiful Soup
Intro
In this tutorial, we'll be scraping information on the state senators of Illinois, available here, as well as the list of... |
1,986 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Regression.
Author
Step1: 1. The regression problem
The goal of regression methods is to predict the value of some target variable $S$ from the observation of one or more in... | Python Code:
# Import some libraries that will be necessary for working with data and displaying plots
# To visualize plots in the notebook
%matplotlib inline
import numpy as np
import scipy.io # To read matlab files
import pandas as pd # To read data tables from csv files
# For plots and graphical results
imp... |
1,987 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to PySpark
We'll talk a little bit about the Spark's precursor, Hadoop, and then we'll discuss the advantages and utility of Spark on top of Hadoop.
Next, we'll discuss what Das... | Python Code:
import findspark
findspark.init()
Explanation: Introduction to PySpark
We'll talk a little bit about the Spark's precursor, Hadoop, and then we'll discuss the advantages and utility of Spark on top of Hadoop.
Next, we'll discuss what Dash offers in conjunction with Spark.
Finally, we will implement a sim... |
1,988 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using FISSA with CNMF from MATLAB
CNMF is blind source separation toolbox for cell detection and signal extraction.
Here we illustrate how one can use the ROIs detected by CNMF, and use FIS... | Python Code:
# FISSA package
import fissa
# For plotting our results, import numpy and matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Need this utility from scipy to load data from matfiles
from scipy.io import loadmat
Explanation: Using FISSA with CNMF from MATLAB
CNMF is blind source separation toolb... |
1,989 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Flavours of Gradient Descent
A quick recap of the Gradient Descent method
Step1: Batch Gradient Descent
In most supervised ML applications, we will try to learn a pattern from a number of l... | Python Code:
%matplotlib inline
import numpy as np
def L(x):
return x**2 - 2*x + 1
def L_prime(x):
return 2*x - 2
def converged(x_prev, x, epsilon):
"Return True if the abs value of all elements in x-x_prev are <= epsilon."
absdiff = np.abs(x-x_prev)
return np.all(absdiff <= epsilon)
def gradie... |
1,990 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
.. _tut_compute_covariance
Step1: Source estimation method such as MNE require a noise estimations from the
recordings. In this tutorial we cover the basics of noise covariance and
construc... | Python Code:
import os.path as op
import mne
from mne.datasets import sample
Explanation: .. _tut_compute_covariance:
Computing covariance matrix
End of explanation
data_path = sample.data_path()
raw_empty_room_fname = op.join(
data_path, 'MEG', 'sample', 'ernoise_raw.fif')
raw_empty_room = mne.io.read_raw_fif(raw_... |
1,991 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Library Exploration
Step1: Corresponded Tag-POStag Table
<table class="c-table o-block"><tr class="c-table__row"><th class="c-table__head-cell u-text-label">Tag</th><th class="c-table__head... | Python Code:
import spacy
nlp = spacy.load('en')
text = u"We are living in Singapore.\nIt's blazing outside today!\n"
doc = nlp(text)
for token in doc:
print((token.text, token.lemma, token.tag, token.pos))
for token in doc:
print((token.text, token.lemma_, token.tag_, token.pos_)) # lemma means *root form*
Exp... |
1,992 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Experiments for FOSSACS'19
Paper
Step1: Hack that alows to parse ltl3ba automata without universal branching.
Step2: $\newcommand{\F}{\mathsf{F}}$
$\newcommand{\G}{\mathsf{G}}$
$\newcomman... | Python Code:
from ltlcross_runner import LtlcrossRunner
from IPython.display import display
import pandas as pd
import spot
import sys
spot.setup(show_default='.a')
pd.options.display.float_format = '{: .0f}'.format
pd.options.display.latex.multicolumn_format = 'c'
Explanation: Experiments for FOSSACS'19
Paper: LTL to ... |
1,993 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solcing Crimes with Data Science
Markus Harrer
INNOQ Deutschland
Facts of the case
a white bus with a red sign on the side window was stolen
police did an innovative mpbile phone investigati... | Python Code:
import pandas as pd
cdr = pd.read_excel("cdr_data_export.xlsx")
cdr.head()
Explanation: Solcing Crimes with Data Science
Markus Harrer
INNOQ Deutschland
Facts of the case
a white bus with a red sign on the side window was stolen
police did an innovative mpbile phone investigation
there was only phone numbe... |
1,994 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DO NOT FORGET TO DROP ISSUE_D AFTER PREPPING
Step1: Until I figure out a good imputation method (e.g. bayes PCA), just drop columns with null still
Step2: straight up out of box elastic ne... | Python Code:
platform = 'lendingclub'
store = pd.HDFStore(
'/Users/justinhsi/justin_tinkering/data_science/lendingclub/{0}_store.h5'.
format(platform),
append=True)
loan_info = store['train_filtered_columns']
columns = loan_info.columns.values
# checking dtypes to see which columns need one hotting, and whi... |
1,995 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1
Step1: Step2 | Python Code:
batchlogfile = 'sample_dataset/batch_log.json'
df_batch = pd.read_json(batchlogfile, lines=True)
index_purchase = ['event_type','id','timestamp','amount']
index_friend = ['event_type','id1','id2','timestamp']
#df_batch.head()
#df_batch.describe()
# Read D and T
df_DT=df_batch[df_batch['D'].notnull()]
df_DT... |
1,996 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing the nscore transformation table
Step1: Getting the data ready for work
If the data is in GSLIB format you can use the function pygslib.gslib.read_gslib_file(filename) to import the ... | Python Code:
#general imports
import matplotlib.pyplot as plt
import pygslib
from matplotlib.patches import Ellipse
import numpy as np
import pandas as pd
#make the plots inline
%matplotlib inline
Explanation: Testing the nscore transformation table
End of explanation
#get the data in gslib format into a pandas... |
1,997 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What is classification ?
Import the data you'll be using
Visualize/Analyze your dataset
Perform classification on it
1.a - We use the mnist dataset
Step1: 1.b - How does Mnist look like ?
... | Python Code:
import keras
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print "input of training set has shape {} and output has shape {}".format(x_train.shape, y_train.shape)
print "input of testing set has shape {} and output has shape {}".format(x_test.shape, y_test.shape)... |
1,998 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Selecting variants by number of unique barcodes
This notebook gets scores for the variants in an Experiment that are linked to multiple barcodes, and plots the relationship between each vari... | Python Code:
% matplotlib inline
import os.path
from collections import Counter
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from enrich2.variant import WILD_TYPE_VARIANT
import enrich2.plots as enrich_plot
pd.set_option("display.max_rows", 10) # rows shown when pretty-printing
Explanation: Se... |
1,999 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Parameter identification example
Here is a simple toy model that we use to demonstrate the working of the inference package
$\emptyset \xrightarrow[]{k_1} X \; \; \; \; X \xrightarrow[]{d_1}... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = "retina"
from matplotlib import rcParams
rcParams["savefig.dpi"] = 100
rcParams["figure.dpi"] = 100
rcParams["font.size"] = 20
Explanation: Parameter identification example
Here is a simple toy model that we use to demonstrate the working of the infe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.