Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
9,300 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Drive-it DQN
Model
\begin{equation}
l_1 = relu( x W_1 + b_1) \
l_2 = relu( x W_2 + b_2) \
l_3 = relu( x W_3 + b_3) \
Q(s,a) = l_1 W_o + b_o \
\end{equation}
Step1: Visualization
We use PCA ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import seaborn as sns
style.use('ggplot')
%matplotlib inline
sns.set()
Explanation: Drive-it DQN
Model
\begin{equation}
l_1 = relu( x W_1 + b_1) \
l_2 = relu( x W_2 + b_2) \
l_3 = relu( x W_3 + b_3) \
Q(s,a) = l_1 W_o + b_o \
\... |
9,301 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NoSQL (MongoDB) (sesión 4)
Esta hoja muestra cómo acceder a bases de datos MongoDB y también a conectar la salida con Jupyter. Se puede utilizar el shell propio de MongoDB en la máquina virt... | Python Code:
!pip install --upgrade pymongo
from pprint import pprint as pp
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
%matplotlib inline
matplotlib.style.use('ggplot')
Explanation: NoSQL (MongoDB) (sesión 4)
Esta hoja muestra cómo acceder a bases de datos MongoDB y también a conectar la sali... |
9,302 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
3. ANOVA tables and post-hoc comparisons
<div class="alert alert-info"><h4>Note</h4><p>ANOVAs and post-hoc tests are only available for
Step1: Type III SS inferences will only be valid if ... | Python Code:
# import basic libraries and sample data
import os
import pandas as pd
from pymer4.utils import get_resource_path
from pymer4.models import Lmer
# IV3 is a categorical predictors with 3 levels in the sample data
df = pd.read_csv(os.path.join(get_resource_path(), "sample_data.csv"))
# # We're going to fit a... |
9,303 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
YouTube on Android
The goal of this experiment is to run Youtube videos on a Pixel device running Android and collect results.
Step1: Support Functions
This function helps us run our experi... | Python Code:
from conf import LisaLogging
LisaLogging.setup()
%pylab inline
import json
import os
# Support to access the remote target
import devlib
from env import TestEnv
# Import support for Android devices
from android import System, Screen, Workload
# Support for trace events analysis
from trace import Trace
# Su... |
9,304 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Goal
Follow-up to
Step1: BD min/max
Step2: Nestly
assuming fragments already simulated
Step3: Nestly params
Step4: Copying input files
Step5: Multi-window HR-SIP
Step6: Making confusio... | Python Code:
import os
import glob
import itertools
import nestly
%load_ext rpy2.ipython
%load_ext pushnote
%%R
library(ggplot2)
library(dplyr)
library(tidyr)
library(gridExtra)
Explanation: Goal
Follow-up to: atomIncorp_taxaIncorp
Determining the effect of 'heavy' BD window (number of windows & window sizes) on HR-SIP... |
9,305 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Elasticity in 2D
Introduction
This example provides a demonstration of using PyMKS to compute the linear strain field for a two-phase composite material. The example introduces the go... | Python Code:
import pymks
%matplotlib inline
%load_ext autoreload
%autoreload 2
import numpy as np
import matplotlib.pyplot as plt
n = 21
from pymks.tools import draw_microstructures
from pymks.datasets import make_delta_microstructures
X_delta = make_delta_microstructures(n_phases=2, size=(n, n))
draw_microstructures(... |
9,306 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
0) Critique the most important figure from a seminal paper in your field. Provide the original figure/caption. In your own words, what story is this figure trying to convey? What does it do ... | Python Code:
data = pd.read_table("hw_2_data/ay250.txt", sep="\t")
data.head()
np.shape(data)
fig = plt.figure()
ax = fig.add_subplot(111)
colors = ["red", "green", "blue", "black"]
linestyles = ["--", "-"]
for i, col in enumerate(data.columns):
ax.plot(np.arange(50)/5, data[col], label = col, color = colors[i%4], ... |
9,307 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Some notes
should rename the tables consistently
e.g. dfsummary, dfdata, dfinfo, dfsteps, dffid
have to take care so that it also can read "old" cellpy-files
should make (or check if it is a... | Python Code:
my_data.make_step_table()
filename2 = Path("/Users/jepe/Arbeid/Data/celldata/20171120_nb034_11_cc.nh5")
my_data.save(filename2)
print(f"size: {filename2.stat().st_size/1_048_576} MB")
my_data2 = cellreader.CellpyData()
my_data2.load(filename2)
dataset2 = my_data2.dataset
print(dataset2.steps.columns)
del m... |
9,308 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lineare Diskriminanzanalyse
Araz, Hasenklever, Pede
Laden von Bibliotheken
Step1: Laden der Merkmalsmatrix
und Vorverarbeitung von Zeilen und Spalten nach Anzahl von NaNs und stark korrelie... | Python Code:
%reload_ext autoreload
%autoreload 2
import numpy as np
import os
import pandas as pd
import random
import scipy
from scipy.stats import zscore
# interactive
from ipywidgets.widgets import interact, IntSlider, FloatSlider
from IPython.display import display
from sklearn.discriminant_analysis import LinearD... |
9,309 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stability map with MEGNO and WHFast
In this tutorial, we'll create a stability map of a two planet system using the chaos indicator MEGNO (Mean Exponential Growth of Nearby Orbits) and the s... | Python Code:
def simulation(par):
a, e = par # unpack parameters
sim = rebound.Simulation()
sim.integrator = "whfast"
sim.integrator_whfast_safe_mode = 0
sim.dt = 5.
sim.add(m=1.) # Star
sim.add(m=0.000954, a=5.204, M=0.600, omega=0.257, e=0.048)
sim.add(m=0.000285, a=a, M=0.871, omega=1... |
9,310 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setup
Step1: Background
Recall that the simplistic measurement equation can be defined as follows
Step2: The effect of a large range of w values is apparent from the equation for phase err... | Python Code:
%install_ext https://raw.githubusercontent.com/mkrphys/ipython-tikzmagic/master/tikzmagic.py
%load_ext tikzmagic
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
Explanation: Setup
End of explanation
%%tikz --scale 2 --size 600,600 -f png
\draw [black, domain=0:180] plot ({2*cos(\... |
9,311 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook was used for developing a script to translate MagIC format files from the 2.5 data format to the 3.0 format. This functionality is now implemented in Pmag GUI.
Getting start... | Python Code:
from importlib import reload
import pmagpy.contribution_builder as cb
from pmagpy import ipmag
import os
import json
import numpy as np
import sys
import pandas as pd
import numpy as np
from pandas import DataFrame
from pmagpy import builder2 as builder
from pmagpy import validate_upload2 as validate_uploa... |
9,312 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning Introduction
Step1: References
Step2: Conditional statements
Step3: Loops
Step4: Data structures
Step5: Pandas basics
Step6: House Sales in King County, USA
Dataset fe... | Python Code:
from IPython.display import Image, display, HTML
Image("images/munich.jpg")
display(HTML("<table><tr><td><p><b>Rain Princess - Leonid Afremov</b></p><img src='images/princess.jpeg'></td><td><b><p>Munich + Rain Princess + Machine Learning</b></p><img src='images/munich-princess-out.jpg'></td></tr></table>")... |
9,313 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
Step1: Set Path Information
Step2: Livneh Domain File
Along with the VIC model parameters, we also need a domain file that describes the spatial extent and active grid cells in th... | Python Code:
%matplotlib inline
import os
import getpass
from datetime import datetime
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
# For more information on tonic, see: https://github.com/UW-Hydro/tonic/
import tonic.models.vic.grid_params as gp
# Metadata to be used later
user = getpass.getu... |
9,314 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Datapot Usage Examples
Step1: Dataset with timestamp features extraction.
Convert CSV file to JSON lines
Step2: Creating the DataPot object.
Step3: Let's call the fit method. It automatic... | Python Code:
import datapot as dp
from datapot import datasets
import pandas as pd
from __future__ import print_function
import sys
import bz2
import time
import xgboost as xgb
from sklearn.model_selection import cross_val_score
import datapot as dp
from datapot.utils import csv_to_jsonlines
Explanation: Datapot Usage ... |
9,315 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ubrzavanje Pythona
Step1: Katkada korištenje Numpy-a ne daje dovoljno ubrzanje, ili je teško/nespretno vektorizirati kod. Tada postoji više opcija
spori dio koda (koji dio koda je spor može... | Python Code:
from IPython.display import Image
Image("https://raw.github.com/jrjohansson/scientific-python-lectures/master/images/optimizing-what.png")
Explanation: Ubrzavanje Pythona
End of explanation
# olakšava rad u Cythonu u IPythonu
%load_ext Cython
a=10
b=20
Explanation: Katkada korištenje Numpy-a ne daje dovolj... |
9,316 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2.3
Step1: CI for continuous data, Pg 18
Step2: Numpy uses a denominator of N in the standard deviation calculation by
default, instead of N-1. To use N-1, the unbiased estimator-- and to
... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# use matplotlib style sheet
plt.style.use('ggplot')
Explanation: 2.3: Classical confidence intervals
End of explanation
# import the t-distribution fr... |
9,317 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sorting a List of Dictionaries by a Common Key
Problem
Sort the entries according to one or more of the dictionary values.
Solution
Sorting this type of structure is easy using the operator ... | Python Code:
from operator import itemgetter
rows_by_fname = sorted(rows, key=itemgetter('fname'))
rows_by_uid = sorted(rows, key=itemgetter('uid'))
rows_by_fname
rows_by_uid
Explanation: Sorting a List of Dictionaries by a Common Key
Problem
Sort the entries according to one or more of the dictionary values.
Solution... |
9,318 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistic Regression with a Neural Network mindset
Welcome to your first (required) programming assignment! You will build a logistic regression classifier to recognize cats. This assignment... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset
%matplotlib inline
Explanation: Logistic Regression with a Neural Network mindset
Welcome to your first (required) programming assignment! You will b... |
9,319 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Introduction-to-Outlier-Mitigation" data-toc-modified-id="Introduction-to-Outlier-Mitigation-1"><span class="toc-item-num">1 &n... | Python Code:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import scipy as scipy
from matplotlib import rc
# set to use tex, but make sure it is sans-serif fonts only
rc('text', usetex=True)
rc('text.latex', preamble=r'\usepackage{cmbright}')
rc('font', **{'family': '... |
9,320 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Plots
Step1: Duncan's Prestige Dataset
Load the Data
We can use a utility function to load any R dataset available from the great <a href="https
Step2: Influence plots
Influence... | Python Code:
%matplotlib inline
from statsmodels.compat import lzip
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.formula.api import ols
plt.rc("figure", figsize=(16, 8))
plt.rc("font", size=14)
Explanation: Regression Plots
End of explanation
prestige = sm.datasets.ge... |
9,321 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Auto-caption
Date
Step1: Read file
Step2: Access data of multiIndex dataframe
pandas, how to access multiIndex dataframe?
Step3: Dataframe that i want to match
Step5: string matching fun... | Python Code:
# system
import os
import sys
# 3rd party lib
import pandas as pd
from sklearn.cluster import KMeans
from fuzzywuzzy import fuzz # stirng matching
print('Python verison: {}'.format(sys.version))
print('\n############################')
print('Pandas verison: {}'.format(pd.show_versions()))
Explanation: Auto... |
9,322 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time Series Prediction with BQML and AutoML
Objectives
1. Learn how to use BQML to create a classification time-series model using CREATE MODEL.
2. Learn how to use BQML to create a linear... | Python Code:
PROJECT = !(gcloud config get-value core/project)
PROJECT = PROJECT[0]
%env PROJECT = {PROJECT}
%env REGION = "us-central1"
Explanation: Time Series Prediction with BQML and AutoML
Objectives
1. Learn how to use BQML to create a classification time-series model using CREATE MODEL.
2. Learn how to use BQM... |
9,323 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
'orb' Datasets and Options
Setup
Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't ... | Python Code:
!pip install -I "phoebe>=2.1,<2.2"
Explanation: 'orb' Datasets and Options
Setup
Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release).
End of explanation
%matplotlib... |
9,324 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bipartite node layout
By default, nodes are partitioned into two subsets using a two-coloring of the graph.
The median heuristic proposed in Eades & Wormald (1994) is used to reduce edge cro... | Python Code:
import matplotlib.pyplot as plt
from netgraph import Graph
edges = [
(0, 1),
(1, 2),
(2, 3),
(3, 4),
(5, 6)
]
Graph(edges, node_layout='bipartite', node_labels=True)
plt.show()
Explanation: Bipartite node layout
By default, nodes are partitioned into two subsets using a two-coloring of ... |
9,325 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification problems are a broad category of machine learning problems that involve the prediction of values taken from a discrete, finite number of cases.
In this example, we'll build a... | Python Code:
import pandas as pd
iris = pd.read_csv('../datasets/iris.csv')
# Print some info and statistics about the dataset
iris.info()
iris.Class.unique()
iris.describe()
# Encode the classes to numeric values
class_encodings = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2}
iris.Class = iris.Class.ma... |
9,326 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SciPy를 사용한 기초적인 검정
SciPy 파이썬 패키지는 다음과 같은 다양한 검정 명령을 제공한다.
이항 검정 (Binomial test)
카이 제곱 검정 (Chi-square test)
단일 표본 z-검정 (One-sample z-test)
단일 표본 t-검정 (One-sample t-test)
독립 표본 t-검정 (Independe... | Python Code:
N = 10
theta_0 = 0.5
np.random.seed(0)
x = sp.stats.bernoulli(theta_0).rvs(N)
n = np.count_nonzero(x)
n
sp.stats.binom_test(n, N)
Explanation: SciPy를 사용한 기초적인 검정
SciPy 파이썬 패키지는 다음과 같은 다양한 검정 명령을 제공한다.
이항 검정 (Binomial test)
카이 제곱 검정 (Chi-square test)
단일 표본 z-검정 (One-sample z-test)
단일 표본 t-검정 (One-sample t-t... |
9,327 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting Started
To begin with, cobrapy comes with bundled models for Salmonella and E. coli, as well as a "textbook" model of E. coli core metabolism. To load a test model, type
Step1: The ... | Python Code:
from __future__ import print_function
import cobra.test
# "ecoli" and "salmonella" are also valid arguments
model = cobra.test.create_test_model("textbook")
Explanation: Getting Started
To begin with, cobrapy comes with bundled models for Salmonella and E. coli, as well as a "textbook" model of E. coli cor... |
9,328 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re going ... |
9,329 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 Google LLC. Licensed under the Apache License, Version 2.0 (the "License");
Open Buildings - spatial analysis examples
This notebook demonstrates some analysis methods with Op... | 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... |
9,330 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EEG source localization given electrode locations on an MRI
This tutorial explains how to compute the forward operator from EEG data
when the electrodes are in MRI voxel coordinates.
Ste... | Python Code:
# Authors: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD Style.
import os.path as op
import nibabel
from nilearn.plotting import plot_glass_brain
import numpy as np
import mne
from mne.channels import compute_native_head_t, read_custom_montage
from mne.viz import plot_alignment
Explanation: EEG so... |
9,331 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Finding Correlations in a CSV of Malware Events via Hypergraph Views
To find patterns and outliers in CSVs and event data, Graphistry provides the hypergraph transform.
As an example, this ... | Python Code:
import pandas as pd
import graphistry as g
# To specify Graphistry account & server, use:
# graphistry.register(api=3, username='...', password='...', protocol='https', server='hub.graphistry.com')
# For more options, see https://github.com/graphistry/pygraphistry#configure
df = pd.read_csv('./barncat.1k.c... |
9,332 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Below are examples of the theorems proved in Kleinberg's paper (https
Step1: 1. K-Cluster Stopping Condition - Fails Richness Condition
k-cluster stopping condition
Step2: Given these inpu... | Python Code:
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
data, labels = make_blobs(n_samples=10, n_features=2, centers=2,cluster_std=3,random_state=5)
plt.scatter(data[:,0], data[:,1], c = labels, cmap='coolwarm');
Explanation: Below are examples of ... |
9,333 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CCSDT theory for a closed-shell reference
In this notebook we will use wicked to generate equations for the CCSDT method
Step2: ```python
def evaluate_residual_0_0(H,T)
Step3: Prepare inte... | Python Code:
import wicked as w
import psi4
import forte
import forte.utils
from forte import forte_options
import numpy as np
import time
w.reset_space()
w.add_space("o", "fermion", "occupied", ["i", "j", "k", "l", "m", "n"])
w.add_space("v", "fermion", "unoccupied", ["a", "b", "c", "d", "e", "f"])
Top = w.op("T", ["v... |
9,334 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step 1
Step1: Step 2 | Python Code:
mnist = input_data.read_data_sets('/data/mnist', one_hot=True)
Explanation: Step 1: Read in data<br>
using TF Learn's built in function to load MNIST data to the folder data/mnist
End of explanation
with tf.Session() as sess:
start_time = time.time()
sess.run(tf.global_variables_initializer())
n_batch... |
9,335 | 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', 'nasa-giss', 'sandbox-3', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: NASA-GISS
Source ID: SANDBOX-3
Topic: Atmos
Sub-Topics: Dynamical Core, ... |
9,336 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dimension Reduction and Visualization (single cell as bulk & bulk)
Step1: Prior smushing
Step2: For single cell and bulk combined wide mtx and metadata | Python Code:
# Import required modules
# Python plotting library
import matplotlib.pyplot as plt
# Numerical python library
import numpy as np
# Dataframes in Python
import pandas as pd
# Statistical plotting library we'll use
import seaborn as sns
# Import packages for dimension reduction
from sklearn.decomposition im... |
9,337 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Wayne H Nixalo - 09 Aug 2017
FADL2 L9
Step1: Content Recreation
Step2: In this implementation, need to define an object that'll allow us to separately access the loss function and gradient... | Python Code:
%matplotlib inline
import importlib
import os, sys
sys.path.insert(1, os.path.join('../utils'))
from utils2 import *
from scipy.optimize import fmin_l_bfgs_b
from scipy.misc import imsave
from keras import metrics
from vgg16_avg import VGG16_Avg
limit_mem()
path = '../data/nst/'
# names = os.listdir(path)
... |
9,338 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Install Twitter Sentiment with Watson scala library from Github
Step1: Run the Twitter sentiment application using the JavaWrapper
Step2: Run the Twitter sentiment application using Scala
... | Python Code:
import pixiedust
pixiedust.installPackage("https://github.com/ibm-cds-labs/spark.samples/raw/master/dist/streaming-twitter-assembly-1.6.jar")
Explanation: Install Twitter Sentiment with Watson scala library from Github
End of explanation
from pixiedust.utils.javaBridge import *
demo = JavaWrapper("com.ibm.... |
9,339 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Access a Database with Python - Iris Dataset
The Iris dataset is a popular dataset especially in the Machine Learning community, it is a set of features of 50 Iris flowers and their classif... | Python Code:
import os
data_iris_folder_content = os.listdir("data/iris")
error_message = "Error: sqlite file not available, check instructions above to download it"
assert "database.sqlite" in data_iris_folder_content, error_message
Explanation: Access a Database with Python - Iris Dataset
The Iris dataset is a popula... |
9,340 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Advanced automatic differentiation
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Controll... | 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... |
9,341 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Enter State Farm
Step1: Setup batches
Step2: Rather than using batches, we could just import all the data into an array to save some processing time. (In most examples I'm using the batche... | Python Code:
from theano.sandbox import cuda
cuda.use('gpu0')
%matplotlib inline
from __future__ import print_function, division
path = "data/state/"
#path = "data/state/sample/"
import utils; reload(utils)
from utils import *
from IPython.display import FileLink
batch_size=64
Explanation: Enter State Farm
End of expla... |
9,342 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: 探索 TF-Hub CORD-19 Swivel 嵌入向量
<table class="tfo-notebook-buttons" align="le... | Python Code:
# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved.
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
9,343 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This workbook shows a example derived from the EDA exercise in Chapter 2 of Doing Data Science, by o'Neil abd Schutt
Step1: Well. Half a million rows. That would be painful in excel.
Add ... | Python Code:
clicks = Table.read_table("http://stat.columbia.edu/~rachel/datasets/nyt1.csv")
clicks
Explanation: This workbook shows a example derived from the EDA exercise in Chapter 2 of Doing Data Science, by o'Neil abd Schutt
End of explanation
age_upper_bounds = [18, 25, 35, 45, 55, 65]
def age_range(n):
if n ... |
9,344 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SVD Applied to a Word-Document Matrix
This notebook applies the SVD to a simple word-document matrix. The aim is to see what the reconstructed reduced dimension matrix looks like.
Step1: A ... | Python Code:
#import pandas for conviently labelled arrays
import pandas
# import numpy for SVD function
import numpy
# import matplotlib.pyplot for visualising arrays
import matplotlib.pyplot as plt
Explanation: SVD Applied to a Word-Document Matrix
This notebook applies the SVD to a simple word-document matrix. The a... |
9,345 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CSE 6040, Fall 2015 [05, Part B]
Step1: Exercise
Step2: Example
Step3: Exercise. Try modifying and extending the above code to retrieve the 13th entry in the search results.
Step4: Inter... | Python Code:
# Download the Georgia Tech home page
import requests
response = requests.get ('http://www.gatech.edu')
webpage = response.text # or response.content for raw bytes
print (webpage[0:100]) # Prints the first hundred characters only
Explanation: CSE 6040, Fall 2015 [05, Part B]: Web services 101
The second p... |
9,346 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Worked machine learning examples using SDSS data</h1>
[AstroHackWeek 2014, 2016- J. S. Bloom @profjsb]
<hr>
Here we'll see some worked ML examples using scikit-learn on Sloan Digital Sky... | Python Code:
## get the data locally ... I put this on a gist
!curl -k -O https://gist.githubusercontent.com/anonymous/53781fe86383c435ff10/raw/4cc80a638e8e083775caec3005ae2feaf92b8d5b/qso10000.csv
!curl -k -O https://gist.githubusercontent.com/anonymous/2984cf01a2485afd2c3e/raw/964d4f52c989428628d42eb6faad5e212e79b665... |
9,347 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex client library
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Restart the kernel
Once you've installed the Vertex client library and Google clo... | Python Code:
import os
import sys
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install -U google-cloud-aiplatform $USER_FLAG
Explanation: Vertex client library: AutoML text multi-label classification model for online predic... |
9,348 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Unsupervised Analysis of Days of Week
Treating crossings each day of features to learn about the relationships between various days
Step1: Get Data
Step2: Principal Components Analysis
Ste... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn')
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn.mixture import GaussianMixture
Explanation: Unsupervised Analysis of Days of Week
Treating crossings each day of features to learn about the ... |
9,349 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Collating for real with CollateX. Plain texts
In this exercise, follow the instructions here
Step1: Or directly in the commandline
Step2: Now we're ready to make a collation object. We do ... | Python Code:
!pip install --upgrade collatex
Explanation: Collating for real with CollateX. Plain texts
In this exercise, follow the instructions here: read the Markdown cells and execute the Code cells (the ones with In + a number on their left).
Not sure how to execute cells in a Notebook? Check the Jupyter Notebook... |
9,350 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div Style="text-align
Step1: Cargamos imágenes y las covertimos a escala de grises
Step2: Ejemplo de fitolito en escala de grises
Step3: Dividimos el conjunto de imágenes para el entrena... | Python Code:
%matplotlib inline
#para dibujar en el propio notebook
import numpy as np #numpy como np
import matplotlib.pyplot as plt #matplotlib como plot
from skimage.feature import daisy
from skimage.color import rgb2gray
from sklearn.cluster import MiniBatchKMeans as KMeans
from sklearn import svm
import warnings... |
9,351 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
102 - Training Regression Algorithms with the L-BFGS Solver
In this example, we run a linear regression on the Flight Delay dataset to predict the delay times.
We demonstrate how to use the ... | Python Code:
import numpy as np
import pandas as pd
import mmlspark
Explanation: 102 - Training Regression Algorithms with the L-BFGS Solver
In this example, we run a linear regression on the Flight Delay dataset to predict the delay times.
We demonstrate how to use the TrainRegressor and the ComputePerInstanceStatisti... |
9,352 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data passing tutorial
Data passing is the most important aspect of Pipelines.
In Kubeflow Pipelines, the pipeline authors compose pipelines by creating component instances (tasks) and connec... | Python Code:
# Put your KFP cluster endpoint URL here if working from GCP notebooks (or local notebooks). ('https://xxxxx.notebooks.googleusercontent.com/')
kfp_endpoint='https://XXXXX.{pipelines|notebooks}.googleusercontent.com/'
# Install Kubeflow Pipelines SDK. Add the --user argument if you get permission errors.
!... |
9,353 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Author
Step1: According to the S-2 data product specifics, band 4 and band 5 are represented with rasters of different sizes and that can be easily verified
Step2: The obtained results co... | Python Code:
import snappy
from snappy import ProductIO
file_path = 'C:\Program Files\snap\S2A_MSIL1C_20170202T090201_N0204_R007_T35SNA_20170202T090155.SAFE\MTD_MSIL1C.xml'
product = ProductIO.readProduct(file_path)
list(product.getBandNames())
Explanation: Author: Antonio Vecoli
Date: 06/06/2017
Tech For Space www.te... |
9,354 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Encore une instruction pour bouger
QUESTIONS
Lorsque la liste pos contient 6 angles en degrés, que permet de faire le jeu d'instructions suivant ?
Quelle différence avec m.goal_position = ... | Python Code:
i = 0
for m in poppy.motors:
m.compliant = False
m.goto_position(pos[i], 0.5, wait = True)
i = i + 1
Explanation: Encore une instruction pour bouger
QUESTIONS
Lorsque la liste pos contient 6 angles en degrés, que permet de faire le jeu d'instructions suivant ?
Quelle différence avec m.goal_po... |
9,355 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This notebook demonstrates how to carry out an ordering of a disordered structure using pymatgen.
Step1: Note that each site is now 50% occupied by Cu and Au. Because the order... | Python Code:
# Let us start by creating a disordered CuAu fcc structure.
from pymatgen import Structure, Lattice
specie = {"Cu0+": 0.5, "Au0+": 0.5}
cuau = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3.677), [specie], [[0, 0, 0]])
print cuau
Explanation: Introduction
This notebook demonstrates how to carry out an ... |
9,356 | Given the following text description, write Python code to implement the functionality described.
Description:
Check whether an array of strings can correspond to a particular number X
Function to find the maximum base possible for the number N ; Function to find the decimal equivalent of the number ; Condition to chec... | Python Code:
def val(c ) :
if(c >= '0' and c <= '9' ) :
return int(c )
else :
return c - ' A ' + 10
def toDeci(strr , base ) :
lenn = len(strr )
power = 1
num = 0
for i in range(lenn - 1 , - 1 , - 1 ) :
if(val(strr[i ] ) >= base ) :
return - 1
num += val(strr[i ] ) * power
power ... |
9,357 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generating symbolic expressions
For larger reaction systems it is preferable to generate the system of ordinary differential equations from some serialized format and then generate the callb... | Python Code:
reactions = [
('k1', {'A': 1}, {'B': 1, 'A': -1}),
('k2', {'B': 1, 'C': 1}, {'A': 1, 'B': -1}),
('k3', {'B': 2}, {'B': -1, 'C': 1})
]
names, params = 'A B C'.split(), 'k1 k2 k3'.split()
tex_names = ['[%s]' % n for n in names]
Explanation: Generating symbolic expressions
For larger reaction syst... |
9,358 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
pricing is a DataFrame with the same structure as the return value of history on quantopian.
Step1: Pandas' built-in groupby and apply operations are extremely powerful. For more informati... | Python Code:
pricing.head(10)
Explanation: pricing is a DataFrame with the same structure as the return value of history on quantopian.
End of explanation
from pandas.tseries.tools import normalize_date
def my_grouper(ts):
"Function to apply to the index of the DataFrame to break it into groups."
# Returns midn... |
9,359 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
多変量解析
圓川隆夫「多変量のデータ解析」(1988, 朝倉書店)をもとに多変量解析の演習を行います。
Step1: 重回帰分析
以下のように変数を設定する。
$
y =
\begin{bmatrix}
y_{1} \
y_{2} \
\vdots \
y_{n}
\end{bmatrix}
,
X =
\begin{bmatrix}
x_{11} & \cdots & ... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: 多変量解析
圓川隆夫「多変量のデータ解析」(1988, 朝倉書店)をもとに多変量解析の演習を行います。
End of explanation
data = pd.read_csv("tab22.csv") # http://shimotsu.web.fc2.com/Site/duo_bian_liang_jie_xi.html
data
Explanation: 重回帰分析
以下のように変数を設定する。
... |
9,360 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tools
Purpose
Step1: Lists
Step2: Loops and List Comprehension
Step3: If, elif, else
Step4: Functions
Step5: NumPy | Python Code:
# python has /types
print(type(1) == int)
print(type(1.) == float)
print(type(1j) == complex)
type(None)
# What happens if you add values of different types?
print(1 + 1.)
Explanation: Tools
Purpose: To introduce and provide resources for the tools used to build and work with <a href="http://simpeg.xyz">Si... |
9,361 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Graph Analysis with networkx
Graph theory deals with various properties and algorithms concerned with Graphs. Although it is very easy to implement a Graph ADT in Python, we ... | Python Code:
import networkx as nx
Explanation: Introduction to Graph Analysis with networkx
Graph theory deals with various properties and algorithms concerned with Graphs. Although it is very easy to implement a Graph ADT in Python, we will use networkx library for Graph Analysis as it has inbuilt support for visuali... |
9,362 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Self Employment Data 2015
from OECD
Step1: Solutions with Pandas
Basic Calculations and Statistics
Exercise 1
Calculate for each country the overallselfemployment_rate
Step2: Exercise 2
Ca... | Python Code:
countries = ['AUS', 'AUT', 'BEL', 'CAN', 'CZE', 'FIN', 'DEU', 'GRC', 'HUN', 'ISL', 'IRL', 'ITA', 'JPN',
'KOR', 'MEX', 'NLD', 'NZL', 'NOR', 'POL', 'PRT', 'SVK', 'ESP', 'SWE', 'CHE', 'TUR', 'GBR',
'USA', 'CHL', 'COL', 'EST', 'ISR', 'RUS', 'SVN', 'EU28', 'EA19', 'LVA']
male_selfemp... |
9,363 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learning Internal Representation by Error Propagation
A example implementation of the following classic paper that changed the history of deep learning
Rumelhart, D. E., Hinton, G. E., & Wil... | Python Code:
person_1_input = [[1.0 if target == person else 0.0 for target in range(24) ] for person in range(24)]
person_2_output = person_1_input[:] # Data copy - Person 1 is the same data as person 2.
relationship_input = [[1.0 if target == relationship else 0.0 for target in range(12) ] for relationship in range(1... |
9,364 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Batch Normalization – Practice
Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll create a convolutional neural network with 20 convolutional l... | Python Code:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False)
Explanation: Batch Normalization – Practice
Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll crea... |
9,365 | 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', 'ec-earth-consortium', 'ec-earth3-cc', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: EC-EARTH-CONSORTIUM
Source ID: EC-EARTH3-CC
Topic: Land
Sub-T... |
9,366 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hmwk #1
Step1: Represent the following table using a data structure of your choice
Step2: Calculate the mean temperature and mean humidity
Step3: Print outlook and play for those days whe... | Python Code:
import pandas as pd
%pylab inline
Explanation: Hmwk #1
End of explanation
df = pd.read_csv("weather.csv", header=0, index_col=0)
df
Explanation: Represent the following table using a data structure of your choice
End of explanation
mean_temp = df["temperature"].mean()
mean_temp
mean_humidity = df["humidity... |
9,367 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to objects and classes in Python
We will touch upon some basic aspects, including
- code reuse
- abstraction
- Encapsulation
- subclasses and hierarchies
Step1: In the abov... | Python Code:
class Dog:
def __init__(self, name):
self.age = 0
self.name = name
self.noise = "Woof!"
self.food = "dog biscuits"
def make_sound(self):
print(self.noise)
def eat_food(self):
print("Eating " + self.food + ".")
def increa... |
9,368 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create a function map for substring comparison
~~~
d = {'a'
Step1: Changing value changes the function behavior as well
Step2: Solution 2 - function factory using closure
Step3: Changing ... | Python Code:
d = {'a': 'AB', 'b': 'C'}
funcs = {}
for key, value in d.items():
funcs[key] = lambda v: v in value
# True, True, False ?
print(funcs['a']('AB'), funcs['a']('A'), funcs['a']('C'))
# False, True ?
print(funcs['b']('AB'), funcs['b']('C'))
Explanation: Create a function map for substring comparison
~... |
9,369 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistic Regression
Aaron Gonzales
CS529, Machine Learning
Project 3
Instructor
Step1: I had previously extracted the ffts and mcfts from the data; all of them live in the /data/ folder of ... | Python Code:
%load_ext autoreload
%autoreload 2
import numpy as np
import sklearn.metrics as metrics
import utils as utils
from LogisticRegressionClassifier import LogisticRegressionClassifier
%pylab inline
Explanation: Logistic Regression
Aaron Gonzales
CS529, Machine Learning
Project 3
Instructor: Trilce Estrada
Ove... |
9,370 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: 自定义联合算法,第 2 部分:实现联合平均
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 实现联合平均
与图像分类联合学习一样,我们将使用 M... | 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... |
9,371 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021
Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: 📦 Assortment Quality - Product and Brand coverage monitoring
This is not an officially su... | Python Code:
#@title Copyright 2021 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/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
9,372 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to use Xarray accessor
This example shows how to use the SpatialData accessor to extend the capabilities of xarray.
To extend xarray.DataArray you need only to load also pymepps with "im... | Python Code:
import matplotlib.pyplot as plt
import xarray as xr
import pymepps
Explanation: How to use Xarray accessor
This example shows how to use the SpatialData accessor to extend the capabilities of xarray.
To extend xarray.DataArray you need only to load also pymepps with "import pymepps". The extensions could b... |
9,373 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this notebook, we demonstrate how to create and modify a Titan graph in python, and then visualize the result using Graphistry's visual graph explorer.
We assume the gremlin server for ou... | Python Code:
import asyncio
import aiogremlin
# Create event loop and initialize gremlin client
loop = asyncio.get_event_loop()
client = aiogremlin.GremlinClient(url='ws://localhost:8182/', loop=loop) # Default url
Explanation: In this notebook, we demonstrate how to create and modify a Titan graph in python, and then... |
9,374 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Curious Case of Economic Growth in Asia
A research project at NYU's Stern School of Business.
Written by Hanjo Kim (hjk490@nyu.edu), Simon (Seon Mok) Lee (sml523@nyu.edu) under the direction... | Python Code:
import pandas as pd # data package
import matplotlib.pyplot as plt # graphics module
import numpy as np # foundation for Pandas
%matplotlib inline
'''
We downloaded the data from our sources (specific in the bottom) and uploaded them to our github accounts,
... |
9,375 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Given two sets of points in n-dimensional space, how can one map points from one set to the other, such that each point is only used once and the total Manhattan distance between th... | Problem:
import numpy as np
import scipy.spatial
import scipy.optimize
points1 = np.array([(x, y) for x in np.linspace(-1,1,7) for y in np.linspace(-1,1,7)])
N = points1.shape[0]
points2 = 2*np.random.rand(N,2)-1
C = scipy.spatial.distance.cdist(points1, points2, metric='minkowski', p=1)
_, result = scipy.optimize.line... |
9,376 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 6
Imports
Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell.
Step1: Exploring the Fermi distribution
In quantum statistics, the ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import Image
from IPython.html.widgets import interact, interactive, fixed
Explanation: Interact Exercise 6
Imports
Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell.
End of... |
9,377 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hi-C quality check
The file is organized in 4 lines per read
Step1: Count the number of lines in the file (4 times the number of reads)
Step2: There are 400 M lines in the file, which mean... | Python Code:
%%bash
dsrc d -s FASTQs/mouse_B_rep1_1.fastq.dsrc | head -n 8
Explanation: Hi-C quality check
The file is organized in 4 lines per read:
1. starting with @, the header of the DNA sequence with the read id (plus optional fields)
2. the DNA sequence
3. starting with +, the header of the sequence quality ... |
9,378 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matrix Methods Example - Frame 1
This is the same frame as solved using the method of slope-deflection
here. All of the data are provided
in CSV form directly in the cells, below.
Step1:
... | Python Code:
from __future__ import division, print_function
from IPython import display
import salib.nbloader # so that we can directly import other notebooks
import Frame2D_v03 as f2d
Explanation: Matrix Methods Example - Frame 1
This is the same frame as solved using the method of slope-deflection
here. All of t... |
9,379 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reusable Plates
First, we show how to create a reusable plate and fill it with materials.
Step1: Once a plate is created, it can be used in multiple experiments as demonstrated below.
This ... | Python Code:
import murraylab_tools.echo as mt_echo
import os.path
import numpy as np
# Relevant input and output files. Check these out for examples of input file format.
dilution_inputs = os.path.join("reusable_plate_examples", "inputs")
dilution_outputs = os.path.join("reusable_plate_examples", "outputs")
plate_fil... |
9,380 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Wright-Fisher model of mutation, selection and random genetic drift
A Wright-Fisher model has a fixed population size N and discrete non-overlapping generations. Each generation, each indivi... | Python Code:
import numpy as np
import itertools
Explanation: Wright-Fisher model of mutation, selection and random genetic drift
A Wright-Fisher model has a fixed population size N and discrete non-overlapping generations. Each generation, each individual has a random number of offspring whose mean is proportional to ... |
9,381 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 parts of this notebook are from this Jupyter notebook by Heiner Igel (@heinerigel), Lion ... | Python Code:
# Execute this cell to load the notebook's style sheet, then ignore it
from IPython.core.display import HTML
css_file = '../style/custom.css'
HTML(open(css_file, "r").read())
Explanation: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 parts of this note... |
9,382 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Q4
Now we'll start working with some basic Python data structures.
A
In this question, you'll implement a cumulative product method. Given a list, you'll compute a list that's the same lengt... | Python Code:
def cumulative_product(start_list):
out_list = []
### BEGIN SOLUTION
### END SOLUTION
return out_list
inlist = [89, 22, 3, 24, 8, 59, 43, 97, 30, 88]
outlist = [89, 1958, 5874, 140976, 1127808, 66540672, 2861248896, 277541142912, 8326234287360, 732708617287680]
assert set(c... |
9,383 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Raspberry Electrophoresis
1 Tutorial Outline
Welcome to the raspberry electrophoresis ESPResSo tutorial! This tutorial assumes some basic knowledge of ESPResSo.
The first step is compiling E... | Python Code:
import espressomd
espressomd.assert_features(["ELECTROSTATICS", "ROTATION", "ROTATIONAL_INERTIA", "EXTERNAL_FORCES",
"MASS", "VIRTUAL_SITES_RELATIVE", "CUDA", "LENNARD_JONES"])
from espressomd import interactions
from espressomd import electrostatics
from espressomd import lb
fr... |
9,384 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time Series Filters
Step1: Hodrick-Prescott Filter
The Hodrick-Prescott filter separates a time-series $y_t$ into a trend $\tau_t$ and a cyclical component $\zeta_t$
$$y_t = \tau_t + \zeta... | Python Code:
%matplotlib inline
from __future__ import print_function
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
dta = sm.datasets.macrodata.load_pandas().data
index = pd.Index(sm.tsa.datetools.dates_from_range('1959Q1', '2009Q3'))
print(index)
dta.index = index
del dta['year']
del... |
9,385 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implementation of a Radix-2 Fast Fourier Transform
Import standard modules
Step3: This assignment is to implement a python-based Fast Fourier Transform (FFT). Building on $\S$ 2.8 ➞ ... | 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
import cmath
Explanation: Implementation of a Radix-2 Fast Fourier Transform
Import standard modules:
End of explanation
def loop_DFT(x):
Implement... |
9,386 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to build a machine learning marketing model for banking using Google Cloud Platform and Python
This notebook shows you how to build a marketing model for banking using Google Cloud Platf... | Python Code:
!pip install pandas-profiling
!pip install lime
Explanation: How to build a machine learning marketing model for banking using Google Cloud Platform and Python
This notebook shows you how to build a marketing model for banking using Google Cloud Platform (GCP). Many financial institutions use traditional o... |
9,387 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
6 Conditional Loops
Loops
Loops are a big deal in computing and robotics! Think about the kinds of tasks that computers and robots often get used for
Step1: If you've done it right, your ou... | Python Code:
word = input("What is the magic word? ")
while word!="abracadabra":
word = input("Wrong. Try again. What is the magic word? ")
print("Correct")
Explanation: 6 Conditional Loops
Loops
Loops are a big deal in computing and robotics! Think about the kinds of tasks that computers and robots often get used ... |
9,388 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Lecture 4
Step2: <p class='alert alert-success'>
Solve the questions in green blocks. Save the file as ME249-Lecture-4-YOURNAME.ipynb and change YOURNAME in the bottom cell. Send the... | Python Code:
%matplotlib inline
# plots graphs within the notebook
%config InlineBackend.figure_format='svg' # not sure what this does, may be default images to svg format
from IPython.display import Image
from IPython.core.display import HTML
def header(text):
raw_html = '<h4>' + str(text) + '</h4>'
return ra... |
9,389 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome to the Tutorial!
First I'll introduce the theory behind neural nets. then we will implement one from scratch in numpy, (which is installed on the uni computers) - just type this code... | Python Code:
import numpy as np
my_vector = np.asarray([1,2,3])
my_matrix = np.asarray([[1,2,3],[10,10,10]])
print(my_matrix*my_vector)
Explanation: Welcome to the Tutorial!
First I'll introduce the theory behind neural nets. then we will implement one from scratch in numpy, (which is installed on the uni computers) - ... |
9,390 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistic Regression
Notebook version
Step1: 1. Introduction
1.1. Binary classification
The goal of a classification problem is to assign a class or category to every instance or observation... | Python Code:
# To visualize plots in the notebook
%matplotlib inline
# Imported libraries
import csv
import random
import matplotlib
import matplotlib.pyplot as plt
import pylab
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_mod... |
9,391 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center">Text Classification on CNAE-9 Data Set</h1>
In this notebook, we build a Text Classification Model on <a href="https
Step1: Getting the Data
Step2: The result is a 1080*... | Python Code:
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import seaborn as sns
%load_ext version_information
%version_information scipy, numpy, pandas, matplotlib, seaborn, version_information
Explanation: <h1 align="center">Text Classification on CN... |
9,392 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NetworkX
NetworkX is a Python library for doing in-memory graph analysis.
Step1: Implicit node creation on edge add
Step2: Just a touch of computational theory
Dijkstra's algorithm
Finds t... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import networkx as nx
# A SIMPLE EXAMPLE
G=nx.Graph()
G.add_node("a")
G.add_node("b")
G.add_node("c")
G.add_node("d")
G.add_node("e")
G.add_node("f")
G.add_edge('a', 'c')
G.add_edge('b', 'c')
G.add_edge('e', 'd')
G.add_edge('c', 'e')
G.add_edge('e', 'f')
G... |
9,393 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
QuTiP example
Step1: Landau-Zener-Stuckelberg interferometry
Step2: Versions | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from qutip import *
from qutip.ui.progressbar import TextProgressBar as ProgressBar
Explanation: QuTiP example: Landau-Zener-Stuckelberg inteferometry
J.R. Johansson and P.D. Nation
For more information about QuTiP see http://qutip.org
E... |
9,394 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: 保存和恢复模型
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https
Step2: 获取示例数据集
为了演示如何保存和加载权重,您将使用 MNIST 数据... | 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... |
9,395 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: The list of all the emails from Sara are in the from_sara list likewise for emails from Chris (from_chris).
The actual documents are in the Enron email dataset, which you downloaded/u... | Python Code:
from_sara = open('../text_learning/from_sara.txt', "r")
from_chris = open('../text_learning/from_chris.txt', "r")
from_data = []
word_data = []
from nltk.stem.snowball import SnowballStemmer
import string
filePath = '/Users/omojumiller/mycode/hiphopathy/HipHopDataExploration/JayZ/'
f = open(filePath+"JayZ... |
9,396 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reading ns-ALEX data from Photon-HDF5
In this notebook we show how to read a ns-ALEX smFRET measurement stored in *
Photon-HDF5 format
using python and a few common scientific libraries (nu... | Python Code:
from __future__ import division, print_function # only needed on py2
%matplotlib inline
import numpy as np
import tables
import matplotlib.pyplot as plt
Explanation: Reading ns-ALEX data from Photon-HDF5
In this notebook we show how to read a ns-ALEX smFRET measurement stored in *
Photon-HDF5 format
usin... |
9,397 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1"><a href="#Pandas-Python-Data-Analysis-Library"><span class="toc-item-num">1 - </span><a href="http
Step1: Pandas Python Data Analysis Library
If you f... | Python Code:
import pandas as pd
import numpy as np
import seaborn as sns
from IPython.display import display, HTML
Explanation: Table of Contents
<p><div class="lev1"><a href="#Pandas-Python-Data-Analysis-Library"><span class="toc-item-num">1 - </span><a href="http://pandas.pydata.org" target="_blank">Pandas</a> Pytho... |
9,398 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST Image Classification with TensorFlow
This notebook demonstrates how to implement a simple linear image model on MNIST using the tf.keras API. It builds the foundation for this <a href=... | Python Code:
import os
import shutil
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard
from tensorflow.keras.layers import Dense, Flatten, Softmax
print(tf.__version__)
!python3 -m pip fr... |
9,399 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Jupyter Notebooks
We are going to be using jupyter notebooks for this course and a version of python known as ipython in the notebooks.
The notebook is a live document that can contain a nu... | Python Code:
## Example of a simple python code cell
print "Hello little world"
a = 1
## The last statement in a cell prints its value
a
## (this is sometimes a little confusing - add a pass statement to get rid of this !)
#pass
Explanation: Jupyter Notebooks
We are going to be using jupyter notebooks for this course ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.