Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
13,200 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div align="center">
<h1>Welcome to </h1>
<br>
</div>
<div align="center">
<img src='media/mapamundi-bilbao.jpg' width="100%" />
</div>
<div align="center">
<h1>Welcome to </h1>
</div>
<di... | Python Code:
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
data = [('year', 'location', 'attendees'),
(2002, 'Charleroi', 240),
(2003, 'Charleroi', 300),
(2004, 'Göteborg', 'nan'),
(2005, 'Göteborg', 'nan'),
(2006, 'Geneva', 'nan'),
... |
13,201 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Goal 1
Injest file as pure text
Step1: Import data as a list of lines
Step2: Import data as a data frame
Step3: Goal 2
Step4: Goal 3 | Python Code:
MovieTextFile = open("tmdb_5000_movies.csv")
# for line in MovieTextFile:
# print(line) # not quite right
# type(MovieTextFile)
Explanation: Goal 1
Injest file as pure text
End of explanation
import csv
with open("tmdb_5000_movies.csv",encoding="utf8") as f:
reader = csv.reader(f)
MovieList = li... |
13,202 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predicting Like Polynomial Terms
Remember in Algebra how you had to combine "like terms" to simplify problems?
You'd see expressions such as 60 + 2x^3 - 6x + x^3 + 17x in which there are 5 ... | Python Code:
!pip install "thinc>=8.0.0" mathy_core
Explanation: Predicting Like Polynomial Terms
Remember in Algebra how you had to combine "like terms" to simplify problems?
You'd see expressions such as 60 + 2x^3 - 6x + x^3 + 17x in which there are 5 total terms but only 4 are "like terms".
2x^3 and x^3 are like, ... |
13,203 | 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 euclidean 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)
_, result = scipy.optimize.linear_sum_assignment(C) |
13,204 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hausaufgaben Einstieg in Python - Lektion 2
1.Kreiere eine Liste aus Zahlen, die aus 10 Elementen besteht, und ordne sie der Variabel a zu.
Step1: 2.Mache dasselbe mit einer Liste aus 100 E... | Python Code:
a = list(range(10))
a
Explanation: Hausaufgaben Einstieg in Python - Lektion 2
1.Kreiere eine Liste aus Zahlen, die aus 10 Elementen besteht, und ordne sie der Variabel a zu.
End of explanation
b = list(range(100))
b
Explanation: 2.Mache dasselbe mit einer Liste aus 100 Elementen und ordne sie der Variabel... |
13,205 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Processing Test
Consolidating the returned CSVs into one is relatively painless
Main issue is that for some reason the time is still in GMT, and needs 5 hours in milliseconds subtracted from... | Python Code:
s3_client = boto3.client('s3')
resource = boto3.resource('s3')
# Disable signing for anonymous requests to public bucket
resource.meta.client.meta.events.register('choose-signer.s3.*', disable_signing)
def file_list(client, bucket, prefix=''):
paginator = client.get_paginator('list_objects')
for re... |
13,206 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What patterns do we see if we average a set of similar/related words(names) and find the words with highest cosine similarity with our average vector?
Step1: Let's see what we get
We will s... | Python Code:
def best_avgs(words, all_vecs,k=10):
from operator import itemgetter
## get word embeddings for the words in our input array
embs = np.array([thrones2vec[word] for word in words])
#calculate its average
avg = np.sum(embs,axis=0)/len(words)
# Cosine Similarity wit... |
13,207 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification
Consider a binary classification problem. The data and target files are available online. The domain of the problem is chemoinformatics. Data is about toxicity of 4K small mol... | Python Code:
from eden.util import load_target
y = load_target( 'http://www.bioinf.uni-freiburg.de/~costa/bursi.target' )
Explanation: Classification
Consider a binary classification problem. The data and target files are available online. The domain of the problem is chemoinformatics. Data is about toxicity of 4K smal... |
13,208 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PROV-O Diagram Rendering Example
This example takes a PROV-O activity graph and uses the PROV Python library, which is an implementation of the Provenance Data Model by the World Wide Web Co... | Python Code:
from prov.model import ProvDocument
import prov.model as pm
Explanation: PROV-O Diagram Rendering Example
This example takes a PROV-O activity graph and uses the PROV Python library, which is an implementation of the Provenance Data Model by the World Wide Web Consortium, to create a graphical representati... |
13,209 | 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 ... |
13,210 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
https
Step1: 2
Step2: 3
Step3: 4
Step4: 5
Step5: 6 | Python Code:
# %sh
# wget https://raw.githubusercontent.com/jgoodall/cinevis/master/data/csvs/moviedata.csv
# ls -l
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
hollywood_movies = pd.read_csv('moviedata.csv')
print hollywood_movies.head()
print hollywood_movies['exclude']... |
13,211 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning with TensorFlow
Credits
Step2: Download the data from the source website if necessary.
Step3: Read the data into a string.
Step4: Build the dictionary and replace rare words... | Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
import collections
import math
import numpy as np
import os
import random
import tensorflow as tf
import urllib
import zipfile
from matplotlib import pylab
from sklearn.manifold import TSNE
Explanat... |
13,212 | 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
Text Overlay Filter Example
In this notebook, we will demonstrate how to use the overlay filter. The overlay filter scrolls text... | 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
Text Overlay Filter Example
In this notebook, we will demonstrate how to use... |
13,213 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Portfolio Optimization
“Modern Portfolio Theory (MPT), a hypothesis put forth by Harry Markowitz in his paper “Portfolio Selection,” (published in 1952 by the Journal of Finance) is an inves... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
# Download and get Daily Returns
aapl = pd.read_csv('AAPL_CLOSE',
index_col = 'Date',
parse_dates = True)
cisco = pd.read_csv('CISCO_CLOSE',
index_col = 'Date'... |
13,214 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cvxpylayers tutorial
Step1: Parametrized convex optimization problem
$$
\begin{array}{ll} \mbox{minimize} & f_0(x;\theta)\
\mbox{subject to} & f_i(x;\theta) \leq 0, \quad i=1, \ldots, m\
& ... | Python Code:
import cvxpy as cp
import matplotlib.pyplot as plt
import numpy as np
import torch
from cvxpylayers.torch import CvxpyLayer
torch.set_default_dtype(torch.double)
np.set_printoptions(precision=3, suppress=True)
Explanation: Cvxpylayers tutorial
End of explanation
n = 7
# Define variables & parameters
x = cp... |
13,215 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
Tasks for those who "feel like a pro"
Step1: data containers
list
tuple
set
dictionary
for more details see docs
Step2: Indexing starts with zero.
General indexing rule (... | Python Code:
greeting = 'Hello'
guest = "John"
my_string = 'Hello "John"'
named_greeting = 'Hello, {name}'.format(name=guest)
named_greeting2 = '{}, {}'.format(greeting, guest)
print named_greeting
print named_greeting2
Explanation: Table of Contents
Tasks for those who "feel like a pro":
Learning Resources
Online
Read... |
13,216 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analysis of Preliminary Trail Data Pulled from Cavendish Balance
Step1: The weird behavior at the beginning occured when we were making an alteration to the experimental setup itself (doing... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import math as m
from scipy.signal import argrelextrema as argex
plt.style.use('ggplot')
data_dir = '../data/'
trial_data = np.loadtxt(data_dir+'20171025_cavendish_new_wire_free_decay.txt', delimiter='\t')
plt.plot(tr... |
13,217 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Delayed yield
Introduction
Delayed yield is a phenomenon of well drawdown in a confined aquifer, which seems to follow two differnt Theis curves, the first corresponding to the Theis curve b... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
from scipy.special import expi, k0, k1 # exp. integral and two bessel functions
from wells import Wh # Hantush well function defined in module wells
def W(u): return -expi(-u) # Theis well function
Se = 1e-3
Sy = 1e-1
u = np.logspace(-5., 2., 81)
ue = u
u... |
13,218 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dataset
Initial data are read from an image, then n_data samples will be extracted from the data.
The image contains 200x200 = 40k pixels
We will extract 400k random points from the image an... | Python Code:
image_df = pd.DataFrame(image.reshape(-1,image.shape[-1]),columns=['red','green','blue'])
image_df.describe()
n_data = image.reshape(-1,image.shape[-1]).shape[0]*10 # 10 times the original number of pixels : overkill!
x = np.random.random_sample(n_data)*image.shape[1]
y = np.random.random_sample(n_data)*im... |
13,219 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Minimal Example to Produce a Synthetic Light Curve
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 yo... | Python Code:
!pip install -I "phoebe>=2.1,<2.2"
%matplotlib inline
Explanation: Minimal Example to Produce a Synthetic Light Curve
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 lat... |
13,220 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image features exercise
Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more detai... | Python Code:
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
from __future__ import print_function
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.c... |
13,221 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex AI Pipelines
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Install the latest GA version of google-cloud-pipeline-components library as well.
... | Python Code:
import os
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG
Explanation: Vertex AI Pipelines: model train, upload, and deploy using google-cloud-pipeline-compone... |
13,222 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Finite Time of Integration (fti)
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab).
... | Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
Explanation: Finite Time of Integration (fti)
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab).
End of explanation
import phoebe
from phoebe import u # units
import... |
13,223 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="http
Step1: Multiple Risk Factors
The example is based on a multiple, correlated risk factors, all (for the ease of exposition) geometric_brownian_motion objects.
Step2: Using 2,... | Python Code:
from dx import *
import time
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
%matplotlib inline
np.random.seed(10000)
Explanation: <img src="http://hilpisch.com/tpq_logo.png" alt="The Python Quants" width="45%" align="right" border="4">
Quite Complex Portfolios
This part illustrates that y... |
13,224 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Flax Imagenet Example
<a href="https
Step3: Imports / Helpers
Step7: Dataset
Step8: Training from scratch
Step9: Load pre-trained model
Step10: Inference | Python Code:
# Install ml-collections & latest Flax version from Github.
!pip install -q clu ml-collections git+https://github.com/google/flax
example_directory = 'examples/imagenet'
editor_relpaths = ('configs/default.py', 'input_pipeline.py', 'models.py', 'train.py')
repo, branch = 'https://github.com/google/flax', '... |
13,225 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Classification & How To "Frame Problems" for a Neural Network
by Andrew Trask
Twitter
Step1: Note
Step2: Lesson
Step3: Project 1
Step4: We'll create three Counter objects, one ... | Python Code:
def pretty_print_review_and_label(i):
print(labels[i] + "\t:\t" + reviews[i][:80] + "...")
g = open('reviews.txt','r') # What we know!
reviews = list(map(lambda x:x[:-1],g.readlines()))
g.close()
g = open('labels.txt','r') # What we WANT to know!
labels = list(map(lambda x:x[:-1].upper(),g.readlines())... |
13,226 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create a classifier to predict the wine color from wine quality attributes using this dataset
Step1: Split the data into features (x) and target (y, the last column in the table)
Remember y... | Python Code:
import pg8000
conn = pg8000.connect(host='training.c1erymiua9dx.us-east-1.rds.amazonaws.com', database="training", port=5432, user='dot_student', password='qgis')
import pandas as pd
df = pd.read_sql("select * from winequality", conn)
df.head()
import numpy as np
data = df.as_matrix()
len(data)
Explanation... |
13,227 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matrix and Covariance
The mat_handler.py module contains matrix class, which is the backbone of pyemu. The matrix class overloads all common mathematical operators and also uses an "auto-al... | Python Code:
from __future__ import print_function
import os
import numpy as np
from pyemu import Matrix, Cov
Explanation: Matrix and Covariance
The mat_handler.py module contains matrix class, which is the backbone of pyemu. The matrix class overloads all common mathematical operators and also uses an "auto-align" fu... |
13,228 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
13,229 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SYDE 556/750
Step1: Some sort of mapping between neural activity and a state in the world
my location
head tilt
image
remembered location
Intuitively, we call this "representation"
In neuro... | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo('KE952yueVLA', width=720, height=400, loop=1, autoplay=0)
from IPython.display import YouTubeVideo
YouTubeVideo('lfNVv0A8QvI', width=720, height=400, loop=1, autoplay=0)
Explanation: SYDE 556/750: Simulating Neurobiological Systems
Accompanying Reading... |
13,230 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Statistiques Wikipedia - énoncé
On s'instéresse aux statistiques de consultations de Wikipédia
Step1: Récupération des données
Les statistiques sont disponibles pour chaque heure et chaque... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: Statistiques Wikipedia - énoncé
On s'instéresse aux statistiques de consultations de Wikipédia : pageviews. Ce TD commence par récupération des données avant de s'intéresser aux séries temporelles.
End of explanation
import os
fol... |
13,231 | 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: Examples
One more time, I'll load the data from the NSFG.
Step2: And compute the distribution of birth weight for first bab... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import nsfg
import first
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/lice... |
13,232 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro
You will think about and calculate permutation importance with a sample of data from the Taxi Fare Prediction competition.
We won't focus on data exploration or model building for now.... | Python Code:
# Loading data, dividing, modeling and EDA below
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
data = pd.read_csv('../input/new-york-city-taxi-fare-prediction/train.csv', nrows=50... |
13,233 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Go down for licence and other metadata about this presentation
Licence
Unless stated otherwise all content is released under a [CC0]+BY licence. I'd appreciate it if you reference this but i... | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo('F4rFuIb1Ie4')
Explanation: Go down for licence and other metadata about this presentation
Licence
Unless stated otherwise all content is released under a [CC0]+BY licence. I'd appreciate it if you reference this but it is not necessary.
Using Ipython f... |
13,234 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We start by adding some data from an hdf file.
You will also need the python package h5py.
The data object keeps the loaded data, electrode geometry, ground truth, and offers some pre-proces... | Python Code:
# Data path/filename
t_ind = 38
data_path = '../data/'
file_name = data_path + 'data_sim_low.hdf5'
data_options = {'flag_cell': True, 'flag_electode': False}
data = data_in(file_name, **data_options)
Explanation: We start by adding some data from an hdf file.
You will also need the python package h5py.
The... |
13,235 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Classes
Point class
We will write a class for a point in a two dimensional Euclidian space ($\mathbb{R}^2$).
We start with the class definition (def) and the constructor (__init__) wh... | Python Code:
class Point():
Holds on a point (x,y) in the plane
def __init__(self, x=0, y=0):
assert isinstance(x, (int, float)) and isinstance(y, (int, float))
self.x = float(x)
self.y = float(y)
p = Point(1,2)
print("point", p.x, p.y)
origin = Point()
print("origin", origin.x, ori... |
13,236 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Part 1
Step2: 1.2) Finding Features
1.2.1) Find Candidate Features
Now that we have the DCIDs of all counties for your state of interest, let's figure out what featur... | Python Code:
# We need to install the Data Commons API, since they don't ship natively with
# most python installations.
# In Colab, we'll be installing the Data Commons python and pandas APIs through pip.
!pip install datacommons --upgrade --quiet
!pip install datacommons_pandas --upgrade --quiet
# We'll also install ... |
13,237 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Setup
Change to GPU runtime
Step2: The jaxlib version must correspond to the version of the existing CUDA installation you want to use, with cuda110 for CUDA 11.0, cu... | Python Code:
#@title Default title text
# 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 wri... |
13,238 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
scipy.stats - computational statistics
T-test and ANOVA (one way)
linear regression, curve fitting and parameter estimation
statistical enrichment analysis (GO enrichment, fisher test)
diffe... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
from scipy import stats
df = pd.read_csv('data/gex.txt', sep = '\t', index_col = 0)
print(df.head(4))
#df.iloc[:,1:].astype(float)
#print df.dtypes
#print type(df.GSM21712.values)
pmatrix = np.zeros((6,6))# the P-value matrix
i = -1
for ci in df.col... |
13,239 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex Training
Step1: Restart the kernel
After you install the additional packages, you need to restart the notebook kernel so it can find the packages.
Step2: Before you begin
Select a G... | Python Code:
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
! pip3... |
13,240 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Jacobiana
$$\frac{dx}{dt}=a_{1}x-b_{1}x^{2}+c_{1}xy$$
$$\frac{dy}{dt}=a_{2}y-b_{2}y^{2}+c_{1}xy$$
$$\frac{dx}{dt}=(1-x-y)x$$
$$\frac{dy}{dt}=(4-7x-3y)y$$
Step1: Equilibrios
Step2: Jacobian... | Python Code:
import numpy as np
# importamos bibliotecas para plotear
import matplotlib
import matplotlib.pyplot as plt
# para desplegar los plots en el notebook
%matplotlib inline
# para cómputo simbólico
from sympy import *
init_printing()
x, y = symbols('x y')
f = (1-x-y)*x
f
g = (4-7*x-3*y)*y
g
Explanation: Jacobia... |
13,241 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 6 – Decision Trees
This notebook contains all the sample code and solutions to the exercises in chapter 6.
<table align="left">
<td>
<a target="_blank" href="https
Step1: Trai... | Python Code:
# To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
%matplotlib inline
import matplotlib as mpl
import matplotl... |
13,242 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
While nan == nan is always False, in many cases people want to treat them as equal, and this is enshrined in pandas.DataFrame.equals: | Problem:
import pandas as pd
import numpy as np
np.random.seed(10)
df = pd.DataFrame(np.random.randint(0, 20, (10, 10)).astype(float), columns=["c%d"%d for d in range(10)])
df.where(np.random.randint(0,2, df.shape).astype(bool), np.nan, inplace=True)
def g(df):
return df.columns[df.iloc[0,:].fillna('Nan') == df.ilo... |
13,243 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
analysing tabular data
Step1: variables
Step2: this is 60 by 40
Step3: lets get the first 10 columns for the firsst 4 rows
print(data[0
Step4: we dont need to start slicng at 0
Step5: w... | Python Code:
import numpy
numpy.loadtxt
numpy.loadtxt(fname='data/weather-01.csv' delimiter = ',')
numpy.loadtxt(fname='data/weather-01.csv'delimiter=',')
numpy.loadtxt(fname='data/weather-01.csv',delimiter=',')
Explanation: analysing tabular data
End of explanation
weight_kg=55
print (weight_kg)
print('weight in pound... |
13,244 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BGS Morphological Properties
The goal of this notebook is to quantify the average morphological properties of the BGS sample. Specifically, the DESI-Data simulations require knowledge of the... | Python Code:
import os
import numpy as np
import matplotlib.pyplot as plt
import fitsio
from astropy.table import Table
from corner import corner
plt.style.use('seaborn-talk')
%matplotlib inline
basicdir = os.path.join(os.getenv('IM_DATA_DIR'), 'upenn-photdec', 'basic-catalog', 'v2')
adddir = os.path.join(os.getenv('IM... |
13,245 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Further Python Basics
Step1: Magics!
% and %% magics
interact
embed image
embed links, youtube
link notebooks
Check out http
Step3: Numpy
If you have arrays of numbers, use numpy or pandas... | Python Code:
names = ['alice', 'jonathan', 'bobby']
ages = [24, 32, 45]
ranks = ['kinda cool', 'really cool', 'insanely cool']
for (name, age, rank) in zip(names, ages, ranks):
print(name, age, rank)
for index, (name, age, rank) in enumerate(zip(names, ages, ranks)):
print(index, name, age, rank)
# return, esc,... |
13,246 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Square Wave Generator
A square wave is a periodic waveform that alternates between two discrete values.
Here's an example square wave that is generated using a simple Python function.
Step1... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
x = np.arange(0, 100)
def square(x):
return (x % 50) < 25
plt.plot(x, square(x))
import magma as m
m.set_mantle_target("ice40")
Explanation: Square Wave Generator
A square wave is a periodic waveform that alternates between two discr... |
13,247 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stokes solver for asymptotic flow
Inport away.
Step1: Load a frame from a real simulation.
Step2: Load the governing properties from the frame.
Step3: Load the last midplane slice of the ... | Python Code:
%matplotlib inline
import matplotlib
matplotlib.rcParams['figure.figsize'] = (10.0, 16.0)
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
from scipy import fftpack
from numpy import fft
import json
from functools import partial
class Foo: pass
from chest import Chest
from slict import... |
13,248 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 4
Step1: Experiment parameters (SPM12)
It's always a good idea to specify all parameters that might change between experiments at the beginning of your script.
Step2: Specify Nodes... | Python Code:
from nilearn import plotting
%matplotlib inline
from os.path import join as opj
from nipype.interfaces.io import SelectFiles, DataSink
from nipype.interfaces.spm import (OneSampleTTestDesign, EstimateModel,
EstimateContrast, Threshold)
from nipype.interfaces.utility impor... |
13,249 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nous pouvons indiquer l'hyperplane séparateur (ci-bas).
à discuter
Step1: Un exemple plus approfondi
Exercices
* Jouez avec le code pour comprendre la forme de chaque variable.
* Découvrez... | Python Code:
# Inspired by https://stackoverflow.com/questions/20045994/how-do-i-plot-the-decision-boundary-of-a-regression-using-matplotlib
# and http://stackoverflow.com/questions/28256058/plotting-decision-boundary-of-logistic-regression
X = np.array(rouge + bleu)
y = [1] * len(rouge) + [0] * len(bleu)
logreg = Logi... |
13,250 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Try what you've learned so far
Now we have some time fo you to try out Python basics that you've just learned.
1. Float point precision
One thing to be aware of with floating point arithmeti... | Python Code:
0.1 + 0.2 == 0.3
0.2 + 0.2 == 0.4
Explanation: Try what you've learned so far
Now we have some time fo you to try out Python basics that you've just learned.
1. Float point precision
One thing to be aware of with floating point arithmetic is that its precision is limited, which can cause equality tests to ... |
13,251 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Credentials
Make sure to go through Setup first!
Let's check that the environment variables have been set... We'll just try one
Step1: Google Cloud Storage
Let's see if we can create a buck... | Python Code:
GPRED_PROJECT_ID = %env GPRED_PROJECT_ID
Explanation: Credentials
Make sure to go through Setup first!
Let's check that the environment variables have been set... We'll just try one:
End of explanation
import datetime
now = datetime.datetime.now()
BUCKET_NAME = 'test_' + GPRED_PROJECT_ID + now.strftime("%Y... |
13,252 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Train Model with XLA_CPU (and CPU*)
Some operations do not have XLA_CPU equivalents, so we still need to use CPU.
Step1: Reset TensorFlow Graph
Useful in Jupyter Notebooks
Step2: Create Te... | Python Code:
import tensorflow as tf
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
tf.logging.set_verbosity(tf.logging.INFO)
Explanation: Train Model with XLA_CPU (and CPU*)
Some operations do not have XLA_CPU equivalents, so we still need to use CPU.
End of explanation
tf.reset_default_graph()
Expl... |
13,253 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kernel Density Estimation
Kernel density estimation is the process of estimating an unknown probability density function using a kernel function $K(u)$. While a histogram counts the number o... | Python Code:
%matplotlib inline
import numpy as np
from scipy import stats
import statsmodels.api as sm
import matplotlib.pyplot as plt
from statsmodels.distributions.mixture_rvs import mixture_rvs
Explanation: Kernel Density Estimation
Kernel density estimation is the process of estimating an unknown probability densi... |
13,254 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Twitter
Step2: Our query this time is going to extract the both the hashtag and the tweets associated with the hashtag. We are going to created documents full of tweets that are defined by ... | Python Code:
# BE SURE TO RUN THIS CELL BEFORE ANY OF THE OTHER CELLS
import psycopg2
import pandas as pd
import re
# pull in our stopwords
from nltk.corpus import stopwords
stops = stopwords.words('english')
Explanation: Twitter: An Analysis
Part 7
We've explored the basics of natural language processing using Postgre... |
13,255 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setup and basic objects
Get started with EnOSlib on Grid'5000.
Website
Step1: Resources abstractions
In this notebook we won't execute anything remotely, instead we'll just cover some basic... | Python Code:
import enoslib as en
Explanation: Setup and basic objects
Get started with EnOSlib on Grid'5000.
Website: https://discovery.gitlabpages.inria.fr/enoslib/index.html
Instant chat: https://framateam.org/enoslib
Source code: https://gitlab.inria.fr/discovery/enoslib
This is the first notebooks of a series that... |
13,256 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Autoencoder
Sticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. Again, loading modules and the data.
Step1: Network Archit... | Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
img = mnist.train.images[2]
plt.imshow(img.reshape((28, 28)), cmap='Greys_r')
Explanati... |
13,257 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Excercises Electric Machinery Fundamentals
Chapter 2
Problem 2-3
Step1: Description
Consider a simple power system consisting of an ideal voltage source, an ideal step-up transformer, a tra... | Python Code:
%pylab notebook
%precision 4
Explanation: Excercises Electric Machinery Fundamentals
Chapter 2
Problem 2-3
End of explanation
VS = 480.0 * exp(0j) # [Ohm] using polar syntax
Zline = 3.0 + 4.0j # [Ohm] using cartesian syntax
Zload = 30.0 + 40.0j # [Ohm] using cartesian syntax
Explanation: Description
C... |
13,258 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Additional forces
REBOUND is a gravitational N-body integrator. But you can also use it to integrate systems with additional, non-gravitational forces.
This tutorial gives you a very quick o... | Python Code:
import rebound
sim = rebound.Simulation()
sim.integrator = "whfast"
sim.add(m=1.)
sim.add(m=1e-6,a=1.)
sim.move_to_com() # Moves to the center of momentum frame
Explanation: Additional forces
REBOUND is a gravitational N-body integrator. But you can also use it to integrate systems with additional, non-gr... |
13,259 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Set the fn variable to the filename of either the training or test dataset
Step1: After running the cell below, you can move the slider to visualize the various instances of the dataset, ch... | Python Code:
#training data
#fn = 'data/ocr/optdigits.tra'
#testing data
fn = 'data/ocr/optdigits.tes'
header="x11,x12,x13,x14,x15,x16,x17,x18,x21,x22,x23,x24,x25,x26,x27,x28,x31,x32,x33,x34,x35,x36,x37,x38,x41,x42,x43,x44,x45,x46,x47,x48,x51,x52,x53,x54,x55,x56,x57,x58,x61,x62,x63,x64,x65,x66,x67,x68,x71,x72,x73,x74,x... |
13,260 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Aerosol
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'bnu', 'sandbox-1', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: BNU
Source ID: SANDBOX-1
Topic: Aerosol
Sub-Topics: Transport, Emissions, ... |
13,261 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Estimating Sentiment Orientation with SKLearn
Jason Brietstone jb4562@nyu.edu & Amar Patel acp455@stern.nyu.edu
Natural language processsing is a booming field in the finance industry becaus... | Python Code:
import nltk
#nltk.download()
Explanation: Estimating Sentiment Orientation with SKLearn
Jason Brietstone jb4562@nyu.edu & Amar Patel acp455@stern.nyu.edu
Natural language processsing is a booming field in the finance industry because of the massive amounts of user generated data that has recently become av... |
13,262 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning with TensorFlow
Credits
Step2: First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The lab... | Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
import matplotlib.pyplot as plt
import numpy as np
import os
import tarfile
import urllib
from IPython.display import display, Image
from scipy import ndimage
from sklearn.linear_model import Logist... |
13,263 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Tutorial #16
Reinforcement Learning (Q-Learning)
by Magnus Erik Hvass Pedersen
/ GitHub / Videos on YouTube
Introduction
This tutorial is about so-called Reinforcement Learning in... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
import gym
import numpy as np
import math
Explanation: TensorFlow Tutorial #16
Reinforcement Learning (Q-Learning)
by Magnus Erik Hvass Pedersen
/ GitHub / Videos on YouTube
Introduction
This tutorial is about so-called Reinforcemen... |
13,264 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
XDAWN Decoding From EEG data
ERP decoding with Xdawn ([1], [2]). For each event type, a set of
spatial Xdawn filters are trained and applied on the signal. Channels are
concatenated and resc... | Python Code:
# Authors: Alexandre Barachant <alexandre.barachant@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metri... |
13,265 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tubular surfaces
A tubular surface (or tube surface) is generated by a 3D curve, called spine, and a moving circle of radius r, with center on the spine and included in planes orthogonal to... | Python Code:
import numpy as np
from scipy import integrate
def curv(s):#curvature
return 3*np.sin(s/10.)*np.sin(s/10.)
def tors(s):#torsion is constant
return 0.35
def Frenet_eqns(x, s):# right side vector field of the system of ODE
return [ curv(s)*x[3],
curv(s)*x[4],
curv(s)... |
13,266 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy Exercise 1
Imports
Step1: Checkerboard
Write a Python function that creates a square (size,size) 2d Numpy array with the values 0.0 and 1.0
Step2: Use vizarray to visualize a checker... | Python Code:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import antipackage
import github.ellisonbg.misc.vizarray as va
Explanation: Numpy Exercise 1
Imports
End of explanation
def checkerboard(size):
a = np.zeros((size,size), dtype = np.float)
b = 2
if size %... |
13,267 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework #2
This notebook is due on Friday, October 7th, 2016 at 11
Step1: Question
Step2: Question 1
Step3: Question 2
Step4: Question 3
Step5: Section 3
Step6: Part 2
Step8: Section... | Python Code:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
'''
count_times = the time since the start of data-taking when the data was
taken (in seconds)
count_rates = the number of counts since the last time data was taken, at
the time in count_times
'''
count_ti... |
13,268 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Partition
<script type="text/javascript">
localStorage.setItem('language', 'language-py')
</script>
<table align="left" style="margin-right
Step2: Examples
In the fol... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License")
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this fi... |
13,269 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Figure 1. Sketch of a cell (top left) with the horizontal (red) and vertical (green) velocity nodes and the cell-centered node (blue). Definition of the normal vector to "surface" (segment) ... | 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
import matplotlib.pyplot as plt #calls the plotting library hereafter referred as to plt
import numpy as np
Explanation: Figure 1. Sketch of a cell... |
13,270 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification example
In this example we will be exploring an exercise of binary classification using logistic regression to estimate whether a room is occupied or not, based on physical pa... | Python Code:
%matplotlib inline
import pandas as pd #used for reading/writing data
import numpy as np #numeric library library
from matplotlib import pyplot as plt #used for plotting
import sklearn #machine learning library
occupancyData = pd.read_csv('data/occupancy_data/datatraining.txt')
Explanation: Classification... |
13,271 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Python tutorial
Launch this notebook with
Step2: types
Step3: variables
Step4: control statements
Step5: Excercise
Step6: Functions
Step7: Exercise
Step8: return
Step9: exerci... | Python Code:
1 + 1
12 * 44
Hello Data Skills!
'Hello Data Skills!'
print 'Hello Data Skills!'
print "Hello Data Skills!"
print 'Hello Data Skills!'
print Hello Data Skills!
Explanation: Python tutorial
Launch this notebook with:
1. Open terminal
2. type cd training/python
3. type ipython notebook
basics
End of explanat... |
13,272 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bike Availability Preprocessing
Data Dictionary
The raw data contains the following data per station per reading
Step4: Parse Raw Data
Define the Parsing Functions
Step5: Quick Data View
L... | Python Code:
%matplotlib inline
import logging
import itertools
import json
import os
import pickle
import folium
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from datetime import datetime
from os import listdir
from os.path import... |
13,273 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Week 9 - Dataset preprocessing
Before we utilize machine learning algorithms we must first prepare our dataset. This can often take a significant amount of time and can have a large impact o... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
%matplotlib inline
Explanation: Week 9 - Dataset preprocessing
Before we utilize machine learning algorithms we must first prepare our dataset. This can often take a significant amount of time and can have a large impact on the performa... |
13,274 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Loading Data From An HTTP Server Tutorial
MLDB gives users full control over where and how data is persisted. MLDB handles multiple protocol for URLs (see Files and URLs). In this tutorial, ... | Python Code:
from pymldb import Connection
mldb = Connection()
Explanation: Loading Data From An HTTP Server Tutorial
MLDB gives users full control over where and how data is persisted. MLDB handles multiple protocol for URLs (see Files and URLs). In this tutorial, we provide examples to load files via <code> http:// <... |
13,275 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Example
Step2: MCMC inference
Step3: With PyMC3 version >=3.9 the return_inferencedata=True kwarg makes the sample function return an arviz.InferenceData object inst... | Python Code:
# import pymc3 # colab uses 3.7 by default (as of April 2021)
# arviz needs 3.8+
#!pip install pymc3>=3.8 # fails to update
#!pip install pymc3==3.11 # latest number is hardcoded
!pip install -U pymc3>=3.8
import pymc3 as pm
print(pm.__version__)
#!pip install arviz
import arviz as az
print(az.__version__)... |
13,276 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Brainstorm Elekta phantom dataset tutorial
Here we compute the evoked from raw for the Brainstorm Elekta phantom
tutorial dataset. For comparison, see
Step1: The data were collected with a... | Python Code:
# Authors: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import find_events, fit_dipole
from mne.datasets import fetch_phantom
from mne.datasets.brainstorm import bst_phantom_elekta
from mne.io imp... |
13,277 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
draw a Histogram of array L
| Python Code::
import matplotlib.pyplot as plt
plt.hist(L)
|
13,278 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to generate histograms using the Apache Spark DataFrame API
This provides and example of how to generate frequency histograms using the Spark DataFrame API.
Disambiguation
Step1: Genera... | Python Code:
# Start the Spark Session
# This uses local mode for simplicity
# the use of findspark is optional
# install pyspark if needed
# ! pip install pyspark
# import findspark
# findspark.init("/home/luca/Spark/spark-3.3.0-bin-hadoop3")
from pyspark.sql import SparkSession
spark = (SparkSession.builder
... |
13,279 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Probability is
How likely something is to happen.
Let's start with obligatory example of coin-toss<br>
Here is our virtual coin so that everyone can see it
Step1: Seems like it will take e... | Python Code:
from IPython.display import HTML
HTML('<iframe src="https://nipunsadvilkar.github.io/coin-flip/" width="100%" height="700px" scrolling="no" style="margin-top: -70px;" frameborder="0"></iframe>')
Explanation: Probability is
How likely something is to happen.
Let's start with obligatory example of coin-toss... |
13,280 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Collections
Let's start with lists
Step1: You can mix all kind of types inside a list
Even other lists, of course
Step2: What about tuples?
Step3: What about both together?
Step4: Let's ... | Python Code:
spam = ["eggs", 7.12345] # This is a list, a comma-separated sequence of values between square brackets
print spam
print type(spam)
eggs = [spam,
1.2345,
"fooo"] # No problem with multi-line declaration
print eggs
Explanation: Collections
Let's start with lists
End of explanation... |
13,281 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Read the parquet file into a pandas dataframe. Using fastparquet here because pyarrow couldn't read in a file of this size for some reason
Step1: Get the list of ids from the processed xml ... | Python Code:
notes_file = 'synthnotes/data/note-events.parquet'
pq_root_path = 'synthnotes/data/xml_extracted'
pf = ParquetFile(notes_file)
df = pf.to_pandas()
Explanation: Read the parquet file into a pandas dataframe. Using fastparquet here because pyarrow couldn't read in a file of this size for some reason
End of e... |
13,282 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Copyright 2017 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 th... | Python Code:
#@title Setup Environment
#@test {"output": "ignore"}
import glob
BASE_DIR = "gs://download.magenta.tensorflow.org/models/music_vae/colab2"
print('Installing dependencies...')
!apt-get update -qq && apt-get install -qq libfluidsynth1 fluid-soundfont-gm build-essential libasound2-dev libjack-dev
!pip instal... |
13,283 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introdução ao NumPy
Operações matriciais
Uma das principais vantagens da estrutura ndarray é sua habilidade de processamento matricial.
Assim, para se multiplicar todos os elementos de um ar... | Python Code:
a = np.arange(20).reshape(5,4)
b = 2 * np.ones((5,4))
c = np.arange(12,0,-1).reshape(4,3)
print('a=\n', a )
print('b=\n', b )
print('c=\n', c )
Explanation: Introdução ao NumPy
Operações matriciais
Uma das principais vantagens da estrutura ndarray é sua habilidade de processamento matricial.
Assim, par... |
13,284 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'inpe', 'sandbox-2', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: INPE
Source ID: SANDBOX-2
Topic: Atmoschem
Sub-Topics: Transport, Emi... |
13,285 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling HIV infection
Modeling and Simulation in Python
Copyright 2021 Allen Downey
License
Step1: During the initial phase of HIV infection, the concentration of the virus in the bloodstr... | Python Code:
# install Pint if necessary
try:
import pint
except ImportError:
!pip install pint
# download modsim.py if necessary
from os.path import exists
filename = 'modsim.py'
if not exists(filename):
from urllib.request import urlretrieve
url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/... |
13,286 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Overview Scientific Packages for Python
Package can be seen as a container of variables and functions provided by others to help us accomplish our tasks
Import Packages into our enviroment
T... | Python Code:
import math
math.factorial(5) # functions in math package
math.e # variables in math package
Explanation: Overview Scientific Packages for Python
Package can be seen as a container of variables and functions provided by others to help us accomplish our tasks
Import Packages into our enviroment
To use a p... |
13,287 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework 4
Regression
Allen Downey
MIT License
Step1: Simple regression
An important thing to remember about regression is that it is not symmetric; that is, the regression of A onto B is n... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='white')
from utils import decorate
from thinkstats2 import Pmf, Cdf
import thinkstats2
import thinkplot
Explanation: Homework 4
Regression
Allen Downey
MIT License
End of explanati... |
13,288 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinary Differential Equations Exercise 1
Imports
Step2: Lorenz system
The Lorenz system is one of the earliest studied examples of a system of differential equations that exhibits chaotic... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
from IPython.html.widgets import interact, fixed
Explanation: Ordinary Differential Equations Exercise 1
Imports
End of explanation
def lorentz_derivs(yvec, t, sigma, rho, beta):
Compute the the der... |
13,289 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Simple Autoencoder
We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed represen... | Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
Explanation: A Simple Autoencoder
We'll start off by building a simple autoencoder to c... |
13,290 | 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', 'noaa-gfdl', 'gfdl-esm4', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: NOAA-GFDL
Source ID: GFDL-ESM4
Topic: Ocean
Sub-Topics: Timestepping Fra... |
13,291 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building the dataset of research papers
(Adapted from
Step1: The datasets will be saved as serialized Python objects, compressed with bzip2.
Saving/loading them will therefore require the p... | Python Code:
from Bio import Entrez
# NCBI requires you to set your email address to make use of NCBI's E-utilities
Entrez.email = "Your.Name.Here@example.org"
Explanation: Building the dataset of research papers
(Adapted from: Building the "evolution" research papers dataset - Luís F. Simões. Converted to Python 3 and... |
13,292 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MaxPooling2D
[pooling.MaxPooling2D.0] input 6x6x3, pool_size=(2, 2), strides=None, padding='valid', data_format='channels_last'
Step1: [pooling.MaxPooling2D.1] input 6x6x3, pool_size=(2, 2)... | Python Code:
data_in_shape = (6, 6, 3)
L = MaxPooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format='channels_last')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(270)
data_i... |
13,293 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An Introduction to Inference in Pyro
Much of modern machine learning can be cast as approximate inference and expressed succinctly in a language like Pyro. To motivate the rest of this tutor... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import torch
import pyro
import pyro.infer
import pyro.optim
import pyro.distributions as dist
pyro.set_rng_seed(101)
Explanation: An Introduction to Inference in Pyro
Much of modern machine learning can be cast as approximate inference and expressed succi... |
13,294 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
同時改訂(simultaneous revisions)とは
「各 t 期において,N 人全員が行動を (変えたければ) 変えることができる.」
協調ゲーム (coordination game)
以下の利得表のもと各人は戦略をとる場合を考える。
[(4, 4), (0, 3)]
[(3, 0), (2, 2)]
混合戦略ナッシュ均衡の組は、
(1, 0), (1, 0)... | Python Code:
%matplotlib inline
from scipy.stats import binom
import matplotlib.pyplot as plt
Explanation: 同時改訂(simultaneous revisions)とは
「各 t 期において,N 人全員が行動を (変えたければ) 変えることができる.」
協調ゲーム (coordination game)
以下の利得表のもと各人は戦略をとる場合を考える。
[(4, 4), (0, 3)]
[(3, 0), (2, 2)]
混合戦略ナッシュ均衡の組は、
(1, 0), (1, 0)
(2/3, 1/3), (2/3, 1/3... |
13,295 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Image Classification
In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile
cifar10_dataset_folder_path = 'cifar-10-batches-py'
# Use Floyd's cifar-10 dataset if present
floyd_cifa... |
13,296 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 20
Modeling and Simulation in Python
Copyright 2021 Allen Downey
License
Step1: So far the differential equations we've worked with have been first
order, which means they involve o... | Python Code:
# install Pint if necessary
try:
import pint
except ImportError:
!pip install pint
# download modsim.py if necessary
from os.path import exists
filename = 'modsim.py'
if not exists(filename):
from urllib.request import urlretrieve
url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/... |
13,297 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Character-level Language Modeling with LSTMs
This notebook is adapted from Keras' lstm_text_generation.py.
Steps
Step1: Loading some text data
Let's use some publicly available philosopy
St... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
Explanation: Character-level Language Modeling with LSTMs
This notebook is adapted from Keras' lstm_text_generation.py.
Steps:
Download a small text corpus and preprocess it.
Extract a character vocabulary and use it to vectorize the text.
Train an LSTM-ba... |
13,298 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TOC trends - October 2018 (Part 2
Step1: 1. 1990 to 2012
The code below is just for testing purposes
Step2: 2. 1990 to 2016
Step3: 3. 2002 to 2016
Step4: 4. 1990 to 2004
Step5: 5. All d... | Python Code:
# User input
# Specify projects of interest
proj_list = ['ICPW_TOCTRENDS_2018',]
# Specify results folder
res_fold = (r'../../update_autumn_2018/results')
Explanation: TOC trends - October 2018 (Part 2: Chemistry trend analysis)
The previous notebook created a new dataset for the trends analysis spanning t... |
13,299 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST SGD
Get the 'pickled' MNIST dataset from http
Step1: In lesson2-sgd we did these things ourselves | Python Code:
path = Config().data/'mnist'
path.ls()
with gzip.open(path/'mnist.pkl.gz', 'rb') as f:
((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding='latin-1')
plt.imshow(x_train[0].reshape((28,28)), cmap="gray")
x_train.shape
x_train,y_train,x_valid,y_valid = map(torch.tensor, (x_train,y_train... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.