Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
2,000 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Cloud - Putting it all together
In this example, we will use all of the features outlined in the Keras cloud guide to train a state-of-the-art model to classify dog breeds using f... | Python Code:
!pip install tensorflow-cloud
import datetime
import os
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_cloud as tfc
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Model
Explanation: TensorFlo... |
2,001 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
These examples are tests for scc_info on alternating automata.
Step1: universal edges are handled as if they were many distinct existencial edges from the point of view of scc_info, so the ... | Python Code:
from IPython.display import display
import spot
spot.setup(show_default='.bas')
spot.automaton('''
HOA: v1
States: 2
Start: 0&1
AP: 2 "a" "b"
acc-name: Buchi
Acceptance: 1 Inf(0)
--BODY--
State: 0
[0] 0
[!0] 1
State: 1
[1] 1 {0}
--END--
''')
Explanation: These examples are tests for scc_info on alternating... |
2,002 | 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... |
2,003 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook is part of the nbsphinx documentation
Step1: A simple output
Step2: The standard output stream
Step3: Normal output + standard output
Step4: The standard error stream is hi... | Python Code:
# 2 empty lines before, 1 after
Explanation: This notebook is part of the nbsphinx documentation: https://nbsphinx.readthedocs.io/.
Code Cells
Code, Output, Streams
An empty code cell:
Two empty lines:
Leading/trailing empty lines:
End of explanation
6 * 7
Explanation: A simple output:
End of explanation
p... |
2,004 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Factorization Machine example
Step1: At first we'll test only with the bare minimum userId, itemId and rating columns.
Step2: So we have the user ids, item ids and the respective ratings i... | Python Code:
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error
from reco.datasets import loadMovieLens100k
from reco.recommender import FM
Explanation: Factorization Machine example
End of explanation
train, test, _, _ = loadMovieLens100k(train_test_split=True)
print(train.head())
Ex... |
2,005 | 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', 'cas', 'fgoals-f3-l', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: CAS
Source ID: FGOALS-F3-L
Topic: Seaice
Sub-Topics: Dynamics, Thermodynam... |
2,006 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Datasets
Datasets tell PHOEBE how and at what times to compute the model. In some cases these will include the actual observational data, and in other cases may only include the times at wh... | Python Code:
!pip install -I "phoebe>=2.2,<2.3"
Explanation: Datasets
Datasets tell PHOEBE how and at what times to compute the model. In some cases these will include the actual observational data, and in other cases may only include the times at which you want to compute a synthetic model.
Adding a dataset - even if... |
2,007 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Titanic
Step1: 2. Loading/Examining the Data <a class="anchor" id="second-bullet"></a>
Step2: 3. All the Features! <a class="anchor" id="third-bullet"></a>
We will be extracting the featur... | Python Code:
# data analysis and wrangling
import pandas as pd
import numpy as np
import scipy
# visualization
import matplotlib.pyplot as plt
import seaborn as sns
# machine learning
from sklearn.svm import SVC
from sklearn import preprocessing
import fancyimpute
from sklearn.model_selection import train_test_split
fr... |
2,008 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Data
Step2: Markov chain Monte Carlo (MCMC)
We set up the model in numpyro and run MCMC.
Note that the log_rate parameter doesn't have the obs=... argument set, sin... | Python Code:
try:
import tinygp
except ImportError:
%pip install -q tinygp
try:
import numpyro
except ImportError:
# It is much faster to use CPU than GPU.
# This is because Colab has multiple CPU cores, so can run the 2 MCMC chains in parallel
%pip uninstall -y jax jaxlib
%pip install -q nu... |
2,009 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Goal One
Injest a csv file as pure text... (just 500 chars)
Step1: Then as a list of lines... (just one line)
Step2: Then as a data frame... (just Avatar)
Step3: Goal Two
Right now, the ... | Python Code:
with open('tmdb_5000_movies.csv','r') as f:
rtext=''
for line in f:
rtext += line
rtext[:500]
Explanation: Goal One
Injest a csv file as pure text... (just 500 chars)
End of explanation
with open('tmdb_5000_movies.csv','r') as f:
lines = [line for line in f]
lines[0]
Explanation: Then as... |
2,010 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Random forest
Out-of-bag score
Feature importances
Линейные классификаторы
$$a(x) = sign(\left<w^Tx\right> - w_0)$$
Step1: Градиентный спуск¶
$$M_i(w, w_0) = y_i(\left<x, w\right> - w_0)$$
... | Python Code:
def get_grid(data, step=0.1):
x_min, x_max = data.x.min() - 1, data.x.max() + 1
y_min, y_max = data.y.min() - 1, data.y.max() + 1
return np.meshgrid(np.arange(x_min, x_max, step),
np.arange(y_min, y_max, step))
from sklearn.cross_validation import cross_val_score
def get_... |
2,011 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EECS 445 - Introduction to Machine Learning
Lecture 2
Step1: TODAY
Step2: Basic matrix multiplication
Step3: Matrix Transpose
The transpose $A^T$ of a matrix $A$ is what you get from "swa... | Python Code:
from IPython.core.display import HTML, Image
from IPython.display import YouTubeVideo
from sympy import init_printing, Matrix, symbols, Rational
import sympy as sym
from warnings import filterwarnings
init_printing(use_latex = 'mathjax')
filterwarnings('ignore')
%pylab inline
import numpy as np
Explanation... |
2,012 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Medical Text Classification with IPython Notebook
The purpose of this notebook is to show a simple medical text classification workflow using IPython notebook.
Standard imports and settings
... | Python Code:
%matplotlib inline
import matplotlib as mpl
mpl.rcParams['font.size'] = 16.0
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd # process data with pandas dataframe
pd.set_option('display.width', 500)
pd.set_option('display.max_columns', 100)
pd.set_option('display.notebook_r... |
2,013 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Background information on filtering
Here we give some background information on filtering in general, and
how it is done in MNE-Python in particular.
Recommended reading for practical applic... | Python Code:
import numpy as np
from numpy.fft import fft, fftfreq
from scipy import signal
import matplotlib.pyplot as plt
from mne.time_frequency.tfr import morlet
from mne.viz import plot_filter, plot_ideal_filter
import mne
sfreq = 1000.
f_p = 40.
flim = (1., sfreq / 2.) # limits for plotting
Explanation: Backgrou... |
2,014 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
pomegranate / libpgm comparison
authors
Step1: Lets first compare the two packages based on number of variables.
Step2: We can see many expected results from this graph. libpgm implements ... | Python Code:
%pylab inline
import seaborn, time
seaborn.set_style('whitegrid')
Explanation: pomegranate / libpgm comparison
authors: Jacob Schreiber (jmschreiber91@gmail.com)
<a href="https://github.com/CyberPoint/libpgm">libpgm</a> is a python package for creating and using Bayesian networks. I was unable to figure ou... |
2,015 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise 03
Analyze the baby names dataset using pandas
Step1: segment the data into boy and girl names
Step2: Analyzing the popularity of a name over time | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
# Load dataset
names = pd.read_csv('baby-names2.csv')
names.head()
names[names.year == 1993].head()
Explanation: Exercise 03
Analyze the baby names dataset using pandas
End of explanation
boys = names[names.s... |
2,016 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img align="left" src="imgs/logo.jpg" width="50px" style="margin-right
Step1: I. Background
A. Preprocessing the Database
In a real application, there is a lot of data preparation, parsing,... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import re
import sys
import numpy as np
# Connect to the database backend and initalize a Snorkel session
from lib.init import *
from lib.scoring import *
from lib.lf_factories import *
from snorkel.lf_helpers import test_LF
from snorkel.annotations imp... |
2,017 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Description
Determining how differences in our isopycnic cfg conditions vary in meaningful ways from those of Clay et al., 2003. Eur Biophys J
Needed to determine whether the Clay et al., 20... | Python Code:
import numpy as np
%load_ext rpy2.ipython
%%R
library(ggplot2)
library(dplyr)
Explanation: Description
Determining how differences in our isopycnic cfg conditions vary in meaningful ways from those of Clay et al., 2003. Eur Biophys J
Needed to determine whether the Clay et al., 2003 function describing dif... |
2,018 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Artifact Correction with ICA
ICA finds directions in the feature space
corresponding to projections with high non-Gaussianity. We thus obtain
a decomposition into independent components, and... | Python Code:
import numpy as np
import mne
from mne.datasets import sample
from mne.preprocessing import ICA
from mne.preprocessing import create_eog_epochs, create_ecg_epochs
# getting some data ready
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read... |
2,019 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Coin games
Step1: Playing the games
Game 1
Game 1 represents a Markov chain on a countable state space that follows a random walk. If we denote by the random variable $X_n$ the bankroll at ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
Explanation: Coin games: classical and quantum
In this notebook we play a set of interesting coin tossing games using coins obeying classical (games 1-2) and quantum (game 3) mechanics.
Game 1: Gambler's ruin
A gambler enters the casino with a bankroll of ... |
2,020 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
\title{Bitwise Behavior in myHDL
Step1: myHDL Bit Indexing
Bit Indexing is the act of selecting or assigning one of the bits in a Bit Vector
Expected Indexing Selection Behavior
Step2: whi... | Python Code:
#This notebook also uses the `(some) LaTeX environments for Jupyter`
#https://github.com/ProfFan/latex_envs wich is part of the
#jupyter_contrib_nbextensions package
from myhdl import *
from myhdlpeek import Peeker
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
fr... |
2,021 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Statements Assessment Solutions
Use for, split(), and if to create a Statement that will print out words that start with 's'
Step1: Use range() to print all the even numbers from 0 to 10.
S... | Python Code:
st = 'Print only the words that start with s in this sentence'
for word in st.split():
if word[0] == 's':
print word
Explanation: Statements Assessment Solutions
Use for, split(), and if to create a Statement that will print out words that start with 's':
End of explanation
range(0,11,2)
Explan... |
2,022 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RNN Character Model + Lots More
This example trains a RNN to create plausible words from a corpus. But it includes lots of interesting "bells and whistles"
The data used for training is one... | Python Code:
import numpy as np
import theano
import lasagne
#from lasagne.utils import floatX
import pickle
import gzip
import random
import time
WORD_LENGTH_MAX = 16
# Load an interesting corpus (vocabulary words with frequencies from 1-billion-word-corpus) :
with gzip.open('../data/RNN/ALL_1-vocab.txt.gz') as f:
... |
2,023 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
JSON Schema Parser
Notes on the JSON schema / Traitlets package
Goal
Step1: OK, now let's write a traitlets class that does the same thing
Step4: Roadmap
Start by recognizing all simple JS... | Python Code:
import json
import jsonschema
simple_schema = {
"type": "object",
"properties": {
"foo": {"type": "string"},
"bar": {"type": "number"}
}
}
good_instance = {
"foo": "hello world",
"bar": 3.141592653,
}
bad_instance = {
"foo" : 42,
"bar" : "string"
}
# Should succe... |
2,024 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Übungsblatt 1
Step1: Aufgabe 1
Gegeben sei eine parametrische Funktion $y = f(x)$, $y = 1 + a_1x + a_2x^2$ mit Parametern $a_1 = 2.0 ± 0.2$, $a_2 = 1.0 ± 0.1$ und Korrelationskoeffizient $ρ... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
Explanation: Übungsblatt 1: Fehlerrechnung
Aufgabe 1
Aufgabe 2
Aufgabe 3
End of explanation
a1, a1_err = 2.0, 0.2
a2, a2_err = 1.0, 0.1
rho = -0.8
Explanation: Aufgabe 1
Gegeben sei eine parametrische Funktion $y ... |
2,025 | 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... |
2,026 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to get rid of the bad python code
Step1: Handlabeling code
Step2: Analysis
Given the above percentages, we can calculate how many of the code blocks we think are python, and how many o... | Python Code:
import json
import datetime
import tqdm
folder = '/dfs/scratch2/fcipollone/stackoverflow/guesslang_and_ast/outfiles'
lines = []
guess_and_parse = {}
guess_not_parse = {}
parse_not_guess = {}
total = {}
dates = []
for file_num in tqdm.tqdm(range(400)):
filename = folder + '/file' + str(file_num) + '.txt... |
2,027 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
2,028 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
선형 회귀 분석의 기초
회귀 분석(regression analysis)은 입력 자료(독립 변수) $x$와 이에 대응하는 출력 자료(종속 변수) $y$간의 관계를 정량과 하기 위한 작업이다.
회귀 분석에는 결정론적 모형(Deterministic Model)과 확률적 모형(Probabilistic Model)이 있다.
결정론적 모형은 단순히... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline
from sklearn.datasets import make_regression
bias = 100
X0, y, coef = make_regression(n_samples=100, n_features=1, bias=bias, noise=10, coef=True, random_state=1)
X = np.hstack([np.ones_like(X0), X0])
np.ones_like(X0)... |
2,029 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Jupyter Notebook
Jupyter Notebook that evolved out of iPython and is aimed at providing a platform for easy sharing, interaction, and development of open-source software, standards and servi... | Python Code:
!conda list
Explanation: Jupyter Notebook
Jupyter Notebook that evolved out of iPython and is aimed at providing a platform for easy sharing, interaction, and development of open-source software, standards and services. Althought primarily and originally used for phyton interactions, you can interact with... |
2,030 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TF-Slim Walkthrough
This notebook will walk you through the basics of using TF-Slim to define, train and evaluate neural networks on various tasks. It assumes a basic knowledge of neural net... | Python Code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
import math
import numpy as np
import tensorflow as tf
import time
from datasets import dataset_utils
# Main slim library
from te... |
2,031 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing of playing pyguessgame.
Generates random numbers and plays a game.
Create two random lists of numbers 0/9,10/19,20/29 etc to 100.
Compare the two lists. If win mark, if lose mark.
D... | Python Code:
#for ronum in ranumlis:
# print ronum
randict = dict()
othgues = []
othlow = 0
othhigh = 9
for ranez in range(10):
randxz = random.randint(othlow, othhigh)
othgues.append(randxz)
othlow = (othlow + 10)
othhigh = (othhigh + 10)
#print othgues
tenlis = ['zero', 'ten', 'twenty', 'th... |
2,032 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Declaring elements in a function
If we write a function that accepts one or more parameters and constructs an element, we can build plots that do things like
Step2: Th... | Python Code:
import numpy as np
import holoviews as hv
hv.extension('bokeh')
%opts Curve Area [width=600]
Explanation: <a href='http://www.holoviews.org'><img src="assets/hv+bk.png" alt="HV+BK logos" width="40%;" align="left"/></a>
<div style="float:right;"><h2>03. Exploration with Containers</h2></div>
In the first tw... |
2,033 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lets revise
Step1: Multi-class classification
The goal of multi-class classification
is to assign an instance to one of the set of classes. scikit-learn uses a strategy
called one-vs.-all, ... | Python Code:
# reading the data
df = pd.read_csv("data/fertility_Diagnosis.txt", delimiter=',', header=None)
df.iloc[:4,0:9]
X_train, X_test, y_train, y_test = train_test_split(df.iloc[:,0:9], df[9], test_size=0.1)
pipeline = Pipeline([('clf', LogisticRegression())])
parameters = {
'clf__penalty': ('l1', 'l2'),
'c... |
2,034 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Facies classification using Random Forest Classifier (submission 3)
<a rel="license" href="https
Step1: Load training data
Step2: Build features
In the real world it would be unusual to ha... | Python Code:
import pandas as pd
import numpy as np
from math import radians, cos, sin, asin, sqrt
import itertools
from sklearn import neighbors
from sklearn import preprocessing
from sklearn import ensemble
from sklearn.model_selection import LeaveOneGroupOut, LeavePGroupsOut
import inversion
import matplotlib.pyplot... |
2,035 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
After running your Pylearn2 models, it's probably not best to compare them on the score they get on the validation set, as that is used in the training process; so could be the victim of ove... | Python Code:
import pylearn2.utils
import pylearn2.config
import theano
import neukrill_net.dense_dataset
import neukrill_net.utils
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import holoviews as hl
%load_ext holoviews.ipython
Explanation: After running your Pylearn2 models, it's probably not ... |
2,036 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 2
Imports
Step1: Plotting with parameters
Write a plot_sin1(a, b) function that plots $sin(ax+b)$ over the interval $[0,4\pi]$.
Customize your visualization to make it eff... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
Explanation: Interact Exercise 2
Imports
End of explanation
# YOUR CODE HERE
#raise NotImplementedError()
def plot_sine1(a,b):
x =... |
2,037 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep learning for Natural Language Processing
Simple text representations, bag of words
Word embedding and... not just another word2vec this time
1-dimensional convolutions for text
Aggregat... | Python Code:
low_RAM_mode = True
very_low_RAM = False #If you have <3GB RAM, set BOTH to true
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Deep learning for Natural Language Processing
Simple text representations, bag of words
Word embedding and... not just ano... |
2,038 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Decorators
Introduction
A decorator is the name used for a software design pattern. Decorators dynamically alter the functionality of a function, method, or class without having to directly ... | Python Code:
def bread(test_funct):
def hyderabad():
print("</''''''\>")
test_funct()
print("<\______/>")
return hyderabad
def ingredients(test_funct):
def chennai():
print("#tomatoes#")
test_funct()
print("~salad~")
return chennai
def cheese(food="--Say C... |
2,039 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyBroom Example - Simple
This notebook is part of pybroom.
This notebook shows the simplest usage of pybroom when performing
a curve fit of a single dataset. Possible applications are only h... | Python Code:
import numpy as np
from numpy import sqrt, pi, exp, linspace
from lmfit import Model
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format='retina' # for hi-dpi displays
import lmfit
print('lmfit: %s' % lmfit.__version__)
import pybroom as br
Explanation: PyBroom Example -... |
2,040 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
1. Demonstration of the numpy.polynomial package
1.1 And especially a small hand-made pretty printing function for Polynomial objects
1.2 First goal
Step1: And we can then... | Python Code:
from numpy.polynomial import Polynomial as P
Explanation: Table of Contents
1. Demonstration of the numpy.polynomial package
1.1 And especially a small hand-made pretty printing function for Polynomial objects
1.2 First goal: pretty print in ASCII text
1.3 Second goal: pretty-print in $\LaTeX{}$ code
1.4 A... |
2,041 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img width=400 src="http
Step1: More beautiful code through vectorisation
pure python with list comprehension
Step2: Using numpy
Step3: Finding the point with the smallest distance
Step4:... | Python Code:
import numpy as np
Explanation: <img width=400 src="http://www.numpy.org/_static/numpy_logo.png" alt="Numpy"/>
Why do we need numpy?
You may have heard "Python is slow", this is true when it concerns looping over many small python objects
Python is dynamically typed and everything is an object, even an int... |
2,042 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejemplo 2. Estática
Step1: Por medio de un par de cables se quiere sostener un bloque de peso $W = 200\; kgf$. Determine la tensión en cada cuerda si las coordenadas de posición de los punt... | Python Code:
from IPython.display import Image,Latex
Explanation: Ejemplo 2. Estática
End of explanation
Image(filename='FIGURES/Rampa.png',width=250)
Explanation: Por medio de un par de cables se quiere sostener un bloque de peso $W = 200\; kgf$. Determine la tensión en cada cuerda si las coordenadas de posición de lo... |
2,043 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook accompanying pbpython article - Pandas Grouper and Agg Functions Explained
Step1: Read in the sample sales file then convert the date column to a proper date time column
Step2: Ex... | Python Code:
import pandas as pd
import collections
Explanation: Notebook accompanying pbpython article - Pandas Grouper and Agg Functions Explained
End of explanation
df = pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=True")
df["date"] = pd.to_datetime(df['date'])
df.hea... |
2,044 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Parsing STIX Content
Parsing STIX content is as easy as calling the parse() function on a JSON string, dictionary, or file-like object. It will automatically determine the type of the... | Python Code:
from stix2 import parse
input_string = {
"type": "observed-data",
"id": "observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf",
"spec_version": "2.1",
"created": "2016-04-06T19:58:16.000Z",
"modified": "2016-04-06T19:58:16.000Z",
"first_observed": "2015-12-21T19:00:00Z",
"last_ob... |
2,045 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Day 4 pre-class assignment
Goals for today's pre-class assignment
Use the pyplot module to make a figure
Use the NumPy module to manipulate arrays of data
Assignment instructions
Watch the v... | Python Code:
# Imports the functionality that we need to display YouTube videos in a Jupyter Notebook.
# You need to run this cell before you run ANY of the YouTube videos.
from IPython.display import YouTubeVideo
# Display a specific YouTube video, with a given width and height.
# WE STRONGLY RECOMMEND that you ... |
2,046 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
List comprehensions
Q
Step1: Compare it with this
Step2: As with many Python statements, you can almost read-off the meaning of this statement in plain English
Step3: Conditionals
Step4: ... | Python Code:
L = []
for n in range(12):
L.append(n ** 2)
L
Explanation: List comprehensions
Q: Why doesn't the list comprehension syntax make any sense to me / how can list comprehension be "more readable" than not using a list comprehension.
List comprehensions are simply a way to compress a list-building for-loop... |
2,047 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
After moving the sensors
How do things look after the sensors have been positioned away from the surprise heat source? Let's look at a day's worth of data.
Step1: Much better! The spread lo... | Python Code:
%matplotlib inline
import matplotlib
matplotlib.rcParams['figure.figsize'] = (12, 5)
import pandas as pd
df = pd.read_csv('after-sensor-move.csv', header=None, names=['time', 'mac', 'f', 'h'], parse_dates=[0])
per_sensor_f = df.pivot(index='time', columns='mac', values='f')
downsampled_f = per_sensor_f.res... |
2,048 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intelligent Systems Assignment 2
Bayes' net inference
Names
Step1: a. Bayes' net for instant perception and position.
Build a Bayes' net that represent the relationships between the random ... | Python Code:
class Directions:
NORTH = 'North'
SOUTH = 'South'
EAST = 'East'
WEST = 'West'
STOP = 'Stop'
Explanation: Intelligent Systems Assignment 2
Bayes' net inference
Names:
IDs:
End of explanation
def getMapa():
mapa = [[0] * 6 for i in range(1, 6)]
mapa[1][1] = 1
mapa[1][3] = 1
... |
2,049 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Language Processing and Python
Computing with Language
Step1: concordance is a view that shows every occurrence of a word alongside some context
Step2: similar shows other words that appea... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import nltk
from nltk.book import *
text1
text2
Explanation: Language Processing and Python
Computing with Language: Texts and Words
Ran the following in python3 interpreter:
import nltk
nltk.download()
Select book to download corpora for NLTK Book
End of ... |
2,050 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic Ultrastorage
Step1: Creating storage systems
A Storage system is a collection of storage units. It is the responsability of the storage system to add items to the various storage unit... | Python Code:
import IPython
IPython.__version__
import ultrastorage
ultrastorage.__version__
Explanation: Basic Ultrastorage: Storage system
For reproducibility.
End of explanation
from ultrastorage.storagesystem import StorageSystem
from ultrastorage.item import Item
Explanation: Creating storage systems
A Storage sys... |
2,051 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
0. Calibrate MCA Channels to sources of known emission energy
Step1: 1. Test how the energy of scattered atoms varies with scattering angle
Step2: 2. Use (1) to determine keV mass of elect... | Python Code:
CS137Peaks = np.array([165.85]) #Channel Number of photopeak
CS137Energy = np.array([661.7]) #Accepted value of emission energy
BA133Peaks = np.array([21.59, 76.76, 90.52])
BA133Energy = np.array([81.0, 302.9, 356.0])
Mn54Peaks = np.array([207.72])
Mn54Energy = np.array([834.8])
Na22Peaks = np.array([128.8... |
2,052 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a classifier
This is it. You have seen how to define neural networks, compute loss and make
updates to the weights of the network.
Now you might be thinking,
What about data?
Genera... | Python Code:
import torch
import torchvision
import torchvision.transforms as transforms
Explanation: Training a classifier
This is it. You have seen how to define neural networks, compute loss and make
updates to the weights of the network.
Now you might be thinking,
What about data?
Generally, when you have to deal w... |
2,053 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial on RVM Regression
In this tutorial we play around with linear regression in form of Relevance Vector Machines (RVMs) using linear and localized kernels. And heeeere we go!
Step1: F... | Python Code:
%matplotlib inline
from linear_model import RelevanceVectorMachine, distribution_wrapper, GaussianFeatures, \
FourierFeatures, repeated_regression, plot_summary
from sklearn import preprocessing
import numpy as np
from scipy import stats
import matplotlib#
import matplotlib.pylab as plt
matplotlib.rc('... |
2,054 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro to Thinc for beginners
Step1: There are also some optional extras to install, depending on whether you want to run this on GPU, and depending on which of the integrations you want to ... | Python Code:
!pip install "thinc==8.0.0rc6.dev0" "ml_datasets>=0.2.0a0" "tqdm>=4.41"
Explanation: Intro to Thinc for beginners: defining a simple model and config & wrapping PyTorch, TensorFlow and MXNet
This example shows how to get started with Thinc, using the "hello world" of neural network models: recognizing hand... |
2,055 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
K Nearest Neighbor (KNN) is a popular non-parametric method. The prediction (for regression/classification) is obtained by looking into the K closest memorized examples.
The algorithm itself... | Python Code:
import numpy as np
import operator
class KNearestNeighbors():
def __init__(self, k, model_type='regression', weights='uniform'):
# model_type can be either 'classification' or 'regression'
# weights = 'uniform', the K nearest neighbors are equally weighted
# weights = 'distance'... |
2,056 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualização de dados com Python
1 - Turbo introdução aos gráficos
Cleuton Sampaio, DataLearningHub
Nesta lição veremos a parte básica de geração de gráficos, com formatação e posicionamento... | Python Code:
import numpy as np
%matplotlib inline
temp_cidade1 = np.array([33.15,32.08,32.10,33.25,33.01,33.05,32.00,31.10,32.27,33.81])
temp_cidade2 = np.array([35.17,36.23,35.22,34.33,35.78,36.31,36.03,36.23,36.35,35.25])
temp_cidade3 = np.array([22.17,23.25,24.22,22.31,23.18,23.31,24.11,23.53,24.38,21.25])
Explana... |
2,057 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2
Step1: 3
Step2: 4
Step3: 6
Step4: 7
Step5: 9
Step6: 10
Step7: 11
Step8: 13
Step9: 14
Step10: 16
Step11: 17 | Python Code:
# Let's parse the data from the last mission as an example.
# First, we open the wait times file from the last mission.
f = open("crime_rates.csv", 'r')
data = f.read()
rows = data.split('\n')
full_data = []
for row in rows:
split_row = row.split(",")
full_data.append(split_row)
weather_data = []
f... |
2,058 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced
Step1: Helper functions to make the code more readable.
Step2: Create model
Step3: Run training | Python Code:
# Author: Robert Guthrie
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.optim as optim
torch.manual_seed(1)
Explanation: Advanced: Making Dynamic Decisions and the Bi-LSTM CRF
Dynamic versus Static Deep Learning Toolkits
Pytorch is a dynamic neural network kit. Another ex... |
2,059 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We compute confusion matrix using the final object (not just the sklearn svm). But we do it without sound segmentation.
Step1: FILTERING THRESHOLD .. | Python Code:
files = glob.glob('/mnt/protolab_innov/data/sounds/dataset_demo/*/*.wav')
files = glob.glob('/home/lgeorge/Downloads/dataset/*/*.wav')
_class = [os.path.basename(f).split('-')[0] for f in files]
df = pd.DataFrame(zip(_class, files), columns=['classname', 'filename'])
mask_to_remove = df.filename.str.contai... |
2,060 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced
Step1: Default Animations
By passing animate=True to b.show(), b.savefig(), or the final call to b.plot() along with save=filename or show=True will create an animation instead of ... | Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
import phoebe
from phoebe import u # units
import numpy as np
import matplotlib.pyplot as plt
logger = phoebe.logger()
b = phoebe.default_binary()
times = np.linspace(0,1,51)
b.add_dataset('lc', compute_times=times, dataset='lc01')
b.add_dataset('orb', compute_times=time... |
2,061 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bayesian Signed-Rank Test
Module signrank in bayesiantests computes the Bayesian equivalent of the Wilcoxon signed-rank test. It returns probabilities that, based on the measured performance... | Python Code:
import numpy as np
scores = np.loadtxt('Data/accuracy_nbc_aode.csv', delimiter=',', skiprows=1, usecols=(1, 2))
names = ("NBC", "AODE")
Explanation: Bayesian Signed-Rank Test
Module signrank in bayesiantests computes the Bayesian equivalent of the Wilcoxon signed-rank test. It returns probabilities that, b... |
2,062 | Given the following text description, write Python code to implement the functionality described.
Description:
You have to write a function which validates a given date string and
returns True if the date is valid otherwise False.
The date is valid if all of the following rules are satisfied:
1. The date st... | Python Code:
def valid_date(date):
try:
date = date.strip()
month, day, year = date.split('-')
month, day, year = int(month), int(day), int(year)
if month < 1 or month > 12:
return False
if month in [1,3,5,7,8,10,12] and day < 1 or day > 31:
retur... |
2,063 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Word Embeddings
Word embedding is a mapping of a word to a d-dimensional vector space.
This real valued vector representation captures semantic and syntactic features.
Polyglot offers a simp... | Python Code:
from polyglot.mapping import Embedding
Explanation: Word Embeddings
Word embedding is a mapping of a word to a d-dimensional vector space.
This real valued vector representation captures semantic and syntactic features.
Polyglot offers a simple interface to load several formats of word embeddings.
End of e... |
2,064 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Text classification with TensorFlow Lite Model Maker
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="http... | 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,065 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CBOE VXN Index
In this notebook, we'll take a look at the CBOE VXN Index dataset, available on the Quantopian Store. This dataset spans 02 Feb 2001 through the current day. This data has a d... | Python Code:
# For use in Quantopian Research, exploring interactively
from quantopian.interactive.data.quandl import cboe_vxn as dataset
# import data operations
from odo import odo
# import other libraries we will use
import pandas as pd
# Let's use blaze to understand the data a bit using Blaze dshape()
dataset.dsha... |
2,066 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create your own region
Creating own regions is straightforward. Import regionmask and check the version
Step1: Import numpy
Assume you have two custom regions in the US, you can easily use ... | Python Code:
import cartopy.crs as ccrs
import numpy as np
import matplotlib.pyplot as plt
import regionmask
regionmask.__version__
Explanation: Create your own region
Creating own regions is straightforward. Import regionmask and check the version:
End of explanation
US1 = np.array([[-100.0, 30], [-100, 40], [-120, 35... |
2,067 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using a feature representation learned for signature images
This notebook contains code to pre-process signature images and to obtain feature-vectors using the learned feature representation... | Python Code:
import numpy as np
# Functions to load and pre-process the images:
from scipy.misc import imread, imsave
from preprocess.normalize import normalize_image, resize_image, crop_center, preprocess_signature
# Functions to load the CNN model
import signet
from cnn_model import CNNModel
# Functions for plotting:... |
2,068 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introdução à Programação em Python
Vetores e Matrizes
Na matemática, uma Matriz é uma tabela de valores com $m$ linhas e $n$ colunas.
$$
\left( \begin{array}{cccc}
1 & 2 & 3 & 4 \
5 & 6 & 7 ... | Python Code:
u = [1,2,3]
v = [4,5,6]
print(u + v)
print(u + 1)
Explanation: Introdução à Programação em Python
Vetores e Matrizes
Na matemática, uma Matriz é uma tabela de valores com $m$ linhas e $n$ colunas.
$$
\left( \begin{array}{cccc}
1 & 2 & 3 & 4 \
5 & 6 & 7 & 8 \
9 & 10 & 11 & 12 \end{array} \right)
$$
Um Vetor... |
2,069 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Denoise algorithm
This notebook defines the denoise algorithm (step C defined in Towsey 2013) and compares the speed of different implementations. This is a step in processing recordings of ... | Python Code:
import numpy as np
from scipy.ndimage import generic_filter
from numba import jit, guvectorize, float64
import pyprind
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Denoise algorithm
This notebook defines the denoise algorithm (step C defined in Towsey 2013) and compares the speed of diff... |
2,070 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Classification
The goal of a classification task is to predict whether a given observation in a dataset (e.g. a text in a collection of text files) possesses some particular ... | Python Code:
import os
open(os.path.join('data_a', 'archeological', '10.2307_104838.txt')).read()
Explanation: Introduction to Classification
The goal of a classification task is to predict whether a given observation in a dataset (e.g. a text in a collection of text files) possesses some particular property or attribu... |
2,071 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quickstart
We will be working on a mutagenicity dataset, released by Kazius et al.. 4337 compounds, provided as the file mols.sdf, were subjected to the AMES test. The results are given in... | Python Code:
import skchem
import pandas as pd
Explanation: Quickstart
We will be working on a mutagenicity dataset, released by Kazius et al.. 4337 compounds, provided as the file mols.sdf, were subjected to the AMES test. The results are given in labels.csv. We will clean the molecules, perform a brief chemical sp... |
2,072 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting the full vector-valued MNE solution
The source space that is used for the inverse computation defines a set of
dipoles, distributed across the cortex. When visualizing a source esti... | Python Code:
# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
#
# License: BSD-3-Clause
import numpy as np
import mne
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, apply_inverse
print(__doc__)
data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
smoothing_steps ... |
2,073 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutions
In this notebook, we explore the concept of convolutional neural networks.
You may want to read this wikipedia page if you're not familiar with the concept of a convolution.
In ... | Python Code:
# Which is easily implemented on python :
def _convolve(x, w, type='valid'):
# x and w are np vectors
conv = []
for i in range(len(x)):
if type == 'valid':
conv.append((x[i: i+len(w)] * w).sum())
return np.array(conv)
def convolve(X, w):
# Convolves a batch X to w
... |
2,074 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Autoencoder
Sticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. Again, loading modules and the data.
Step1: Network Archit... | Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
img = mnist.train.images[2]
plt.imshow(img.reshape((28, 28)), cmap='Greys_r')
Explanati... |
2,075 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Atlanta Police Department
The Atlanta Police Department provides Part 1 crime data at http
Step1: Review
Step2: We need to enter the descriptions for each entry in our dictionary manually.... | Python Code:
import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
# load data set
df = pd.read_csv('/home/data/APD/COBRA-YTD-multiyear.csv.gz')
print "Shape of table: ", df.shape
Explanation: Atlanta Police Department
The Atlanta Police Department provides Part 1 crime data at http... |
2,076 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PS Orthotile and Landsat 8 Crossovers
Have you ever wanted to compare PS images to Landsat 8 images? Both image collections are made available via the Planet API. However, it takes a bit of ... | Python Code:
# Notebook dependencies
from __future__ import print_function
import datetime
import json
import os
import ipyleaflet as ipyl
import ipywidgets as ipyw
from IPython.core.display import HTML
from IPython.display import display
import pandas as pd
from planet import api
from planet.api import filters
from sh... |
2,077 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sample, Explore, and Clean Taxifare Dataset
Learning Objectives
- Practice querying BigQuery
- Sample from large dataset in a reproducible way
- Practice exploring data using Pandas
- Identi... | Python Code:
from google.cloud import bigquery
PROJECT = !gcloud config get-value project
PROJECT = PROJECT[0]
%env PROJECT=$PROJECT
Explanation: Sample, Explore, and Clean Taxifare Dataset
Learning Objectives
- Practice querying BigQuery
- Sample from large dataset in a reproducible way
- Practice exploring data using... |
2,078 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
VARMAX models
This is a notebook stub for VARMAX models. Full development will be done after impulse response functions are available.
Step1: Model specification
The VARMAX class in Statsmo... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import statsmodels.api as sm
import dismalpy as dp
import matplotlib.pyplot as plt
dta = pd.read_stata('data/lutkepohl2.dta')
dta.index = dta.qtr
endog = dta.ix['1960-04-01':'1978-10-01', ['dln_inv', 'dln_inc', 'dln_consump']]
Explanation: VARMAX mo... |
2,079 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to kgof
This notebook will introduce you to kgof (kernel goodness-of-fit), a Python package implementing a linear-time kernel-based goodness-of-fit test as described in
A Line... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import kgof
import kgof.data as data
import kgof.density as density
import kgof.goftest as gof
import kgof.kernel as kernel
import kgof.util as util
import matplotlib
import matplotlib.pyplot as plt
import autograd.numpy as np
import scipy.stats as stat... |
2,080 | 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... |
2,081 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
prelim_month_human - confusion matrix
old file name
Step1: Setup - Imports
Back to Table of Contents
Step2: Setup - Initialize Django
Back to Table of Contents
First, initialize my dev dja... | Python Code:
# set the label we'll be looking at throughout
current_label = "prelim_month_human"
Explanation: prelim_month_human - confusion matrix
old file name: 2017.10.21 - work log - prelim_month_human - confusion matrix
Confusion matrix for data where coder 1 is ground truth, coder 2 is uncorrected human coding.
<... |
2,082 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejercicios 3
1 Ejercicio
Escribe una expresión Python para recuperar el valor del elemento con clave 'Hola' del un diccionario d.
* Comprueba que si d es {} la ejecución produce un error.
* ... | Python Code:
d1 = { }
d2 = {'Hola': ['Hi','Hello'], 'Adios': ['Bye'] }
# Sol:
d2['Hola']
Explanation: Ejercicios 3
1 Ejercicio
Escribe una expresión Python para recuperar el valor del elemento con clave 'Hola' del un diccionario d.
* Comprueba que si d es {} la ejecución produce un error.
* ¿ Y si d es {'Hola': ['Hi... |
2,083 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A First Look at the SDSS Photometric "Galaxy" Catalog
The Sloan Digital Sky Survey imaged over 10,000 sq degrees of sky (about 25% of the total), automatically detecting, measuring and catal... | Python Code:
%load_ext autoreload
%autoreload 2
import numpy as np
import SDSS
import pandas as pd
import matplotlib
%matplotlib inline
objects = "SELECT top 10000 \
ra, \
dec, \
dered_u as u, \
dered_g as g, \
dered_r as r, \
dered_i as i, \
petroR50_i AS size \
FROM PhotoObjAll \
WHERE \
((type = '3' OR type = '6') A... |
2,084 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What is Apache Spark?
distributed framework
in-memory data structures
data processing
it improves (most of the times) Hadoop workloads
Spark enables data scientists to tackle problems with ... | Python Code:
import pyspark
sc = pyspark.SparkContext(appName="my_spark_app")
Explanation: What is Apache Spark?
distributed framework
in-memory data structures
data processing
it improves (most of the times) Hadoop workloads
Spark enables data scientists to tackle problems with larger data sizes than they could befor... |
2,085 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Whole dataset
Step1: Data pre-processing
Load the data set and seperate the dataset into predictors and targets. the first column of targets is the EUI need to be predicted, the third colum... | Python Code:
from sklearn import linear_model
import csv
import numpy as np
from matplotlib import pyplot as plt
from sklearn.preprocessing import Imputer
from sklearn.linear_model import lasso_path
from sklearn.linear_model import LassoCV
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_er... |
2,086 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Convolutional GANs
In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called a Deep Convolutional GAN, or DCGAN for short. The D... | Python Code:
%matplotlib inline
import pickle as pkl
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import loadmat
import tensorflow as tf
!mkdir data
Explanation: Deep Convolutional GANs
In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called... |
2,087 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Wissenschaftliches Python Tutorial
Nachdem wir uns im Python Tutorial um die Grundlagen gekümmert haben, wollen wir uns nun mit einigen Bibliotheken beschäftigen, die das wissenschaftliche A... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy
Explanation: Wissenschaftliches Python Tutorial
Nachdem wir uns im Python Tutorial um die Grundlagen gekümmert haben, wollen wir uns nun mit einigen Bibliotheken beschäftigen, die das wissenschaftliche Arbeiten erleichtern. ... |
2,088 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setup
Step1: Code
Day 1
Step2: We will form the direction map since they are finite.
Step3: Day 2
Step4: part2
You finally arrive at the bathroom (it's a several minute walk from the lob... | Python Code:
import sys
import os
import re
import collections
import itertools
import bcolz
import pickle
import numpy as np
import pandas as pd
import gc
import random
import smart_open
import h5py
import csv
import tensorflow as tf
import gensim
import string
import datetime as dt
from tqdm import tqdm_notebook as t... |
2,089 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gradient Checking
Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking.
You are part of a team working to make mobile paym... | Python Code:
# Packages
import numpy as np
from testCases import *
from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector
Explanation: Gradient Checking
Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking.
... |
2,090 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial 1
This is a direct port of the R dftools tutorial to Python.
Objective of tutorial
Step1: Download the HI-mass data of Westmeier et al. 2017
Step2: There are 31 galaxies in this s... | Python Code:
%matplotlib inline
import pydftools as df
from pydftools.plotting import mfplot
import numpy as np
from urllib.request import Request, urlopen # For getting the data online
from IPython.display import display, Math, Latex, Markdown, TextDisplayObject
Explanation: Tutorial 1
This is a direct port of the R d... |
2,091 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Loading and modifying a SMIRNOFF-format force field
This notebook illustrates how to load a SMIRNOFF-format force field, apply it to an example molecule, get the energy, then manipulate the ... | Python Code:
from openff.toolkit.topology import Molecule, Topology
from openff.toolkit.typing.engines.smirnoff.forcefield import ForceField
from openff.toolkit.utils import get_data_file_path
from simtk import openmm, unit
import numpy as np
Explanation: Loading and modifying a SMIRNOFF-format force field
This noteboo... |
2,092 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
不均一分散
『Rによる計量経済学』第6章「不均一分散」をPythonで実行する。
テキスト付属データセット(「k0601.csv」等)については出版社サイトよりダウンロードしてください。
例題6-1
「k0601.csv」を用いた均一分散のデータである場合の回帰分析。
BP統計量による不均一分散の有無の仮説検定を行います。
Step1: Breush-Pagan Test
... | Python Code:
%matplotlib inline
# -*- coding:utf-8 -*-
from __future__ import print_function
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.stats.diagnostic as smsdia
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
# データ読み込み
data = pd.read_csv('e... |
2,093 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data exploration
We use the dataset found at https
Step1: Loading data
... just works. read_csv() comes with many convenient arguments, such as skiprows, nrows, na_values, etc. Note that, a... | Python Code:
import pandas as pd
df = pd.read_csv('../data/tidy_who.csv')
Explanation: Data exploration
We use the dataset found at https://github.com/mkcor/data-wrangling/blob/master/data/tidy_who.csv
(see the notebook at the root of that repo for the generation of this dataset).
End of explanation
df.head()
df.shape
... |
2,094 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logic Test
A notebook to test the classes and methods within SeaFallLogic.py.
Step1: Ship test
Create a ship object and change its values.
Step2: Island Test
See how class inheritence work... | Python Code:
%matplotlib inline
import numpy
import matplotlib
from matplotlib.patches import Circle, Wedge, Polygon
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.path as mpath
import numpy as ... |
2,095 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Per session and per user analysis
Analysis of users.
Table of Contents
Preparation
Function tests
User metrics checks
Preparation
<a id=preparation />
Step1: Per-session analysis
Step2: Pe... | Python Code:
%run "../Functions/3. Per session and per user analysis.ipynb"
rmdf152.head()
Explanation: Per session and per user analysis
Analysis of users.
Table of Contents
Preparation
Function tests
User metrics checks
Preparation
<a id=preparation />
End of explanation
testSessionId = "fab3ea03-6ff1-483f-a90a-74ff4... |
2,096 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Planar data classification with one hidden layer
Welcome to your week 3 programming assignment. It's time to build your first neural network, which will have a hidden layer. You will see a b... | Python Code:
# Package imports
import numpy as np
import matplotlib.pyplot as plt
from testCases import *
import sklearn
import sklearn.datasets
import sklearn.linear_model
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets
%matplotlib inline
np.random.seed(1) # set a see... |
2,097 | Given the following text description, write Python code to implement the functionality described.
Description:
Check if all the digits of the given number are same
Python3 program for the above approach ; Function to check if all the digits in the number N is the same or not ; Get the length of N ; Form the number M of... | Python Code:
import math
def checkSameDigits(N ) :
length = int(math . log10(N ) ) + 1 ;
M =(int(math . pow(10 , length ) ) - 1 ) //(10 - 1 ) ;
M *= N % 10 ;
if(M == N ) :
return "Yes ";
return "No ";
if __name__== "__main __":
N = 222 ;
print(checkSameDigits(N ) ) ;
|
2,098 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Distribution of local maxima in a Gaussian Random Field
In this notebook, I apply the distribution of local maxima of Cheng & Schwartzman. I reproduce the figure with the distribution in 1D... | Python Code:
% matplotlib inline
import numpy as np
import math
import nibabel as nib
import scipy.stats as stats
import matplotlib.pyplot as plt
from nipy.labs.utils.simul_multisubject_fmri_dataset import surrogate_3d_dataset
import palettable.colorbrewer as cb
from nipype.interfaces import fsl
import os
import pandas... |
2,099 | 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', 'ncc', 'sandbox-3', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: NCC
Source ID: SANDBOX-3
Sub-Topics: Radiative Forcings.
Properties: 85... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.