Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
11,300 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Double Pendulum
Let's setup some parameters
Step1: How many steps are there?
Step2: Helper functions for various calculations
Calculate various derivatives
The time derivative of $\theta_1... | Python Code:
import numpy as np
g = 9.8 # m/s
l1 = 1.2 # m
l2 = .7 # m
theta1_0 = np.pi/5 # other initial angle
theta2_0 = np.pi # initial angle
m1 = .10 # kg
m2 = .05 # kg
dt = 1.e-3 # time ste... |
11,301 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning
Assignment 2
Previously in 1_notmnist.ipynb, we created a pickle with formatted datasets for training, development and testing on the notMNIST dataset.
The goal of this assignm... | Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
Explanation: Deep Learning
Assignment 2
Previousl... |
11,302 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Writing a LogPDF
Probability density functions in Pints can be defined via models and problems, but they can also be defined directly.
In this example, we implement the Rosenbrock function a... | Python Code:
import numpy as np
import pints
class Rosenbrock(pints.LogPDF):
def __init__(self, a=1, b=100):
self._a = a
self._b = b
def __call__(self, x):
return - np.log((self._a - x[0])**2 + self._b * (x[1] - x[0]**2)**2)
def n_parameters(self):
return 2
Explanation: Writi... |
11,303 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2.1 Advanced Indexing
Indexing files
As was shown earlier, we can create an index of the data space using the index() method
Step1: We will use the Collection class to manage the index dire... | Python Code:
import signac
project = signac.get_project(root='projects/tutorial')
index = list(project.index())
for doc in index[:3]:
print(doc)
Explanation: 2.1 Advanced Indexing
Indexing files
As was shown earlier, we can create an index of the data space using the index() method:
End of explanation
index = signa... |
11,304 | 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', 'noaa-gfdl', 'gfdl-esm4', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: NOAA-GFDL
Source ID: GFDL-ESM4
Topic: Atmoschem
Sub-Topics: Tran... |
11,305 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise 1
Work on this before the next lecture on 10 April. We will talk about questions, comments, and solutions during the exercise after the second lecture.
Please do form study groups! ... | Python Code:
%config InlineBackend.figure_format='retina'
%matplotlib inline
import numpy as np
np.random.seed(123)
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (8, 8)
plt.rcParams["font.size"] = 14
from sklearn.utils import check_random_state
Explanation: Exercise 1
Work on this before the next lec... |
11,306 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: 2017 Hurricane Tracks
Demonstrates how to plot all the North American hurricane tracks in 2017, starting from the BigQuery public dataset.
Step2: Plot one of the hurricanes
Let's jus... | Python Code:
%bash
apt-get update
apt-get -y install python-mpltoolkits.basemap
from mpl_toolkits.basemap import Basemap
import google.datalab.bigquery as bq
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
query=
#standardSQL
SELECT
name,
latitude,
longitude,
iso_time,
usa_sshs
FROM
... |
11,307 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spatiotemporal permutation F-test on full sensor data
Tests for differential evoked responses in at least
one condition using a permutation clustering test.
The FieldTrip neighbor templates ... | Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mne.viz import plot_topomap
import mne
from mne.stats import spatio_temporal_cluster_test
from mne.datasets import... |
11,308 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First, here's the SPA power function
Step1: Here are two helper functions for computing the dot product over space, and for plotting the results | Python Code:
def power(s, e):
x = np.fft.ifft(np.fft.fft(s.v) ** e).real
return spa.SemanticPointer(data=x)
Explanation: First, here's the SPA power function:
End of explanation
def spatial_dot(v, X, Y, Z, xs, ys, transform=1):
vs = np.zeros((len(ys),len(xs)))
for i,x in enumerate(xs):
for j, y ... |
11,309 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise 6.7
Step1: Create Sarsa Agent
Step2: Evaluate agents with different action set
Step3: Exercise 6.8 | Python Code:
import numpy as np
ACTION_TO_XY = {
'left': (-1, 0),
'right': (1, 0),
'up': (0, 1),
'down': (0, -1),
'up_left': (-1, 1),
'down_left': (-1, -1),
'up_right': (1, 1),
'down_right': (1, -1),
'stop': (0, 0)
}
# convert tuples to np so we can do math with states
ACTION_TO_XY =... |
11,310 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Principal Component Analysis in Shogun
By Abhijeet Kislay (GitHub ID
Step1: Some Formal Background (Skip if you just want code examples)
PCA is a useful statistical technique that has found... | Python Code:
%pylab inline
%matplotlib inline
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
# import all shogun classes
from shogun import *
import shogun as sg
Explanation: Principal Component Analysis in Shogun
By Abhijeet Kislay (GitHub ID: <a href='https://github.com/kislayabhi'>kislayabhi... |
11,311 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mousai
Step1: Overview
A wide array of contemporary problems can be represented by nonlinear ordinary differential equations with solutions that can be represented by Fourier Series
Step2: ... | Python Code:
%matplotlib inline
%load_ext autoreload
%autoreload 2
import scipy as sp
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import mousai as ms
from scipy import pi, sin
matplotlib.rcParams['figure.figsize'] = (11, 5)
from traitlets.config.manager import BaseJSONConfigManager
path = "/Use... |
11,312 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: MedMNIST
MedMNIST, a collection of 10 pre-processed medical open datasets. MedMNIST is standardized to perform classification tasks on lightweight 28 * 28 images, whic... | Python Code:
# import package
import matplotlib.pyplot as plt
import numpy as np
import os
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import (Input, Dense, Dropout, Activation, ... |
11,313 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This section reviews the various methods for reading and modifying metadata within a ReproPhylo Project. Utilizing it will be discussed in later sections.
3.4.1 What is metadata in ReproPhyl... | Python Code:
from IPython.display import Image
Image('images/genbank_terminology.jpg', width=400)
Explanation: This section reviews the various methods for reading and modifying metadata within a ReproPhylo Project. Utilizing it will be discussed in later sections.
3.4.1 What is metadata in ReproPhylo?
Within a ReproPh... |
11,314 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: <a ><img src = "https
Step2: The code in the indent is executed N times, each time the value of i is increased by 1 for every execution. The statement executed is to p... | Python Code:
range(3)
Explanation: <a href="http://cocl.us/topNotebooksPython101Coursera"><img src = "https://ibm.box.com/shared/static/yfe6h4az47ktg2mm9h05wby2n7e8kei3.png" width = 750, align = "center"></a>
<a href="https://www.bigdatauniversity.com"><img src = "https://ibm.box.com/shared/static/ugcqz6ohbvff804xp84y4... |
11,315 | Given the following text description, write Python code to implement the functionality described.
Description:
Filter an input list of strings only for ones that contain given substring
This is how the function will work:
filter_by_substring([], 'a')
[]
This is how the function will work:
filter_by_sub... | Python Code:
from typing import List
def filter_by_substring(strings: List[str], substring: str) -> List[str]:
return [x for x in strings if substring in x] |
11,316 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bienvenida a otra reunión de pyladies!!
Yo sé que después de las vacaciones lo que ya habías aprendido en python tal vez no esté tan fresco. Así que vamos a enumerar (y explicar) brevemente ... | Python Code:
#Obtén el cuadrado de 1
1**2
#Obtén el cuadrado de 2
2**2
#Obtén el cuadrado de 3
3**2
#Obtén el cuadrado de 4
4**2
#Obtén el cuadrado de 5
5**2
#Obtén el cuadrado de 6
6**2
#Obtén el cuadrado de 7
7**2
#Obtén el cuadrado de 8
8**2
#Obtén el cuadrado de 9
9**2
#Obtén el cuadrado de 10
10**2
Explanation: Bi... |
11,317 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Processing MOC maps
Multi-Order Coverage maps represent regions in a spheric surface defined by tree-like structures with the aim of producing maps through different spatial resolutions. In ... | Python Code:
# Let's handle units
from astropy import units as u
# Structure to map healpix' levels to their angular sizes
#
healpix_levels = {
0 : 58.63 * u.deg,
1 : 29.32 * u.deg,
2 : 14.66 * u.deg,
3 : 7.329 * u.deg,
4 : 3.665 * u.deg,
5 : 1.832 * u.deg,
6 : 54.97 * u.arcmin, ... |
11,318 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
第13章 ニューラルネットワーク
著者オリジナル
Step1: 13.1.3 Theano を設定する
Step2: 環境変数で設定の変更が可能
export THEANO_FLAGS=floatX=float32
cpuを使って計算する場合
THEANO_FLAGS=device=cpu,floatX=float64 python <pythonスクリプト>
... | Python Code:
import theano
from theano import tensor as T
# 初期化: scalar メソッドではスカラー(単純な配列)を生成
x1 = T.scalar()
w1 = T.scalar()
w0 = T.scalar()
z1 = w1 * x1 + w0
# コンパイル
net_input = theano.function(inputs=[w1, x1, w0], outputs=z1)
# 実行
net_input(2.0, 1.0, 0.5)
Explanation: 第13章 ニューラルネットワーク
著者オリジナル: https://github.com/rasb... |
11,319 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spatiotemporal permutation F-test on full sensor data
Tests for differential evoked responses in at least
one condition using a permutation clustering test.
The FieldTrip neighbor templates ... | Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
# Jona Sassenhagen <jona.sassenhagen@gmail.com>
#
# License: BSD-3-Clause
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import mne
from mne.stats import spatio_temporal_cluster_test
fr... |
11,320 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Coding the Bose-Hubbard Hamiltonian with QuSpin
The purpose of this tutorial is to teach the interested user to construct bosonic Hamiltonians using QuSpin. To this end, below we focus on th... | Python Code:
from quspin.operators import hamiltonian # Hamiltonians and operators
from quspin.basis import boson_basis_1d # Hilbert space boson basis
import numpy as np # generic math functions
Explanation: Coding the Bose-Hubbard Hamiltonian with QuSpin
The purpose of this tutorial is to teach the interested user to ... |
11,321 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Function to compute escape velocity given halo parameters
Step3: Functions to compute halo parameters given cosmology and Mvir
Step6: Use these basic relations to get rvir<->mir con... | Python Code:
def NFW_escape_vel(r, Mvir, Rvir, CvirorRs, truncated=False):
NFW profile escape velocity
Parameters
----------
r : Quantity w/ length units
Radial distance at which to compute the escape velocity
Mvir : Quantity w/ mass units
Virial Mass
CvirorRs : Quantity w/ ... |
11,322 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
T81-558
Step1: Several Useful Functions
These are functions that I reuse often to encode the feature vector (FV).
Step2: Read in Raw KDD-99 Dataset
Step3: Encode the feature vector
Encode... | Python Code:
# Imports for this Notebook
# Imports
import pandas as pd
from sklearn import preprocessing
from sklearn.cross_validation import train_test_split
import tensorflow.contrib.learn as skflow
from sklearn import metrics
Explanation: T81-558: Applications of Deep Neural Networks
TensorFlow (SKFLOW) Meets KDD-99... |
11,323 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 Google LLC
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 Licens... | Python Code:
import tensorflow as tf
import numpy as np
np.random.seed(123)
Explanation: Copyright 2019 Google LLC
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/LICE... |
11,324 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center>
<img src="../../img/ods_stickers.jpg">
Открытый курс по машинному обучению
</center>
Автор материала
Step1: Проверка стационарности и STL-декомпозиция ряда
Step2: Стационарность
К... | Python Code:
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
from matplotlib import pyplot as plt
plt.rcParams['figure.figsize'] = 12, 10
import pandas as pd
from scipy import stats
import statsmodels.api as sm
import matplotlib.pyplot as plt
from itertools import product
def invboxcox(y,lmbda):
... |
11,325 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Read in semi-structured data with pandas
When analyzing software systems in a Software Analytics style with pandas, you might face data that isn't yet in a tabular format you can easily read... | Python Code:
!cp ../../joa_spring-petclinic/git_log_numstat.log datasets/git_log_raw_stats_spring_petclinic.log
import pandas as pd
log = pd.read_csv(
"datasets/git_log_raw_stats_spring_petclinic.log",
sep="\n",
names=['raw'])
log.head()
Explanation: Read in semi-structured data with pandas
When analyzing s... |
11,326 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Librosa demo
This notebook demonstrates some of the basic functionality of librosa version 0.4.
Following through this example, you'll learn how to
Step1: By default, librosa will resample ... | Python Code:
from __future__ import print_function
# We'll need numpy for some mathematical operations
import numpy as np
# matplotlib for displaying the output
import matplotlib.pyplot as plt
import matplotlib.style as ms
ms.use('seaborn-muted')
%matplotlib inline
# and IPython.display for audio output
import IPython.... |
11,327 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Open Context Zooarchaeology Measurements
This code gets meaurement data from Open Context to hopefully do some interesting things.
In the example given here, we're retrieving zooarchaeologic... | Python Code:
# This imports the OpenContextAPI from the api.py file in the
# opencontext directory.
%run '../opencontext/api.py'
Explanation: Open Context Zooarchaeology Measurements
This code gets meaurement data from Open Context to hopefully do some interesting things.
In the example given here, we're retrieving zoo... |
11,328 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
https
Step1: Step 0 - hyperparams
vocab_size and max sequence length are the SAME thing
decoder RNN hidden units are usually same size as encoder RNN hidden units in translation but for our... | Python Code:
from __future__ import division
import tensorflow as tf
from os import path
import numpy as np
import pandas as pd
import csv
from sklearn.model_selection import StratifiedShuffleSplit
from time import time
from matplotlib import pyplot as plt
import seaborn as sns
from mylibs.jupyter_notebook_helper impor... |
11,329 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basics of Machine Learning
Tutorial held at University of Zurich, 23-24 March 2016
(c) 2016 Jan Šnajder (jan.snajder@fer... | Python Code:
import scipy as sp
import scipy.stats as stats
import matplotlib.pyplot as plt
from numpy.random import normal
from SU import *
%pylab inline
Explanation: Basics of Machine Learning
Tutorial held at University of Zurich, 23-24 March 2016
(c) 2016 Jan Šnajder (jan.snaj&#... |
11,330 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Excercises Electric Machinery Fundamentals
Chapter 6
Problem 6-5
Step1: Description
A 208-V four-pole 60-Hz Y-connected wound-rotor induction motor is rated at 30 hp. Its equivalent circuit... | Python Code:
%pylab notebook
Explanation: Excercises Electric Machinery Fundamentals
Chapter 6
Problem 6-5
End of explanation
R1 = 0.10 # [Ohm]
R2 = 0.07 # [Ohm]
Xm = 10.0 # [Ohm]
X1 = 0.21 # [Ohm]
X2 = 0.21 # [Ohm]
Pfw = 500 # [W]
Pmisc = 0 # [W]
Pcore = 400 # [W]
V = 208 # [V]
Explanation: ... |
11,331 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tasa atractiva mínima (MARR)
Juan David Velásquez Henao
jdvelasq@unal.edu.co
Universidad Nacional de Colombia, Sede Medellín
Facultad de Minas
Medellín, Colombia
Haga click aquí para accede... | Python Code:
# Importa la librería financiera.
# Solo es necesario ejecutar la importación una sola vez.
import cashflows as cf
Explanation: Tasa atractiva mínima (MARR)
Juan David Velásquez Henao
jdvelasq@unal.edu.co
Universidad Nacional de Colombia, Sede Medellín
Facultad de Minas
Medellín, Colombia
Haga click aquí ... |
11,332 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Machine Learning Engineer Nanodegree
Deep Learning
Project
Step3: Preprocess data
Step6: Find path names of files and prepare one-hot encoder
Step13: Load images and labels into ar... | Python Code:
from urllib.request import urlretrieve
import tarfile
from os.path import isdir, isfile
from os import remove
def folder_file_name(urlpath):
Takes a URL and returns the characters after the final '/' as
the filename. In the filename, everything up until the first
period is declared to be ... |
11,333 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Shifty Lines
Step1: Let's first load our first example spectrum
Step2: Next, we're going to need the lines we're interested in. Let's use the Silicon lines. Note that these are all in elec... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context("notebook", font_scale=2.5, rc={"axes.labelsize": 26})
sns.set_style("darkgrid")
plt.rc("font", size=24, family="serif", serif="Computer Sans")
plt.rc("text", usetex=True)
import cPickle as pickle
import numpy as np
im... |
11,334 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 1
Step1: Essential Libraries and Tools
NumPy
Step2: SciPy
Step3: Usually it isn't possible to create dense representations of sparse data (they won't fit in memory), so we need to... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import mglearn
from IPython.display import display
%matplotlib inline
Explanation: Chapter 1: Introduction
End of explanation
import numpy as np
x = np.array([[1,2,3],[4,5,6]])
print("x:\n{}".format(x))
Explanation: Essential Libraries ... |
11,335 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compare the RG-Drude and Mie scattering cross-sections
Step1: Set up grain size distributions and materials
Step2: Set up the three grain scattering models
The <code>ss.makeScatModel()</co... | Python Code:
from astrodust import distlib
from astrodust.extinction import sigma_scat as ss
import astrodust.constants as c
NH, d2g = 1.e21, 0.009
MDUST = NH * c.m_p * d2g
ERANGE = np.logspace(-0.6,1.0,20)
Explanation: Compare the RG-Drude and Mie scattering cross-sections
End of explanation
RHO_SIL, RHO_GRA, RHO_... |
11,336 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Implementing a Neural Network
In this exercise we will develop a neural network with fully-connected layers to perform classification, and test it out on the CIFAR-10 dataset.
Step2: ... | Python Code:
# A bit of setup
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.neural_net import TwoLayerNet
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for aut... |
11,337 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import the Python API module and Instantiate the GIS object
Import the Python API
Step1: Create an GIS object instance using the account currently logged in through ArcGIS Pro
Step2: Get a... | Python Code:
import arcgis
Explanation: Import the Python API module and Instantiate the GIS object
Import the Python API
End of explanation
gis_retail = arcgis.gis.GIS('Pro')
Explanation: Create an GIS object instance using the account currently logged in through ArcGIS Pro
End of explanation
trade_area_itemid = 'bf36... |
11,338 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Disaggregation - Hart Active and Reactive data
Customary imports
Step1: Show versions for any diagnostics
Step2: Load dataset
Step3: Period of interest 4 days during holiday
No human acti... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
from os.path import join
from pylab import rcParams
import matplotlib.pyplot as plt
rcParams['figure.figsize'] = (13, 6)
plt.style.use('ggplot')
#import nilmtk
from nilmtk import DataSet, TimeFrame, MeterGroup, HDFDataStore
from nilmtk.disaggregate.... |
11,339 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CycleGAN
Author
Step1: Prepare the dataset
In this example, we will be using the
horse to zebra
dataset.
Step2: Create Dataset objects
Step3: Visualize some samples
Step5: Building block... | Python Code:
import os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow_addons as tfa
import tensorflow_datasets as tfds
tfds.disable_progress_bar()
autotune = tf.data.AUTOTUNE
Explanation: CycleGAN
Author: A_K_... |
11,340 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Annotated PMI Keywords with Categories
In this notebook we evaluate the differences in PMI keywords for each gender. We load the data from the previous notebooks; recall that we load PMI dat... | Python Code:
import pandas as pd
import re
import numpy as np
import dbpedia_config
from scipy.stats import chisquare
target_folder = dbpedia_config.TARGET_FOLDER
Explanation: Annotated PMI Keywords with Categories
In this notebook we evaluate the differences in PMI keywords for each gender. We load the data from the p... |
11,341 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analysis on the Movie Lens dataset using pandas
I am creating the notebook for the mini project for course DSE200x - Python for Data Science on edX. The project requires each participant to ... | Python Code:
# The first step is to import the dataset into a pandas dataframe.
import pandas as pd
#path = 'C:/Users/hrao/Documents/Personal/HK/Python/ml-20m/ml-20m/'
path = '/Users/Harish/Documents/HK_Work/Python/ml-20m/'
movies = pd.read_csv(path+'movies.csv')
movies.shape
tags = pd.read_csv(path+'tags.csv')
tags.s... |
11,342 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id='top'> </a>
Author
Step1: Formatting for PyUnfold use
Table of contents
Define analysis free parameters
Data preprocessing
Fitting random forest
Fraction correctly identified
Spectrum... | Python Code:
%load_ext watermark
%watermark -u -d -v -p numpy,matplotlib,scipy,pandas,sklearn,mlxtend
Explanation: <a id='top'> </a>
Author: James Bourbeau
End of explanation
from __future__ import division, print_function
import os
from collections import defaultdict
import numpy as np
from scipy.sparse import block_d... |
11,343 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Regression
In this note, I am going to train a linear regression model with gradient decent estimation.
It look pretty easy but it's helpful to increase the understanding modeling whi... | Python Code:
import numpy
import matplotlib.pyplot as plt
%matplotlib inline
numpy.random.seed(seed=1)
x = numpy.random.uniform(0, 1, 20)
# real model
def f(x): return x * 2
noise_variance = 0.2 # Variance of the gaussian noise
# Gaussian noise error for each sample in x
noise = numpy.random.randn(x.shape[0]) * noi... |
11,344 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Calculating r2 score of machine learning model
| Python Code::
model.score(x_test, y_test)
|
11,345 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Transfer Learning
In the field of deep learning, transfer learning is defined as the conveyance of knowledge from one pretrained model to a new model. This simply mean... | Python Code:
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribute... |
11,346 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="http
Step1: Single Risk Factor
The example is based on a single risk factor, a geometric_brownian_motion object.
Step2: American Put Option
We also model only a single derivative... | Python Code:
from dx import *
import time
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
%matplotlib inline
Explanation: <img src="http://hilpisch.com/tpq_logo.png" alt="The Python Quants" width="45%" align="right" border="4">
Parallel Valuation of Large Portfolios
Derivatives (portfolio) valuation by... |
11,347 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Play with some basic functions adapted from tide data functions
Query Builder
Step3: Offset Generator
Step5: Query Generator
TODO
refactor with a decorator
make key an attribute tha... | Python Code:
def query_builder(start_dt, end_dt, station, offset= 1):
Function accepts: a start and end datetime string in the form 'YYYYMMDD mm:ss'
which are <= 1 year apart, a station ID, and an offset.
Function assembles a query parameters/arguments dict and returns an API query and the
query dicti... |
11,348 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy Exercise 4
Imports
Step1: Complete graph Laplacian
In discrete mathematics a Graph is a set of vertices or nodes that are connected to each other by edges or lines. If those edges don... | Python Code:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
Explanation: Numpy Exercise 4
Imports
End of explanation
import networkx as nx
K_5=nx.complete_graph(5)
nx.draw(K_5)
Explanation: Complete graph Laplacian
In discrete mathematics a Graph is a set of vertices or node... |
11,349 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Build names mapping
To make it a little easier to check that I'm using the correct guids, construct a mapping from names back to guid.
Note
Step1: Pikov sprite editor classes
These classes ... | Python Code:
names = {}
for node in graph:
for edge in node:
if edge.guid == "169a81aefca74e92b45e3fa03c7021df":
value = node[edge].value
if value in names:
raise ValueError('name: "{}" defined twice'.format(value))
names[value] = node
names["ctor"]
... |
11,350 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: BERT Question Answer with TensorFlow Lite Model Maker
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="htt... | 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... |
11,351 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
+
Word Count Lab
Step2: (1b) Pluralize and test
Let's use a map() transformation to add the letter 's' to each string in the base RDD we just created. We'll define a Python function that ... | Python Code:
wordsList = ['cat', 'elephant', 'rat', 'rat', 'cat']
wordsRDD = sc.parallelize(wordsList, 4)
# Print out the type of wordsRDD
print type(wordsRDD)
Explanation: +
Word Count Lab: Building a word count application
This lab will build on the techniques covered in the Spark tutorial to develop a simple word c... |
11,352 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
====================================================
How to convert 3D electrode positions to a 2D image.
====================================================
Sometimes we want to convert a ... | Python Code:
# Authors: Christopher Holdgraf <choldgraf@berkeley.edu>
#
# License: BSD (3-clause)
from scipy.io import loadmat
import numpy as np
from matplotlib import pyplot as plt
from os import path as op
import mne
from mne.viz import ClickableImage # noqa
from mne.viz import (plot_alignment, snapshot_brain_monta... |
11,353 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas 入門
Pythonを使ったデータ解析入門 3idea | OpenBook を見ながら、Pandasの基本的な操作を写経してなれる
Pandas 基本操作
https
Step1: Series
ドキュメント
Step2: DataFrame
ドキュメント
Step3: 第3章 Pandas | Python Code:
# numpy と pandas を import する。np, pd と書くのは慣習っぽい
import numpy as np
import pandas as pd
Explanation: Pandas 入門
Pythonを使ったデータ解析入門 3idea | OpenBook を見ながら、Pandasの基本的な操作を写経してなれる
Pandas 基本操作
https://openbook4.me/projects/183/sections/777
End of explanation
# Series
# 軸にラベルを付けた1次元の配列
print(pd.Series([1,2,4]))
# 値と... |
11,354 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a name="top"></a>
<div style="width
Step1: <a name="multipanel"></a>
Multi-panel Plots
Often we wish to create figures with multiple panels of data. It's common to separate variables of di... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, DayLocator
from siphon.simplewebservice.ndbc import NDBC
%matplotlib inline
# Read in some data
df = NDBC.realtime_observations('42039')
# Trim to the last 7 days
df = df[df['time'] > (pd.Timestamp.utcnow() - pd... |
11,355 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generative Adversarial Networks
Generative Adversarial Networks are invented by Ian Goodfellow (https
Step1: MNIST database
The MNIST database (Modified National Institute of Standards and ... | Python Code:
import numpy as np
from keras.datasets import mnist
import keras
from keras.layers import Input, UpSampling2D, Conv2DTranspose, Conv2D, LeakyReLU
from keras.layers.core import Reshape,Dense,Dropout,Activation,Flatten
from keras.models import Sequential
from keras.optimizers import RMSprop, Adam
from tensor... |
11,356 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Module 10
Step1: Ratio and logarithm
If you use linear scale to visualize ratios, it can be quite misleading.
Let's first create some ratios.
Step2: Q
Step3: Q
Step4: Log-binning
Let's f... | Python Code:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
import scipy.stats as ss
import vega_datasets
Explanation: Module 10: Logscale
End of explanation
x = np.array([1, 1, 1, 1, 10, 100, 1000])
y = np.array([1000, 100, 10, 1, 1, 1, 1 ])
ratio = x/y
print(ra... |
11,357 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Manipulation with Numpy and Pandas
Handling with large data is easy in Python. In the simplest way using arrays. However, they are pretty slow. Numpy and Panda are two great libraries f... | Python Code:
import numpy as np
# Generating a random array
X = np.random.random((3, 5)) # a 3 x 5 array
print(X)
Explanation: Data Manipulation with Numpy and Pandas
Handling with large data is easy in Python. In the simplest way using arrays. However, they are pretty slow. Numpy and Panda are two great libraries for... |
11,358 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Star catalogue analysis
Thanks to UCF Physics undergrad Tyler Townsend for contributing to the development of this notebook.
Step1: Getting the data
Step2: Star map
Step3: Let's Graph a C... | Python Code:
# Import modules that contain functions we need
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
Explanation: Star catalogue analysis
Thanks to UCF Physics undergrad Tyler Townsend for contributing to the development of this notebook.
End of explanation
# Read in da... |
11,359 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
Run this cell to set everything up!
Step1: One advantage linear regression has over more complicated algorithms is that the models it creates are explainable -- it's easy to in... | Python Code:
# Setup feedback system
from learntools.core import binder
binder.bind(globals())
from learntools.time_series.ex1 import *
# Setup notebook
from pathlib import Path
from learntools.time_series.style import * # plot style settings
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
impor... |
11,360 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sebastian Raschka, 2015
https
Step1: <br>
<br>
Overview
Streamlining workflows with pipelines
Loading the Breast Cancer Wisconsin dataset
Combining transformers and estimators in a pipeline... | Python Code:
%load_ext watermark
%watermark -a 'Sebastian Raschka' -u -d -v -p numpy,pandas,matplotlib,scikit-learn
# to install watermark just uncomment the following line:
#%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py
Explanation: Sebastian Raschka, 2015
https://github.com/rasbt/... |
11,361 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Read in catalog information from a text file and plot some parameters
Authors
Adrian Price-Whelan, Kelle Cruz, Stephanie T. Douglas
Learning Goals
Read an ASCII file using astropy.io
Convert... | Python Code:
import numpy as np
# Set up matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Read in catalog information from a text file and plot some parameters
Authors
Adrian Price-Whelan, Kelle Cruz, Stephanie T. Douglas
Learning Goals
Read an ASCII file using astropy.io
Convert between repre... |
11,362 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Description of Melbourne Dataset
Load Data
Compute POI Statistics DataFrame
Compute POI Visit Statistics
Visualise & Save POIs
POI vs Photo
POIs with NO Visits
Photo Clusters without Corresp... | Python Code:
% matplotlib inline
import os, sys, time, pickle, tempfile
import math, random, itertools
import pandas as pd
import numpy as np
from joblib import Parallel, delayed
from scipy.misc import logsumexp
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import K... |
11,363 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Add Multiple Layers
In this example, three Layers are added to a Map. Notice the draw order and default symbology for each.
For more information, run help(Layer)
Step1: Using default legend... | Python Code:
from cartoframes.auth import set_default_credentials
from cartoframes.viz import Map, Layer
set_default_credentials('cartoframes')
Map([
Layer('countries'),
Layer('global_power_plants'),
Layer('world_rivers')
])
Explanation: Add Multiple Layers
In this example, three Layers are added to a Map. ... |
11,364 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Preparing the reads
[Loose et al] published their raw read files on ENA. This script uses four of these sets which contain reads of amplicons. These were processed using different "read unti... | Python Code:
%load_ext autoreload
%autoreload 2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn
import porekit
import re
import pysam
import random
import feather
%matplotlib inline
Explanation: Preparing the reads
[Loose et al] published their raw read files on ENA. This script us... |
11,365 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Script to Process the Sensor Readings - ProcessSensorReadings.py
Overview
Step2: The "writeLumbarReadings" method takes the rdd received from Spark Streaming as an input. It then ex... | Python Code:
import json
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.functions import explode
from pyspark.ml.feature import VectorAssembler
from pyspark.mllib.tree import RandomForest,... |
11,366 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
JupyterWorkflow
From exploratory analysis to reproducible research
Mehmetcan Budak
Step1: Look for Annual Trend; growth-decline over ridership
Let's try a rolling window. Over 365 days roll... | Python Code:
URL = "https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD"
from urllib.request import urlretrieve
urlretrieve(URL, "Fremont.csv")
!head Freemont.csv
import pandas as pd
data = pd.read_csv("Fremont.csv")
data.head()
data = pd.read_csv("Fremont.csv", index_col="Date", parse_dates=True)... |
11,367 | Given the following text description, write Python code to implement the functionality described.
Description:
Count composite fibonacci numbers from given array
Python3 program to implement the above approach ; Function to find all Fibonacci numbers up to Max ; Store all Fibonacci numbers upto Max ; Stores previous el... | Python Code:
import math
def createhashmap(Max ) :
hashmap = { ""}
curr = 1
prev = 0
hashmap . add(prev )
while(curr <= Max ) :
hashmap . add(curr )
temp = curr
curr = curr + prev
prev = temp
return hashmap
def SieveOfEratosthenes(Max ) :
isPrime =[1 for x in range(Max + 1 ) ]
isPrime... |
11,368 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this tutorial we will show how to access and navigate the Iteration/Expression Tree (IET) rooted in an Operator.
Part I - Top Down
Let's start with a fairly trivial example. First of all,... | Python Code:
from devito import configuration
configuration['opt'] = 'noop'
configuration['language'] = 'C'
Explanation: In this tutorial we will show how to access and navigate the Iteration/Expression Tree (IET) rooted in an Operator.
Part I - Top Down
Let's start with a fairly trivial example. First of all, we disab... |
11,369 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Loading file and basic information
Step1: Print some basic information about the grid
Step2: List all fields in this plot file
Step3: List all derived fields in the plot file
Step4: W... | Python Code:
import yt
ds = yt.load('/home/ychen/d9/2018_production_runs/20180802_L438_rc10_beta07/data/Group_L438_hdf5_plt_cnt_0100')
print(ds.parameters['run_comment'])
Explanation: 1. Loading file and basic information
End of explanation
ds.print_stats()
Explanation: Print some basic information about the grid
End o... |
11,370 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook shows how BigBang can help you analyze the senders in a particular mailing list archive.
First, use this IPython magic to tell the notebook to display matplotlib graphics inlin... | Python Code:
%matplotlib inline
Explanation: This notebook shows how BigBang can help you analyze the senders in a particular mailing list archive.
First, use this IPython magic to tell the notebook to display matplotlib graphics inline. This is a nice way to display results.
End of explanation
import bigbang.mailman a... |
11,371 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Indexing and Selection
| Operation | Syntax | Result |
|-------------------------------|----------------|-----------|
| Select column | df[col]... | Python Code:
import pandas as pd
import numpy as np
produce_dict = {'veggies': ['potatoes', 'onions', 'peppers', 'carrots'],'fruits': ['apples', 'bananas', 'pineapple', 'berries']}
produce_df = pd.DataFrame(produce_dict)
produce_df
Explanation: Indexing and Selection
| Operation | Syntax | R... |
11,372 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Operations on word vectors
Welcome to your first assignment of this week!
Because word embeddings are very computionally expensive to train, most ML practitioners will load a pre-trained se... | Python Code:
import numpy as np
from w2v_utils import *
Explanation: Operations on word vectors
Welcome to your first assignment of this week!
Because word embeddings are very computionally expensive to train, most ML practitioners will load a pre-trained set of embeddings.
After this assignment you will be able to:
... |
11,373 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Crash Course in Python for Scientists
Rick Muller, Sandia National Laboratories
version 0.62, Updated Dec 15, 2016 by Ryan Smith, Cal State East Bay
Using Python 3.5.2 | Anaconda 4.1.1
Th... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
Explanation: A Crash Course in Python for Scientists
Rick Muller, Sandia National Laboratories
version 0.62, Updated Dec 15, 2016 by Ryan Smith, Cal State East Bay
Using Python 3.5.2 | Anaconda 4.1.1
This work is licensed under a Creati... |
11,374 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Character-Level LSTM in PyTorch
In this notebook, I'll construct a character-level LSTM with PyTorch. The network will train character by character on some text, then generate new text chara... | Python Code:
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
Explanation: Character-Level LSTM in PyTorch
In this notebook, I'll construct a character-level LSTM with PyTorch. The network will train character by character on some text, then generate new text character by character. ... |
11,375 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Marvin query Results
Now that you have performed your first query, let's take at what Marvin returns as a Marvin Results object.
Step1: Let's look at the Marvin Results object. We can see ... | Python Code:
from marvin import config
config.setRelease('MPL-4')
from marvin.tools.query import Query, Results, doQuery
# make a query
myquery = 'nsa.sersic_logmass > 10.3 AND nsa.z < 0.1'
q = Query(searchfilter=myquery)
# run a query
r = q.run()
Explanation: Marvin query Results
Now that you have performed your fir... |
11,376 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GeoPyMC Simulation Tutorial
Step1: Initializing the Class
First we need to create the GeoPyMC_sim object providing a name for the simulation project.
Step2: The first thing we need to do i... | Python Code:
import sys, os
sys.path.append(r"C:\Users\Miguel\workspace\pygeomod\pygeomod")
import geoPyMC
import pymc as pm
import numpy as np
import geogrid
import matplotlib.pyplot as plt
reload (geoPyMC)
%matplotlib inline
Explanation: GeoPyMC Simulation Tutorial
End of explanation
GeoBay = geoPyMC.GeoPyMC_sim("exa... |
11,377 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
============================================================
Define target events based on time lag, plot evoked response
============================================================
This sc... | Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne import io
from mne.event import define_target_events
from mne.datasets import sample
import matplotlib.pyplot as plt
print(__doc__)
data_path = sample.data_path()
Explanation: ==============================... |
11,378 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hidden Markov Models (HMMs) are powerful, flexible methods for representing and classifying data with trends over time, and have been a key component in speech recognition systems for many y... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from utils import progress_bar_downloader
import os
#Hosting files on my dropbox since downloading from google code is painful
#Original project hosting is here: https://code.google.com/p/hmm-speech-recognition/downloads/list
#Audio is i... |
11,379 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
how to load a custom pretrained model and make predictions using the model
| Python Code::
import tensorflow as tf
model = tf.keras.models.load_model('filename')
pred = model.predict(X_val)
|
11,380 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Feature Columns
Learning Objectives
Load a CSV file using Pandas
Create an input pipeline using tf.data
Create multiple types of feature columns
Introduction
In this notebook... | Python Code:
# You can use any Python source file as a module by executing an import statement in some other Python source file.
# The import statement combines two operations; it searches for the named module, then it binds the results of that search
# to a name in the local scope.
import numpy as np
import pandas as ... |
11,381 | 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', 'bnu', 'sandbox-3', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: BNU
Source ID: SANDBOX-3
Topic: Seaice
Sub-Topics: Dynamics, Thermodynamics,... |
11,382 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
network(), radar() and site() objects
This notebook introduces the high-level python interface with the radar.dat and hdw.dat content.
For more in-depth access (i.e., your own hdw.dat), lo... | Python Code:
# Import radar module
%pylab inline
from davitpy.pydarn.radar import *
Explanation: network(), radar() and site() objects
This notebook introduces the high-level python interface with the radar.dat and hdw.dat content.
For more in-depth access (i.e., your own hdw.dat), look at the radInfoIO module:
radI... |
11,383 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
Machine learning literature makes heavy use of probabilistic graphical models
and bayesian statistics. In fact, state of the art (SOTA) architectures, such as
[variational autoe... | Python Code:
x1 = np.random.uniform(size=500)
x2 = np.random.uniform(size=500)
fig = plt.figure();
ax = fig.add_subplot(1,1,1);
ax.scatter(x1,x2, edgecolor='black', s=80);
ax.grid();
ax.set_axisbelow(True);
ax.set_xlim(-0.25,1.25); ax.set_ylim(-0.25,1.25)
ax.set_xlabel('Pixel 2'); ax.set_ylabel('Pixel 1'); plt.savefig(... |
11,384 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
Glossary
2. Mathematical Groundwork
Previous
Step1: Import section specific modules
Step4: Convolution
Definition of the convolution
Properties of the convolution
Convolution examp... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import HTML
HTML('../style/course.css') #apply general CSS
Explanation: Outline
Glossary
2. Mathematical Groundwork
Previous: 2.4 The Fourier Transform
Next: 2.6 Cross-correlation and auto-correlation
Import standar... |
11,385 | 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... |
11,386 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have a raster with a set of unique ID patches/regions which I've converted into a two-dimensional Python numpy array. I would like to calculate pairwise Euclidean distances betwee... | Problem:
import numpy as np
import scipy.spatial.distance
example_array = np.array([[0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 2, 0, 2, 2, 0, 6, 0, 3, 3, 3],
[0, 0, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3],
[0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 3, 0],
... |
11,387 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
How can I perform regression in sklearn, using SVM and a polynomial kernel (degree=2)? | Problem:
import numpy as np
import pandas as pd
import sklearn
X, y = load_data()
assert type(X) == np.ndarray
assert type(y) == np.ndarray
# fit, then predict X
from sklearn.svm import SVR
svr_poly = SVR(kernel='poly', degree=2)
svr_poly.fit(X, y)
predict = svr_poly.predict(X) |
11,388 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: Assignments
Send in a rough outline of your project idea. This is not graded, I will ask for a more complete description later for inclusion in grading.
Plot the performance of the RC... | Python Code:
def plot_arm_frequency(simulation, ax, marker='.', linestyle='', color='k', label=''):
Plot the frequency with which the second arm is chosen
NOTE: Currently only works for two arms
ax.plot(simulation.arm_choice.mean(axis=0),
marker=marker, linestyle=linestyle, color=color, label=l... |
11,389 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy Exercise 4
Imports
Step1: Complete graph Laplacian
In discrete mathematics a Graph is a set of vertices or nodes that are connected to each other by edges or lines. If those edges don... | Python Code:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
Explanation: Numpy Exercise 4
Imports
End of explanation
import networkx as nx
K_5=nx.complete_graph(5)
nx.draw(K_5)
Explanation: Complete graph Laplacian
In discrete mathematics a Graph is a set of vertices or node... |
11,390 | Given the following text description, write Python code to implement the functionality described.
Description:
Maximum difference between node and its ancestor in a Directed Acyclic Graph ( DAG )
Python3 program for the above approach ; Function to perform DFS Traversal on the given graph ; Update the value of ans ; Up... | Python Code:
ans = 0
def DFS(src , Adj , arr , currentMin , currentMax ) :
global ans
ans = max(ans , max(abs(currentMax - arr[src - 1 ] ) , abs(currentMin - arr[src - 1 ] ) ) )
currentMin = min(currentMin , arr[src - 1 ] )
currentMax = min(currentMax , arr[src - 1 ] )
for child in Adj[src ] :
DFS(child... |
11,391 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Priprava podatkov
Najprej sem pri Gašperju v Blenderju narisal krivuljo. Dobil sem triangulacijo objekta. Odstranil sem stranice, ki se nahajajo v dveh trikotnikih in tako sem dobil zunanjos... | Python Code:
-
triangles = ((0, 1, 2),
(3, 4, 5),
(6, 7, 8),
(4, 9, 10),
(6, 8, 11),
(12, 3, 13),
(11, 8, 14),
(9, 15, 16),
(11, 14, 17),
(15, 18, 16),
(14, 19, 17),
(20, 21, 22),
(14, 23, 19),
(18, 24, 16),
(14, 25, 26),
(27, 28, 29),
(25, 30, 26),
(28, 31, 32),
(33, 19, 23),
(31, 34, 35),
(23, 14, 26),
(34... |
11,392 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; and to You under the Apache License, Version 2.0.
Classify images from MNIST using LeNet
D... | Python Code:
from __future__ import division
from builtins import zip
from builtins import str
from builtins import range
from past.utils import old_div
from future import standard_library
from __future__ import print_function
from tqdm import tnrange, tqdm_notebook
standard_library.install_aliases()
import pickle, gzi... |
11,393 | 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... |
11,394 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tests for the Bootstrap code
Step1: Generate test files
Step2: b camera
Arcs
Step3: Flats
Step4: Test via script
desi_bootcalib.py \
--fiberflat /Users/xavier/DESI/Wavelengths/pix-su... | Python Code:
# import
Explanation: Tests for the Bootstrap code
End of explanation
def pix_sub(infil, outfil, rows=(80,310)):
hdu = fits.open(infil)
# Trim
img = hdu[0].data
sub_img = img[:,rows[0]:rows[1]]
# New
newhdu = fits.PrimaryHDU(sub_img)
# Header
for key in ['CAMERA','VSPECTER',... |
11,395 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulating DESI Spectra
The goal of this notebook is to demonstrate how to generate some simple DESI spectra using the quickgen utility. For simplicity we will only generate 1D spectra and ... | Python Code:
import os
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy.table import Table
import desispec.io
import desisim.io
from desisim.obs import new_exposure
from desisim.scripts import quickgen
from desispec.scripts import group_spectra
%pylab inline
Explanation: Simul... |
11,396 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Democracy and Economic Dvelopment
Michelle Sabbagh
Data Bootcamp Final Project
I. Overview
Central Research Question
Step1: Step Two
Step2: Step Three
Step3: Access just one level of the ... | Python Code:
%matplotlib inline
import pandas
import wbdata
import matplotlib.pyplot as plt
import seaborn as sns
Explanation: Democracy and Economic Dvelopment
Michelle Sabbagh
Data Bootcamp Final Project
I. Overview
Central Research Question: What is the relationship, if any, between a country’s level of freedo... |
11,397 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Inception-v3 Feature Extraction setup
Step1: Some Functions for working with Inception-v3
Step2: Putting it to use!
Step3: How about more than one image
If you put your images ... | Python Code:
import os
import tensorflow as tf
# import tensorflow.python.platform
from tensorflow.python.platform import gfile
import numpy as np
import pandas as pd
Explanation: TensorFlow Inception-v3 Feature Extraction setup:
Special thanks to KERNIX for their extremely helpful blog
http://www.kernix.com/blog/image... |
11,398 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Lattice estimators
In this tutorial, we will cover basics of TensorFlow Lattice estimators.
Step1: Synthetic dataset
Here we create a synthetic dataset.
Step2: DNN Estimator
Now... | Python Code:
# import libraries
!pip install tensorflow_lattice
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_lattice as tfl
import tempfile
from six.moves import urllib
Explanation: TensorFlow Lattice estimators
In this tutorial, we will cover basics of TensorFlow Lattice... |
11,399 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DO NOT FORGET TO DROP ISSUE_D AFTER PREPPING
Step1: Until I figure out a good imputation method (e.g. bayes PCA), just drop columns with null still
Step2: instantiate network
Step3: get t... | Python Code:
platform = 'lendingclub'
use_cuda = True
dtype = torch.cuda.FloatTensor
save_path = "model_dump/nn_1_0_0/"
store = pd.HDFStore(
dc.home_path+'/justin_tinkering/data_science/lendingclub/{0}_store.h5'.
format(platform),
append=True)
loan_info = store['train_filtered_columns']
columns = loan_info.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.