Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
8,400 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'niwa', 'sandbox-2', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: NIWA
Source ID: SANDBOX-2
Sub-Topics: Radiative Forcings.
Properties: ... |
8,401 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DSGRN Query Functions
Step1: We show here the network being considered in this example
Step2: Query Overview
In order to perform queries on the database sometimes preprocessing is necessar... | Python Code:
from DSGRN import *
database = Database("querytest.db")
database.parametergraph.dimension()
Explanation: DSGRN Query Functions
End of explanation
database
print(database.network.specification())
Explanation: We show here the network being considered in this example:
End of explanation
monostable_query_obje... |
8,402 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This tutorial introduces the basic features for simulating titratable systems via the constant pH method.
The constant pH method is one of the methods implemented for simulating... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import scipy.constants # physical constants
import espressomd
import pint # module for working with units and dimensions
from espressomd import electrostatics, polymer, reaction_ensemble
from espressomd.interactions import HarmonicBond
ureg = pint.UnitRe... |
8,403 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The inimitable schema library
Part 2
By @stavros
Structured data is everywhere
Step1: How do we validate it?
Step2: <div style="text-align
Step4: Tricks | Python Code:
data = {
"operation": "upload", # "upload" or "delete"
"timeout": 3600, # Optional, how long the sig should be valid for.
"md5": "deadbeefetc", # Optional
"files": {
"5gbCtxlvljhx5-al": {
"size": 65536,
"shred_date": "2015-05-02T00:00:00Z" # Must be a dat... |
8,404 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning Engineer Nanodegree
Model Evaluation & Validation
Project 1
Step1: Data Exploration
In this first section of this project, you will make a cursory investigation about the B... | Python Code:
# Import libraries necessary for this project
import numpy as np
import pandas as pd
import visuals as vs # Supplementary code
from sklearn.cross_validation import ShuffleSplit
# Pretty display for notebooks
%matplotlib inline
# Load the Boston housing dataset
data = pd.read_csv('housing.csv')
prices = dat... |
8,405 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
As seen above we have a clear outsider that lies way outside SF, probably a typo. Hence we sort this datapoint out,
Step1: The points now all seem to be within SF borders
Step3: I will now... | Python Code:
X = X[X['lon'] < -122]
X.plot(kind='scatter', x='lon', y='lat')
Explanation: As seen above we have a clear outsider that lies way outside SF, probably a typo. Hence we sort this datapoint out,
End of explanation
from sklearn.cluster import KMeans
#To work with out cluster we have to turn our panda datafram... |
8,406 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dice, Polls & Dirichlet Multinomials
As part of a longer term project to learn Bayesian Statistics, I'm currently reading Bayesian Data Analysis, 3rd Edition by Andrew Gelman, John Carlin, H... | Python Code:
y = np.asarray([20, 21, 17, 19, 17, 28])
k = len(y)
p = 1/k
n = y.sum()
n, p
Explanation: Dice, Polls & Dirichlet Multinomials
As part of a longer term project to learn Bayesian Statistics, I'm currently reading Bayesian Data Analysis, 3rd Edition by Andrew Gelman, John Carlin, Hal Stern, David Dunson, Ak... |
8,407 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
10 For-Loop-Rückblick-Übungen
In den Teilen der folgenden Übungen habe ich den Code mit "XXX" ausgewechselt. Es gilt in allen Übungen, den korrekten Code auszuführen und die Zelle dann auszu... | Python Code:
primzweibissieben = [2, 3, 5, 7]
for prime in primzweibissieben:
print(prime)
Explanation: 10 For-Loop-Rückblick-Übungen
In den Teilen der folgenden Übungen habe ich den Code mit "XXX" ausgewechselt. Es gilt in allen Übungen, den korrekten Code auszuführen und die Zelle dann auszuführen.
1.Drucke alle... |
8,408 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercici de navegació
<span title="Roomba navigating around furniture"><img src="img/roomba.jpg" align="right" width=200></span>
Un robot mòbil com el Roomba de la imatge ha d'evitar xocar a... | Python Code:
from functions import connect, touch, forward, backward, left, right, stop, disconnect
from time import sleep
connect()
Explanation: Exercici de navegació
<span title="Roomba navigating around furniture"><img src="img/roomba.jpg" align="right" width=200></span>
Un robot mòbil com el Roomba de la imatge ha ... |
8,409 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Denoising using a TV-2 filter
In this demo we show how to use the ISS filter described in Nonlinear inverse scale space methods
M Burger, G Gilboa, S Osher, J Xu - Communications in Mathemat... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import advancedfilters as af
Explanation: Denoising using a TV-2 filter
In this demo we show how to use the ISS filter described in Nonlinear inverse scale space methods
M Burger, G Gilboa, S Osher, J Xu - Communications in Mathematical Sciences, 2006
End ... |
8,410 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook is developed as part of the KIPAC/StatisticalMethods course, (c) 2019 Adam Mantz, licensed under the GPLv2.
What's the deal with REPLACE_WITH_YOUR_SOLUTION?
Tutorial notebooks ... | Python Code:
class SolutionMissingError(Exception):
def __init__(self):
Exception.__init__(self,"You need to complete the solution for this code to work!")
def REPLACE_WITH_YOUR_SOLUTION():
raise SolutionMissingError
REMOVE_THIS_LINE = REPLACE_WITH_YOUR_SOLUTION
Explanation: This notebook is developed a... |
8,411 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Сравнение метрик качества бинарной классификации
Programming Assignment
В этом задании мы разберемся, в чем состоит разница между разными метриками качества. Мы остановимся на задаче бинарно... | Python Code:
import numpy as np
from matplotlib import pyplot as plt
import seaborn
%matplotlib inline
Explanation: Сравнение метрик качества бинарной классификации
Programming Assignment
В этом задании мы разберемся, в чем состоит разница между разными метриками качества. Мы остановимся на задаче бинарной классификаци... |
8,412 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 2
Imports
Step1: Plotting with parameters
Write a plot_sin1(a, b) function that plots $sin(ax+b)$ over the interval $[0,4\pi]$.
Customize your visualization to make it eff... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
Explanation: Interact Exercise 2
Imports
End of explanation
plt.xticks?
def plot_sin1(a,b):
x=np.linspace(0,4*np.pi,300)
plt.f... |
8,413 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SQL Alchemy Core Examples
This file contains SQLAlchemy core examples.
Test we have SQL Alchemy
Step1: Fetch an SQLite engine and create an in memory database
Step2: Now lets make a couple... | Python Code:
import sqlalchemy
sqlalchemy.__version__
Explanation: SQL Alchemy Core Examples
This file contains SQLAlchemy core examples.
Test we have SQL Alchemy
End of explanation
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:')
Explanation: Fetch an SQLite engine and create an in mem... |
8,414 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: DELF と TensorFlow Hub を使用して画像を一致させる方法
<table class="tfo-notebook-buttons" a... | Python Code:
# Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
8,415 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: 开始使用 TensorBoard
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: 在本例中使用 MNIST 数据集。接下来编写一个函数... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
8,416 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 3 – Classification
This notebook contains all the sample code and solutions to the exercises in chapter 3.
Setup
First, let's make sure this notebook works well in both python 2 and ... | 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
import matplotlib.pypl... |
8,417 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example on the use of correspondence tables
In this simple example it is shown how a vector classified according to one classification is converted into another classification
The first clas... | Python Code:
import numpy as np
import pandas as pd
Explanation: Example on the use of correspondence tables
In this simple example it is shown how a vector classified according to one classification is converted into another classification
The first classification has four categories: A, B, C, D
The second classificat... |
8,418 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Let´s reproject to Alberts or something with distance
Step1: Uncomment to reproject
proj string taken from
Step2: The area is very big -> 35000 points.
We need to make a subset of this
Ste... | Python Code:
new_data.crs = {'init':'epsg:4326'}
Explanation: Let´s reproject to Alberts or something with distance
End of explanation
new_data = new_data.to_crs("+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=37.5 +lon_0=-96 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs ")
new_data['newLon'] = new_data.apply(la... |
8,419 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Python and Natural Language Technologies
Lecture 03, Week 04
Object oriented programming
27 September 2017
Introduction
Python has been object oriented since its first versio... | Python Code:
class ClassWithInit:
def __init__(self):
pass
class ClassWithoutInit:
pass
Explanation: Introduction to Python and Natural Language Technologies
Lecture 03, Week 04
Object oriented programming
27 September 2017
Introduction
Python has been object oriented since its first version
basica... |
8,420 | 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.1 installed. (You can comment out this line if you don't use pip for your installation or ... | Python Code:
!pip install -I "phoebe>=2.1,<2.2"
Explanation: Finite Time of Integration (fti)
Setup
Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release).
End of explanation
%matp... |
8,421 | 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... |
8,422 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ABU量化系统使用文档
<center>
<img src="./image/abu_logo.png" alt="" style="vertical-align
Step2: 1. 狗股理论进行选股
狗股理论是美国基金经理迈克尔·奥希金斯于1991年提出的一种投资策略。
投资股票是为了获取回报,纸上富贵固然令人热血沸腾,但现金收入才是实实在在的回报。现金收入... | Python Code:
# 基础库导入
from __future__ import print_function
from __future__ import division
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import os
import sys
# 使用insert 0即只使用github,避免交叉使用了pip安装的... |
8,423 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple Aggregation
Step1: Pandas
Step2: What is the row sum?
Step3: Column sum?
Step4: Spark
Step5: How do we skip the header? How about using find()? What is Boolean value for true w... | Python Code:
import numpy as np
data = np.arange(1000).reshape(100,10)
print data.shape
Explanation: Simple Aggregation
End of explanation
import pandas as pd
pand_tmp = pd.DataFrame(data,
columns=['x{0}'.format(i) for i in range(data.shape[1])])
pand_tmp.head()
Explanation: Pandas
End of explanation
pand... |
8,424 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quickstart
geoplot is a geospatial data visualization library designed for data scientists and geospatial analysts that just want to get things done. In this tutorial we will learn the basic... | Python Code:
# Configure matplotlib.
%matplotlib inline
# Unclutter the display.
import pandas as pd; pd.set_option('max_columns', 6)
Explanation: Quickstart
geoplot is a geospatial data visualization library designed for data scientists and geospatial analysts that just want to get things done. In this tutorial we wil... |
8,425 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learning curve
Table of contents
Data preprocessing
Fitting random forest
Feature importance
Step1: Data preprocessing
Load simulation dataframe and apply specified quality cuts
Extract des... | Python Code:
import sys
sys.path.append('/home/jbourbeau/cr-composition')
print('Added to PYTHONPATH')
import argparse
from collections import defaultdict
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn.apionly as sns
from sklearn.metric... |
8,426 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
問題:去掉 list中不重複的數字
例如輸入 [ 1, 1, 2, 3, 3],2沒有重複出現,所以要去掉 2,回傳 [ 1, 1, 3, 3]
限制:只能用原生 python,numpy之類的東西不能用
解題想法:
1. 找出 list中,會重複出現的元素。可以用 count()方法來解
2. 開個空 list,把 1的結果存起來。可以用 append()方法
3. 寫個 f... | Python Code:
def Non_unique(numlist):
result=[]
for n in numlist:
n_replicate=numlist.count(n)
if n_replicate >= 2:
result.append(n)
return result
Explanation: 問題:去掉 list中不重複的數字
例如輸入 [ 1, 1, 2, 3, 3],2沒有重複出現,所以要去掉 2,回傳 [ 1, 1, 3, 3]
限制:只能用原生 python,numpy之類的東西不能用
解題想法:
1. 找出 list中... |
8,427 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Train and test our model
| Python Code::
model = Net().to(device)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
EPOCHS = 15
train_max=0
test_max=0
for epoch in range(EPOCHS):
print("EPOCH:", epoch)
train(model, device, train_loader, optimizer, epoch)
test(model, device, test_loader)
print(f"\nMaximum training accur... |
8,428 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Runs this to start from scratch
Both should return an error if no credentials were previously set and your are using the service account of the instance.
Step1: Authentication
As a develope... | Python Code:
!gcloud auth revoke --quiet
!gcloud auth application-default revoke --quiet
Explanation: Runs this to start from scratch
Both should return an error if no credentials were previously set and your are using the service account of the instance.
End of explanation
# General
import google.auth
credentials, pro... |
8,429 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification in Sci-kit Learn
This code predicts the newsgroup from a list of 20 possible news groups. Its trainind on the commonly used 20-newsgroups dataset that is a "unusual" clasifica... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.core.display import display, HTML
from IPython.display import Audio
import os
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer
from sklearn.pipeline import P... |
8,430 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Statements Assessment Test
Lets test your knowledge!
Use for, split(), and if to create a Statement that will print out words that start with 's'
Step1: Use range() to print all the even nu... | Python Code:
st = 'Print only the words that start with s in this sentence'
#Code here
Explanation: Statements Assessment Test
Lets test your knowledge!
Use for, split(), and if to create a Statement that will print out words that start with 's':
End of explanation
#Code Here
Explanation: Use range() to print all the e... |
8,431 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Encoding and Decoding Simple Data Types
Step1: Encoding, then re-decoding may not give exactly the same type of object
Step2: you can see that, tuple become list
Human-consumable vs. Compa... | Python Code:
data = [{'a': 'A', 'b': (2, 4), 'c': 3.0}]
print('DATA:', repr(data))
data_string = json.dumps(data)
print('JSON:', data_string)
print(type(data_string))
Explanation: Encoding and Decoding Simple Data Types
End of explanation
data = [{'a': 'A', 'b': (2, 4), 'c': 3.0}]
print('DATA :', data)
data_string = ... |
8,432 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In today's post we will take a look at the NLP classification task. One of the simpler algorithms is Bag-Of-Words. Each word is one-hot encoded, then the words of a document are averaged an... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from bs4 import BeautifulSoup
from matplotlib import pyplot as plt
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.feature_selection import SelectKBest, chi2
from sklea... |
8,433 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PubChemPy examples
Table of Contents
1. Introduction
2. Getting Started
2. Getting Started
Retrieving a Compound
Retrieving information about a specific Compound in the PubChem database is s... | Python Code:
import pubchempy as pcp
Explanation: PubChemPy examples
Table of Contents
1. Introduction
2. Getting Started
2. Getting Started
Retrieving a Compound
Retrieving information about a specific Compound in the PubChem database is simple.
Begin by importing PubChemPy:
End of explanation
c = pcp.Compound.from_ci... |
8,434 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Week 2 - Implementation of Shaffer et al
Due January 25 at 8 PM
Step1: (1) Estimation of a sample mean from a normally distributed variable.
Let us assume that a true distribution of a proc... | Python Code:
# This line tells matplotlib to include plots here
% matplotlib inline
import numpy as np # We'll need numpy later
from scipy.stats import kstest, ttest_ind, ks_2samp, zscore
import matplotlib.pyplot as plt # This lets us access the pyplot functions
Explanation: Week 2 - Implementation of Shaffer et al
Due... |
8,435 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow training of an artificial neural network to recognize handwritten digits in the MNIST dataset and export it to Oracle RDBMS
This notebook contains the preparation steps for the no... | Python Code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Import data
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('data_dir', '/tmp/data/', 'Directory for... |
8,436 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: Lab
Step4: 2. Explore the Baseball data
Step5: 3. Blend it all together | Python Code:
Since the data is unavailabe from data camp, let's create
some of our own
# Import numpy
import numpy as np
from numpy import random
from numpy import column_stack
# np_baseball is un-available, so let's generate some random distribution!
height = np.round( np.random.normal( 5.50, 5.0, 1015 ), 2 )
weight =... |
8,437 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using ZEMAX and PyZDDE with IPython/Jupyter notebook
<img src="https
Step1: Create PyZDDE object
Step2: Load an existing lens design file (Cooke 40 degree field) into Zemax's DDE server
St... | Python Code:
# imports
from __future__ import division
import os
import matplotlib.pyplot as plt
import pyzdde.zdde as pyz
%matplotlib inline
Explanation: Using ZEMAX and PyZDDE with IPython/Jupyter notebook
<img src="https://raw.githubusercontent.com/indranilsinharoy/PyZDDE/master/Doc/Images/articleBanner_00_usingZema... |
8,438 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Investigating the character of the Theis well function
Introduction
In the previous section the Theis well function was introduced. The function, which is in fact the function known a... | Python Code:
import scipy.special as sp
import numpy as np
from scipy.special import expi
def W(u): return -expi(-u)
def W1(u):
Returns Theis' well function axpproximation by numerical intergration
Works only for scalar u
if not np.isscalar(u):
raise ValueError("","u must be a scalar")
... |
8,439 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
디리클레 분포
디리클레 분포(Dirichlet distribution)는 베타 분포의 확장판이라고 할 수 있다. 베타 분포는 0과 1사이의 값을 가지는 단일(univariate) 확률 변수의 베이지안 모형에 사용되고 디리클레 분포는 0과 1사이의 사이의 값을 가지는 다변수(multivariate) 확률 변수의 베이지안 모형에 사용된다. 다... | Python Code:
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
fig = plt.figure()
ax = Axes3D(fig)
x = [1,0,0]
y = [0,1,0]
z = [0,0,1]
verts = [zip(x, y,z)]
ax.add_collection3d(Poly3DCollection(verts, edgecolor="k", lw=5, alpha=0.4))
ax.text(1, 0, 0, "(1,0,0)", position=(0.... |
8,440 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Titanic Data Analysis
1. Introduction
In this project I will perform a data analysis on the sample Titanic dataset. The dataset contains
demographics and passenger information of 891 out of ... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter
titanic=pd.read_csv("titanic-data.csv")
titanic.head()
Explanation: Titanic Data Analysis
1. Introduction
In this project I will perform a data analysis on the sample Titanic dataset. The dataset contains... |
8,441 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using an SBML model
Getting started
Installing libraries
Before you start, you will need to install a couple of libraries
Step1: Sharing the data
If you set this variable to true, we will e... | Python Code:
import sys
import os
import copy
import PyFBA
import pickle
Explanation: Using an SBML model
Getting started
Installing libraries
Before you start, you will need to install a couple of libraries:
The ModelSeedDatabase has all the biochemistry we'll need. You can install that with git clone.
The PyFBA libra... |
8,442 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Self-Driving Car Engineer Nanodegree
Project
Step1: Read in an Image
Step9: Ideas for Lane Detection Pipeline
Some OpenCV functions (beyond those introduced in the lesson) that might be us... | Python Code:
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
Explanation: Self-Driving Car Engineer Nanodegree
Project: Finding Lane Lines on the Road
In this project, you will use the tools you learned about in the lesson... |
8,443 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visual Model Selection with Yellowbrick
In this tutorial, we are going to look at scores for a variety of Scikit-Learn models and compare them using visual diagnostic tools from Yellowbrick ... | Python Code:
import os
import pandas as pd
names = [
'class',
'cap-shape',
'cap-surface',
'cap-color'
]
mushrooms = os.path.join('data','agaricus-lepiota.txt')
dataset = pd.read_csv(mushrooms)
dataset.columns = names
dataset.head()
features = ['cap-shape', 'cap-surface', 'cap-color']
target = ['clas... |
8,444 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interpolation Exercise 2
Step1: Sparse 2d interpolation
In this example the values of a scalar field $f(x,y)$ are known at a very limited set of points in a square domain
Step2: Use meshgr... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set_style('white')
from scipy.interpolate import griddata
Explanation: Interpolation Exercise 2
End of explanation
# YOUR CODE HERE
five_1=np.ones(11)*-5
four_1=np.ones(2)*-4
three_1=np.ones(2)*-3
two_1=np.ones(... |
8,445 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
automaton.star(algo = "auto")
Build an automaton that recognizes the Kleene star of the input automaton.
The algorithm has to be one of these
Step1: This is what the general algorithm for s... | Python Code:
import vcsn
Explanation: automaton.star(algo = "auto")
Build an automaton that recognizes the Kleene star of the input automaton.
The algorithm has to be one of these:
"general": general star, no additional preconditions.
"standard": standard star.
"auto": default parameter, same as "standard" if parameter... |
8,446 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Senior Income and Home Value Distributions For San Diego County
This package extracts the home value and household income for households in San DIego county with one or more household member... | Python Code:
%matplotlib inline
%load_ext metatab
%load_ext autoreload
%autoreload 2
%mt_lib_dir lib
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import metatab as mt
import seaborn as sns; sns.set(color_codes=True)
import sqlite3
from IPython.display import display_html... |
8,447 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced Feature Engineering in BQML
Learning Objectives
Evaluate the model
Extract temporal features, feature cross temporal features
Apply ML.FEATURE_CROSS to categorical features
Create a... | Python Code:
import tensorflow as tf
print("TensorFlow version: ",tf.version.VERSION)
# Install the Google Cloud BigQuery
!pip install --user google-cloud-bigquery==1.25.0
Explanation: Advanced Feature Engineering in BQML
Learning Objectives
Evaluate the model
Extract temporal features, feature cross temporal features
... |
8,448 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step22: Comparing the spectrum of different graphs
Assume we have a graph with $N$ nodes $(0\ldots N-1)$ and undirected, unweighted edges between those notes. Then the Adjacency Matrix $A$ o... | Python Code:
import numpy as np
class GraphMatrix:
class to manage and create graph matrices
the constructor takes the dimension of the matrix
version = "2.0"
def __init__(self, dimension):
self.array = np.zeros((dimension,dimension))
self.dim = dimension
... |
8,449 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SQL
Accessing data stored in databases is a routine exercise. I demonstrate a few helpful methods in the Jupyter Notebook.
Step1: SQL
CREATE TABLE presidents (first_name, last_name, year_of... | Python Code:
!hive create_features.sql
import warnings
warnings.filterwarnings('ignore')
!conda install -c conda-forge ipython-sql -y
%load_ext sql
%config SqlMagic.autopandas=True
import pandas as pd
import sqlite3
Explanation: SQL
Accessing data stored in databases is a routine exercise. I demonstrate a few helpful m... |
8,450 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 14
Step1: Python also has a module called types, which has the definitions of the basic types of the interpreter.
Example
Step2: Through introspection, it is possible to determine ... | Python Code:
trospection or reflection is the ability of software to identify and report their own internal structures, such as types, variabl# Getting some information
# about global objects in the program
from types import ModuleType
def info(n_obj):
# Create a referênce to the object
obj = globals()[n_obj]
... |
8,451 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fire up graphlab create
Step1: Load some house value vs. crime rate data
Dataset is from Philadelphia, PA and includes average house sales price in a number of neighborhoods. The attribute... | Python Code:
import sys
sys.path.append('C:\Anaconda2\envs\dato-env\Lib\site-packages')
import graphlab
Explanation: Fire up graphlab create
End of explanation
sales = graphlab.SFrame.read_csv('Philadelphia_Crime_Rate_noNA.csv/')
sales
Explanation: Load some house value vs. crime rate data
Dataset is from Philadelphia,... |
8,452 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SA360 Report
Move SA360 report to BigQuery.
License
Copyright 2020 Google LLC,
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance ... | Python Code:
!pip install git+https://github.com/google/starthinker
Explanation: SA360 Report
Move SA360 report to BigQuery.
License
Copyright 2020 Google LLC,
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the Li... |
8,453 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Preprocessing train dataset
Divide the train folder into two folders mytrain_ox and myvalid_ox
Step1: Visualize the size of the original train dataset.
Step2: Shuffle and split the train f... | Python Code:
from sklearn.model_selection import train_test_split
import seaborn as sns
import os
import shutil
import pandas as pd
%matplotlib inline
df = pd.read_csv('list.txt', sep=' ')
df.ix[2000:2005]
Explanation: Preprocessing train dataset
Divide the train folder into two folders mytrain_ox and myvalid_ox
End of... |
8,454 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GTEx MatrixTables
To create MatrixTables containing all variant-gene associations tested in each tissue (including non-significant associations) for GTEx v8.
There are two MatrixTables, one ... | Python Code:
import subprocess
import hail as hl
hl.init()
Explanation: GTEx MatrixTables
To create MatrixTables containing all variant-gene associations tested in each tissue (including non-significant associations) for GTEx v8.
There are two MatrixTables, one is for the eQTL tissue-specific all SNP gene associations ... |
8,455 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Instant Recognition with Caffe
In this example we'll classify an image with the bundled CaffeNet model based on the network architecture of Krizhevsky et al. for ImageNet. We'll compare CPU ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Make sure that caffe is on the python path:
caffe_root = '../' # this file is expected to be in {caffe_root}/examples
import sys
sys.path.insert(0, caffe_root + 'python')
import caffe
plt.rcParams['figure.figsize'] = (10, 10)
plt.rcPa... |
8,456 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ChainerRL Quickstart Guide
This is a quickstart guide for users who just want to try ChainerRL for the first time.
If you have not yet installed ChainerRL, run the command below to install i... | Python Code:
import chainer
import chainer.functions as F
import chainer.links as L
import chainerrl
import gym
import numpy as np
Explanation: ChainerRL Quickstart Guide
This is a quickstart guide for users who just want to try ChainerRL for the first time.
If you have not yet installed ChainerRL, run the command belo... |
8,457 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Masking and padding with Keras
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 시작하기
마스킹 은 시퀀스 처리... | 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... |
8,458 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NumPy 연산
벡터화 연산
NumPy는 코드를 간단하게 만들고 계산 속도를 빠르게 하기 위한 벡터화 연산(vectorized operation)을 지원한다. 벡터화 연산이란 반복문(loop)을 사용하지 않고 선형 대수의 벡터 혹은 행렬 연산과 유사한 코드를 사용하는 것을 말한다.
예를 들어 다음과 같은 연산을 해야 한다고 하자.
$$
... | Python Code:
x = np.arange(1, 101)
x
y = np.arange(101, 201)
y
%%time
z = np.zeros_like(x)
for i, (xi, yi) in enumerate(zip(x, y)):
z[i] = xi + yi
z
z
Explanation: NumPy 연산
벡터화 연산
NumPy는 코드를 간단하게 만들고 계산 속도를 빠르게 하기 위한 벡터화 연산(vectorized operation)을 지원한다. 벡터화 연산이란 반복문(loop)을 사용하지 않고 선형 대수의 벡터 혹은 행렬 연산과 유사한 코드를 사용하는 것을... |
8,459 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Find collocations with typhon
Step1: Collocations between two data arrays
Let's try out the simplest case
Step2: Now, let’s find all measurements of primary that have a maximum distance of... | Python Code:
import cartopy.crs as projections
import numpy as np
import matplotlib.pyplot as plt
from datetime import timedelta
import xarray as xr
from typhon.plots import worldmap
from typhon.collocations import Collocator, expand, collapse
from typhon.files import FileSet, NetCDF4
from typhon.collocations import Co... |
8,460 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Searching for products within the datacube
In order to know what kinds of products are available for analysis, the datacube provides a function that will query the database and return a list... | Python Code:
import datacube
dc = datacube.Datacube(app='list-available-products-example')
Explanation: Searching for products within the datacube
In order to know what kinds of products are available for analysis, the datacube provides a function that will query the database and return a list of all the available prod... |
8,461 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anna KaRNNa
In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.... | Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
Explanation: Anna KaRNNa
In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.
This network ... |
8,462 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sequence Modeling with EDeN
The case for real valued vector labels
Aim
Step1: Artificial data generation
Step2: Discriminative model on categorical labels
Step3: Note
Step4: Model Auto O... | Python Code:
#code for making artificial dataset
import random
def swap_two_characters(seq):
'''define a function that swaps two characters at random positions in a string '''
line = list(seq)
id_i = random.randint(0,len(line)-1)
id_j = random.randint(0,len(line)-1)
line[id_i], line[id_j] = line[id_... |
8,463 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
10 - Ensemble Methods - Continuation
by Alejandro Correa Bahnsen
version 0.2, May 2016
Part of the class Machine Learning for Security Informatics
This notebook is licensed under a Creative ... | Python Code:
# read in and prepare the chrun data
# Download the dataset
import pandas as pd
import numpy as np
data = pd.read_csv('../datasets/churn.csv')
# Create X and y
# Select only the numeric features
X = data.iloc[:, [1,2,6,7,8,9,10]].astype(np.float)
# Convert bools to floats
X = X.join((data.iloc[:, [4,5]] ==... |
8,464 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Express Deep Learning in Python - Examples
We will run a couple of examples to see how different parameters affect the performance of the classifier.
Step1: Convolutional 1
Step2: Convolut... | Python Code:
import numpy
import keras
import os
from keras import backend as K
from keras import losses, optimizers, regularizers
from keras.datasets import mnist
from keras.layers import Activation, ActivityRegularization, Conv2D, Dense, Dropout, Flatten, MaxPooling2D
from keras.models import Sequential
from keras.ut... |
8,465 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kerék odometria kibővített (EKF) Kálmán-szűrővel
Csúszás nélkül gördülő kerék
A mozgás összefüggéseinek felírása
A munkafüzet (Kalman1.ipnb) és a hozzá tartozó állományok (./img/*, ./dat/a.t... | Python Code:
def h(x,rs,rw):
## mérési egyenlet függvénye
## x = állapot vektor (p,pdot,pdotdot)
## rs = szenzor tengelytől mért távolsága
## rw = kerék sugara
g = 9.81
h1 = -g*np.sin(x[0]/rw) + x[2]*np.cos(x[0]/rw) - x[2]*rs/rw
h2 = -g*np.cos(x[0]/rw) - x[2]*np.sin(x[0]/rw) - (x[1])**2*rs/... |
8,466 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quantifying Influence of The Beatle and The Rolling Stones<br><br>
With the data exported from the MusicBrainz database, which is further cleaned and aggregated in this notebook, I have refi... | Python Code:
### Import as many items as possible to have available.
### Import data from CSV
%matplotlib inline
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Log... |
8,467 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
IBM 人员流失预测
Introduction
address
Step1: 1. Exploratory Data Analysis
让我们通过 Pandas 加载 datasets,我们快速看一下前几行,重点的关注是 attrition
Step2: 从数据集中看,我们的目标列是 Attrition
此外,我们的数据是类型和数字数据混合的,对于这些非数字的类别,我们后面... | Python Code:
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
# Import statements required for Plotly
import plotly.offline as py
py.init_notebook_mode(connected=True)
import plotly.graph_... |
8,468 | 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
Generic Kernal Filter Notebook
In this notebook, we have provided an user interface which allows user to generate various image ... | 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
Generic Kernal Filter Notebook
In this notebook, we have provided an user in... |
8,469 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2017년 2학기 공학수학 기말고사
이름
Step1: 예를 들어, a 어레이를 이용하여 아래 모양의 어레이를 생성할 수 있다.
$$\left [ \begin{matrix} 30 & 32 \ 50 & 52 \end{matrix} \right ]$$
Step2: 문제 1.
(1) a 어레이에 인덱싱과 슬라이싱을 이용하여 아래 모양의 어... | Python Code:
a = np.arange(6) + np.arange(0, 51, 10)[:, np.newaxis]
a
Explanation: 2017년 2학기 공학수학 기말고사
이름 :
학번 :
시험에서 사용하는 모듈 임포트 하기
import __future__ import division, print_function
import numpy as np
import pandas as pd
from datetime import datetime as dt
넘파이 어레이 인덱싱과 슬라이싱
아래 코드로 생성된 어레이를 이용하는 문제이다.
End of explanatio... |
8,470 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I'm working on a problem that has to do with calculating angles of refraction and what not. However, it seems that I'm unable to use the numpy.sin() function in degrees. I have trie... | Problem:
import numpy as np
degree = 90
result = np.sin(np.deg2rad(degree)) |
8,471 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step4: Setting the environment
Step8: Define simple custom strategy
Step9: Configure environment
Step10: Take a look...
Step11: Time to run
Step12: <a name="full"></a>Full Throttle setu... | Python Code:
import sys
sys.path.insert(0,'..')
import IPython.display as Display
import PIL.Image as Image
import numpy as np
import random
from gym import spaces
from btgym import BTgymEnv, BTgymBaseStrategy, BTgymDataset
# Handy functions:
def show_rendered_image(rgb_array):
Convert numpy array to RGB image... |
8,472 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Excercise - Functional Programming
Q
Step1: Ans | Python Code:
names = ["Aalok", "Chandu", "Roshan", "Manish"]
for i in range(len(names)):
names[i] = hash(names[i])
print(names)
Explanation: Excercise - Functional Programming
Q: Try rewriting the code below as a map. It takes a list of real names and replaces them with code names produced using a more robust stra... |
8,473 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Updating final reports for CEC'2015
First, using the webpage pdftables the PDF tables are translate to Excel format.
First, we have put all results in a Excel file.
Then, we are going to us... | Python Code:
import pandas as pd
table_alg =pd.ExcelFile("results_cec2015.pdf.xlsx")
Explanation: Updating final reports for CEC'2015
First, using the webpage pdftables the PDF tables are translate to Excel format.
First, we have put all results in a Excel file.
Then, we are going to use the pandas library to read the... |
8,474 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Civis Python API Client
Stephen Hoover, Lead Data Scientist<br>
August 2017
Civis Platform provides you with a Data Science API which gives you direct access to Civis Platform's cloud-b... | Python Code:
print(f"Using Civis Python API Client version {civis.__version__}.")
Explanation: The Civis Python API Client
Stephen Hoover, Lead Data Scientist<br>
August 2017
Civis Platform provides you with a Data Science API which gives you direct access to Civis Platform's cloud-based infrastructure, data science t... |
8,475 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 Google LLC
Step1: Graph regularization for image classification using synthesized graphs
By Sayak Paul
<br>
<table class="tfo-notebook-buttons" align="left">
<td>
<a ta... | 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... |
8,476 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Bayesian Models
Bayesian models are at the heart of many ML applications, and they can be implemented in regression or classification. For example, the "Naive Bayes" a... | Python Code:
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribute... |
8,477 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Programutveckling med Git
En introduktion
Most images in this presentation are from the Pro Git book. The entire Pro Git book, written by Scott Chacon and Ben Straub and published by Apress,... | Python Code:
from IPython.core.display import HTML
HTML('<iframe width="560" height="315" src="https://www.youtube.com/embed/pOSqctHH9vY" frameborder="0" allowfullscreen></iframe>')
Explanation: Programutveckling med Git
En introduktion
Most images in this presentation are from the Pro Git book. The entire Pro Git book... |
8,478 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing the NYC Subway Dataset
Intro to Data Science
Step1: Class for Creating Training and Testing Samples
Step2: Section 2. Linear Regression
<h3 id='2_1'>2.1 What approach did you use... | Python Code:
import numpy as np
import pandas as pd
import scipy as sp
import scipy.stats as st
import statsmodels.api as sm
import scipy.optimize as op
import matplotlib.pyplot as plt
%matplotlib inline
filename = '/Users/excalibur/py/nanodegree/intro_ds/final_project/improved-dataset/turnstile_weather_v2.csv'
# impor... |
8,479 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
UTC
Coordinated Universal Time / Temps Universel Coordonné
Also called Greenwich Mean Time (GMT)
Time zones vs. Offsets
UTC-6 is an offset
US/Central is a time zone
CST is a hig... | Python Code:
dt_before = datetime(1995, 1, 1, 23, 59, tzinfo=tz.gettz('Pacific/Kiritimati'))
dt_after = add_absolute(dt_before, timedelta(minutes=2))
print(dt_before)
print(dt_after)
Explanation: Introduction
UTC
Coordinated Universal Time / Temps Universel Coordonné
Also called Greenwich Mean Time (GMT)
Time zones vs.... |
8,480 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dependence on primary cosmic ray flux
Step1: Create an instance of an MCEqRun class. Most options are defined in the mceq_config module, and do not require change. Look into mceq_config.py ... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
#import solver related modules
from MCEq.core import MCEqRun
import mceq_config as config
#import primary model choices
import crflux.models as pm
Explanation: Dependence on primary cosmic ray flux
End of explanation
mceq_run = MCEqRun(
#provide the string... |
8,481 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial 07 - Non linear Elliptic problem
Keywords
Step1: 3. Affine Decomposition
For this problem the affine decomposition is straightforward
Step2: 4. Main program
4.1. Read the mesh for... | Python Code:
from dolfin import *
from rbnics import *
Explanation: Tutorial 07 - Non linear Elliptic problem
Keywords: EIM, POD-Galerkin
1. Introduction
In this tutorial, we consider a non linear elliptic problem in a two-dimensional spatial domain $\Omega=(0,1)^2$. We impose a homogeneous Dirichlet condition on the b... |
8,482 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 1, Table 1
This notebook explains how I used the Harvard General Inquirer to streamline interpretation of a predictive model.
I'm italicizing the word "streamline" because I want to ... | Python Code:
# some standard modules
import csv, os, sys
from collections import Counter
import numpy as np
from scipy.stats import pearsonr
# now a module that I wrote myself, located
# a few directories up, in the software
# library for this repository
sys.path.append('../../lib')
import FileCabinet as filecab
Explan... |
8,483 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Images and TensorFlow
TensorFlow is designed to support working with images as input to neural networks. TensorFlow supports loading common file formats (JPG, PNG), working in different colo... | Python Code:
red = tf.constant([255, 0, 0])
Explanation: Images and TensorFlow
TensorFlow is designed to support working with images as input to neural networks. TensorFlow supports loading common file formats (JPG, PNG), working in different color spaces (RGB, RGBA) and common image manipulation tasks. TensorFlow make... |
8,484 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hand tuning hyperparameters
Learning Objectives
Step1: Next, we'll load our data set.
Step2: Examine the data
It's a good idea to get to know your data a little bit before you work with it... | Python Code:
import math
import shutil
import numpy as np
import pandas as pd
import tensorflow as tf
print(tf.__version__)
tf.logging.set_verbosity(tf.logging.INFO)
pd.options.display.max_rows = 10
pd.options.display.float_format = '{:.1f}'.format
Explanation: Hand tuning hyperparameters
Learning Objectives:
* Use t... |
8,485 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convert date time type to seperate the train and test set. becasue the test set data time have to be come later than the train set
Step1: pick random 10000 users row as our train data set
S... | Python Code:
train["date_time"] = pd.to_datetime(train["date_time"])
train["year"] = train["date_time"].dt.year
train["month"] = train["date_time"].dt.month
Explanation: Convert date time type to seperate the train and test set. becasue the test set data time have to be come later than the train set
End of explanation
... |
8,486 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Integration Exercise 1
Imports
Step1: Trapezoidal rule
The trapezoidal rule generates a numerical approximation to the 1d integral
Step2: Now use scipy.integrate.quad to integrate the f an... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy import integrate
Explanation: Integration Exercise 1
Imports
End of explanation
def trapz(f, a, b, N):
h = (b-a)/N
k = np.arange(1,N)
I = h*(0.5*f(a) + 0.5*f(b) + f(a+k*h).sum())
return I
f = lambda x: x**2
g =... |
8,487 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Hub Authors.
Step1: <table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: You will use the AdamW optimizer from t... | 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... |
8,488 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br>
Allen Downey
Read the female respondent file.
Step1: Make a PMF of <tt>numkdhh</tt>, the number of children under 18 in the resp... | Python Code:
%matplotlib inline
import thinkstats2
import thinkplot
import chap01soln
resp = chap01soln.ReadFemResp()
print len(resp)
Explanation: Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br>
Allen Downey
Read the female respondent file.
End of explanation
numkdhh = thinkstats2.Pmf(resp.numkdhh)
numkdhh... |
8,489 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id="top"></a>
Db2 JSON Features
There are a number of routines are that are built-in to Db2 that are used to manipulate JSON
documents. These routines are not externalized in the document... | Python Code:
%run db2.ipynb
Explanation: <a id="top"></a>
Db2 JSON Features
There are a number of routines are that are built-in to Db2 that are used to manipulate JSON
documents. These routines are not externalized in the documentation because they were originally used by the
internal API's of Db2 for managing the Mo... |
8,490 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TMY to Power Tutorial
This tutorial will walk through the process of going from TMY data to AC power using the SAPM.
Table of contents
Step1: Load TMY data
pvlib comes with a couple of TMY ... | Python Code:
# built-in python modules
import os
import inspect
# scientific python add-ons
import numpy as np
import pandas as pd
# plotting stuff
# first line makes the plots appear in the notebook
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
# finally, we import the pvlib library
impo... |
8,491 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Preprocessing using tf.transform and Dataflow </h1>
This notebook illustrates
Step1: You need to restart your kernel to register the new installs running the below cells
Step3: <h2> S... | Python Code:
%%bash
conda update -y -n base -c defaults conda
source activate py2env
pip uninstall -y google-cloud-dataflow
conda install -y pytz
pip install apache-beam[gcp]==2.9.0
pip install apache-beam[gcp] tensorflow_transform==0.8.0
%%bash
pip freeze | grep -e 'flow\|beam'
Explanation: <h1> Preprocessing using tf... |
8,492 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy data structures
When we looked at python data structures, it was obvious that the only way to deal with arrays of values (matrices / vectors etc) would be via lists and lists of lists.... | Python Code:
import numpy as np
## This is a list of everything in the module
np.__all__
an_array = np.array([0,1,2,3,4,5,6])
print an_array
print
print type(an_array)
print
help(an_array)
A = np.zeros((4,4))
print A
print
print A.shape
print
print A.diagonal()
print
A[0,0] = 2.0
print A
np.fill_diagonal(A, 1.0)
print ... |
8,493 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Effect Size
Examples and exercises for a tutorial on statistical inference.
Copyright 2016 Allen Downey
License
Step1: Part One
To explore statistics that quantify effect size, we'll look a... | Python Code:
%matplotlib inline
from __future__ import print_function, division
import numpy
import scipy.stats
import matplotlib.pyplot as pyplot
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
# seed the random number generator so we all get the same results
numpy.random.seed(17)
# so... |
8,494 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this tutorial we examine the effect of changing the target(s) on the results of a horsetail matching optimization.
We'll use TP3 from the demo problems. We also define a function for eas... | Python Code:
from horsetailmatching import HorsetailMatching, GaussianParameter
from horsetailmatching.demoproblems import TP3
from scipy.optimize import minimize
import numpy as np
import matplotlib.pyplot as plt
def plotHorsetail(theHM, c='b', label=''):
(q, h, t), _, _ = theHM.getHorsetail()
plt.plot(q, h, c... |
8,495 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture notes from the fourth week¶
Programming for the Behavioral Sciences
A large part of running behavioural experiments concerns the preparation of stimuli, i.e., what you have your part... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
# A first attempt (we ignore the target for now)
image_size = (1280, 1024) # Size of background in pixels
nDistractors = 10 # Number of distractors
distractor_size = 500
# Generate positions where to put the distractors
xr = np.random.randint(0, image_si... |
8,496 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CSV command-line kung fu
You might be surprised how much data slicing and dicing you can do from the command line using some simple tools and I/O redirection + piping. (See A Quick Introduct... | Python Code:
! grep 'Annie Cyprus' data/SampleSuperstoreSales.csv | head -3
Explanation: CSV command-line kung fu
You might be surprised how much data slicing and dicing you can do from the command line using some simple tools and I/O redirection + piping. (See A Quick Introduction to Pipes and Redirection). We've alre... |
8,497 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
High-performance simulations with TFF
This tutorial will describe how to setup high-performance simulations with TFF
in a variety of common scenarios.
TODO(b/134543154)
Step1: 단일 머신 시뮬레이션
다... | Python Code:
#@test {"skip": true}
!pip install --quiet --upgrade tensorflow-federated
!pip install --quiet --upgrade nest-asyncio
import nest_asyncio
nest_asyncio.apply()
import collections
import time
import tensorflow as tf
import tensorflow_federated as tff
source, _ = tff.simulation.datasets.emnist.load_data()
def... |
8,498 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Regression
Let's fabricate some data that shows a roughly linear relationship between page speed and amount purchased
Step1: As we only have two features, we can keep it simple and j... | Python Code:
%matplotlib inline
import numpy as np
from pylab import *
pageSpeeds = np.random.normal(3.0, 1.0, 1000)
purchaseAmount = 100 - (pageSpeeds + np.random.normal(0, 0.1, 1000)) * 3
scatter(pageSpeeds, purchaseAmount)
Explanation: Linear Regression
Let's fabricate some data that shows a roughly linear relations... |
8,499 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'miroc', 'nicam16-9s', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: MIROC
Source ID: NICAM16-9S
Sub-Topics: Radiative Forcings.
Properti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.