Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
7,800 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Psuedo Weight Pruning and Clustering
2017-05-10
Model
In this post, we use a trained AlexNet model (training on ImageNet dataset). AlexNet has 8 parameterized layers
Step1: The shape of eac... | Python Code:
import numpy as np
import os
import sys
weights_path = '/'.join(os.getcwd().split('/')[:-1]) + '/local-trained/alexnet/weights/'
print(weights_path)
os.listdir(weights_path)
keys = ['conv1', 'conv2', 'conv3', 'conv4', 'conv5', 'fc6', 'fc7', 'fc8']
weights = {}
for k in keys:
weights[k] = np.load(weight... |
7,801 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Long-Short Equity Strategies
By Delaney Granizo-Mackenzie
Part of the Quantopian Lecture Series
Step1: Now that we have factor values and returns, we can see what would happen if we ranked ... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# We'll generate a random factor
current_factor_values = np.random.normal(0, 1, 10000)
equity_names = ['Equity ' + str(x) for x in range(10000)]
# Put it into a dataframe
factor_data = pd.Series(current_factor_values, index = equity_nam... |
7,802 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Save this file as studentid1_studentid2_lab#.ipynb
(Your student-id is the number shown on your student card.)
E.g. if you work with 3 people, the notebook should be named
Step1: Lab 1
Step... | Python Code:
NAME = "Michelle Appel"
NAME2 = "Verna Dankers"
NAME3 = "Yves van Montfort"
EMAIL = "michelle.appel@student.uva.nl"
EMAIL2 = "verna.dankers@student.uva.nl"
EMAIL3 = "yves.vanmontfort@student.uva.nl"
Explanation: Save this file as studentid1_studentid2_lab#.ipynb
(Your student-id is the number shown on your... |
7,803 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Converting a Non-Deterministic <span style="font-variant
Step1: In order to transform a non-deterministic <span style="font-variant
Step2: The function $\delta^$ maps a state into a set o... | Python Code:
def epsClosure(s, delta):
Result = { s }
while True:
NewStates = { p for q in Result
for p in delta.get((q, ''), set())
}
if NewStates <= Result:
return frozenset(Result)
Result |= NewStates
Explanation: Converting a N... |
7,804 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Usage reference guide for haystack-reverse
this is an example of every haystack-reverse commands.
The zeus.vmem.856.dump is there https
Step1: First we need to generate the analysis for the... | Python Code:
!haystack-reverse --help
Explanation: Usage reference guide for haystack-reverse
this is an example of every haystack-reverse commands.
The zeus.vmem.856.dump is there https://dl.dropboxusercontent.com/u/10222931/HAYSTACK/zeus.vmem.856.dump.tgz
It was extracted from pid 856 from the zeus.img image from htt... |
7,805 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MAT245 Lab 10
Multi-Layer Perceptrons
Structure & Flow of Information
Multi-layer perceptrons (MLPs) are a simple class of neural networks. It's easiest to understand how an MLP works by exa... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import expit
from sklearn import datasets, mixture
xs = np.linspace(-5, 5)
fig = plt.figure(figsize=(20, 5))
## Plot relu
ax1 = fig.add_subplot(1, 3, 1)
ax1.plot(xs, np.maximum(0, xs))
## Plot sigmoid
ax2 = fig.add_subplot(1, 3, 2)
ax2.... |
7,806 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: カスタムフェデレーテッドアルゴリズム、パート 1
Step2: フェデレーテッドデータ
TFF の際立った特徴の 1 つは、フェデレーテッドデータに関する TensorFlow ベースの計算をコンパクトに表現できることです。本チュートリアルで使用するフェデレーテッドデータという用語は... | 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... |
7,807 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
K-fold cross validation - Regression Model
Based on the Ludwig regression example
Data set
This example demonstrates teh following
Step1: Contstants
Step2: Clean out previous results
Ste... | Python Code:
import logging
import os
import os.path
import shutil
import tempfile
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import requests
import scipy.stats as stats
import seaborn as sns
from sklearn.model_selection import train_test_split
from ludwig.api import kfold_cross_validate, Lu... |
7,808 | 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', 'nuist', 'sandbox-3', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: NUIST
Source ID: SANDBOX-3
Topic: Atmoschem
Sub-Topics: Transport, E... |
7,809 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hubs
Step1: Exercise
Can you create a ranked list of the importance of each individual, based on the number of neighbors they have?
Hint
Step2: If you inspect the dictionary closely, you ... | Python Code:
# Let's find out the number of neighbors that individual #7 has.
G.neighbors(7)
Explanation: Hubs: How do we evaluate the importance of some individuals in a network?
Within a social network, there will be certain individuals which perform certain important functions. For example, there may be hyper-connec... |
7,810 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Hub Authors.
Step1: <table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: You will use the AdamW optimizer from t... | 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... |
7,811 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with the pyCNN package
The pyCNN package is intended for neural-network processing on the CPU, and is particularly suited for NLP applications. It is a python-wrapper for the CNN pac... | Python Code:
# create a model and add the parameters.
m = Model()
m.add_parameters("W", (8,2))
m.add_parameters("V", (1,8))
m.add_parameters("b", (8))
renew_cg() # new computation graph. not strictly needed here, but good practice.
# associate the parameters with cg Expressions
W = parameter(m["W"])
V = parameter(m["V"... |
7,812 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bienvenid@s a otra reunión de Pyladies!!
En esta sesión aprenderemos a crear nuestras propias funciones en python.Pero primero que son funciones?
Una función en python es un bloque de código... | Python Code:
animales = ['perro', 'gato', 'perico']
len(animales)
animales[1]
x = 4
type(int('43'))
Explanation: Bienvenid@s a otra reunión de Pyladies!!
En esta sesión aprenderemos a crear nuestras propias funciones en python.Pero primero que son funciones?
Una función en python es un bloque de código organizado y reu... |
7,813 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Supervised Learning In-Depth
Step1: Motivating Random Forests
Step2: The binary splitting makes this extremely efficient.
As always, though, the trick is to ask the right questions.
This i... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
Explanation: Supervised Learning In-Depth: Random Forests
Previously we saw a powerful discriminative classifier, Support Vector Machines.
Here we'll take a look at motivating another powerful algorithm. This one ... |
7,814 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dimuon spectrum
<hr style="border-top-width
Step1: A little extra
Step2: Convert to ROOT format and analyse
First of all we convert the csv file into ROOT format, i.e. filling up a TTree d... | Python Code:
import ROOT
Explanation: Dimuon spectrum
<hr style="border-top-width: 4px; border-top-color: #34609b;">
This ROOTbook produces a plot of the dimuon spectrum starting from a subset of the CMS collision events of Run2010B.
Dataset Reference:<br>
McCauley, T. (2014). Dimuon event information derived from the... |
7,815 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Project
Step1: <a id='wrangling'></a>
Data Wrangling
General Properties
Step3: Data Cleaning
As evident from the data, it seems we have cast of the movie as string separated by | symbol. T... | Python Code:
# import necessary libraries
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
Explanation: Project: Investigate TMDb Movie Data
Table of Contents
<ul>
<li><a href="#intro">Introduction</a></li>
<li><a href="#wrangling">Data Wrangling</a></li>
<... |
7,816 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bootstrap replicates
in other words repeating the same experiment for a given number of times.
Step1: For further experiments Sepal Length variable will be used. Additionally, we will focus... | Python Code:
# importing required modules
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# runing the functions script
%run stats_func.py
# loading the iris dataset
df = pd.read_csv('iris.csv')
df.head()
# extracting sepal length and sepal width for furth... |
7,817 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
More solving the problem with some code before I write the code.
This post is a continuation on solving a problem before writing the code.
Defining the problem.
2 objects I want to understan... | Python Code:
import logging
from pprint import pprint
from itertools import chain
from datetime import datetime
Explanation: More solving the problem with some code before I write the code.
This post is a continuation on solving a problem before writing the code.
Defining the problem.
2 objects I want to understand are... |
7,818 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multiple Kernel Learning
By Saurabh Mahindre - <a href="https
Step1: Introduction
<em>Multiple kernel learning</em> (MKL) is about using a combined kernel i.e. a kernel consisting of a line... | Python Code:
%pylab inline
%matplotlib inline
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
# import all shogun classes
from shogun import *
Explanation: Multiple Kernel Learning
By Saurabh Mahindre - <a href="https://github.com/Saurabh7">github.com/Saurabh7</a>
This notebook is about multiple... |
7,819 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nasa-giss', 'giss-e2-1g', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: NASA-GISS
Source ID: GISS-E2-1G
Topic: Land
Sub-Topics: Soil, Snow, Veget... |
7,820 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SciPy 2016 Scikit-learn Tutorial
Unsupervised Learning Part 1 -- Transformation
Many instances of unsupervised learning, such as dimensionality reduction, manifold learning, and feature extr... | Python Code:
ary = np.array([1, 2, 3, 4, 5])
ary_standardized = (ary - ary.mean()) / ary.std()
ary_standardized
Explanation: SciPy 2016 Scikit-learn Tutorial
Unsupervised Learning Part 1 -- Transformation
Many instances of unsupervised learning, such as dimensionality reduction, manifold learning, and feature extractio... |
7,821 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BigQuery basics
BigQuery is a petabyte-scale analytics data warehouse that you can use to run SQL queries over vast amounts of data in near realtime. This page shows you how to get started w... | Python Code:
import pandas
from google.cloud import bigquery
Explanation: BigQuery basics
BigQuery is a petabyte-scale analytics data warehouse that you can use to run SQL queries over vast amounts of data in near realtime. This page shows you how to get started with the Google BigQuery API using the Python client libr... |
7,822 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have many duplicate records - some of them have a bank account. I want to keep the records with a bank account. | Problem:
import pandas as pd
import numpy as np
df = pd.DataFrame({'firstname': ['foo Bar', 'Bar Bar', 'Foo Bar'],
'lastname': ['Foo Bar', 'Bar', 'Foo Bar'],
'email': ['Foo bar', 'Bar', 'Foo Bar'],
'bank': [np.nan, 'abc', 'xyz']})
def g(df):
uniq_indx = (df.s... |
7,823 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook for preprocessing NYT op-ed data
Goal
Step1: 1. Read in the Data
Step2: This dataset has 11,648 op-eds from the NY Times. We have additional information for each article (title, a... | Python Code:
import pandas as pd
import numpy as np
import nltk
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
from nltk.stem.snowball import SnowballStemmer
from nltk.stem.wordnet import WordNetLemmatizer
from sklearn.feature_extraction.text import CountVectorizer
Explanation: Notebook for... |
7,824 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The
Step1:
Step2: Now, we can create an
Step3: Epochs behave similarly to
Step4: You can select subsets of epochs by indexing the
Step5: It is also possible to iterate through
Ste... | Python Code:
import mne
import os.path as op
import numpy as np
from matplotlib import pyplot as plt
Explanation: The :class:Epochs <mne.Epochs> data structure: epoched data
:class:Epochs <mne.Epochs> objects are a way of representing continuous
data as a collection of time-locked trials, stored in an array... |
7,825 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to ML Deployment
Deploying models created using python in a Turi Predictive Service is very easy. This notebook walks you through the step-by-step process.
<img src='images/pre... | Python Code:
# In order to run this code, you need an already trianed model (see the accompanying notebook)
import graphlab as gl
model = gl.load_model('pattern_mining_model.gl')
model
Explanation: Introduction to ML Deployment
Deploying models created using python in a Turi Predictive Service is very easy. This notebo... |
7,826 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Model summary
Run done with model with three convolutional layers, two fully connected layers and a final softmax layer, with a constant of 48 channels per convolutional layer. Initially run... | Python Code:
print('## Model structure summary\n')
print(model)
params = model.get_params()
n_params = {p.name : p.get_value().size for p in params}
total_params = sum(n_params.values())
print('\n## Number of parameters\n')
print(' ' + '\n '.join(['{0} : {1} ({2:.1f}%)'.format(k, v, 100.*v/total_params)
... |
7,827 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Factorial HMM
Example synthetic data
Step1: Test out learned distribution inside of SMC
We'll compare it against a baseline of "bootstrap" SMC, which proposes from the transition dynamics o... | Python Code:
devices = factorial_hmm.gen_devices()
T = 50
np.random.seed(20)
X, Y = factorial_hmm.gen_dataset(devices, T)
plt.figure(figsize=(15,3.5))
plt.plot(Y)
plt.figure(figsize=(15,10))
plt.imshow((X*devices).T, interpolation='None', aspect=1);
plt.yticks(np.arange(len(devices)), devices);
print len(devices), 2**l... |
7,828 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Text Classification using TensorFlow/Keras on Cloud ML Engine </h1>
This notebook illustrates
Step2: We will look at the titles of articles and figure out whether the article came from... | Python Code:
# change these to try this notebook out
BUCKET = 'cloud-training-demos-ml'
PROJECT = 'cloud-training-demos'
REGION = 'us-central1'
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJECT
os.environ['REGION'] = REGION
os.environ['TFVERSION'] = '1.14'
import tensorflow as tf
print(tf.__versio... |
7,829 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejemplo de word2vec con gensim
En la siguiente celda, importamos las librerías necesarias y configuramos los mensajes de los logs.
Step1: Entrenamiento de un modelo
Implemento una clase Cor... | Python Code:
import gensim, logging, os
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
Explanation: Ejemplo de word2vec con gensim
En la siguiente celda, importamos las librerías necesarias y configuramos los mensajes de los logs.
End of explanation
class Corpus(object):
... |
7,830 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Visualizing High-Performance Gradient Boosting with XGBoost and Yellowbrick
In this post we'll explore how to evaluate the performance of a gradient boosting classifier from the xgboo... | Python Code:
%matplotlib inline
import os
import requests
import pandas as pd
import matplotlib.pyplot as plt
from xgboost.sklearn import XGBClassifier
from sklearn.model_selection import train_test_split as tts
from yellowbrick.classifier import ClassBalance, ROCAUC, ClassificationReport, ClassPredictionError
def down... |
7,831 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Landice
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', 'uhh', 'sandbox-3', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: UHH
Source ID: SANDBOX-3
Topic: Landice
Sub-Topics: Glaciers, Ice.
Proper... |
7,832 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Theory and Practice of Visualization Exercise 2
Imports
Step1: Violations of graphical excellence and integrity
Find a data-focused visualization on one of the following websites that is a ... | Python Code:
from IPython.display import Image
Explanation: Theory and Practice of Visualization Exercise 2
Imports
End of explanation
# Add your filename and uncomment the following line:
Image(filename='graph2.JPG')
Explanation: Violations of graphical excellence and integrity
Find a data-focused visualization on one... |
7,833 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We see above that there is a entry called "TOTAL". That obvisously cannot be a name. We would need to remove that from the dataset. Before we do, let's confirm it is what it the name suggest... | Python Code:
print "print out some values of the observation 'TOTAL'"
for name, person in data_dict.iteritems():
if name == 'TOTAL':
print person
salary = []
for name, person in data_dict.iteritems():
if float(person['salary']) > 0:
salary.append(float(person['salary']))
print "the sum of salary of all ... |
7,834 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Triggers" data-toc-modified-id="Triggers-1"><span class="toc-item-num">1&nbs... | Python Code:
from random import randrange
from myhdlpeek import *
setup(use_wavedrom=True, use_jupyter=True)
def create_random_trace(name, num_bits, num_samples):
trace = Trace()
trace.name = name
trace.num_bits = num_bits
for i in range(num_samples):
trace.append(Sample(i, randrange(0,2**num_bi... |
7,835 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Prep
Load in cleaned experiment data, generated from this notebook.
Step1: Grab the min and max submission dates for filtering main_summary.
Step2: Load in main_summary, filtered to t... | Python Code:
S3_PATH = "s3://net-mozaws-prod-us-west-2-pipeline-analysis/taarv2/cleaned_data/"
# Select essential columns.
clean_data = sqlContext.read.parquet(S3_PATH).select('client_id', 'locale', 'branch', 'submission_date_s3')
# Display number of rows per branch.
clean_data.groupBy('branch').count().collect()
Expla... |
7,836 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License").
Text Generation using a RNN
<table class="tfo-notebook-buttons" align="left"><td>
<a ta... | Python Code:
!pip install unidecode
Explanation: Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License").
Text Generation using a RNN
<table class="tfo-notebook-buttons" align="left"><td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/tensorfl... |
7,837 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Contents
This notebook analyses lag-frequency spectrums of the light curves simulated through impulse response approach. First, a simple case with delta impulse response is covered. Subseque... | Python Code:
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
Explanation: Contents
This notebook analyses lag-frequency spectrums of the light curves simulated through impulse response approach. First, a simple case with delta impulse response is covered. Subsequently, an energy-dependent imp... |
7,838 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First off, an acknowledgement of the usefulness of the Software Carpentry materials, and particularly data, in preparing this session - this course is not, however, affiliated with or endors... | Python Code:
with open('data/inflammation-01.csv', 'r') as f:
snippet = f.readlines()[:3]
print(*snippet)
Explanation: First off, an acknowledgement of the usefulness of the Software Carpentry materials, and particularly data, in preparing this session - this course is not, however, affiliated with or endorsed by t... |
7,839 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Part-of-Speech Tagging using NLTK
One task in NLP has been to reliably identify a word's part of speech. This can help us with the ever-present task of identifying content words, but can be ... | Python Code:
import nltk
from nltk import word_tokenize
sentence = "For me it has to do with the work that gets done at the crossroads of \
digital media and traditional humanistic study. And that happens in two different ways. \
On the one hand, it's bringing the tools and techniques of digital media to bear \
on trad... |
7,840 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: 고급 자동 미분
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 그래디언트 기록 제어하기
자동 미분 가이드에서는 그래디언트 계산을 빌드... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
7,841 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quicksort
Summary
| Performance | Complexity |
|-----------------------------|------------------|
|Worst-case | $O(n^2)$ |
|Best-case ... | Python Code:
def partition(lst, start, end):
# in this formulation, the pivot point is the first item
pivot = lst[start]
# start partitioning after the pivot point
first = start + 1
last = end
# keep going until we covered the entire list
while first <= last:
# find the next element... |
7,842 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python design patterns
Covering only a small portion of what exists.
import this
creating main functions
Take a look at this guide
Step1: Explicit is better than implicit
Step2: Simple is ... | Python Code:
import this as t
print(t)
Explanation: Python design patterns
Covering only a small portion of what exists.
import this
creating main functions
Take a look at this guide: http://docs.python-guide.org/en/latest/writing/style/
Take a look at this "Zen of Python" by example: http://artifex.org/~hblanks/talks/... |
7,843 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Algorithms Exercise 1
Imports
Step3: Word counting
Write a function tokenize that takes a string of English text returns a list of words. It should also remove stop words, which are common ... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
Explanation: Algorithms Exercise 1
Imports
End of explanation
things = "hello!"
def ispuct(char, punctuation='`~!@#$%^&*()_-+={[}]|\:;"<,>.?/}\t'):
return (not (char in punctuation))
#x = list(filter(ispuct, things))
#a = ''
#a.... |
7,844 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocean
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cnrm-cerfacs', 'cnrm-esm2-1', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: CNRM-CERFACS
Source ID: CNRM-ESM2-1
Topic: Ocean
Sub-Topics: Timest... |
7,845 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Initial Value Problems
A paper by Jones and Underwood suggests a model for the temperature behaviour $T(t)$ of a PV cell in terms of a nonlinear differential equation. Here we extract the ke... | Python Code:
from __future__ import division
import numpy
%matplotlib notebook
from matplotlib import pyplot
parameters = { "T_ambient" : 290.0,
"c1" : 1.0e-5,
"c2" : 0.9,
"c3" : 0.0,
"c4" : 1.0e-2,
"c5" : 1.0}
T_initial = 300.0
t_end = 1e-2
def... |
7,846 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
#target_text
Explanation: Language Translation
In this project, ... |
7,847 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Class 07
ML Models
Step1: We'll import the DecisionTreeClassifier and use all of the default values except for the random_state. We'll provide that so that the output is consistent run-to-r... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("white")
#Note the new use of the dtype option here. We can directly tell pandas to use the Speed column as a category in one step.
speeddf = pd.read_csv("../Class04/Class04_speed_data.csv",dtype={'Speed':'category'})
#... |
7,848 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<b>Question 3 Is there any difference in app quality for free apps with in-app purchases?</b>
Step1: <p>First, the data set is splitted into two parts, one is app without in-app purchases a... | Python Code:
data_q3['is_InAppPurcased'].value_counts()
free = data_q3.loc[data_q3['is_InAppPurcased'] == 0]
paid = data_q3.loc[data_q3['is_InAppPurcased'] == 1]
free['current_rating'].plot(kind = "density")
paid['current_rating'].plot(kind = "density")
plt.xlabel('Current Rating')
plt.legend(labels = ['free','paid'], ... |
7,849 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gaussian Mixture Models (GMM)
KDE centers each bin (or kernel rather) at each point. In a mixture model we don't use a kernel for each data point, but rather we fit for the locations of the... | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo("B36fzChfyGU")
Explanation: Gaussian Mixture Models (GMM)
KDE centers each bin (or kernel rather) at each point. In a mixture model we don't use a kernel for each data point, but rather we fit for the locations of the kernels--in addition to the width.... |
7,850 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Instacart
This workbook about feature generation
The generated fetaures are stored as csv files, so can be loaded from subseqent pages
TODO
Combine the feature generation for train and test.... | Python Code:
import numpy as np
import pandas as pd
import time
from tqdm import tqdm
import gc
print('loading prior')
priors = pd.read_csv('./data/order_products__prior.csv')
print('loading train')
train_all = pd.read_csv('./data/order_products__train.csv')
## Have split the trian data into two sets, train and eval
... |
7,851 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with ... | Python Code:
import pandas as pd
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
Explanation: Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a n... |
7,852 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning Complications
Author
Step1: Now we plot a single example of both classes, to show what the data looks like. First the pulsar example.
Step2: It is clear that the peak is n... | Python Code:
# Import the libraries to be used throughout.
%pylab inline
import matplotlib.pyplot as plt
# The HTRU 2 profile data is split - one file containing the real pulsar
# profiles, one file containing noise/interference profiles. We load both
# these data sources here. First we construct relative paths to the ... |
7,853 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ipsl', 'sandbox-2', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: IPSL
Source ID: SANDBOX-2
Topic: Atmos
Sub-Topics: Dynamical Core, Radiation,... |
7,854 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Section 5.6
Superposition in space, land strip sudden change same at both ends
IHE, Delft, transient groundwater
@T.N.Olsthoorn, 2019-01-02
Context
The 1D aquifer has a limited width equal t... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import erfc
Explanation: Section 5.6
Superposition in space, land strip sudden change same at both ends
IHE, Delft, transient groundwater
@T.N.Olsthoorn, 2019-01-02
Context
The 1D aquifer has a limited width equal to $L$. The head at $x=... |
7,855 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gaussian Naive Bayes Classification
For most classification problems, it’s nice to have a simple, fast method to provide a quick baseline classification. If the simple and fast method is suf... | Python Code:
from sklearn.datasets import load_digits
digits = load_digits()
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target)
print(len(X_train), len(X_test), y_train, y_test)
clf = GaussianNB(... |
7,856 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Home Depot Product Search Relevance
The challenge is to predict a relevance score for the provided combinations of search terms and products. To create the ground truth labels, Home Depot ha... | Python Code:
import graphlab as gl
from nltk.stem import *
Explanation: Home Depot Product Search Relevance
The challenge is to predict a relevance score for the provided combinations of search terms and products. To create the ground truth labels, Home Depot has crowdsourced the search/product pairs to multiple human ... |
7,857 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TBtrans is capable of calculating transport in $N\ge 1$ electrode systems. In this example we will explore a 4-terminal graphene GNR cross-bar (one zGNR, the other aGNR) system.
Step1: Crea... | Python Code:
graphene = sisl.geom.graphene(orthogonal=True)
R = [0.1, 1.43]
hop = [0., -2.7]
Explanation: TBtrans is capable of calculating transport in $N\ge 1$ electrode systems. In this example we will explore a 4-terminal graphene GNR cross-bar (one zGNR, the other aGNR) system.
End of explanation
elec_y = graphene... |
7,858 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create an interactive TFX pipeline
This notebook is the first of two notebooks that guide you through automating the Real-time Item-to-item Recommendation with BigQuery ML Matrix Factorizati... | Python Code:
%load_ext autoreload
%autoreload 2
!pip install -U -q tfx
Explanation: Create an interactive TFX pipeline
This notebook is the first of two notebooks that guide you through automating the Real-time Item-to-item Recommendation with BigQuery ML Matrix Factorization and ScaNN solution with a pipeline.
Use thi... |
7,859 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Iris introduction course
1. The Iris Cube
Learning Outcome
Step1: 1.1 Introduction to the Iris Cube<a id='intro_to_iris_cube'></a>
The top level object in Iris is called a Cube. A Cube cont... | Python Code:
import iris
Explanation: Iris introduction course
1. The Iris Cube
Learning Outcome: by the end of this section, you will be able to explain the capabilities and functionality of Iris Cubes and Coordinates.
Duration: 1 hour
Overview:<br>
1.1 Introduction to the Iris Cube<br>
1.2 Working with a Cube<br>
1.3... |
7,860 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Displaying text on a PmodOLED
This demonstration shows how to display text on a PmodOLED using the board.
The Digilent Pmod OLED is required. In this example it should be connected to PMODA.... | Python Code:
from pynq.overlays.base import BaseOverlay
from pynq.lib import Pmod_OLED
base = BaseOverlay("base.bit")
pmod_oled = Pmod_OLED(base.PMODA)
pmod_oled.clear()
pmod_oled.write('Welcome to \nPYNQ!')
Explanation: Displaying text on a PmodOLED
This demonstration shows how to display text on a PmodOLED using the ... |
7,861 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Command mode vs Edit mode
By default we are in COMMAND mode
<li>Press **ENTER** the edit the current cell
<li>Press **ESC** to switch back to command mode
## Main command mode shortcu... | Python Code:
a = 1
b = 2
def my_simple_sum(a, b):
Simple addition
:param a: fist number
:param b: second number
print "Sum is:", a+b
my_simple_sum(a,b)
# Further down in the code we do some changes
a = 100
# than we can go back and re-execute just the previous cell
Explanation: Command mode vs Edit... |
7,862 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2022 The TensorFlow Authors.
Step1: Retrain a speech recognition model with TensorFlow Lite Model Maker
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_bl... | 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... |
7,863 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
この例では、GIDで生成されたメッシュを使用しています。メッシュは四面体要素です。
Step1: パラメータの設定
まずはパラメータを設定します。
Step2: メッシュの読み込み
メッシュを外部ファイルから読み込みます。
Step3: メッシュをParaviewのスクリプトでpng画像に打ち出し確認します。
Step4: 横と上から見たメッシュ図です。三脚のメッシュフ... | Python Code:
import getfem as gf
import numpy as np
Explanation: この例では、GIDで生成されたメッシュを使用しています。メッシュは四面体要素です。
End of explanation
file_msh = 'tripod.GiD.msh'
degree = 2
linear = False
incompressible = False # ensure that degree > 1 when incompressible is on..
E = 1e3
Nu = 0.3
Lambda = E*Nu/((1+Nu)*(1-2*Nu))
Mu = E/(2*(1+Nu... |
7,864 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Posterior inference for GGP graph model
In this notebook, we'll infer the posterior distribution of yeast dataset using generalised gamma process graph model.
Original source of the dataset ... | Python Code:
import os
import pickle
import time
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import loadmat
from sgp import GGPgraphmcmc
%matplotlib inline
Explanation: Posterior inference for GGP graph model
In this notebook, we'll infer the posterior distributi... |
7,865 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
eXamine Automation Tutorial
This case study demonstrates how to use the REST API of eXamine to study an annotated module in Cytoscape. The module that we study has 17 nodes and 18 edges and ... | Python Code:
# HTTP Client for Python
import requests
# Cytoscape port number
PORT_NUMBER = 1234
BASE_URL = "https://raw.githubusercontent.com/ls-cwi/eXamine/master/data/"
# The Base path for the CyRest API
BASE = 'http://localhost:' + str(PORT_NUMBER) + '/v1/'
#Helper command to call a command via HTTP POST
def execut... |
7,866 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Function Node
Satra once called the Function module, the "do anything you want card". Which is a perfect description. Because it allows you to put any code you want into an empty node, which... | Python Code:
# Import Node and Function module
from nipype import Node, Function
# Create a small example function
def add_two(x_input):
return x_input + 2
# Create Node
addtwo = Node(Function(input_names=["x_input"],
output_names=["val_output"],
function=add_two),
... |
7,867 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example for dimensionnality reduction
Step1: convert integer in to binary string
Step2: we apply this to a data
we use enumerate to loop
then save a dictionary to encapsulate of the values... | Python Code:
import pandas as pd
import numpy as np
my_data = pd.DataFrame([1,2,3])
Explanation: Example for dimensionnality reduction
End of explanation
def to_binary(value):
return "{0:b}".format(value)
to_binary(5)
unique_values = my_data.thrid.unique()
Explanation: convert integer in to binary string
End of exp... |
7,868 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Landice
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', 'bnu', 'sandbox-1', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: BNU
Source ID: SANDBOX-1
Topic: Landice
Sub-Topics: Glaciers, Ice.
Proper... |
7,869 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Microsoft Emotion API Data
Images were placed into the API by hand since there were so few. This step was automated using the API for the Baseline data
Step1: Plotting sentiment for each im... | Python Code:
def read_jsons(f, candidate):
tmp_dict = {}
with open(f) as json_file:
data = json.load(json_file)
for i in data[0]['scores']:
if data[0]['scores'][i] > 0.55: # confidence score threshold.
tmp_dict[i] = data[0]['scores'][i]
else: tm... |
7,870 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quandl
Step1: Let's go over the columns
Step2: <a id='pipeline'></a>
Pipeline Overview
Accessing the data in your algorithms & research
The only method for accessing partner data within al... | Python Code:
# import the dataset
from quantopian.interactive.data.quandl import yahoo_index_vix as dataset
# Since this data is provided by Quandl for free, there is no _free version of this
# data set, as found in the premium sets. This import gets you the entirety of this data set.
# import data operations
from odo ... |
7,871 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EEG forward operator with a template MRI
This tutorial explains how to compute the forward operator from EEG data
using the standard template MRI subject fsaverage.
.. important
Step1: Load... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Joan Massich <mailsik@gmail.com>
#
# License: BSD Style.
import os.path as op
import mne
from mne.datasets import eegbci
from mne.datasets import fetch_fsaverage
# Download fsaverage files
fs_dir = fetch_fsaverage(verbose=True)
subjects... |
7,872 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploratory Data Analysis
Step1: Data Cleaning
Step2: Random Forest
Step3: Random Forest Results
```
0.79426
['AgeSex', 'AgeSexFare', 'Fare', 'Sex', 'Pclass', 'Age']
create_submission(Ran... | Python Code:
test.info()
train.describe()
# train.Cabin.str.split().str.get(-1).str[0]
# train.Cabin.str.split(expand=True)
# train.Ticket.str.split().str.get(0).str.extract
train.Ticket.str.split()[0:].str[0].head()
print train[train['Survived']==1]["Age"].mean(),
print train[train['Survived']==0]["Age"].mean(),
print... |
7,873 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyGSLIB
Draw
The GSLIb equivalent parameter file is
```
Parameters for DRAW
***
START OF PARAMETERS
Step1: Getting the data ready for work
If the data is... | Python Code:
#general imports
import matplotlib.pyplot as plt
import pygslib
import numpy as np
import pandas as pd
#make the plots inline
%matplotlib inline
Explanation: PyGSLIB
Draw
The GSLIb equivalent parameter file is
```
Parameters for DRAW
***
START OF PARAMETERS:
data/... |
7,874 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook 4
Step2: Download the sequence data
Sequence data for this study are archived on the NCBI sequence read archive (SRA). Below I read in SraRunTable.txt for this project which contai... | Python Code:
### Notebook 4
### Data set 4 (Orestias)
### Authors: Takahashi & Moreno (2015)
### Data Location: DDBJ DRA DRA003595
Explanation: Notebook 4:
This is an IPython notebook. Most of the code is composed of bash scripts, indicated by %%bash at the top of the cell, otherwise it is IPython code. This notebook i... |
7,875 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
A cold atom experimental setup on an optical table is a useful metaphor for the philosophy underlying the cold-atom library. In such an experimental apparatus there are expensiv... | Python Code:
import coldatoms
import numpy as np
%matplotlib notebook
import matplotlib.pyplot as plt
Explanation: Introduction
A cold atom experimental setup on an optical table is a useful metaphor for the philosophy underlying the cold-atom library. In such an experimental apparatus there are expensive, complicated ... |
7,876 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
线性支持向量机的朴素实现
虽然从形式上来说,线性支持向量机(LinearSVM)和感知机的差别只在于损失函数,但如果只是简单地将感知机的训练策略(亦即每次只选出使得损失函数最大的样本点来进行梯度下降)迁移过来的话、会引发一些问题。为方便,我们称感知机的训练策略为极大梯度下降法(注:这不是被广泛承认的称谓,只是本文的一个代称)
我们会先展示极大梯度下降法的有效性,然后会展示极大梯... | Python Code:
import numpy as np
class LinearSVM:
def __init__(self):
self._w = self._b = None
def fit(self, x, y, c=1, lr=0.01, epoch=10000):
x, y = np.asarray(x, np.float32), np.asarray(y, np.float32)
self._w = np.zeros(x.shape[1])
self._b = 0.
for _ in range(ep... |
7,877 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compare Solutions - Homogenous (Eurus)
Brendan Smithyman | October 2015
This notebook shows comparisons between the responses of the different solvers.
Step1: Error plots for Eurus vs. the ... | Python Code:
import sys
sys.path.append('../')
import numpy as np
from zephyr.backend import Eurus, SparseKaiserSource, AnalyticalHelmholtz
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib
%matplotlib inline
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('png')
mat... |
7,878 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Diferencias Finitas
El método de diferencias finitas corresponde a una aproximación discreta del dominio del problema, generando un sistema de ecuaciones para tal efecto. Tanto Ecuaciones di... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Rango de tiempo
tt = np.linspace(0, 1, 100)
# Solución Analítica
def y(t):
return (np.exp(-2*t)*(-3*np.exp(2)+np.exp(4)-np.exp(4*t)+ 3*np.exp(2+4*t)))/(-1+np.exp(4))
yy = y(tt)
# Matriz de diferencias finitas que depende de n
def D... |
7,879 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
syncID
Step1: For this example, we will read in a reflectance tile in ENVI format. NEON provides an h5 plugin for ENVI
Step2: Note that the information is stored differently when read in w... | Python Code:
from spectral import *
import spectral.io.envi as envi
import numpy as np
import matplotlib
#for clean output, to not print warnings, don't use when developing script
import warnings
warnings.filterwarnings('ignore')
Explanation: syncID: 75f8885948494c0dbe6084099c61dd1e
title: "Unsupervised Spectral Classi... |
7,880 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Budget accounting with diffprivlib
Diffprivlib includes a budget accountant to allow you to keep track of privacy budget being spent. The budget accounting is handled by the BudgetAccountant... | Python Code:
import matplotlib.pyplot as plt
from numpy.random import random
from diffprivlib import BudgetAccountant
from diffprivlib.tools import mean, var
X = random(100)
acc = BudgetAccountant(epsilon=5, delta=0)
dp_mean = mean(X, bounds=(0, 1), accountant=acc)
print("Total spent: %r" % (acc.total(),))
print("Remai... |
7,881 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
load a DistilGPT2 tokenizer to process the text subfield
| Python Code::
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
|
7,882 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bayesian Changepoint Detection in Python
This code computes the probability of changepoints in a time series.7 In this notebook I show how you can use it.
First let's generate some data
Step... | Python Code:
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import seaborn
from bayesian_changepoint_detection.generate_data import generate_normal_time_series
%matplotlib inline
%load_ext autoreload
%autoreload 2
partition, data = generate_normal_time_series(7, 50, 200)
Explanation:... |
7,883 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Week 11
Step3: Before we go on a note of caution is needed for class attributes. Do you remember the strange fibonacci sequence function from our first class?
Step6: The same issue ... | Python Code:
class Person(object):
A class definition for a person. The following attributes are supported:
Attributes:
name: A string representing the person's name.
age: An integer representing the person's age.
mammal = True
def __init__(self, name, age):
Return a Perso... |
7,884 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Maximum Likelihood Estimation
Step1: Best parameter for n4
Step2: after removing the constant part
Step3: Coin example
Setup problem
Step4: Looking at the experient shown above, we can e... | Python Code:
from math import factorial as fac
from numpy import math
import numpy as np
import random
from collections import Counter
%matplotlib inline
n = 1000
experiments = []
for i in range(n):
a = random.randint(1, 6)
# key = "{}-{}".format(a, b)
# experiments[key] = experiments.get(key, 0) + 1
ex... |
7,885 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Adding new passbands to PHOEBE
In this tutorial we will show you how to add your own passband to PHOEBE. Adding a passband involves
Step1: I don't care about the details, just show/remind m... | Python Code:
!pip install -I "phoebe>=2.0,<2.1"
Explanation: Adding new passbands to PHOEBE
In this tutorial we will show you how to add your own passband to PHOEBE. Adding a passband involves:
* providing a passband transmission function;
* defining and registering parameters of the passband;
* computing blackbody res... |
7,886 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this notebook we will use the same Cython code as in the last notebook. However, this time we will use the Vode integrator from ODEPACK (available in SciPy in scipy.integrate.ode). The re... | Python Code:
import json
import numpy as np
Explanation: In this notebook we will use the same Cython code as in the last notebook. However, this time we will use the Vode integrator from ODEPACK (available in SciPy in scipy.integrate.ode). The reason for this is that it will be a fairer comparison against our upcoming... |
7,887 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
See environment_setup.README (below) for instructions about the use of the DC3_plots_NALMA script. It is a version of the script used to process the DC3 dataset as in Barth et al. (2015, BAM... | Python Code:
%%bash
cat /data/GLM-wkshp/flashsort/environment_setup.README
# Links to representative PDFs.
from IPython.display import display, HTML, Image
class PDF(object):
def __init__(self, filename):
self.filename = filename
def _repr_pdf_(self):
return open(self.filename, 'rb').read()
base... |
7,888 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interpolation with RBF
$$
f( x) =\sum ^{P}{p=1} a{p} .R_{p} +b
$$
$$
R_{p} = e^{-\frac{1}{2\sigma ^{2}} .\parallel ( X_{i}) -( X_{p}) \parallel ^{2}}
$$
$$
\sigma =\frac{P_{max} -P_{min}}{\s... | Python Code:
def rbf(inp, out, center):
def euclidean_norm(x1, x2):
return sqrt(((x1 - x2)**2).sum(axis=0))
def gaussian (x, c):
return exp(+1 * pow(euclidean_norm(x, c), 2))
R = np.ones((len(inp), (len(center) + 1)))
for i, iv in enumerate(inp):
for j, jv in enumerate(... |
7,889 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This IPython notebook explains a basic workflow two tables using py_entitymatching. Our goal is to come up with a workflow to match DBLP and ACM datasets. Specifically, we want ... | Python Code:
import sys
sys.path.append('/Users/pradap/Documents/Research/Python-Package/anhaid/py_entitymatching/')
import py_entitymatching as em
import pandas as pd
import os
# Display the versions
print('python version: ' + sys.version )
print('pandas version: ' + pd.__version__ )
print('magellan version: ' + em.__... |
7,890 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating gallery images for annotation review
Overview
Step1: Connect girder client and set parameters
A csv file like the one in
histomicstk/annotations_and_masks/tests/test_files/sample_G... | Python Code:
import os
import tempfile
import shutil
from imageio import imread
from pandas import read_csv
import girder_client
from histomicstk.annotations_and_masks.review_gallery import \
get_all_rois_from_folder_v2, get_all_rois_from_slide_v2, \
_plot_rapid_review_vis, create_review_galleries
import matplo... |
7,891 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2D Poisson Problem
We solve the following problem
Step1: Test set 2
Step2: Test set 3
Step3: Test set 4
Step4: Test set 5
Step5: Test set 6
Step6: 3D Poisson Problem
Weak Scaling Test
... | Python Code:
omg=numpy.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1])
tPCG = numpy.array([5.72, 4.54, 3.78, 3.14, 2.71, 2.38, 2.06, 1.95, 2.49, 10.15])
tPCGF = numpy.array([2.48, 2.14, 2.03, 2.6, 10.7])
tPBICGSTAB = numpy.array([2.79, 2.58, 2.48, 3, 12.1])
pyplot.plot(omg, tPCG, label="PCG")
pyplot.plot(omg[5:... |
7,892 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Clean up data
Sometimes, unwanted data needs to be deleted.
Each of the screenshot data was manually checked, and was moved to the wrong/ directory.
This notebook iterates through the wrong/... | Python Code:
%ls -lh ../data/csv
import pandas as pd
import os
parent_path = os.path.dirname(os.getcwd())
csv_file = '97802012'
csv_file_name = csv_file + '.csv'
csv_dir_path = os.path.join(parent_path, 'data', 'csv')
csv_file_path = os.path.join(csv_dir_path, csv_file_name)
img_dir_path = os.path.join(parent_path, 'd... |
7,893 | 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... |
7,894 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Conformal Kernel Distribution Embedding
Conformal Anomaly Detector via RBF Kernel Embddeing
Below are shown sample results obtained in this project. On left are level sets of the nominal biv... | Python Code:
import time
import os
import numpy as np
from sklearn.grid_search import ParameterGrid
from sklearn.base import clone
from sklearn.gaussian_process import GaussianProcess
from scipy.stats import norm
from joblib import Parallel, delayed
from utils.state import _save
from utils.functions_1d import f6, press... |
7,895 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Random variables
When the objective is to predict the category (qualitative, such as predicting political party affiliation), we term the it as predicting a qualitative random variable. On t... | Python Code:
import math
def bin_prob(n,y,pi):
a = math.factorial(n)/(math.factorial(y)*math.factorial(n-y))
b = math.pow(pi, y) * math.pow((1-pi), (n-y))
p_y = a*b
return p_y
Explanation: Random variables
When the objective is to predict the category (qualitative, such as predicting political party aff... |
7,896 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Basics with Numpy (optional assignment)
Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will help fam... | Python Code:
### START CODE HERE ### (≈ 1 line of code)
test = None
### END CODE HERE ###
print ("test: " + test)
Explanation: Python Basics with Numpy (optional assignment)
Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will help famili... |
7,897 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistic Regression with L2 regularization
The goal of this second notebook is to implement your own logistic regression classifier with L2 regularization. You will do the following
Step1: ... | Python Code:
from __future__ import division
import graphlab
Explanation: Logistic Regression with L2 regularization
The goal of this second notebook is to implement your own logistic regression classifier with L2 regularization. You will do the following:
Extract features from Amazon product reviews.
Convert an SFrame... |
7,898 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A regular expression (regex, RE) is a sequence of characters that define a search pattern. Usually this pattern is used by string searching algorithms for "find" or "find and replace" operat... | Python Code:
import re
Explanation: A regular expression (regex, RE) is a sequence of characters that define a search pattern. Usually this pattern is used by string searching algorithms for "find" or "find and replace" operations on strings. For example, search engines use regular expressions to find matches to your q... |
7,899 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Conda and
binstar are changing the packaging world of Python.
Conda made it easy to install re-locatable python binaries that where hard
to build, while binstar provides a "Linux repository-... | Python Code:
import re
import requests
import numpy as np
from datetime import date
from pandas import DataFrame
from bs4 import BeautifulSoup
from dateutil.relativedelta import relativedelta
def todatetime(ul_str):
upload = re.compile(r'((?P<year>\d+) years?)?( and )?((?P<month>\d+) months?)?( and )?((?P<day>\d+) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.