Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
5,200 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Monads
Monads are the most feared concept of FP, so I reserve a complete chapter for understanding this concept.
What is a monad?
Right now, my understanding is that monads are a very flexib... | Python Code:
class Company():
def __init__(self, name, address=None):
self.address = address
self.name = name
def get_name(self):
return self.name
def get_address(self):
return self.address
Explanation: Monads
Monads are the most feared concept of FP, so I ... |
5,201 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Unlike other programs that have a single programming interface (matlab) or a dominant interface de jour (R with RStudio), Python has a whole ecosystem of programs for writing it. This can be... | Python Code:
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
import IPython
Explanation: Unlike other programs that have a single programming interface (matlab) or a dominant interface de jour (R with RStudio), Python has a whole ecosystem of programs... |
5,202 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
$$\newcommand{\xv}{\mathbf{x}}
\newcommand{\Xv}{\mathbf{X}}
\newcommand{\yv}{\mathbf{y}}
\newcommand{\Yv}{\mathbf{Y}}
\newcommand{\zv}{\mathbf{z}}
\newcommand{\av}{\mathbf{a}}
\newcommand{\W... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
!wget http://www.cs.colostate.edu/~anderson/cs480/notebooks/nn2.tar
!tar xvf nn2.tar
import neuralnetworks as nn
import qdalda
import mlutils as ml
Explanation: $$\newcommand{\xv}{\mathbf{x}}
\newcommand{\Xv}{\mathbf{X}}
\newcommand{\yv}... |
5,203 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with Python
Step1: plot() is a versatile command, and will take an arbitrary number of arguments. For example, to plot x versus y, you can issue the command
Step2: For every x, y p... | Python Code:
import matplotlib.pyplot as mpyplot
mpyplot.plot([1,2,3,4])
mpyplot.ylabel('some numbers')
mpyplot.show()
Explanation: Working with Python: functions and modules
Session 4: Using third party libraries
Matplotlib
Exercise 4.1
BioPython
Working with sequences
Connecting with biological databases
Exercise 4.2... |
5,204 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with Kafka data
During a simulation, the producer and the marketplace are constantly logging sales and the activity on the market to Kafka. These information are organised in topics.... | Python Code:
import sys
sys.path.append('../')
Explanation: Working with Kafka data
During a simulation, the producer and the marketplace are constantly logging sales and the activity on the market to Kafka. These information are organised in topics. In order to estimate customer demand and predict good prices, merchan... |
5,205 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License").
DCGAN
Step1: Import TensorFlow and enable eager execution
Step2: Load the dataset
We ... | Python Code:
# to generate gifs
!pip install imageio
Explanation: Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License").
DCGAN: An example with tf.keras and eager
<table class="tfo-notebook-buttons" align="left"><td>
<a target="_blank" href="https://colab.research.google... |
5,206 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Supervised Classification
Step2: Read the dataset
In this case the training dataset is just a csv file. In case of larger dataset more advanced file fromats like hdf5 are used.
Panda... | Python Code:
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
import os
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
import pandas as pd
from matplotlib.colors import ListedColormap
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.model_selection ... |
5,207 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An Introduction to CausalGraphicalModels
CausalGraphicalModel is a python module for describing and manipulating Causal Graphical Models and Structural Causal Models. Behind the curtain, it ... | Python Code:
from causalgraphicalmodels import CausalGraphicalModel
sprinkler = CausalGraphicalModel(
nodes=["season", "rain", "sprinkler", "wet", "slippery"],
edges=[
("season", "rain"),
("season", "sprinkler"),
("rain", "wet"),
("sprinkler", "wet"),
("wet", "slippery... |
5,208 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Graphical User Interfaces
Object oriented programming and particularly inheritance is commonly used for creating GUIs. There are a large number of different frameworks supporting building GU... | Python Code:
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello World\n(click me)"
... |
5,209 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step2: Part 1
Step3: Next, let's demonstrate the different sorts of grids we get with different numbers of layers. We'll look at grids with between 3 and 1023 nodes.
Step4: ... | Python Code:
import cProfile
import io
import pstats
import time
import warnings
from pstats import SortKey
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import xarray as xr
from landlab.components import FlowDirectorSteepest, NetworkSedimentTransporter
from landlab.data_record import DataRecor... |
5,210 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
Step1: In this chapter, We want to introduce you to the wonderful world of graph visualization.
You probably have seen graphs that are visualized as hairballs.
Apart from commu... | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo(id="v9HrR_AF5Zc", width="100%")
Explanation: Introduction
End of explanation
from nams import load_data as cf
import networkx as nx
import matplotlib.pyplot as plt
G = cf.load_seventh_grader_network()
nx.draw(G)
Explanation: In this chapter, We want to ... |
5,211 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling and Simulation in Python
Insulin minimal model
Copyright 2017 Allen Downey
License
Step1: Data
We have data from Pacini and Bergman (1986), "MINMOD
Step2: The insulin minimal mode... | Python Code:
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import functions from the modsim.py module
from modsim import *
Explanation: Modeling and Si... |
5,212 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Regression Algorithms using Apache SystemML
This notebook shows
Step2: Import SystemML API
Step3: Import numpy, sklearn, and define some helper functions
Step5: Example 1
Step6: E... | Python Code:
!pip show systemml
Explanation: Linear Regression Algorithms using Apache SystemML
This notebook shows:
- Install SystemML Python package and jar file
- pip
- SystemML 'Hello World'
- Example 1: Matrix Multiplication
- SystemML script to generate a random matrix, perform matrix multiplication, and co... |
5,213 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
tmp-API-check
The clustergrammer_widget class is now being loaded into the Network class. The class and widget instance are saved in th Network instance, net. This allows us to load data, cl... | Python Code:
import numpy as np
import pandas as pd
from clustergrammer_widget import *
net = Network(clustergrammer_widget)
Explanation: tmp-API-check
The clustergrammer_widget class is now being loaded into the Network class. The class and widget instance are saved in th Network instance, net. This allows us to load ... |
5,214 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: For this problem set, we'll be using the Jupyter notebook
Step4: Your function should print [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] for $n=10$. Check that it does
Step6: Part B (1 po... | Python Code:
def squares(n):
Compute the squares of numbers from 1 to n, such that the
ith element of the returned list equals i^2.
### BEGIN SOLUTION
if n < 1:
raise ValueError("n must be greater than or equal to 1")
return [i ** 2 for i in range(1, n + 1)]
### END SOLUTION
E... |
5,215 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CNN-Project-Exercise
We'll be using the CIFAR-10 dataset, which is very famous dataset for image recognition!
The CIFAR-10 dataset consists of 60000 32x32 colour images in 10 classes, with ... | Python Code:
# Put file path as a string here
CIFAR_DIR = './data./cifar-10-batches-py/'
Explanation: CNN-Project-Exercise
We'll be using the CIFAR-10 dataset, which is very famous dataset for image recognition!
The CIFAR-10 dataset consists of 60000 32x32 colour images in 10 classes, with 6000 images per class. There... |
5,216 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Submission Notebook
Chris Madeley
ToC
References
Statistical Test
Linear Regression (Questions)
Visualisation
Conclusion
Reflection
Change Log
<b>Revision 1
Step1: 0. References
In general,... | Python Code:
# Imports
# Numeric Packages
from __future__ import division
import numpy as np
import pandas as pd
import scipy.stats as sps
# Plotting packages
import matplotlib.pyplot as plt
from matplotlib import ticker
import seaborn as sns
%matplotlib inline
sns.set_style('whitegrid')
sns.set_context('talk')
# Other... |
5,217 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Lists Quick Reference
Table Of Contents
<a href="#1.-Construction">Construction</a>
<a href="#2.-Accessing-Data">Accessing Data</a>
<a href="#3.-Modifying">Modifying</a>
<a href="#4.-... | Python Code:
#create an empty list
empty_list=[]
empty_list=list()
simpsons = ['homer', 'marge', 'bart']
Explanation: Python Lists Quick Reference
Table Of Contents
<a href="#1.-Construction">Construction</a>
<a href="#2.-Accessing-Data">Accessing Data</a>
<a href="#3.-Modifying">Modifying</a>
<a href="#4.-Sorting">Sor... |
5,218 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tic Tac Toe
This is the solution for the Milestone Project! A two player game made within a Jupyter Notebook. Feel free to download the notebook to understand how it works!
First some import... | Python Code:
# Specifically for the iPython Notebook environment for clearing output.
from IPython.display import clear_output
# Global variables
board = [' '] * 10
game_state = True
announce = ''
Explanation: Tic Tac Toe
This is the solution for the Milestone Project! A two player game made within a Jupyter Notebook. ... |
5,219 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Run code to get all URLs
```
with open("all_urls.txt", "wb+") as fp
Step2: Load expanded data
Step3: Extract tweet features | Python Code:
len(data)
data[0].keys()
data[0][u'source']
data[0][u'is_quote_status']
data[0][u'quoted_status']['text']
data[0]['text']
count_quoted = 0
has_coordinates = 0
count_replies = 0
language_ids = defaultdict(int)
count_user_locs = 0
user_locs = Counter()
count_verified = 0
for d in data:
count_quoted += d.... |
5,220 | 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', 'snu', 'sandbox-1', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: SNU
Source ID: SANDBOX-1
Topic: Ocean
Sub-Topics: Timestepping Framework, Adve... |
5,221 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this notebook we'll look at interfacing between the composability and ability to generate complex visualizations that HoloViews provides, the power of pandas library dataframes for manipu... | Python Code:
import itertools
import numpy as np
import pandas as pd
import seaborn as sb
import holoviews as hv
np.random.seed(9221999)
Explanation: In this notebook we'll look at interfacing between the composability and ability to generate complex visualizations that HoloViews provides, the power of pandas library d... |
5,222 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Jump_to notebook introduction in lesson 10 video
Early stopping
Better callback cancellation
Jump_to lesson 10 video
Step1: Other callbacks
Step2: LR Finder
NB
Step3: NB
Step4: Export | Python Code:
x_train,y_train,x_valid,y_valid = get_data()
train_ds,valid_ds = Dataset(x_train, y_train),Dataset(x_valid, y_valid)
nh,bs = 50,512
c = y_train.max().item()+1
loss_func = F.cross_entropy
data = DataBunch(*get_dls(train_ds, valid_ds, bs), c)
#export
class Callback():
_order=0
def set_runner(self, ru... |
5,223 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bayesian Rolling Regression in PyMC3
Author
Step1: Lets load the prices of GDX and GLD.
Step2: Plotting the prices over time suggests a strong correlation. However, the correlation seems t... | Python Code:
%matplotlib inline
import pandas as pd
from pandas_datareader import data
import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt
Explanation: Bayesian Rolling Regression in PyMC3
Author: Thomas Wiecki
Pairs trading is a famous technique in algorithmic trading that plays two stocks against ea... |
5,224 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="../Pierian-Data-Logo.PNG">
<br>
<strong><center>Copyright 2019. Created by Jose Marcial Portilla.</center></strong>
MNIST Code Along with CNN
Now that we've seen the results of an ... | Python Code:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from torchvision.utils import make_grid
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt... |
5,225 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Analysis for Twitter
Overview
This tutorial is going to introduce some simple tools for detecting sentiment in Tweets. We will be using a set of tools called the Natural Language T... | Python Code:
3 + 4
Explanation: Sentiment Analysis for Twitter
Overview
This tutorial is going to introduce some simple tools for detecting sentiment in Tweets. We will be using a set of tools called the Natural Language Toolkit (NLTK). This is collection of software written in the Python programming language. An impor... |
5,226 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The model in theory
We are going to use 4 features
Step1: Read data
Step2: Plot
Step3: Price
Step4: MACD
Step5: Stochastics Oscillator
Step6: Average True Range
Step7: Create complete... | Python Code:
def MACD(df,period1,period2,periodSignal):
EMA1 = pd.DataFrame.ewm(df,span=period1).mean()
EMA2 = pd.DataFrame.ewm(df,span=period2).mean()
MACD = EMA1-EMA2
Signal = pd.DataFrame.ewm(MACD,periodSignal).mean()
Histogram = MACD-Signal
return Histogram
def stochastics_osc... |
5,227 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Say that I want to train BaggingClassifier that uses DecisionTreeClassifier: | Problem:
import numpy as np
import pandas as pd
from sklearn.ensemble import BaggingClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
X_train, y_train = load_data()
assert type(X_train) == np.ndarray
assert type(y_train) == np.ndarray
X_test = X_train
param_grid... |
5,228 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2.0 - 2.1 Migration
Step1: In this tutorial we will review the changes in the PHOEBE mesh structures. We will first explain the changes and then demonstrate them in code. As usual, let us i... | Python Code:
!pip install -I "phoebe>=2.1,<2.2"
Explanation: 2.0 - 2.1 Migration: Meshes
Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release).
End of explanation
import phoebe
b ... |
5,229 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression functions demo notebook
If you have not already done so, run the following command to install the statsmodels package
Step1: The following function runs a random model with a ran... | Python Code:
from data_cleaning_utils import import_data
dat = import_data('../Data/Test/pool82014-10-02cleaned_Subset.csv')
Explanation: Regression functions demo notebook
If you have not already done so, run the following command to install the statsmodels package:
easy_install -U statsmodels
Run the following comman... |
5,230 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Controlando o programa
programas simples são sequencias lineares de operaçoes
existem opções para adotar um fluxo menos linear
opções para tomar decisões e poder executar uma ou outra instru... | Python Code:
x=int(input("entre com um numero inteiro não maior que 10 :"))
if x > 10:
print "oops, vamos arrumar isso..."
x = 10
print "seu número é ",x
Explanation: Controlando o programa
programas simples são sequencias lineares de operaçoes
existem opções para adotar um fluxo menos linear
opções p... |
5,231 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Let’s embrace WebAssembly!
Presentation made at EuroPython 2018 - Edinburgh (by Almar Klein)
This Notebook is
Step1: Compiling 'find_prime()' to WASM
Note
Step2: Run in Browser
Step3: Ru... | Python Code:
# in RISE mode, click <Shift>+<Enter> to execute a cell
def find_prime(nth):
n = 0
i = -1
while n < nth:
i = i + 1
if i <= 1:
continue # nope
elif i == 2:
n = n + 1
else:
gotit = 1
for j in range(2, ... |
5,232 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center>
<img src="../../img/ods_stickers.jpg">
Открытый курс по машинному обучению. Сессия № 2
Автор материала
Step1: Теперь перейдем непосредственно к машинному обучению.
Данные по кредит... | Python Code:
import math
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n - r)
p, N, m, s = 0.8, 7, 4, 0
for i in range(m, N+1):
s += nCr(N, i) * p**i * (1 - p) ** (N - i)
print(s)
Explanation: <center>
<img src="../../img/ods_stickers.jpg">
Открытый курс по машинному обучению. Сессия № 2
Автор мат... |
5,233 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
STUDENT LOANS CHALLENGE
COURSERA ML CHALLENGE
<br>
This notebook was created to document the steps taken to solve the Predict Students’ Ability to Repay Educational Loans posted on the Data ... | Python Code:
# data analysis and manipulation
import numpy as np
import pandas as pd
np.set_printoptions(threshold=1000)
# visualization
import seaborn as sns
import matplotlib.pyplot as plt
#machine learning
import tensorflow as tf
#Regular expression
import re
Explanation: STUDENT LOANS CHALLENGE
COURSERA ML CHALLENG... |
5,234 | 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" style="margin-top
Step1: Each of the 4 dataframes loaded above represents a company's average sales over time. Check... | Python Code:
# Run the following to import necessary packages and import dataset. Do not use any additional plotting libraries.
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
matplotlib.style.use('ggplot')
d1 = "dataset/sales1.csv"
d2 = "dataset/sales2.csv"
d... |
5,235 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have two tensors of dimension (2*x, 1). I want to check how many of the last x elements are equal in the two tensors. I think I should be able to do this in few lines like Numpy b... | Problem:
import numpy as np
import pandas as pd
import torch
A, B = load_data()
cnt_equal = int((A[int(len(A) / 2):] == B[int(len(A) / 2):]).sum()) |
5,236 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to search the IOOS CSW catalog with Python tools
This notebook demonstrates a how to query a Catalog Service for the Web (CSW), like the IOOS Catalog, and to parse its results into endpo... | Python Code:
import os
import sys
ioos_tools = os.path.join(os.path.pardir)
sys.path.append(ioos_tools)
Explanation: How to search the IOOS CSW catalog with Python tools
This notebook demonstrates a how to query a Catalog Service for the Web (CSW), like the IOOS Catalog, and to parse its results into endpoints that can... |
5,237 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
파이썬 기본 자료형
문제
실수(부동소수점)를 하나 입력받아, 그 숫자를 반지름으로 하는 원의 면적과 둘레의 길이를 튜플로 리턴하는 함수 circle_radius를 구현하는 코드를 작성하라,
```
.
```
문자열 자료형
아래 사이트는 커피 콩의 현재 시세를 보여준다.
http
Step1: 문제
0부터 1000까지의 숫자들 중에서 홀수이... | Python Code:
odd_1000 = [x**2 for x in range(0, 1000) if x % 2 == 1]
# 리스트의 처음 다섯 개 항목
odd_1000[:5]
Explanation: 파이썬 기본 자료형
문제
실수(부동소수점)를 하나 입력받아, 그 숫자를 반지름으로 하는 원의 면적과 둘레의 길이를 튜플로 리턴하는 함수 circle_radius를 구현하는 코드를 작성하라,
```
.
```
문자열 자료형
아래 사이트는 커피 콩의 현재 시세를 보여준다.
http://beans-r-us.appspot.com/prices.html
위 사이트의 내용을 htm... |
5,238 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting data with Python
matplotlib is the main plotting library for Python
Step1: Simple Plotting
Step2: Simple plotting - with style
The default style of matplotlib is a bit lacking in ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from astropy.table import QTable
Explanation: Plotting data with Python
matplotlib is the main plotting library for Python
End of explanation
t = np.linspace(0,2,100) # 100 points linearly spaced between 0.0 and 2.0
s = np.... |
5,239 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'test-institute-2', 'sandbox-1', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: TEST-INSTITUTE-2
Source ID: SANDBOX-1
Topic: Land
Sub-Topics: Soil,... |
5,240 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multisectoral energy system with oemof
General description
Step1: Import input data
Step2: Add entities to energy system
Step3: Optimize energy system and plot results
Step4: Adding the ... | Python Code:
from oemof.solph import EnergySystem
import pandas as pd
# initialize energy system
energysystem = EnergySystem(timeindex=pd.date_range('1/1/2016',
periods=168,
freq='H'))
Explanation: Multisectoral en... |
5,241 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Post-training integer quantization with int16 activations
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href=... | 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... |
5,242 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Seaice
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify ... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'sandbox-1', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: EC-EARTH-CONSORTIUM
Source ID: SANDBOX-1
Topic: Seaice
Sub-T... |
5,243 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 14
Step1: Create a point source theory RVT motion
Step2: Create site profile
This is about the simplest profile that we can create. Linear-elastic soil and rock.
Step3: Create the... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pysra
%matplotlib inline
# Increased figure sizes
plt.rcParams["figure.dpi"] = 120
Explanation: Example 14: RVT SRA with multiple motions and simulated profiles
Example with multiple input motions and simulated soil profiles.
End... |
5,244 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Wiki-Vote Experiments Output Visualization
Step1: Parse results
Step2: PageRank Seeds Percentage
How many times the "Top X" nodes from PageRank have led to the max infection
Step3: Avg ad... | Python Code:
#!/usr/bin/python
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from stats import parse_results, get_percentage, get_avg_per_seed, draw_pie, draw_bars, draw_bars_comparison, draw_avgs
Explanation: Wiki-Vote Experiments Output Visualization
End of explanation
pr, eigen, bet = parse_r... |
5,245 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stochastic examples
This example is designed to show how to use the stochatic optimization
algorithms for descrete and semicontinous measures from the POT library.
Step1: COMPUTE TRANSPORTA... | Python Code:
# Author: Kilian Fatras <kilian.fatras@gmail.com>
#
# License: MIT License
import matplotlib.pylab as pl
import numpy as np
import ot
import ot.plot
Explanation: Stochastic examples
This example is designed to show how to use the stochatic optimization
algorithms for descrete and semicontinous measures fro... |
5,246 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Knuth-Bendix Completion Algorithm
This notebook presents the Knuth-Bendix completion algorithm for transforming a set of equations into a confluent term rewriting system. This notebook ... | Python Code:
%run Parser.ipynb
t = parse_term('x * y * z')
t
to_str(t)
eq = parse_equation('i(x) * x = 1')
eq
to_str(parse_file('Examples/group-theory-1.eqn'))
Explanation: The Knuth-Bendix Completion Algorithm
This notebook presents the Knuth-Bendix completion algorithm for transforming a set of equations into a confl... |
5,247 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Collect and Clean Twitter Data
The twitter data was obtained using the Trump Twitter Archive, the data is from 01/20/2017 - 03/02/2018 2
Step1: Using Pandas I will read the twitter json fil... | Python Code:
# load json twitter data
twitter_json = r'data/twitter_01_20_17_to_3-2-18.json'
# Convert to pandas dataframe
tweet_data = pd.read_json(twitter_json)
Explanation: Collect and Clean Twitter Data
The twitter data was obtained using the Trump Twitter Archive, the data is from 01/20/2017 - 03/02/2018 2:38 PM M... |
5,248 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dotstar LED
Dotstar LEDs are individually addressable LED strips for use with Arduinos, Raspberry Pis, and the Minnowboard. It connects to the device through the SPI pins and is driven here ... | Python Code:
from pyDrivers import dotstar
Explanation: Dotstar LED
Dotstar LEDs are individually addressable LED strips for use with Arduinos, Raspberry Pis, and the Minnowboard. It connects to the device through the SPI pins and is driven here by Python.
Start by importing the class file for the LEDs:
End of explana... |
5,249 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with data 2017. Class 1
Contact
Javier Garcia-Bernardo
garcia@uva.nl
0. Structure
About Python
Data types, structures and code
Read csv files to dataframes
Basic operations with data... | Python Code:
##Some code to run at the beginning of the file, to be able to show images in the notebook
##Don't worry about this cell
#Print the plots in this screen
%matplotlib inline
#Be able to plot images saved in the hard drive
from IPython.display import Image
#Make the notebook wider
from IPython.core.display ... |
5,250 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: <font size = "5"> Image Registration </font>
<hr style="height
Step2: Import the usual libraries
You can load that library with the code cell above
Step3: Load an image stack
Step4... | Python Code:
import sys
from pkg_resources import get_distribution, DistributionNotFound
def test_package(package_name):
Test if package exists and returns version or -1
try:
version = (get_distribution(package_name).version)
except (DistributionNotFound, ImportError) as err:
version = '-1'
... |
5,251 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h2> Goal
Step1: <h2> Only 11 features are within 5ppm of one-another
Step2: <h2> Even for all the features (not just those that were in the dataframe and passed QC), only ~1% are indisti... | Python Code:
import pandas as pd
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
import seaborn as sns
%matplotlib inline
# import the data
local_path = '/home/irockafe/Dropbox (MIT)/Alm_Lab/projects/'
project_path = ('/revo_healthcare/data/proc... |
5,252 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Custom Generator objects
This example should guide you to build your own simple generator.
Step1: Basic knowledge
We assume that you have completed at least some of the previous examples an... | Python Code:
from adaptivemd import (
Project, Task, File, PythonTask
)
project = Project('tutorial')
engine = project.generators['openmm']
modeller = project.generators['pyemma']
pdb_file = project.files['initial_pdb']
Explanation: Custom Generator objects
This example should guide you to build your own simple gen... |
5,253 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learning Algorithms - Unsupervised Learning
Reminder
Step1: PCA revisited
Step2: The pca.explained_variance_ is like the magnitude of a components influence (amount of variance explained) ... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
Explanation: Learning Algorithms - Unsupervised Learning
Reminder: In machine learning, the problem of unsupervised learning is that of trying to find hidden structure in unlabeled data. Since the training set given to the learner is un... |
5,254 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reinforcement Learning (DQN) tutorial
Author
Step2: Replay Memory
We'll be using experience replay memory for training our DQN. It stores
the transitions that the agent observes, allowing u... | Python Code:
import gym
import math
import random
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from collections import namedtuple
from itertools import count
from copy import deepcopy
from PIL import Image
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as au... |
5,255 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting the full vector-valued MNE solution
The source space that is used for the inverse computation defines a set of
dipoles, distributed across the cortex. When visualizing a source esti... | Python Code:
# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, apply_inverse
print(__doc__)
data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
# Read evoked ... |
5,256 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table style="width
Step1: Use debugging tools throughout!
Don't forget all the fun debugging tools we covered while you work on these exercises.
%debug
%pdb
import q;q.d()
And (if necessa... | Python Code:
%matplotlib inline
from __future__ import print_function
import os
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
PROJ_ROOT = os.path.join(os.pardir, os.pardir)
Explanation: <table style="width:100%; border: 0px solid black;">
<tr style="width: 100%; border: 0px solid black;"... |
5,257 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
엔트로피
엔트로피(entropy)는 확률 변수가 담을 수 있는 정보의 양을 나타내는 값으로 다음과 같이 정의한다.
확률 변수 $X$가 이산 확률 변수이면
$$ H[X] = -\sum_{k=1}^K p(x_k) \log_2 p(x_k) $$
확률 변수 $X$가 연속 확률 변수이면
$$ H[X] = -\int p(x) \log_2 p(x) \... | Python Code:
-1/6*np.log2(1/6)*6
-1/2*np.log2(1/2)-1/4*np.log2(1/4)-1/8*np.log2(1/8)-1/16*np.log2(1/16)-1/32*np.log2(1/32)-1/32*np.log2(1/32)
Explanation: 엔트로피
엔트로피(entropy)는 확률 변수가 담을 수 있는 정보의 양을 나타내는 값으로 다음과 같이 정의한다.
확률 변수 $X$가 이산 확률 변수이면
$$ H[X] = -\sum_{k=1}^K p(x_k) \log_2 p(x_k) $$
확률 변수 $X$가 연속 확률 변수이면
$$ H[X] =... |
5,258 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Beta Hedging
By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie with example algorithms by David Edwards
Part of the Quantopian Lecture Series
Step1: Now we can perform the regr... | Python Code:
# Import libraries
import numpy as np
from statsmodels import regression
import statsmodels.api as sm
import matplotlib.pyplot as plt
import math
# Get data for the specified period and stocks
start = '2014-01-01'
end = '2015-01-01'
asset = get_pricing('TSLA', fields='price', start_date=start, end_date=end... |
5,259 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Resampling
documentation
Step1: create a time series that includes a simple pattern
Step2: Downsample the series into 3 minute bins and sum the values of the timestamps falling into a bin
... | Python Code:
# min: minutes
my_index = pd.date_range('9/1/2016', periods=9, freq='min')
my_index
Explanation: Resampling
documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html
For arguments to 'freq' parameter, please see Offset Aliases
create a date range to use as an index... |
5,260 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LDA and NMF on New Job-Skill Matrix
Step1: LDA and NMF
Global arguments
Step2: Trainning LDA
Step3: Evaluation of LDA on test set by perplexity
Step4: Save LDA models
Step5: Assignning ... | Python Code:
import ja_helpers as ja_helpers; from ja_helpers import *
HOME_DIR = 'd:/larc_projects/job_analytics/'; DATA_DIR = HOME_DIR + 'data/clean/'
RES_DIR = HOME_DIR + 'results/skill_cluster/new/'
skill_df = pd.read_csv(DATA_DIR + 'skill_index.csv')
doc_skill = mmread(DATA_DIR + 'doc_skill.mtx')
skills = skill_df... |
5,261 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cleaning Your Data
Let's take a web access log, and figure out the most-viewed pages on a website from it! Sounds easy, right?
Let's set up a regex that lets us parse an Apache access log li... | Python Code:
import re
format_pat= re.compile(
r"(?P<host>[\d\.]+)\s"
r"(?P<identity>\S*)\s"
r"(?P<user>\S*)\s"
r"\[(?P<time>.*?)\]\s"
r'"(?P<request>.*?)"\s'
r"(?P<status>\d+)\s"
r"(?P<bytes>\S*)\s"
r'"(?P<referer>.*?)"\s'
r'"(?P<user_agent>.*?)"\s*'
)
Explanation: Cleaning Your Dat... |
5,262 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Built-In and custom scoring functions
Using built-in scoring functions
Step1: Binary confusion matrix
Step2: Scorers for cross-validation and grid-search
Step3: Defining your own scoring ... | Python Code:
from sklearn.datasets import make_classification
from sklearn.cross_validation import train_test_split
X, y = make_classification(random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression()
lr.fit(X_... |
5,263 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Flowers Image Classification with TensorFlow on Cloud ML Engine
This notebook demonstrates how to do image classification from scratch on a flowers dataset using the Estimator API.
Step1: I... | Python Code:
import os
PROJECT = "cloud-training-demos" # REPLACE WITH YOUR PROJECT ID
BUCKET = "cloud-training-demos-ml" # REPLACE WITH YOUR BUCKET NAME
REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1
MODEL_TYPE = "cnn"
# do not change these
os.environ["PROJECT"] = PROJECT
os.environ["BUCKET"... |
5,264 | 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="#Using-Turtle-graphics
Step1: Import everything from Turtle graphics
Step2: ... | Python Code:
from random import choice
choice([1,2,3])
choice([1,2,3])
Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Using-Turtle-graphics:-a-Tkinter-based-turtle-graphics-module-for-Python" data-toc-modified-id="Using-Turtle-graphics:-a-T... |
5,265 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Permutations
Step4: Helper code
Let's start by defining a few functions that will help us construct and inspect automata
Step5: All permutations
Step6: Window of length d
Here we keep tra... | Python Code:
import fst
Explanation: Permutations
End of explanation
# Let's see the input as a simple linear chain FSA
def make_input(srcstr, sigma = None):
converts a nonempty string into a linear chain acceptor
@param srcstr is a nonempty string
@param sigma is the source vocabulary
assert(... |
5,266 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Toggle Button Menu
Example showing how to construct a toggle button widget that can be used to select a cube dimension.
Step1: Load cube.
Step2: Compose list of options and then construct ... | Python Code:
import ipywidgets
import IPython.display
import iris
Explanation: Toggle Button Menu
Example showing how to construct a toggle button widget that can be used to select a cube dimension.
End of explanation
cube = iris.load_cube(iris.sample_data_path('A1B.2098.pp'))
print cube
Explanation: Load cube.
End of ... |
5,267 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generate names
Struggle to find a name for the variable? Let's see how you'll come up with a name for your son/daughter. Surely no human has expertize over what is a good child name, so let ... | Python Code:
start_token = " "
with open("names") as f:
names = f.read()[:-1].split('\n')
names = [start_token+name for name in names]
print ('n samples = ',len(names))
for x in names[::1000]:
print (x)
Explanation: Generate names
Struggle to find a name for the variable? Let's see how you'll come up w... |
5,268 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have two data points on a 2-D image grid and the value of some quantity of interest at these two points is known. | Problem:
import scipy.interpolate
x = [(2,2), (1,2), (2,3), (3,2), (2,1)]
y = [5,7,8,10,3]
eval = [(2.7, 2.3)]
result = scipy.interpolate.griddata(x, y, eval) |
5,269 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
k-Nearest Neighbors
Introdução
O k-Nearest Neighbors (ou KNN) é uma técnica de classificação bem simples que consiste em prever uma classe alvo ao encontrar a(s) classe(s) vizinha(s) mais pr... | Python Code:
from csv import reader
from math import sqrt
# carregar um arquivo csv
def load_csv(filename):
dataset = list()
with open(filename, 'r') as file:
csv_reader = reader(file)
for row in csv_reader:
if not row:
continue
dataset.append(row)
ret... |
5,270 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using LAMMPS with iPython and Jupyter
LAMMPS can be run interactively using iPython easily. This tutorial shows how to set this up.
Installation
Download the latest version of LAMMPS into a ... | Python Code:
from lammps import IPyLammps
L = IPyLammps()
# 2d circle of particles inside a box with LJ walls
import math
b = 0
x = 50
y = 20
d = 20
# careful not to slam into wall too hard
v = 0.3
w = 0.08
L.units("lj")
L.dimension(2)
L.atom_style("bond")
L.boundary("f f p")
L.lattice("hex", 0.85)
L.r... |
5,271 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
*****Not Working*******
In this notebook, we will implement matlab imfilter method in python. Here we will implement four modes know as - (clip, wrap, copy, reflect) in old_matlab, (0, circu... | Python Code:
import cv2
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage as scp
Explanation: *****Not Working*******
In this notebook, we will implement matlab imfilter method in python. Here we will implement four modes know as - (clip, wrap, copy, reflect) in old_matlab, (0, circular, replicate... |
5,272 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multiple Linear Regression
By Evgenia "Jenny" Nitishinskaya, Maxwell Margenot, Delaney Granizo-Mackenzie, and Gilbert Wasserman.
Part of the Quantopian Lecture Series
Step1: Multiple linear... | Python Code:
import numpy as np
import pandas as pd
import statsmodels.api as sm
# If the observations are in a dataframe, you can use statsmodels.formulas.api to do the regression instead
from statsmodels import regression
import matplotlib.pyplot as plt
Explanation: Multiple Linear Regression
By Evgenia "Jenny" Nitis... |
5,273 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center">Non-Rigid Registration
Step1: Utilities
Load utilities that are specific to the POPI data, functions for loading ground truth data, display and the labels for masks.
Step... | Python Code:
import SimpleITK as sitk
import registration_utilities as ru
import registration_callbacks as rc
from __future__ import print_function
import matplotlib.pyplot as plt
%matplotlib inline
from ipywidgets import interact, fixed
#utility method that either downloads data from the MIDAS repository or
#if alread... |
5,274 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Glance of LSTM structure and embedding layer
We will build a LSTM network to learn from char only. At each time, input is a char. We will see this LSTM is able to learn words and grammers ... | Python Code:
from lstm import lstm_unroll, lstm_inference_symbol
from bucket_io import BucketSentenceIter
from rnn_model import LSTMInferenceModel
# Read from doc
def read_content(path):
with open(path) as ins:
content = ins.read()
return content
# Build a vocabulary of what char we have in the cont... |
5,275 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In depth with SVMs
Step1: The rbf kernel has an inverse bandwidth-parameter gamma, where large gamma mean a very localized influence for each data point, and
small values mean a very global... | Python Code:
from sklearn.metrics.pairwise import rbf_kernel
line = np.linspace(-3, 3, 100)[:, np.newaxis]
kernel_value = rbf_kernel(line, [[0]], gamma=1)
plt.plot(line, kernel_value)
Explanation: In depth with SVMs: Support Vector Machines
SVM stands for "support vector machines". They are efficient and easy to use es... |
5,276 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fundamentals of Python
written by Gene Kogan
This notebook contains a small review of Python basics. We will only review several core concepts in Python with which we will be working a lot. ... | Python Code:
myVariable = 'hello world'
print(myVariable)
Explanation: Fundamentals of Python
written by Gene Kogan
This notebook contains a small review of Python basics. We will only review several core concepts in Python with which we will be working a lot. The lecture video for this notebook will discuss some of th... |
5,277 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Semantic Segmentation
In this exercise we will train an end-to-end convolutional neural network for semantic segmentation.
The goal of semantic segmentation is to classify the image on the p... | Python Code:
%matplotlib inline
import time
from os.path import join
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import utils
from data import Dataset
tf.set_random_seed(31415)
tf.logging.set_verbosity(tf.logging.ERROR)
plt.rcParams["figure.fig... |
5,278 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook performs the same task as DistanceComputtion.ipynb but for the topics, ie it computes the distance matrix for each votation subjects based on the topic modelling results.
Step1... | Python Code:
import pandas as pd
import glob
import os
import numpy as np
import matplotlib.pyplot as plt
import sklearn
import sklearn.ensemble
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score, train_test_split, cross_val_predict, learning_curve
import sklearn.met... |
5,279 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ColorScale
The colors for the ColorScale can be defined one of two ways
Step1: Attributes
ColorScales share attributes with the other Scale types
Step2: Mid
In addition they also have a mi... | Python Code:
import numpy as np
import bqplot.pyplot as plt
from bqplot import ColorScale, DateColorScale, OrdinalColorScale, ColorAxis
# setup data for plotting
np.random.seed(0)
n = 100
x_data = range(n)
y_data = np.cumsum(np.random.randn(n) * 100.0)
def create_fig(color_scale, color_data, fig_margin=None):
# all... |
5,280 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: syncID
Step3: Read in SERC Reflectance Tile
Step4: Extract NIR and VIS bands
Now that we have uploaded all the required functions, we can calculate NDVI and plot it.
Below we print... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore') #don't display warnings
# %load ../neon_aop_hyperspectral.py
Created on Wed Jun 20 10:34:49 2018
@author: bhass
import matplotlib.pyplot as plt
import numpy as np
import h5py, os, copy
d... |
5,281 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classical Planning
Classical Planning Approaches
Introduction
Planning combines the two major areas of AI
Step1: Planning as Planning Graph Search
A planning graph is a directed graph organ... | Python Code:
from planning import *
Explanation: Classical Planning
Classical Planning Approaches
Introduction
Planning combines the two major areas of AI: search and logic. A planner can be seen either as a program that searches for a solution or as one that constructively proves the existence of a solution.
Currently... |
5,282 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Recurrent neural networks
Import various modules that we need for this notebook (now using Keras 1.0.0)
Step1: Load the MNIST dataset, flatten the images, convert the class labels, and scal... | Python Code:
%pylab inline
import copy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras.datasets import imdb, reuters
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.optimizers import SGD, RMSprop
from keras.utils import n... |
5,283 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Total Calls by Community Area
In the WBEZ article and CNT analysis of neighborhood flooding, they used zip code as the primary identifier of geography. While the relied on additional data so... | Python Code:
flood_comm_top = flood_comm_sum.sort_values(by='Count Calls', ascending=False)[:20]
flood_comm_top.plot(kind='bar',x='Community Area',y='Count Calls')
# WBEZ zip data
wbez_zip = pd.read_csv('wbez_flood_311_zip.csv')
wbez_zip_top = wbez_zip.sort_values(by='number_of_311_calls',ascending=False)[:20]
wbez_zip... |
5,284 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Source localization with MNE/dSPM/sLORETA/eLORETA
The aim of this tutorial is to teach you how to compute and apply a linear
inverse method such as MNE/dSPM/sLORETA/eLORETA on evoked/raw/epo... | Python Code:
# sphinx_gallery_thumbnail_number = 10
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
Explanation: Source localization with MNE/dSPM/sLORETA/eLORETA
The aim of this tutorial is to teach you how ... |
5,285 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Document retrieval from wikipedia data
Fire up GraphLab Create
Step1: Load some text data - from wikipedia, pages on people
Step2: Data contains
Step3: Explore the dataset and checkout th... | Python Code:
import graphlab
graphlab.product_key.set_product_key("7348-CE53-3B3E-DBED-152B-828E-A99E-F303")
Explanation: Document retrieval from wikipedia data
Fire up GraphLab Create
End of explanation
people = graphlab.SFrame('people_wiki.gl/people_wiki.gl')
Explanation: Load some text data - from wikipedia, pages o... |
5,286 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modelo de evolución de un Pulsar Binario
Cálculo Simbólico de $a$ en función de $e$
Dividiendo las ecuaciones para $\dot{a}$ y $\dot{e}$ podemos eliminar el tiempo de estas expresiones y enc... | Python Code:
from sympy import *
init_printing(use_unicode=True)
a0 = Symbol('a_0')
e0 = Symbol('e_0')
e = Symbol('e')
a = Symbol('a')
integrando = Rational(12,19)*((1+Rational(73,24)*e**2+Rational(37,96)*e**4)
/(e*(1-e**2)*(1+Rational(121,304)*e**2)))
integrando
Integral = integrate(in... |
5,287 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Question Answer with TensorFlow Lite Model Maker
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
St... | 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... |
5,288 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Summary report on temperature datasets
In this notebook we inspect the temperature datasets
along with the station metadata.
At the end, a figure showing the locations of the sites on a map ... | Python Code:
# boilerplate includes
import sys
import os
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
#from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.basemap import Basemap
import matplotlib.patheffects as path_effects
import pandas as pd
import seaborn as sns
import datetime
#... |
5,289 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
處理旅程資訊
先照之前的,讀取資料
Step1: 時間的格式固定
Step2: 先用慢動作來解析看看格式
Step3: Q
把上面改成 tqdm.tqdm.pandas(tqdm.tqdm_notebook)?
偵測站
手冊附錄
https
Step4: Q
查看一下內容,比方看國道五號
python
node_data[node_data['編號'].str.star... | Python Code:
import tqdm
import tarfile
import pandas
from urllib.request import urlopen
# 檔案名稱格式
filename_format="M06A_{year:04d}{month:02d}{day:02d}.tar.gz".format
xz_filename_format="xz/M06A_{year:04d}{month:02d}{day:02d}.tar.xz".format
csv_format = "M06A/{year:04d}{month:02d}{day:02d}/{hour:02d}/TDCS_M06A_{year:04d... |
5,290 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Linear Regression
Adapted from Chapter 3 of An Introduction to Statistical Learning
Predictive modeling, using a data samples to make predictions about unobserved or future e... | Python Code:
# imports
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
# read data into a DataFrame
data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0)
data.head()
Explanation: Introduction to Linear Regression
Adapted from Chapter 3 of An Introduction to Statist... |
5,291 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ch 10
Step1: Split the timeseries dataset into two components. The first section will be for training, and the next section will be for testing.
Step2: Download some CSV timeseries data. L... | Python Code:
%matplotlib inline
import csv
import numpy as np
import matplotlib.pyplot as plt
def load_series(filename, series_idx=1):
try:
with open(filename) as csvfile:
csvreader = csv.reader(csvfile)
data = [float(row[series_idx]) for row in csvreader if len(row) > 0... |
5,292 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Optimization Exercise 1
Imports
Step1: Hat potential
The following potential is often used in Physics and other fields to describe symmetry breaking and is often known as the "hat potential... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
Explanation: Optimization Exercise 1
Imports
End of explanation
# YOUR CODE HERE
def hat(x,a,b):
v=-1*a*x**2+b*x**4
return v
assert hat(0.0, 1.0, 1.0)==0.0
assert hat(0.0, 1.0, 1.0)==0.0
assert hat(1.... |
5,293 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classic Approach
Step1: First Step
Step2: Second Step
Step3: By just randomly guessing, we get approx. 1/3 right, which is what we expect
Step4: Third Step
Step5: This is the baseline w... | Python Code:
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
%pylab inline
import pandas as pd
print(pd.__version__)
Explanation: Classic Approach
End of explanation
df = pd.read_csv('./insurance-customers-300.csv', sep=';')
y=df['group']
df.drop('group', axis='columns', inplace=True)
X = df.as_mat... |
5,294 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualizing Networks
The following demonstrates basic use of nupic.frameworks.viz.NetworkVisualizer to visualize a network.
Before you begin, you will need to install the otherwise optional ... | Python Code:
from nupic.engine import Network, Dimensions
# Create Network instance
network = Network()
# Add three TestNode regions to network
network.addRegion("region1", "TestNode", "")
network.addRegion("region2", "TestNode", "")
network.addRegion("region3", "TestNode", "")
# Set dimensions on first region
region1 ... |
5,295 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Transferência de Aprendizado com uma ConvNet Pré-Treinada
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href=... | 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... |
5,296 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing a Model
Based on Kevin Markham's video series
Step1: Logistic regression
Step2: Classification accuracy
Step3: Generating an Optimal KNN classifier
Look back at 04_model_training ... | Python Code:
# read in the iris data
from sklearn.datasets import load_iris
iris = load_iris()
# create X (features) and y (response)
X = iris.data
y = iris.target
Explanation: Testing a Model
Based on Kevin Markham's video series: Introduction to machine learning with scikit-learn
jupyter notebook 05_model_evaluation_... |
5,297 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Class 4
Step1: matplotlib
matplotlib is a powerful plotting module that is part of Python's standard library. The website for matplotlib is at http
Step2: Next, we want to make sure that t... | Python Code:
# Import numpy
import numpy as np
# Define T and g
T = 40
y0 =50
g = 0.01
# Compute yT using the direct approach and print
yT = (1+g)**T*y0
print('Direct approach: ',yT)
# Initialize a 1-dimensional array called y that has T+1 zeros
y = np.zeros(T+1)
# Set the initial value of y to equal y0
y[0] = y0
#... |
5,298 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Tipos de fronteras en Clasificación
Primero, se generan los conjuntos de datos con los que se analizarán las distintas fronteras y algoritmos a utilizar
Step1: A continuación, se visuali... | Python Code:
# Generacion de los datos para analisis
from sklearn.utils import check_random_state
import matplotlib.patches as mpatches
import numpy as np
def build_data(seed, noise_seed=64, n_samples=500, noise=20):
n_samples=500
mean = (0,-4)
C = np.array([[0.3, 0.1], [0.1, 1.5]])
np.random.seed(seed)... |
5,299 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Zero-copy communication between C++ and Python
Numpy arrays are just C arrays wrapped with metadata in Python. Thus, we can share data between C and Python without even copying. In general, ... | Python Code:
import numpy
import commonblock
tracks = commonblock.NumpyCommonBlock(
trackermu_qoverp = numpy.zeros(1000, dtype=numpy.double),
trackermu_qoverp_err = numpy.zeros(1000, dtype=numpy.double),
trackermu_phi = numpy.zeros(1000, dtype=numpy.double),
trackermu_eta = numpy.zeros... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.