Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
300 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 9</font>
Download
Step1: Número de veículos pertencentes a cada marca
Step2: Preço médio dos veículos com base no ti... | Python Code:
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())
# Imports
import os
import subprocess
import stat
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib as mat
import matplotlib.pypl... |
301 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Examples and Exercises from Think Stats, 2nd Edition
http
Step1: Hypothesis testing
The following is a version of thinkstats2.HypothesisTest with just the essential methods
Step2: And here... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import random
import thinkstats2
import thinkplot
Explanation: Examples and Exercises from Think Stats, 2nd Edition
http://thinkstats2.com
Copyright 2016 Allen B. Downey
MIT License: https://opensource.org/licenses/MIT
En... |
302 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load the data
For this work, we're going to use the same retail sales data that we've used before. It can be found in the examples directory of this repository.
Step1: Like all good modelin... | Python Code:
sales_df = pd.read_csv('../examples/retail_sales.csv', index_col='date', parse_dates=True)
sales_df.head()
Explanation: Load the data
For this work, we're going to use the same retail sales data that we've used before. It can be found in the examples directory of this repository.
End of explanation
sales_d... |
303 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Saving figure source data
Many scientific journals are (for good reason) requiring that authors upload the source data for their figures. For complex analysis pipelines this can be complicat... | Python Code:
import numpy as np
import figurefirst
fifi = figurefirst
from IPython.display import display,SVG,Markdown
layout = fifi.FigureLayout('figure_template.svg', hide_layers=['template'])
layout.make_mplfigures(hide=True)
Explanation: Saving figure source data
Many scientific journals are (for good reason) requi... |
304 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple MLP demo for TIMIT using Keras
This notebook describes how to reproduce the results for the simple MLP architecture described in this paper
Step1: Here we import the stuff we use bel... | Python Code:
import os
os.environ['CUDA_VISIBLE_DEVICES']='0'
Explanation: Simple MLP demo for TIMIT using Keras
This notebook describes how to reproduce the results for the simple MLP architecture described in this paper:
ftp://ftp.idsia.ch/pub/juergen/nn_2005.pdf
And in Chapter 5 of this thesis:
http://www.cs.toronto... |
305 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time Series Classification and Clustering
In a typical classification problem you are given a set of input features and a set of discrete output classes and you want to model the relationshi... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
x=np.linspace(0,50,100)
ts1=pd.Series(3.1*np.sin(x/1.5)+3.5)
ts2=pd.Series(2.2*np.sin(x/3.5+2.4)+3.2)
ts3=pd.Series(0.04*x+3.0)
#ts1.plot()
#ts2.plot()
#ts3.plot()
#plt.ylim(-2,10)
#plt.legend(['ts1','ts2','ts3'])
#plt.show()
Explanation... |
306 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
The purpose of this challenge is to classify authors using different novels that they have written. In this case supervised techniques have been used and compared to see which ... | Python Code:
# Create a list of all of our book files.
book_filenames_austen = sorted(glob.glob("/home/borjaregueral/challengesuper2/austen/*.txt"))
book_filenames_chesterton = sorted(glob.glob("/home/borjaregueral/challengesuper2/chesterton/*.txt"))
book_filenames_conandoyle = sorted(glob.glob("/home/borjaregueral/cha... |
307 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Serving ML Predictions in batch and real-time
Learning Objectives
1. Copy trained model into your bucket
2. Deploy AI Platform trained model
Introduction
In this notebook, we will create a p... | Python Code:
PROJECT = "cloud-training-demos" # Replace with your PROJECT
BUCKET = PROJECT
REGION = "us-central1" # Choose an available region for Cloud MLE
TFVERSION = "2.6" # TF version for CMLE to use
import os
os.environ["BUCKET"] = BUCKET
os.environ["PROJECT"] = PROJECT
os.environ["REGI... |
308 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Variables
resources used - http
Step1: Running the graph in a tf session
Step2: Section 2 - moving average | Python Code:
import tensorflow as tf
x = tf.constant(35, name='x')
y = tf.Variable(x + 5, name='y')
model = tf.global_variables_initializer()
Explanation: Variables
resources used - http://learningtensorflow.com/lesson2/
Section 1 - a simple representation
A simple representation of variables and constants in a tf grap... |
309 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Algorithmn Re-Assesment
Introduction
Step1: Inspired by the Classifier comparision from SciKit Example, we are trying to see which algorithm work better.
Due to heavyness of data, we are av... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCV
from sklearn.ensemble import RandomForestClassifier
from skle... |
310 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CHIPPR
This notebook demonstrates the use of the Cosmological Hierarchical Inference with Probabilistic Photometric Redshifts (CHIPPR) package to estimate population distributions based on a... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import timeit
import cProfile, pstats, StringIO
import os
import chippr
help(chippr)
Explanation: CHIPPR
This notebook demonstrates the use of the Cosmological Hierarchical Inference with Probabilistic Photometric Redshifts (CHIPPR) pack... |
311 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
Glossary
Positional Astronomy
Previous
Step1: Import section specific modules
Step2: 3.3 Horizontal Coordinates (ALT,AZ)
3.3.1 Coordinate Definitions
In $\S$ 3.2.1 ➞ we intr... | 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
Positional Astronomy
Previous: 3.2 Hour Angle (HA) and Local Sidereal Time (LST)
Next: 3.4 Direction Cosine Coordinates ($l,m,... |
312 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
4. Solving the model
4.1 Solow model as an initial value problem
The Solow model with can be formulated as an initial value problem (IVP) as follows.
$$ \dot{k}(t) = sf(k(t)) - (g + n + \del... | Python Code:
solowpy.CobbDouglasModel.analytic_solution?
Explanation: 4. Solving the model
4.1 Solow model as an initial value problem
The Solow model with can be formulated as an initial value problem (IVP) as follows.
$$ \dot{k}(t) = sf(k(t)) - (g + n + \delta)k(t),\ t\ge t_0,\ k(t_0) = k_0 \tag{4.1.0} $$
The solutio... |
313 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Calgary Coffee Shops
By
Step1: Load from xml to mongobd
Load the data from xml and convert to json so it can be loaded into mongodb.
osmToMongo.py handles the conversion to json as well as ... | Python Code:
#Creates and uses sample file if True
USE_SAMPLE = False
k = 10
inputFile = "calgary_canada.osm"
sampleFile = "calgary_canada_sample.osm"
if USE_SAMPLE:
import createTestFile
createTestFile.createTestFile(inputFile,sampleFile,k)
print '%s created from %s for testing.' % (sampleFi... |
314 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solution of Fox et al. 2015
Step1: First, we read the input, and take a look at the column names
Step2: Extract the unique manuscripts and count them
Step3: Now we want to elaborate the d... | Python Code:
import pandas
import numpy as np
Explanation: Solution of Fox et al. 2015
End of explanation
fox = pandas.read_csv("../data/Fox2015_data.csv")
fox.columns
Explanation: First, we read the input, and take a look at the column names
End of explanation
unique_ms = list(set(fox['MsID']))
num_ms = len(unique_ms)... |
315 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Podemos ver que el método no converge con el numero de clusters. Se estabiliza ligeramente con alrededor de 10 clusters, por lo que ese puede ser un numero util de clusters, sin embargo el d... | Python Code:
fig,ax=subplots(3,3,figsize=(10, 10))
n=1
for i in range(3):
for j in range(3):
ax[i,j].scatter(X[:,0],X[:,n],c=Y)
n+=1
Xnorm=sklearn.preprocessing.normalize(X)
pca=sklearn.decomposition.PCA()
pca.fit(Xnorm)
fig,ax=subplots(1,3,figsize=(16, 4))
ax[0].scatter(pca.transform(X)[:,0],Y,c=Y)... |
316 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center> <h1>Python in the Lab</h1> </center>
Topics
Python
Control Flow
Data Structures
Modules and Packages
Object-oriented programming
Iterators
Generators
Decorators
Magic Methods
Conte... | Python Code:
import IPython
IPython.__version__
Explanation: <center> <h1>Python in the Lab</h1> </center>
Topics
Python
Control Flow
Data Structures
Modules and Packages
Object-oriented programming
Iterators
Generators
Decorators
Magic Methods
Context Manager
All the other cool stuff
Science
Plotting
Numerical Calcul... |
317 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The
Step1:
Step2: Now, we can create an
Step3: Epochs behave similarly to
Step4: You can select subsets of epochs by indexing the
Step5: Note the '/'s in the event code labels. The... | Python Code:
import mne
import os.path as op
import numpy as np
from matplotlib import pyplot as plt
Explanation: The :class:Epochs <mne.Epochs> data structure: epoched data
:class:Epochs <mne.Epochs> objects are a way of representing continuous
data as a collection of time-locked trials, stored in an array... |
318 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--BOOK_INFORMATION-->
This notebook contains an excerpt from the Python Data Science Handbook by Jake VanderPlas; the content is available on GitHub.
The text is released under the CC-BY-N... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np
Explanation: <!--BOOK_INFORMATION-->
This notebook contains an excerpt from the Python Data Science Handbook by Jake VanderPlas; the content is available on GitHub.
The text is released under the CC-BY-NC... |
319 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reproducible visualization
In "The Functional Art
Step1: World Population Prospects
Step2: First problem... The book states on page 8
Step3: Let's make some art
Step4: For one thing, the... | Python Code:
!wget 'http://esa.un.org/unpd/wpp/DVD/Files/1_Indicators%20(Standard)/EXCEL_FILES/2_Fertility/WPP2015_FERT_F04_TOTAL_FERTILITY.XLS'
Explanation: Reproducible visualization
In "The Functional Art: An introduction to information graphics and visualization" by Alberto Cairo, on page 12 we are presented with a... |
320 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Jeté de balle – Niveau 1 - Python
TP1
Pour commencer votre programme python devra contenir les lignes de code ci-dessous et le logiciel V-REP devra être lancé.
Dans V-REP (en haut à gauche) ... | Python Code:
import time
from poppy.creatures import PoppyTorso
poppy = PoppyTorso(simulator='vrep')
Explanation: Jeté de balle – Niveau 1 - Python
TP1
Pour commencer votre programme python devra contenir les lignes de code ci-dessous et le logiciel V-REP devra être lancé.
Dans V-REP (en haut à gauche) utilise les deux... |
321 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Project Euler
Step1: Certain functions in the itertools module may be useful for computing permutations
Step2: The below is what I think should work however it takes a while to run so I en... | Python Code:
assert 65 ^ 42 == 107
assert 107 ^ 42 == 65
assert ord('a') == 97
assert chr(97) == 'a'
Explanation: Project Euler: Problem 59
https://projecteuler.net/problem=59
Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange).... |
322 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classifying Images With Scikit_Learn
Step1: Naive Bayes Using Scikit_Lerarn
Step2: Pre-Processing The Data
machine learning algorithms can work only on numeric data, so our next step will ... | Python Code:
import sklearn as sk
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn .datasets import fetch_olivetti_faces
faces = fetch_olivetti_faces()
faces.DESCR
faces.keys()
faces.images.shape
faces.data.shape
faces.target.shape
np.max(faces.data)
np.min(faces.data)
np.median(faces.... |
323 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TMY data and diffuse irradiance models
This tutorial explores using TMY data as inputs to different plane of array diffuse irradiance models.
This tutorial has been tested against the follow... | Python Code:
# built-in python modules
import os
import inspect
# scientific python add-ons
import numpy as np
import pandas as pd
# plotting stuff
# first line makes the plots appear in the notebook
%matplotlib inline
import matplotlib.pyplot as plt
# seaborn makes your plots look better
try:
import seaborn as sn... |
324 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Given a 2D set of points spanned by axes $x$ and $y$ axes, we will try to fit a line that best approximates the data. The equation of the line, in slope-intercept form, is defined by
Step1: ... | Python Code:
def generate_random_points_along_a_line (slope, intercept, num_points, abs_value, abs_noise):
# randomly select x
x = np.random.uniform(-abs_value, abs_value, num_points)
# y = mx + b + noise
y = slope*x + intercept + np.random.uniform(-abs_noise, abs_noise, num_points)
return x, y
def ... |
325 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Strings and Stuff in Python
Step1: Strings are just arrays of characters
Step2: Arithmetic with Strings
Step3: You can compare strings
Step4: Python supports Unicode characters
You can ... | Python Code:
import numpy as np
Explanation: Strings and Stuff in Python
End of explanation
s = 'spam'
s,len(s),s[0],s[0:2]
s[::-1]
Explanation: Strings are just arrays of characters
End of explanation
s = 'spam'
e = "eggs"
s + e
s + " " + e
4 * (s + " ") + e
print(4 * (s + " ") + s + " and\n" + e) # use \n to get... |
326 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deploying Tensorflow models on Verta
Within Verta, a "Model" can be any arbitrary function
Step1: 0.1 Verta import and setup
Step2: 1. Model Training
1.1 Load training data
Step3: 1.2 Def... | Python Code:
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda, Compose
import matplotlib.pyplot as plt
Explanation: Deploying Tensorflow models on Verta
Within Verta, a "Model" can be any arbitrary function: a ... |
327 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="static/pybofractal.png" alt="Pybonacci" style="width
Step1: Set Definitions
Sets are created as attributes object of the main model objects and all the information is given as par... | Python Code:
# Import of the pyomo module
from pyomo.environ import *
# Creation of a Concrete Model
model = ConcreteModel()
Explanation: <img src="static/pybofractal.png" alt="Pybonacci" style="width: 200px;"/>
<img src="static/cacheme_logo.png" alt="CAChemE" style="width: 300px;"/>
The Transport Problem
Note: Adapt... |
328 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Overview of MEG/EEG analysis with MNE-Python
This tutorial covers the basic EEG/MEG pipeline for event-related analysis
Step1: Loading data
MNE-Python data structures are based around the F... | Python Code:
import os
import numpy as np
import mne
Explanation: Overview of MEG/EEG analysis with MNE-Python
This tutorial covers the basic EEG/MEG pipeline for event-related analysis:
loading data, epoching, averaging, plotting, and estimating cortical activity
from sensor data. It introduces the core MNE-Python dat... |
329 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reshaping data with stack and unstack
Pivoting
Data is often stored in CSV files or databases in so-called “stacked” or “record” format
Step1: A better representation might be one where the... | Python Code:
df = pd.DataFrame({'subject':['A', 'A', 'B', 'B'],
'treatment':['CH', 'DT', 'CH', 'DT'],
'concentration':range(4)},
columns=['subject', 'treatment', 'concentration'])
df
Explanation: Reshaping data with stack and unstack
Pivoting
Data is often stored... |
330 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Assignment Jan 2017. Water company uses ASR system to prevent extraction from tiver during summer
Step1: Because the river is regarded as a straight fixed-head boundary along the y-axis at ... | Python Code:
# import the necessary fucntionality
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import exp1 as W # Theis well function
def newfig(title='?', xlabel='?', ylabel='?', xlim=None, ylim=None, xscale=None, yscale=None, figsize=(10, 8),
fontsize=16):
sizes = ['xx-small',... |
331 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cargue de datos s SciDB
1) Verificar Prerequisitos
Python
SciDB-Py requires Python 2.6-2.7 or 3.3
Step1: NumPy
tested with version 1.9 (1.13.1)
Step2: Requests
tested with version 2.7 (2.1... | Python Code:
import sys
sys.version_info
Explanation: Cargue de datos s SciDB
1) Verificar Prerequisitos
Python
SciDB-Py requires Python 2.6-2.7 or 3.3
End of explanation
import numpy as np
np.__version__
Explanation: NumPy
tested with version 1.9 (1.13.1)
End of explanation
import requests
requests.__version__
Explana... |
332 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LAB 5a
Step1: If the above command resulted in an installation, please restart the notebook kernel and re-run the notebook.
Import necessary libraries.
Step2: Set environment variables.
Se... | Python Code:
try:
import hypertune
except ImportError:
!pip3 install -U cloudml-hypertune --user
print("Please restart the kernel and re-run the notebook.")
Explanation: LAB 5a: Training Keras model on Vertex AI
Learning Objectives
Setup up the environment
Create trainer module's task.py to hold hyperparam... |
333 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Gradient-Boosting-Machine-(GBM)" data-toc-modified-id="Gradient-Boosting-Mac... | Python Code:
# code for loading the format for the notebook
import os
# path : store the current path to convert back to it later
path = os.getcwd()
os.chdir(os.path.join('..', '..', 'notebook_format'))
from formats import load_style
load_style(css_style = 'custom2.css', plot_style = False)
os.chdir(path)
# 1. magic fo... |
334 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Don't forget to delete the hdmi_out and hdmi_in when finished
Mirror Filter Example
In this notebook, we will demonstrate how to use the mirror filter. We utilize Pynq’s ability to buffer HD... | Python Code:
from pynq.drivers.video import HDMI
from pynq import Bitstream_Part
from pynq.board import Register
from pynq import Overlay
Overlay("demo.bit").download()
Explanation: Don't forget to delete the hdmi_out and hdmi_in when finished
Mirror Filter Example
In this notebook, we will demonstrate how to use the m... |
335 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Station Plot with Layout
Make a station plot, complete with sky cover and weather symbols, using a
station plot layout built into MetPy.
The station plot itself is straightforward, but there... | Python Code:
import cartopy.crs as ccrs
import cartopy.feature as feat
import matplotlib.pyplot as plt
import numpy as np
from metpy.calc import get_wind_components
from metpy.cbook import get_test_data
from metpy.plots import simple_layout, StationPlot, StationPlotLayout
from metpy.units import units
Explanation: Stat... |
336 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a better model
Step1: Are we underfitting?
Our validation accuracy so far has generally been higher than our training accuracy. That leads to two obvious questions
Step2: ...and l... | Python Code:
#from theano.sandbox import cuda
%matplotlib inline
import utils
import importlib
importlib.reload(utils)
from utils import *
from __future__ import division, print_function
#path = "data/dogscats/sample/"
path = "data/dogscats/"
model_path = path + 'models/'
if not os.path.exists(model_path): os.mkdir(mod... |
337 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Attention Basics
In this notebook, we look at how attention is implemented. We will focus on implementing attention in isolation from a larger model. That's because when implementing attenti... | Python Code:
dec_hidden_state = [5,1,20]
Explanation: Attention Basics
In this notebook, we look at how attention is implemented. We will focus on implementing attention in isolation from a larger model. That's because when implementing attention in a real-world model, a lot of the focus goes into piping the data and j... |
338 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Probability Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: A Tour of Oryx
<table class="tfo-notebook-buttons" align="left">
... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
339 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predicting Seizure — Kaggle competition 2016
Introduction
Work in progress
An interesting article to start working with. It hasn't many details on implementation, but gives some ideas of wha... | Python Code:
import scipy.io
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
Explanation: Predicting Seizure — Kaggle competition 2016
Introduction
Work in progress
An interesting article to start working with. It hasn't many details on implementation, but gives some ideas of what to do.
First step... |
340 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing the GIFGIF dataset
GIFGIF is a project from the MIT media lab that aims at understanding the emotional content of animated GIF images.
The project covers 17 emotions, including hap... | Python Code:
import choix
import collections
import numpy as np
from IPython.display import Image, display
# Change this with the path to the data on your computer.
PATH_TO_DATA = "/tmp/gifgif/gifgif-dataset-20150121-v1.csv"
Explanation: Analyzing the GIFGIF dataset
GIFGIF is a project from the MIT media lab that aims ... |
341 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Load Corpus
The corpus I am using is just one I found online. The corpus you choose is central to generating realistic text.
Step2: Build Markov Chain
Step3: Generate One Twe... | Python Code:
import markovify
Explanation: Title: Generate Tweets Using Markov Chains
Slug: generate_tweets_using_markov_chain
Summary: Generate Tweets Using Markov Chains
Date: 2016-11-01 12:00
Category: Python
Tags: Other
Authors: Chris Albon
Preliminaries
End of explanation
# Get raw text as string
with open("bro... |
342 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dimensionality Reduction with the Shogun Machine Learning Toolbox
By Sergey Lisitsyn (lisitsyn) and Fernando J. Iglesias Garcia (iglesias).
This notebook illustrates <a href="http
Step1: Th... | Python Code:
import numpy
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
def generate_data(curve_type, num_points=1000):
if curve_type=='swissroll':
tt = numpy.array((3*numpy.pi/2)*(1+2*numpy.random.rand(num_points)))
height = numpy.array((numpy.random.rand(num_points)-0.5))
X = numpy.ar... |
343 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PropBank in NLTK
(C) 2019 by Damir Cavar
The material in this notebook is based on
Step1: Each propbank instance defines the following member variables
Step2: The location of the predicate... | Python Code:
from nltk.corpus import propbank
pb_instances = propbank.instances()
print(pb_instances)
Explanation: PropBank in NLTK
(C) 2019 by Damir Cavar
The material in this notebook is based on:
- The NLKT Howto on Propbank
- The Proposition Bank Website
- The Propbank GitHub repo
- The Google Propbank Archive
The ... |
344 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook was copied from this location.
Precision and Recall
Useful links
* https
Step1: Confusion matrix
Step2: The table below shows an example confusion matrix for a hypothetical t... | Python Code:
import sklearn
import pandas as pd
import numpy as np
Explanation: This notebook was copied from this location.
Precision and Recall
Useful links
* https://en.wikipedia.org/wiki/Confusion_matrix
* http://scikit-learn.org/stable/whats_new.html#version-0-17-1
A popular way to evaluate the performance of a ma... |
345 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step 1
Step1: Step 2
Step2: Step 3
Step3: Step 4
Step4: Let's now proceed to tokenize these tweets in addition to lemmatizing them! This will help improve the performance of our LDA mode... | Python Code:
gabr_tweets = extract_users_tweets("gabr_ibrahim", 2000)
Explanation: Step 1: Obtain my tweets!
I will obtain my entire tweet history! Note: For 2nd degree potential followers, I only extract 200 of their most recent tweets!
End of explanation
gabr_dict = dict()
gabr_dict['gabr_ibrahim'] = {"content" : [],... |
346 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python for Bioinformatics
This Jupyter notebook is intented to be used alongside the book Python for Bioinformatics
Chapter 2
Step1: Mathematical Operations
Step2: BATCH MODE
Listing 2.1
S... | Python Code:
print('Hello World!')
print("Hello", "World!")
print("Hello","World!",sep=";")
print("Hello","World!",sep=";",end='\n\n')
name = input("Enter your name: ")
name
1+1
'1'+'1'
"A string of " + 'characters'
'The answer is ' + 42
'The answer is ' + str(42)
'The answer is {0}'.format(42)
number = 42
'The answer ... |
347 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy Gems, Part 3
Much of scientific computing revolves around the manipulation of indices. Most formulas involve sums of things and at the core of it the formulas differ by which things we... | Python Code:
import numpy as np
np.random.seed(1234)
x = np.random.choice(10, replace=False, size=10)
s = np.argsort(x)
inverse = np.empty_like(s)
inverse[s] = np.arange(len(s), dtype=int)
np.all(x == inverse)
Explanation: Numpy Gems, Part 3
Much of scientific computing revolves around the manipulation of indices. Most... |
348 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook to work with Altimetry and Lake Surface Area
Step1: GRLM Altimetry data from July 22 2008 to September 3, 2016
Create new columns of year, month, day in a convenient format
Step2: ... | Python Code:
% matplotlib inline
import pandas as pd
import glob
import matplotlib.pyplot as plt
GRLM = "345_GRLM10.txt"; print GRLM
df_grlm = pd.read_csv(GRLM, skiprows=43, delim_whitespace=True, names="mission,cycle,date,hour,minute,lake_height,error,mean(decibels),IonoCorrection,TropCorrection".split(","), engine='p... |
349 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
[Py-OO] Aula 03
Modelo de dados do Python
O que você vai aprender nesta aula?
Após o término da aula você terá aprendido
Step1: Podemos acessar as cartas do baralho por índice
Step2: També... | Python Code:
from exemplos.baralho import Baralho
baralho = Baralho()
Explanation: [Py-OO] Aula 03
Modelo de dados do Python
O que você vai aprender nesta aula?
Após o término da aula você terá aprendido:
O que é o modelo de dados do Python
Para que servem e como funcionam métodos mágicos
Protocolos em Python
Sequência... |
350 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Verifying Non-Uniformity of Subvolumes
Here, I sample subvolumes of a predetermined size, count the synapse contents, and then plot that distribution in order to show that the synapses are n... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
Explanation: Verifying Non-Uniformity of Subvolumes
Here, I sample subvolumes of a predetermined size, count the synapse contents, and then plot that distribution in order to show that the s... |
351 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib Exercise 1
Imports
Step1: Line plot of sunspot data
Download the .txt data for the "Yearly mean total sunspot number [1700 - now]" from the SILSO website. Upload the file to the ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Matplotlib Exercise 1
Imports
End of explanation
import os
assert os.path.isfile('yearssn.dat')
Explanation: Line plot of sunspot data
Download the .txt data for the "Yearly mean total sunspot number [1700 - now]" from the S... |
352 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
Preperation
Import packages
Step1: Block the output of all cores except for one
Step2: Define an md.export_cfg object
md.export_cfg has a call method that we can use to create... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import mapp4py
from mapp4py import md
from lib.elasticity import rot, cubic, resize, displace, crack
Explanation: Introduction
Preperation
Import packages
End of explanation
from mapp4py import mpi
if mpi().rank!=0:
with open(os.devnull, 'w') as f:
... |
353 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
This question may not be clear, so please ask for clarification in the comments and I will expand. | Problem:
import numpy as np
import pandas as pd
import torch
mask, clean_input_spectrogram, output= load_data()
for i in range(len(mask[0])):
if mask[0][i] == 1:
mask[0][i] = 0
else:
mask[0][i] = 1
output[:, mask[0].to(torch.bool), :] = clean_input_spectrogram[:, mask[0].to(torch.bool), :] |
354 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Benchmarking Thinc layers with a custom benchmark layer
This notebook shows how to write a benchmark layer that can wrap any layer(s) in your network and that logs the execution times of the... | Python Code:
!pip install "thinc>=8.0.0a0"
Explanation: Benchmarking Thinc layers with a custom benchmark layer
This notebook shows how to write a benchmark layer that can wrap any layer(s) in your network and that logs the execution times of the initialization, forward pass and backward pass. The benchmark layer can a... |
355 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copula - Multivariate joint distribution
Step1: When modeling a system, there are often cases where multiple parameters are involved. Each of these parameters could be described with a give... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy import stats
sns.set_style("darkgrid")
sns.mpl.rc("figure", figsize=(8, 8))
%%javascript
IPython.OutputArea.prototype._should_scroll = function(lines) {
return false;
}
Explanation: Copula - Multivariate joint distribut... |
356 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Project 2
In this project, you will implement the exploratory analysis plan developed in Project 1. This will lay the groundwork for our our first modeling exercise in Project 3.
Step 1
Step... | Python Code:
#imports
from __future__ import division
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
import pylab as pl
import numpy as np
%matplotlib inline
Explanation: Project 2
In this project, you will implement the exploratory analysis plan developed in Project... |
357 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
These are the search queries for the Spotify Web API
Step1: 1) With "Lil Wayne" and "Lil Kim" there are a lot of "Lil" musicians. Do a search and print a list of 50 that are playable in the... | Python Code:
response = requests.get('https://api.spotify.com/v1/search?query=Lil&type=artist&limit=50&market=US')
Lil_data = response.json()
Lil_data.keys()
Lil_data['artists'].keys()
Explanation: These are the search queries for the Spotify Web API
End of explanation
Lil_artists = Lil_data['artists']['items']
for art... |
358 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Q1
In this question, you'll write some coding that performs string manipulation. This is pretty much your warm-up.
Part A
What's your favorite positive number? Reassign the favorite_number v... | Python Code:
favorite_number = -1
### BEGIN SOLUTION
### END SOLUTION
print("My favorite number is: " + str(favorite_number))
assert favorite_number >= 0
Explanation: Q1
In this question, you'll write some coding that performs string manipulation. This is pretty much your warm-up.
Part A
What's your favorite positive n... |
359 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Descriptive statistics
Goals of this lesson
Students will learn
Step1: 0. Open dataset and load package
This dataset examines the relationship between multitasking and working memory. Link ... | Python Code:
# load packages we will be using for this lesson
import pandas as pd
Explanation: Descriptive statistics
Goals of this lesson
Students will learn:
How to group and categorize data in Python
How to generative descriptive statistics in Python
End of explanation
# use pd.read_csv to open data into python
df =... |
360 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocean
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'dwd', 'sandbox-2', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: DWD
Source ID: SANDBOX-2
Topic: Ocean
Sub-Topics: Timestepping Framework, Adve... |
361 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gibbs Sampling Example
Imagine your posterior distribution has the following form
Step1: First, let's make a contour plot of the posterior density.
Step2: Now let's run the sampler, by ite... | Python Code:
f= lambda x,y: np.exp(-(x*x*y*y+x*x+y*y-8*x-8*y)/2.)
Explanation: Gibbs Sampling Example
Imagine your posterior distribution has the following form:
$$ f(x, y \mid data) = (1/C)e^{-\frac{(x^2y^2+x^2+y^2-8x-8y)}{2}} $$
As is typical in Bayesian inference, you don't know what C (the normalizing constant) is... |
362 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Libraries, utilities and definitions
Step1: Fractal dimension feature selection algorithm
The algorithm is adjusted to the dataset of the experiment so the number of attributes must be modi... | Python Code:
import numpy as np
import pandas as pd
from math import log
from os import listdir
from os.path import isfile, join
from scipy.stats import linregress
from sklearn.metrics.pairwise import euclidean_distances
from sklearn.preprocessing import StandardScaler
from time import time
from timeit import timeit
#R... |
363 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FDMS TME3
Kaggle How Much Did It Rain? II
Florian Toque & Paul Willot
Data Vize
Step1: 13.765.202 lines in train.csv
8.022.757 lines in test.csv
Load the dataset
Step2: Per wikipedia... | Python Code:
# from __future__ import exam_success
from __future__ import absolute_import
from __future__ import print_function
%matplotlib inline
import sklearn
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import random
import pandas as pd
import scipy.stats as stats
# Sk cheats
from sklear... |
364 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Figure 1(i)
Step3: We start by defining a few helper variables and functions which be used for creating the plots below.
Step4: The plots are produced below.
Note that 'trans' is a list of... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
Explanation: Figure 1(i): Hysteresis Plots
This notebook reproduces the three hysteresis plots in figure 1(i) which appear in the paper. The show $\left< m_z\right>$ vs. $H$, where $\left< m_z\right>$ is the spatially averaged out-of-pla... |
365 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anna KaRNNa
In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book... | Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
Explanation: Anna KaRNNa
In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.
This network... |
366 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Adding Stellar Data to STELLAB
Contributors
Step1: The goal is to add your data to STELLAB to produce plots such as the plot below
Step2: Adding your own data.
Step3: Uploading data
comin... | Python Code:
%matplotlib nbagg
import matplotlib.pyplot as plt
from NuPyCEE import stellab as st
Explanation: Adding Stellar Data to STELLAB
Contributors: Christian Ritter
In construction
End of explanation
s1=st.stellab()
xaxis='[Fe/H]'
yaxis='[O/Fe]'
s1.plot_spectro(fig=1,xaxis=xaxis,galaxy='carina')
plt.xlim(-4.5,1... |
367 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using GraphLab Create with Apache Spark
In this notebook we demonstrate how to use Apache Spark with GraphLab Create. For this notebook, we will utilize Apache Spark as a platform for doing ... | Python Code:
# To use GraphLab Create within PySpark, you need to set the $SPARK_HOME and $PYTHONPATH
# environment variables on the driver. A common usage:
!export SPARK_HOME="your-spark-home-dir"
!export PYTHONPATH=$SPARK_HOME/python/:$SPARK_HOME/python/lib/py4j-0.8.2.1-src.zip:$PYTHONPATH
Explanation: Using GraphLab... |
368 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Q-learning
In this notebook, we'll build a neural network that can learn to play games through reinforcement learning. More specifically, we'll use Q-learning to train an agent to play ... | Python Code:
import gym
import tensorflow as tf
import numpy as np
Explanation: Deep Q-learning
In this notebook, we'll build a neural network that can learn to play games through reinforcement learning. More specifically, we'll use Q-learning to train an agent to play a game called Cart-Pole. In this game, a freely sw... |
369 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas
Pandas Objects
In the previous chapter we discussed the very basics of Python and NumPy. Here we go one step further and introduce the Pandas package and its data structures. At the v... | Python Code:
# We start by importing the NumPy, Pandas packages
import numpy as np
import pandas as pd
Explanation: Pandas
Pandas Objects
In the previous chapter we discussed the very basics of Python and NumPy. Here we go one step further and introduce the Pandas package and its data structures. At the very basic leve... |
370 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Local Search
Utility Functions
The module extractVariables implements the function $\texttt{extractVars}(e)$ that takes a Python expression $e$ as its argument and returns the set of all var... | Python Code:
import extractVariables as ev
Explanation: Local Search
Utility Functions
The module extractVariables implements the function $\texttt{extractVars}(e)$ that takes a Python expression $e$ as its argument and returns the set of all variables and function names occurring in $e$.
End of explanation
def collect... |
371 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Measuring monotonic relationships
By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie with example algorithms by David Edwards
Reference
Step1: Spearman Rank Correlation
Intuitio... | Python Code:
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import math
# Example of ranking data
l = [10, 9, 5, 7, 5]
print 'Raw data: ', l
print 'Ranking: ', list(stats.rankdata(l, method='average'))
Explanation: Measuring monotonic relationships
By Evgenia "Jenny" Nitishinskaya and De... |
372 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have written a custom model where I have defined a custom optimizer. I would like to update the learning rate of the optimizer when loss on training set increases. | Problem:
import numpy as np
import pandas as pd
import torch
optim = load_data()
for param_group in optim.param_groups:
param_group['lr'] = 0.001 |
373 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The following PNCollection objects will contain all the terms in the different parts of the binding energy.
Step1: Individual energy terms
In this notebook, every term will be multiplied by... | Python Code:
BindingEnergy_NoSpin = PNCollection()
BindingEnergy_Spin = PNCollection()
BindingEnergy_NSTides = PNCollection()
Explanation: The following PNCollection objects will contain all the terms in the different parts of the binding energy.
End of explanation
BindingEnergy_NoSpin.AddDerivedVariable('E_coeff', -(M... |
374 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deputado Histogramado
expressao.xyz/deputado/
Como processar as sessões do parlamento Português
Índice
Reunír o dataset
Contando as palavras mais comuns
Fazendo histogramas
Representações ge... | Python Code:
%matplotlib inline
import pylab
import matplotlib
import pandas
import numpy
dateparse = lambda x: pandas.datetime.strptime(x, '%Y-%m-%d')
sessoes = pandas.read_csv('sessoes_democratica_org.csv',index_col=0,parse_dates=['data'], date_parser=dateparse)
del sessoes['tamanho']
total0 = numpy.sum(sessoes['ses... |
375 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Custom training loop with Keras and MultiWorkerMirroredStrategy
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank"... | 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... |
376 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
numpy scipy pandas matplotlib scikit-learn
NumPy
Step1: Unlike Python lists (which are limited to one dimension), NumPy arrays can be multi-dimensional. For example, here we will reshape ou... | Python Code:
import numpy as np
x = np.arange(1, 10)
x
x ** 2
Explanation: numpy scipy pandas matplotlib scikit-learn
NumPy: Numerical Python
NumPy provides an efficient way to store and manipulate multi-dimensional dense arrays in Python. The important features of NumPy are:
It provides an ndarray structure, which all... |
377 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'messy-consortium', 'sandbox-1', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: MESSY-CONSORTIUM
Source ID: SANDBOX-1
Sub-Topics: Radiative... |
378 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<i class="fa fa-book"></i> Primero librerias
Step1: <i class="fa fa-database"></i> Vamos a crear datos de jugete
Crea varios "blobs"
recuerda la funcion de scikit-learn datasets.make_blobs(... | Python Code:
import numpy as np
import sklearn as sk
import matplotlib.pyplot as plt
import sklearn.datasets as datasets
import seaborn as sns
%matplotlib inline
Explanation: <i class="fa fa-book"></i> Primero librerias
End of explanation
centers = [[1, 1], [-1, -1], [1, -1]]
X,Y = datasets.make_blobs(n_samples=1000, c... |
379 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Parameter selection, Validation, and Testing
Most models have parameters that influence how complex a model they can learn. Remember using KNeighborsRegressor.
If we change the number of nei... | Python Code:
from sklearn.model_selection import cross_val_score, KFold
from sklearn.neighbors import KNeighborsRegressor
# generate toy dataset:
x = np.linspace(-3, 3, 100)
rng = np.random.RandomState(42)
y = np.sin(4 * x) + x + rng.normal(size=len(x))
X = x[:, np.newaxis]
cv = KFold(shuffle=True)
# for each parameter... |
380 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Make Hazard Curves and Maps
This notebook illustrates how to make hazard curves and hazard maps by combining results from several events.
First set up some things needed in notebook....
Step... | Python Code:
%pylab inline
from __future__ import print_function
from ptha_paths import data_dir, events_dir
import sys, os
from ipywidgets import interact
from IPython.display import Image, display
Explanation: Make Hazard Curves and Maps
This notebook illustrates how to make hazard curves and hazard maps by combining... |
381 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a Sentiment Analysis LSTM Using Noisy Crowd Labels
In this tutorial, we'll provide a simple walkthrough of how to use Snorkel to resolve conflicts in a noisy crowdsourced dataset fo... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import os
import numpy as np
from snorkel import SnorkelSession
session = SnorkelSession()
Explanation: Training a Sentiment Analysis LSTM Using Noisy Crowd Labels
In this tutorial, we'll provide a simple walkthrough of how to use Snorkel to resolve con... |
382 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Coupling GIPL and ECSimpleSnow models
Before you begin, install
Step1: Load ECSimpleSnow module from PyMT
Step2: Load GIPL module from PyMT
Step3: Call the setup method on both ECSimpleSn... | Python Code:
import pymt.models
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import matplotlib.colors as mcolors
from matplotlib.colors import LinearSegmentedColormap
sns.set(style='whitegrid', font_scale= 1.2)
Explanation: Coupling GIPL and ECSimpleSnow models
Before you begin, install:
con... |
383 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Connect Four
This notebook defines the game Connect Four.
Connect Four is played on a board of dimension $6 \times 7$, i.e. there are $6$ rows $7$ columns. Instead of Red and Yellow we call... | Python Code:
gPlayers = [ 'X', 'O' ]
Explanation: Connect Four
This notebook defines the game Connect Four.
Connect Four is played on a board of dimension $6 \times 7$, i.e. there are $6$ rows $7$ columns. Instead of Red and Yellow we call the players X and O. Player X starts. Player X and O take turns to choose col... |
384 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Classical Harmonic Oscillator
Many problems in physics come down to this simple relation
Step2: We notice that after a few oscillations our numerical solution does not agree so well ... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
def undamped_oscillator_euler(x0,v0,k,m,tmax,dt):
Numerically integrate the equation of motion for an undamped harmonic oscillator
using a simple euler method.
# calculate the number of time steps
n... |
385 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Morphological Transformations other than opening and closing morphological operation MORPH_GRADIENT will give the difference between dilation and erosion top_hat will give the diff... | Python Code::
import cv2
import numpy as np
%matplotlib notebook
%matplotlib inline
from matplotlib import pyplot as plt
img = cv2.imread("HappyFish.jpg",cv2.IMREAD_GRAYSCALE)
_,mask = cv2.threshold(img, 220,255,cv2.THRESH_BINARY_INV)
kernal = np.ones((5,5),np.uint8)
dilation = cv2.dilate(mask,kernal,iterations = 3)
er... |
386 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
nyc-schools_C
This script averages the ACS variables for the N census tracts closest to each school, and combines these averaged variables with the school outcomes in a single dataframe (sav... | Python Code:
import pandas as pd
import numpy as np
import os
bp_data = '/Users/bryanfry/projects/proj_nyc-schools/data_files'
n_tracts = 10 # Average ACS variable from 20 closest tracts to each school.
Explanation: nyc-schools_C
This script averages the ACS variables for the N census tracts closest to each school, an... |
387 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Autoencoder for PCA - EXERCISE
Follow the bold instructions below to reduce a 30 dimensional data set for classification into a 2-dimensional dataset! Then use the color classes to s... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Linear Autoencoder for PCA - EXERCISE
Follow the bold instructions below to reduce a 30 dimensional data set for classification into a 2-dimensional dataset! Then use the color classes to see if you stil... |
388 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import Socorro crash data into the Data Platform
We want to be able to store Socorro crash data in Parquet form so that it can be made accessible from re
Step4: We create the pyspark dataty... | Python Code:
!conda install boto3 --yes
import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
Explanation: Import Socorro crash data into the Data Platform
We want to be able to store Socorro crash data in Parquet form so that it can be made accessible from re:dash.
See Bug 1273657 fo... |
389 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Extracción de datos web (Web scrapping)
Ante la generación masiva a traves de la red es importante tener herramientas que permitan la extracción de datos a partir de fuentes cuya ubicación e... | Python Code:
import webbrowser
Explanation: Extracción de datos web (Web scrapping)
Ante la generación masiva a traves de la red es importante tener herramientas que permitan la extracción de datos a partir de fuentes cuya ubicación es esta. De esto se trata el web scrapping.
Se pueden tener elementos poco especifico... |
390 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Detecção de Outliers nas Cotas Parlamentares
Primeiro, vamos investigar manualmente alguns gastos dos deputados em 2015. Em seguida, usaremos uma técnica simples de Aprendizado de Máquina (M... | Python Code:
import pandas as pd
ceap = pd.read_csv('dados/ceap2015.csv.zip')
linhas, colunas = ceap.shape
print('Temos {} entradas com {} colunas cada.'.format(linhas, colunas))
print('Primeira entrada:')
ceap.iloc[0]
Explanation: Detecção de Outliers nas Cotas Parlamentares
Primeiro, vamos investigar manualmente algu... |
391 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework #4
These problem sets focus on list comprehensions, string operations and regular expressions.
Problem set #1
Step1: In the following cell, complete the code with an expression tha... | Python Code:
numbers_str = '496,258,332,550,506,699,7,985,171,581,436,804,736,528,65,855,68,279,721,120'
Explanation: Homework #4
These problem sets focus on list comprehensions, string operations and regular expressions.
Problem set #1: List slices and list comprehensions
Let's start with some data. The following cell... |
392 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
You are currently looking at version 1.1 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook ... | Python Code:
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
#print(cancer.DESCR) # Print the data set description
Explanation: You are currently looking at version 1.1 of this notebook. To download notebooks and datafiles, as well as get help on Jupy... |
393 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: <h2>Textbook example
Step2: To complete the model we need to define some parameter values.
Step3: <h2>Solving the model with pyCollocation</h2>
<h3>Defining a `pycollocation.TwoPoin... | Python Code:
from scipy import optimize
def nominal_interest_rate(X, pi, i_star, phi_X, phi_pi):
Nominal interest rate follows a Taylor rule.
return i_star + phi_X * np.log(X) + phi_pi * pi
def output_gap(X, pi, g, i_star, phi_X, phi_pi, rho):
i = nominal_interest_rate(X, pi, i_star, phi_X, phi_pi)
... |
394 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div align="Right">
https
Step1: Print versions
Step2: Defaults
Set date and base paths
Step3: Set log level
Step4: Set URLs and file paths
Inbound URLs
Step5: Prefetched
Step6: Plot a... | Python Code:
import os
import re
import sys
import time
import socket
import platform
import itertools
import requests as req
import logging
from imp import reload
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib as mpl
import matplotlib.cm as cm
import matplotlib.pyplot as plt
%matplotlib... |
395 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring the Lorenz System of Differential Equations
In this Notebook we explore the Lorenz system of differential equations
Step2: Computing the trajectories and plotting the result
We de... | Python Code:
%matplotlib inline
from ipywidgets import interact, interactive
from IPython.display import clear_output, display, HTML
import numpy as np
from scipy import integrate
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
from matplotlib import ani... |
396 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
机器学习工程师纳米学位
监督学习
项目 2
Step1: 练习
Step2: 数据准备
在这个部分中,我们将要为建模、训练和测试准备数据
识别特征和目标列
你获取的数据中通常都会包含一些非数字的特征,这会导致一些问题,因为大多数的机器学习算法都会期望输入数字特征进行计算。
运行下面的代码单元将学生数据分成特征和目标列看一看他们中是否有非数字特征。
Step3: 预处理特征... | Python Code:
# 载入所需要的库
import numpy as np
import pandas as pd
from time import time
from sklearn.metrics import f1_score
# 载入学生数据集
student_data = pd.read_csv("student-data.csv")
print "Student data read successfully!"
Explanation: 机器学习工程师纳米学位
监督学习
项目 2: 搭建一个学生干预系统
欢迎来到机器学习工程师纳米学位的第二个项目!在此文件中,有些示例代码已经提供给你,但你还需要实现更多的功能让项... |
397 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Feature engineering with pandas and scikit-learn
This notebook demonstrates how to use Notebooks to perform feature engineering on a dataset using Pandas.
For each dataset, you will load the... | Python Code:
import os
import pandas as pd
from google.cloud import storage
Explanation: Feature engineering with pandas and scikit-learn
This notebook demonstrates how to use Notebooks to perform feature engineering on a dataset using Pandas.
For each dataset, you will load the data into a Pandas DataFrame, clean and ... |
398 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Business-Intelligence-Laboratory-2021---Pandas" data-toc-modified-id="Busine... | Python Code:
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set_context('notebook')
pd.options.display.max_colwidth = 100
Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Bu... |
399 | 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: Retrain EfficientDet for the Edge TPU with TensorFlow Lite Model Maker
In this tutorial, we'l... | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.