Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
14,000 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hodgkin-Huxley IK Model
This example shows how the Hodgkin-Huxley potassium current (IK) toy model can be used.
This model recreates an experiment where a sequence of voltages is applied to ... | Python Code:
import pints
import pints.toy
import matplotlib.pyplot as plt
import numpy as np
model = pints.toy.HodgkinHuxleyIKModel()
Explanation: Hodgkin-Huxley IK Model
This example shows how the Hodgkin-Huxley potassium current (IK) toy model can be used.
This model recreates an experiment where a sequence of volta... |
14,001 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
胶囊网络(CapsNets)
基于论文:Dynamic Routing Between Capsules,作者:Sara Sabour, Nicholas Frosst and Geoffrey E. Hinton (NIPS 2017)。
部分启发来自于Huadong Liao的实现CapsNet-TensorFlow
<table align="left">
<td>
... | Python Code:
from IPython.display import IFrame
IFrame(src="https://www.youtube.com/embed/pPN8d0E3900", width=560, height=315, frameborder=0, allowfullscreen=True)
Explanation: 胶囊网络(CapsNets)
基于论文:Dynamic Routing Between Capsules,作者:Sara Sabour, Nicholas Frosst and Geoffrey E. Hinton (NIPS 2017)。
部分启发来自于Huadong Liao的实现... |
14,002 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mapping federal crop insurance in the U.S.
A Jupyter notebook (Python 3) by Peter Donovan, info@soilcarboncoalition.org
Open data is not just a thing or a tool. It's a behavior, based on bel... | Python Code:
#some usual imports, including some options for displaying large currency amounts with commas and only 2 decimals
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
pd.set_option('display.float_format', '{:,}'.format)
pd.set_option('display.precision',2)
Explanation: ... |
14,003 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced
Step1: The latex representations of parameters are mostly used while plotting distributions... so let's just create a few dummy distributions so that we can see how they're labeled... | Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
import phoebe
from phoebe import u # units
import numpy as np
logger = phoebe.logger()
Explanation: Advanced: Parameter Latex Representation
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebo... |
14,004 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This is the central location where all variables should be defined, and any relationships between them should be given. Having all definitions collected in one file is useful b... | Python Code:
# Make sure division of integers does not round to the nearest integer
from __future__ import division
import sys
sys.path.insert(0, '..') # Look for modules in directory above this one
# Make everything in python's symbolic math package available
from sympy import * # Make sure sympy functions are used in... |
14,005 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome
This notebook accompanies the Sunokisis Digital Classics common session on Named Entity Extraction, see https
Step1: And more precisely, we are using the following versions
Step2: ... | Python Code:
########
# NLTK #
########
import nltk
from nltk.tag import StanfordNERTagger
########
# CLTK #
########
import cltk
from cltk.tag.ner import tag_ner
##############
# MyCapytain #
##############
import MyCapytain
from MyCapytain.resolvers.cts.api import HttpCTSResolver
from MyCapytain.retrievers.cts5 impo... |
14,006 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matrix generation
Init symbols for sympy
Step1: Lame params
Step2: Metric tensor
${\displaystyle \hat{G}=\sum_{i,j} g^{ij}\vec{R}_i\vec{R}_j}$
Step3: ${\displaystyle \hat{G}=\sum_{i,j} g_... | Python Code:
from sympy import *
from geom_util import *
from sympy.vector import CoordSys3D
N = CoordSys3D('N')
alpha1, alpha2, alpha3 = symbols("alpha_1 alpha_2 alpha_3", real = True, positive=True)
init_printing()
%matplotlib inline
%reload_ext autoreload
%autoreload 2
%aimport geom_util
Explanation: Matrix generati... |
14,007 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TUTORIAL 04 - Graetz problem 2
Keywords
Step1: 3. Affine decomposition
In order to obtain an affine decomposition, we proceed as in the previous tutorial and recast the problem on a fixed, ... | Python Code:
from dolfin import *
from rbnics import *
Explanation: TUTORIAL 04 - Graetz problem 2
Keywords: successive constraints method
1. Introduction
This Tutorial addresses geometrical parametrization and the successive constraints method (SCM). In particular, we will solve the Graetz problem, which deals with fo... |
14,008 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification Uncertainty Analysis in Bayesian Deep Learning with Dropout Variational Inference
Here is astroNN, please take a look if you are interested in astronomy or how neural network ... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format='retina'
from tensorflow.keras.datasets import mnist
from tensorflow.keras import utils
import numpy as np
import pylab as plt
from astroNN.models import MNIST_BCNN
Explanation: Classification Uncertainty Analysis in Bayesian Deep Learning with Dropout... |
14,009 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Analysis on Movie Reviews using LSTM RNN Model
0 - negative
1 - somewhat negative
2 - neutral
3 - somewhat positive
4 - positive
Load Libraries
Step1: Load and Read Datasets
Step2... | Python Code:
import numpy as np
import pandas as pd
from gensim import corpora
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import SnowballStemmer
from keras.preprocessing import sequence
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers ... |
14,010 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example Uses Of “%%script” Magic
The %%script cell magic allows the invocation of any number of external languages without the need for installing any custom Jupyter kernels. The drawback is... | Python Code:
%%script bash
echo 'hi there!'
Explanation: Example Uses Of “%%script” Magic
The %%script cell magic allows the invocation of any number of external languages without the need for installing any custom Jupyter kernels. The drawback is that there is no context maintained between one cell invocation and the ... |
14,011 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
One way of running programs in python is by executing a script, with run <script.py> in python or python <script.py> in terminal.
What if you realize that something in the scrip... | Python Code:
# Let's first define a broken function
def blah(a, b):
c = 10
return a/b - c
# call the function
# define some varables to pass to the function
aa = 5
bb = 10
print blah(aa, bb) # call the function
Explanation: One way of running programs in python is by executing a script, with run <script... |
14,012 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Facies classification using Machine Learning
LA Team Submission ##
Lukas Mosser, Alfredo De la Fuente
In this python notebook we explore many different machine learning algorithms to outperf... | Python Code:
import xgboost as xgb
print xgb.__version__
%matplotlib inline
import pandas as pd
from pandas.tools.plotting import scatter_matrix
from pandas import set_option
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
import matplotlib.colors as colors
from sklearn... |
14,013 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convertir arreglos de numpy en tensores
Step1: Crear tensores directamente
Step2: Operaciones Básicas
Para ver todas las operaciones --> https
Step3: Hacer una sesión interactiva
El levan... | Python Code:
m1 = [[1.0, 2.0],
[3.0, 4.0]]
m2 = np.array([[1.0, 2.0],
[3.0, 4.0]],dtype=np.float32)
m3 = tf.constant([[1.0, 2.0],
[3.0, 4.0]])
print(type(m1))
print(type(m2))
print(type(m3))
t1 = tf.convert_to_tensor(m1, dtype=tf.float32)
t2 = tf.convert_to_tensor(m2, dtype=tf.flo... |
14,014 | 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', 'nuist', 'sandbox-1', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: NUIST
Source ID: SANDBOX-1
Topic: Seaice
Sub-Topics: Dynamics, Thermodynam... |
14,015 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NANO106 - Symmetry Computations on $mmm (D_{2h})$ Point Group
by Shyue Ping Ong
This notebook demonstrates the computation of orbits in the mmm point group. It is part of course material for... | Python Code:
import numpy as np
import itertools
from sympy import symbols
Explanation: NANO106 - Symmetry Computations on $mmm (D_{2h})$ Point Group
by Shyue Ping Ong
This notebook demonstrates the computation of orbits in the mmm point group. It is part of course material for UCSD's NANO106 - Crystallography of Mater... |
14,016 | 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="#Keras-Basics" data-toc-modified-id="Keras-Basics-1"><span class="toc-item-nu... | Python Code:
# code for loading the format for the notebook
import os
# path : store the current path to convert back to it later
path = os.getcwd()
os.chdir(os.path.join('..', 'notebook_format'))
from formats import load_style
load_style(plot_style=False)
os.chdir(path)
# 1. magic to print version
# 2. magic so that t... |
14,017 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Build a fraud detection model on Vertex AI
Step1: <table align="left">
<td>
<a href="https
Step2: Install the latest version of the Vertex AI client library.
Run the following comman... | Python Code:
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
14,018 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Table of Contents
<p><div class="lev1 toc-item"><a href="#Exponential-growth" data-toc-modified-id="Exponential-growth-1"><span class="toc-item-num">1 </span>Exponential gr... | Python Code:
from ipyparallel import Client
cl = Client()
cl.ids
%%px --local
# run whole cell on all engines a well as in the local IPython session
import numpy as np
import sys
sys.path.insert(0, '/home/claudius/Downloads/dadi')
import dadi
%%px --local
# import 1D spectrum of ery on all engines:
fs_ery = dadi.Spectr... |
14,019 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome to Feature Engineering!
In this course you'll learn about one of the most important steps on the way to building a great machine learning model
Step1: You can see here the various i... | Python Code:
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score
df = pd.read_csv("../input/fe-course-data/concrete.csv")
df.head()
Explanation: Welcome to Feature Engineering!
In this course you'll learn about one of the most important steps on the... |
14,020 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture 19
Monday, November 13th 2017
Joins with SQLite, pandas
Starting Up
You can connect to the saved database from last time if you want. Alternatively, for extra practice, you can just... | Python Code:
import sqlite3
import numpy as np
import pandas as pd
import time
pd.set_option('display.width', 500)
pd.set_option('display.max_columns', 100)
pd.set_option('display.notebook_repr_html', True)
db = sqlite3.connect('L19DB_demo.sqlite')
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS candidates")
... |
14,021 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re going ... |
14,022 | 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', 'ncc', 'noresm2-mm', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: NCC
Source ID: NORESM2-MM
Topic: Ocean
Sub-Topics: Timestepping Framework, Ad... |
14,023 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Aprendizaje no supervisado parte 1 - transformación
Muchas formas de aprendizaje no supervisado, como reducción de dimensionalidad, aprendizaje de variedades y extracción de características,... | Python Code:
ary = np.array([1, 2, 3, 4, 5])
ary_standardized = (ary - ary.mean()) / ary.std()
ary_standardized
Explanation: Aprendizaje no supervisado parte 1 - transformación
Muchas formas de aprendizaje no supervisado, como reducción de dimensionalidad, aprendizaje de variedades y extracción de características, encu... |
14,024 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Can define what spread beyond which you assume player has a 0 or 100% chance of winning - using 300 as first guess.
Also, spreads now range only from 0 to positive numbers, because trailing ... | Python Code:
max_spread = 300
counter_dict_by_spread_and_tiles_remaining = {x:{
spread:0 for spread in range(max_spread,-max_spread-1,-1)} for x in range(0,94)}
win_counter_dict_by_spread_and_tiles_remaining = deepcopy(counter_dict_by_spread_and_tiles_remaining)
t0=time.time()
print('There are {} games'.format(len(... |
14,025 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kampff lab - Ultra dense survey
Here a description of the dataset
Step1: create a DataIO (and remove if already exists)
Step2: CatalogueConstructor
Run all chain in one shot.
Step3: Noise... | Python Code:
# suposing the datset is downloaded here
workdir = '/media/samuel/dataspikesorting/DataSpikeSortingHD2/kampff/ultra dense/'
filename = workdir + 'T2/amplifier2017-02-08T21_38_55.bin'
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import tridesclous as tdc
from tridesclous import Da... |
14,026 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification - Decision Tree Primer
Classify Iris (flowers) by their sepal/petal width/length to their species
Step1: Task
Step2: Wait, how do I know that the Decision Tree works???
A
St... | Python Code:
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from plotting_utilities import plot_decision_tree, plot_feature_importances
from sklearn.model_selection import train_test_split
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
iris = load_iris()
ir... |
14,027 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Task #2
Step2: Task #3
Step3: Task #4
Step4: Task #5
Step5: Task #6
Step6: Task #7 | Python Code:
import numpy as np
import pandas as pd
df = pd.read_csv('../TextFiles/moviereviews2.tsv', sep='\t')
df.head()
Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
Text Classification Assessment - Solution
This assessment is very much like the Text Classification Pro... |
14,028 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a name="top"></a>
<div style="width
Step1: In this case, we'll just stick with the standard meteorological data. The "realtime" data from NDBC contains approximately 45 days of data from e... | Python Code:
from siphon.simplewebservice.ndbc import NDBC
data_types = NDBC.buoy_data_types('46042')
print(data_types)
Explanation: <a name="top"></a>
<div style="width:1000 px">
<div style="float:right; width:98 px; height:98px;">
<img src="https://raw.githubusercontent.com/Unidata/MetPy/master/metpy/plots/_static/un... |
14,029 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
5. Getting stuff done with Python
In this unit, we are going to learn a new data structure with richer features compared to lists. The problem with lists, while flexible enough to store dif... | Python Code:
# creating a dictionary and assigning it to a variable
staff = {'name': 'Andy', 'age': 28, 'email': 'andy@company.com' }
staff['name']
staff['age']
print(staff['email'])
# A dictionary is of class dict
print(type(staff))
# list of all keys, note the brackets at the end.
# .keys is a method associated to... |
14,030 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers... | Python Code:
from six.moves import range
all_divides = lambda m, *numbers: all(m % n == 0 for n in numbers)
all_divides(2520, *range(1, 10))
Explanation: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisib... |
14,031 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bayesian Data Analysis, 3rd ed
Chapter 2, demo 4
Authors
Step1: Calculate results
Step2: Plot results | Python Code:
# Import necessary packages
import numpy as np
from scipy.stats import beta
%matplotlib inline
import matplotlib.pyplot as plt
import arviz as az
# add utilities directory to path
import os, sys
util_path = os.path.abspath(os.path.join(os.path.pardir, 'utilities_and_data'))
if util_path not in sys.path and... |
14,032 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a data-toc-modified-id="define-exp.-growth,-then-bottleneck-model-function-1" href="#define-exp.-growth,-then-bottleneck-model-function"><spa... | Python Code:
from ipyparallel import Client
cl = Client()
cl.ids
%%px --local
# run whole cell on all engines a well as in the local IPython session
import numpy # dadi calls numpy (not np)
import sys
sys.path.insert(0, '/home/claudius/Downloads/dadi')
import dadi
Explanation: Table of Contents
<p><div class="lev1 toc-... |
14,033 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial for recording a guitar string stroke and detecting its pitch
I use the python library called sounddevice which allows to easily record audio and represent the result as a numpy arra... | Python Code:
import sounddevice as sd
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Tutorial for recording a guitar string stroke and detecting its pitch
I use the python library called sounddevice which allows to easily record audio and represent the result as a... |
14,034 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sérialisation avec protobuf
protobuf optimise la sérialisation de deux façons. Elle accélère l'écriture et la lecture des données et permet aussi un accès rapide à une information précise da... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: Sérialisation avec protobuf
protobuf optimise la sérialisation de deux façons. Elle accélère l'écriture et la lecture des données et permet aussi un accès rapide à une information précise dans désérialiser les autres. Elle réalise... |
14,035 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Arithmetic Operations
Import the LArray library
Step1: Load the population array from the demography_eurostat dataset
Step2: Basics
One can do all usual arithmetic operations on an array, ... | Python Code:
from larray import *
Explanation: Arithmetic Operations
Import the LArray library:
End of explanation
# load the 'demography_eurostat' dataset
demography_eurostat = load_example_data('demography_eurostat')
# extract the 'country', 'gender' and 'time' axes
country = demography_eurostat.country
gender = demo... |
14,036 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 2 - Probability
This chapter introduces probability theory (and the differences between frequentists and baysians), some common statistics and examples of discrete and continous dist... | Python Code:
ax = plt.subplot(111)
plot_dist(stats.norm, -4, 4, ax)
Explanation: Chapter 2 - Probability
This chapter introduces probability theory (and the differences between frequentists and baysians), some common statistics and examples of discrete and continous distributions. It also presents transformation of var... |
14,037 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lin and Miranda (2008)
This method, described in Lin and Miranda (2008), estimates the maximum inelastic displacement of an existing structure based on the maximum elastic displacement respo... | Python Code:
from rmtk.vulnerability.derivation_fragility.equivalent_linearization.lin_miranda_2008 import lin_miranda_2008
from rmtk.vulnerability.common import utils
%matplotlib inline
Explanation: Lin and Miranda (2008)
This method, described in Lin and Miranda (2008), estimates the maximum inelastic displacement o... |
14,038 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Caracterización de una lente oftálmica mediante la técnica de los Anillos de Newton
Consultar el manual de uso de los cuadernos interactivos (notebooks) que se encuentra disponible en el Ca... | Python Code:
# MODIFICAR EL NOMBRE DEL FICHERO IMAGEN. LUEGO EJECUTAR
########################################################
nombre_fichero_imagen="IMG_20141121_122547.jpg" # Incluir el nombre completo con extensión del fichero imagen
# DESDE AQUÍ NO TOCAR
##########################################... |
14,039 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Edit this next cell to choose a different country / year report
Step1: These next few conversions don't really work. The PPP data field seems wrong.
Step2: Gini can be calculated directly ... | Python Code:
# CHN_1_2013.json
# BGD_3_1988.5.json
# IND_1_1987.5.json
# ARG_2_1987.json
# EST_3_1998.json
# Minimum (spline vs GQ) computed = 19.856 given = 75.812 difference = 73.809%
# Maximum (spline vs GQ) computed = 4974.0 given = 11400.0 difference = 56.363%
with open("../jsoncache/EST... |
14,040 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Algorithm
1. Detailed Pseudocode
Input Space
Step1: 2. Actual Algorithm Code
Step2: 3. Algorithm Space
Success Space
Practically, this algorithm will succeed when there is one or a few ver... | Python Code:
######################################
###THIS IS PSEUDOCODE, WILL NOT RUN###
######################################
def hungarian(costMatrix):
p1CostMatrix = costMatrix.copy()
p2CostMatrix = costMatrix.copy().T
#for every point in the first set
for all p1 in p1CostMatrix:
#find its minimum weighted ed... |
14,041 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting Started with TensorFlow
何はともあれ TensorFlow を始めてみましょう!
Step1: Hello TensorFlow
Python を使って足し算をしてみましょう(決して馬鹿にしているわけではなく大真面目です)!
Step2: 当然ですが 3.0 と答えが表示されます。
今度は TensorFlow で同じような足し算をや... | Python Code:
import tensorflow as tf
import numpy as np
print(tf.__version__)
Explanation: Getting Started with TensorFlow
何はともあれ TensorFlow を始めてみましょう!
End of explanation
a = 1.
b = 2.
c = a + b
print(c)
Explanation: Hello TensorFlow
Python を使って足し算をしてみましょう(決して馬鹿にしているわけではなく大真面目です)!
End of explanation
a = tf.constant(1.)... |
14,042 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial with the Diva synthesizer controlled with Dynamical Movement Primitives
This tutorials shows how to run an agent learning to produce sound trajectories with a simulated vocal tract,... | Python Code:
from __future__ import print_function
import os
import numpy as np
from explauto.environment.diva import DivaEnvironment
diva_cfg = dict(diva_path=os.path.join(os.getenv("HOME"), 'software/DIVAsimulink/'),
synth="octave",
m_mins = np.array([-1]*7), # motor bounds
... |
14,043 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST Image Classification with TensorFlow
This notebook demonstrates how to implement a simple linear image models on MNIST using Estimator.
<hr/>
This <a href="mnist_models.ipynb">companio... | Python Code:
import numpy as np
import shutil
import os
import tensorflow as tf
print(tf.__version__)
Explanation: MNIST Image Classification with TensorFlow
This notebook demonstrates how to implement a simple linear image models on MNIST using Estimator.
<hr/>
This <a href="mnist_models.ipynb">companion notebook</a> ... |
14,044 | Given the following text description, write Python code to implement the functionality described.
Description:
Count Knights that can attack a given pawn in an N * N board
Function to count the knights that are attacking the pawn in an M * M board ; Stores count of knights that are attacking the pawn ; Traverse the kni... | Python Code:
def cntKnightsAttackPawn(knights , pawn , M ) :
cntKnights = 0 ;
for i in range(M ) :
X = abs(knights[i ][0 ] - pawn[0 ] ) ;
Y = abs(knights[i ][1 ] - pawn[1 ] ) ;
if(( X == 1 and Y == 2 ) or(X == 2 and Y == 1 ) ) :
cntKnights += 1 ;
return cntKnights ;
if __name__== ' __main __' :... |
14,045 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Traffic Sign Classification with Keras
Keras exists to make coding deep neural networks simpler. To demonstrate just how easy it is, you’re going to use Keras to build a convolutional neural... | Python Code:
from urllib.request import urlretrieve
from os.path import isfile
from tqdm import tqdm
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=1, total_size=None):
self.total = total_size
self.update((block_num - self.last_block) * block_size)
self.las... |
14,046 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The line below creates a list of three pairs, each pair containing two pandas.Series objects.
A Series is like a dictionary, only its items are ordered and its values must share a data type.... | Python Code:
series = [ordered_words(archive.data) for archive in archives]
Explanation: The line below creates a list of three pairs, each pair containing two pandas.Series objects.
A Series is like a dictionary, only its items are ordered and its values must share a data type. The order keys of the series are its ind... |
14,047 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Classification & How To "Frame Problems" for a Neural Network
by Andrew Trask
Twitter
Step1: Lesson
Step2: Project 1
Step3: Transforming Text into Numbers
Step4: Project 2
Step... | Python Code:
def pretty_print_review_and_label(i):
print(labels[i] + "\t:\t" + reviews[i][:80] + "...")
g = open('reviews.txt','r') # What we know!
reviews = list(map(lambda x:x[:-1],g.readlines()))
g.close()
g = open('labels.txt','r') # What we WANT to know!
labels = list(map(lambda x:x[:-1].upper(),g.readlines())... |
14,048 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Attrribute data from a csv file and a W from a gal file
Step1: Attrribute data from a csv file and an external W object
Step2: Shapefile and mapping results with PySAL Viz | Python Code:
mexico = cp.importCsvData(ps.examples.get_path('mexico.csv'))
mexico.fieldNames
w = ps.open(ps.examples.get_path('mexico.gal')).read()
w.n
cp.addRook2Layer(ps.examples.get_path('mexico.gal'), mexico)
mexico.Wrook
mexico.cluster('arisel', ['pcgdp1940'], 5, wType='rook', inits=10, dissolve=0)
mexico.fieldNam... |
14,049 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
正则表达式
1 基础部分
管道符号(|)匹配多个正则表达式
Step1: 2.3 search
match 从字符串开始位置进行匹配,但是模式出现在字符串的中间的位置比开始位置的概率大得多
Step2: search 函数将返回字符串开始模式首次出现的位置
Step3: 2.4 匹配多个字符串
Step4: 2.5 匹配任意单个字符(.)
句点不能匹配换行符或者匹配非字... | Python Code:
import re
m = re.match('foo', 'foo')
if m is not None: m.group()
m
m = re.match('foo', 'bar')
if m is not None: m.group()
re.match('foo', 'foo on the table').group()
# raise attributeError
re.match('bar', 'foo on the table').group()
Explanation: 正则表达式
1 基础部分
管道符号(|)匹配多个正则表达式:
at | home 匹配 at,home
匹配任意单一字... |
14,050 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple Linear Regression
In this example, we illustrate how to solve a linear regression problem.
Suppose we have training data, can we fit a neural network on it? The trained neural network... | Python Code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# numpy package
import numpy as np
# for plotting
import matplotlib.pyplot as plt
# keras modules
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensor... |
14,051 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Read and clean data using Python and Pandas
Step1: Read the files and load the datasets
Pre-requisite
Step2: act table has 6 observations of 2 variables
Step3: features table has 561 obse... | Python Code:
import pandas as pd
Explanation: Read and clean data using Python and Pandas
End of explanation
cat UCI\ HAR\ Dataset/activity_labels.txt
act = pd.read_table('UCI HAR Dataset/activity_labels.txt', header=None, sep=' ', names=('ID','Activity'))
act
type(act)
act.columns
Explanation: Read the files and load ... |
14,052 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Part-of-Speech Tagging with NLTK
This notebook is a quick demonstration of verta's run.log_setup_script() feature.
We'll create a simple and lightweight text tokenizer and part-of-speech tag... | Python Code:
import six
from verta import Client
from verta.utils import ModelAPI
HOST = "app.verta.ai"
PROJECT_NAME = "Part-of-Speech Tagging"
EXPERIMENT_NAME = "NLTK"
client = Client(HOST)
proj = client.set_project(PROJECT_NAME)
expt = client.set_experiment(EXPERIMENT_NAME)
run = client.set_experiment_run()
Explanati... |
14,053 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training Neural Networks
The network we built in the previous part isn't so smart, it doesn't know anything about our handwritten digits. Neural networks with non-linear activations work lik... | Python Code:
import torch
from torch import nn
import torch.nn.functional as F
from torchvision import datasets, transforms
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
... |
14,054 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create dataframe with missing values
Step2: Drop missing observations
Step3: Drop rows where all cells in that row is NA
Step4: Create a new column full of missing values
St... | Python Code:
import pandas as pd
import numpy as np
Explanation: Title: Missing Data In Pandas Dataframes
Slug: pandas_missing_data
Summary: Missing Data In Pandas Dataframes
Date: 2016-05-01 12:00
Category: Python
Tags: Data Wrangling
Authors: Chris Albon
import modules
End of explanation
raw_data = {'first_name': [... |
14,055 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div align="right">Python 3.6</div>
Testing The Abstract Base Class - Earlier Version of the Code
This notebook was created because it is easier to test out the core logic separately from th... | Python Code:
who
Explanation: <div align="right">Python 3.6</div>
Testing The Abstract Base Class - Earlier Version of the Code
This notebook was created because it is easier to test out the core logic separately from the logic that makes web API calls and extracts data from Google Maps. The intent was to test and deb... |
14,056 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Layout Templates
As we showed in Layout and Styling of Jupyter widgets multiple widgets can be arranged together using the flexible GridBox specification. However, use of the specifica... | Python Code:
# Utils widgets
from ipywidgets import Button, Layout, jslink, IntText, IntSlider
def create_expanded_button(description, button_style):
return Button(description=description, button_style=button_style, layout=Layout(height='auto', width='auto'))
top_left_button = create_expanded_button("Top left", 'in... |
14,057 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We covered a lot of information today and I'd like you to practice developing classification trees on your own. For each exercise, work through the problem, determine the result, and provide... | Python Code:
from sklearn import datasets
import pandas as pd
%matplotlib inline
from sklearn import datasets
from pandas.tools.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import tree
iris = datasets.load_iris()
iris
iris.keys()
iris['target']
iris['target_names']
iris['data']
iris['feat... |
14,058 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quick Reference
Step1: Python
Names
Assign values to names with the assignment operator =.
Values at the end of a cell are printed.
Step2: You can also call the print function
Step4: Func... | Python Code:
import numpy as np
from datascience import *
from pprint import pprint
Explanation: Quick Reference
End of explanation
ten = 3 * 2 + 4
ten
Explanation: Python
Names
Assign values to names with the assignment operator =.
Values at the end of a cell are printed.
End of explanation
print(ten)
# You can also m... |
14,059 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Aerosol
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'miroc', 'sandbox-1', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: MIROC
Source ID: SANDBOX-1
Topic: Aerosol
Sub-Topics: Transport, Emissio... |
14,060 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Transfer Learning
This notebook shows how to use pre-trained models from TensorFlowHub. Sometimes, there is not enough data, computational resources, or time to train a model from... | Python Code:
import os
import pathlib
import IPython.display as display
import matplotlib.pylab as plt
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from PIL import Image
from tensorflow.keras import Sequential
from tensorflow.keras.layers import (
Conv2D,
Dense,
Dropout,
Flatt... |
14,061 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Electromagnetics
Step1: Your Default Parameters should be
Step2: Pipe Widget
In the following app, we consider a loop-loop system with a pipe taget. Here, we simulate two surveys, one wher... | Python Code:
%matplotlib inline
from geoscilabs.em.FDEM3loop import interactfem3loop
from geoscilabs.em.FDEMpipe import interact_femPipe
from matplotlib import rcParams
rcParams['font.size'] = 14
Explanation: Electromagnetics: 3-loop model
In the first part of this notebook, we consider a 3 loop system, consisting of a... |
14,062 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Wing example using guide curves
We still want have more control on the shape of the wing example.
One option is to simply add more profiles and tweak their shape. Another, more elegant way i... | Python Code:
import tigl3.curve_factories
import tigl3.surface_factories
from OCC.gp import gp_Pnt
from OCC.Display.SimpleGui import init_display
import numpy as np
Explanation: Wing example using guide curves
We still want have more control on the shape of the wing example.
One option is to simply add more profiles an... |
14,063 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classify handwritten digits with Keras (MXNet backend)
Data from
Step1: <a id="01">1. Download the MNIST dataset from Internet </a>
I've made the dataset into a zipped tar file. You'll have... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set()
import pandas as pd
import sklearn
import os
import requests
from tqdm._tqdm_notebook import tqdm_notebook
import tarfile
Explanation: Classify handwritten digits with Keras (MXNet backend)
Data from: the ... |
14,064 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: ★ Fundamentals ★
0.1 Horner’s method or Nested multiplication
Step2: Example
Step3: Example
$P(x) = x^6 - 2x^5 + 3x^4 - 4x^3 + 5x^2 - 6x + 7$ at $x = 2$
Step4: 0.1 Computer Probl... | Python Code:
# Import modules
import traceback
import math
import numpy as np
import unittest
def nest(degree, coefficients, x = 0, base_points = None) -> float:
Evaluates polynomial from nested form using Horner’s Method
Examples:
P(x) = 3 * x^2 + 5 * x − 1 and evaluate P(x = 1)
Use n... |
14,065 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GlobalAveragePooling3D
[pooling.GlobalAveragePooling3D.0] input 6x6x3x4, data_format='channels_last'
Step1: [pooling.GlobalAveragePooling3D.1] input 3x6x6x3, data_format='channels_first'
St... | Python Code:
data_in_shape = (6, 6, 3, 4)
L = GlobalAveragePooling3D(data_format='channels_last')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(270)
data_in = 2 * np.random.random(data_in_sha... |
14,066 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejemplo cuencas
En el siguiente ejemplo se presentan las funcionalidades básicas de la herramienta wmf.Stream y wmf.Basin
dentro de los temas tocados se presenta
Step1: Este es como se leen... | Python Code:
#Paquete Watershed Modelling Framework (WMF) para el trabajo con cuencas.
from wmf import wmf
Explanation: Ejemplo cuencas
En el siguiente ejemplo se presentan las funcionalidades básicas de la herramienta wmf.Stream y wmf.Basin
dentro de los temas tocados se presenta:
Trazado de corrientes.
Perfil de corr... |
14,067 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The OpenFermion Developers
Step2: FQE vs OpenFermion vs Cirq
Step3: The first example we will perform is diagonal Coulomb evolution on the Hartree-Fock state. The diagonal ... | 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... |
14,068 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predictive Delay Analytics
Step1: 1. Data acquisition
First, let's acquire the data formated in '02_data_preparation.ipynb'. The figure below gives a glimpse of what the data set looks like... | Python Code:
%matplotlib inline
# import required modules for prediction tasks
import numpy as np
import pandas as pd
import math
import random
Explanation: Predictive Delay Analytics
End of explanation
%%time
# reads all predefined months for a year and merge into one data frame
rawData2014 = pd.DataFrame.from_csv('ca... |
14,069 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced
Step1: Generate data
Let's first initialize a bundle and change some of the parameter values. We'll then export the computed models as "observables" to use with the rv_geometry est... | Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
import phoebe
from phoebe import u # units
import numpy as np
logger = phoebe.logger()
Explanation: Advanced: RV Estimators
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such a... |
14,070 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using the Simulation Archive to restart a simulation
The Simulation Archive (SA) is a binary file that can be used to restart a simulation. This can be useful when running a long simulation.... | Python Code:
import rebound
sim = rebound.Simulation()
sim.integrator = "whfast"
sim.dt = 2.*3.1415/365.*6 # 6 days in units where G=1
sim.add(m=1.)
sim.add(m=1e-3,a=1.)
sim.add(m=5e-3,a=2.25)
sim.move_to_com()
Explanation: Using the Simulation Archive to restart a simulation
The Simulation Archive (SA) is a binary fil... |
14,071 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generative Adversarial Network
In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d... | Python Code:
%matplotlib inline
import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data')
Explanation: Generative Adversarial Network
In this notebook, we'll be building a gen... |
14,072 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib 2015
requires ipython and ipyton-notebook packages
execute
Step1: Above commands enable pylab environment => direct access to numpy, scipy and matplotlib. The option 'inline' res... | Python Code:
%matplotlib inline
from pylab import *
Explanation: Matplotlib 2015
requires ipython and ipyton-notebook packages
execute: ipython notebook
check out this resource for Matplotlib: http://matplotlib.org/gallery.html
End of explanation
xv=[1,2,3,4]; yv=[5,1,4,0]
plot(xv,yv)
Explanation: Above commands enabl... |
14,073 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Build and test the environment
This document explains how to set up your environment for the geocomputing course.
1. Install Anaconda
First, install Anaconda for Python 3.5, following the in... | Python Code:
!python -V
# Should be 3.5
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import ricker
Explanation: Build and test the environment
This document explains how to set up your environment for the geocomputing course.
1. Install Anaconda
First, install Anaconda for Python 3.5, following ... |
14,074 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<span style="color
Step1: Load the data
The treeslider() tool takes the .seqs.hdf5 database file from ipyrad as its input file. Select scaffolds by their index (integer) which can be found ... | Python Code:
# conda install ipyrad -c bioconda
# conda install raxml -c bioconda
# conda install toytree -c eaton-lab
import ipyrad.analysis as ipa
import toytree
Explanation: <span style="color:gray">ipyrad-analysis toolkit:</span> treeslider
<h5><span style="color:red">(Reference only method)</span></h5>
With refere... |
14,075 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualizing SourceTracker 2 Results
Once you have run sourcetracker2 to produce the mixing proportions of our sources to your sink samples, you'll likely want to visualize the results for un... | Python Code:
# Import packages of interest
# You might need to install these in your local environment
# which can be easily accomplished with $pip (package)
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline
# Move into our tiny test directory
cd ../data/tiny-test/
# read in the mixing proportions ... |
14,076 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
medication
The medications table reflects the active medication orders for patients. These are orders but do not necessarily reflect administration to the patient. For example, while existen... | Python Code:
# Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import psycopg2
import getpass
import pdvega
# for configuring connection
from configobj import ConfigObj
import os
%matplotlib inline
# Create a database connection using settings from config file
config='../db/conf... |
14,077 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Обнаружение статистически значимых отличий в уровнях экспрессии генов больных раком
Данные для этой задачи взяты из исследования, проведённого в Stanford School of Medicine. В исследовании б... | Python Code:
from __future__ import division
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels.sandbox.stats.multicomp import multipletests
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.a... |
14,078 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex AI
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Restart the kernel
Once you've installed the additional packages, you need to restart the not... | Python Code:
import os
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG
Explanation: Vertex AI: Vertex AI Migration: AutoML Image Classification
<table align="left">
<td>
... |
14,079 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DeepDreaming with TensorFlow
Loading and displaying the model graph
Naive feature visualization
Multiscale image generation
Laplacian Pyramid Gradient Normalization
Playing with feature visu... | Python Code:
# boilerplate code
from __future__ import print_function
import os
from io import BytesIO
import numpy as np
from functools import partial
import PIL.Image
from IPython.display import clear_output, Image, display, HTML
import tensorflow as tf
Explanation: DeepDreaming with TensorFlow
Loading and displaying... |
14,080 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Abstract
In order to optimize dataframe
Step1: Original Article
https
Step2: First Look
Step3: Under the hood, pandas groups the columns into block of values of the same type
Step4: Subt... | Python Code:
import os
import pandas as pd
# Load Data
gl = pd.read_csv('..\data\game_logs.csv')
# Available also at https://data.world/dataquest/mlb-game-logs
# Data Preview
gl.head()
Explanation: Abstract
In order to optimize dataframe:
Downcasting numeric columns
python
df_num = df.select_dtypes(include=['int64','fl... |
14,081 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial on Units and UnitConverters in Parcels
In most applications, Parcels works with spherical meshes, where longitude and latitude are given in degrees, while depth is given in meters.... | Python Code:
%matplotlib inline
from parcels import Field, FieldSet
import numpy as np
xdim, ydim = (10, 20)
data = {'U': np.ones((ydim, xdim), dtype=np.float32),
'V': np.ones((ydim, xdim), dtype=np.float32),
'temp': 20*np.ones((ydim, xdim), dtype=np.float32)}
dims = {'lon': np.linspace(-15, 5, xdim, d... |
14,082 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Content under Creative Commons Attribution license CC-BY 4.0, code under MIT license (c)2014 M.Z. Jorisch
<h1 align="center">Orbital</h1>
<h1 align="center">Perturbations</h1>
In this... | Python Code:
from matplotlib import pyplot
import numpy
from numpy import linalg
%matplotlib inline
from matplotlib import rcParams
rcParams['font.family'] = 'serif'
rcParams['font.size'] = 16
def Kepler_eqn(e, M):
Takes the eccentricity and mean anomaly of an orbit to solve Kepler's equation
Parameters:
... |
14,083 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Goal
Simulating fullCyc Day1 control gradients
Not simulating incorporation (all 0% isotope incorp.)
Don't know how much true incorporatation for emperical data
Using parameters inferred fro... | Python Code:
import os
import glob
import re
import nestly
%load_ext rpy2.ipython
%%R
library(ggplot2)
library(dplyr)
library(tidyr)
library(gridExtra)
library(phyloseq)
## BD for G+C of 0 or 100
BD.GCp0 = 0 * 0.098 + 1.66
BD.GCp100 = 1 * 0.098 + 1.66
Explanation: Goal
Simulating fullCyc Day1 control gradients
Not simu... |
14,084 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Use decision optimization to help a sports league schedule its games
This tutorial includes everything you need to set up decision optimization engines, build mathematical programming models... | Python Code:
import sys
try:
import docplex.cp
except:
if hasattr(sys, 'real_prefix'):
#we are in a virtual env.
!pip install docplex
else:
!pip install --user docplex
Explanation: Use decision optimization to help a sports league schedule its games
This tutorial includes everything ... |
14,085 | 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: The dataset above shows how much funding (i.e., 'Expenditures' column) the state gave to in... | Python Code:
# Run the following to import necessary packages and import dataset
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
datafile = "dataset/funding.csv"
df = pd.read_csv(datafile)
df.drop('Dummy', axis=1, inplace=True)
df.head(n=5) # Pri... |
14,086 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Week 11 - Regression and Classification
In previous weeks we have looked at the steps needed in preparing different types of data for use by machine learning algorithms.
Step1: All the diff... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
from sklearn import datasets
diabetes = datasets.load_diabetes()
# Description at http://www4.stat.ncsu.edu/~boos/var.select/diabetes.html
X = diabetes.data
y = diabetes.target
print(X.shape, y.shape)
from sklearn import linear_model
clf... |
14,087 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Word prediction based on Quadgram
This program reads the corpus line by line so it is slower than the program which reads the corpus
in one go.This reads the corpus one line at a time loads ... | Python Code:
#import the modules necessary
from nltk.util import ngrams
from collections import defaultdict
import nltk
import string
import time
start_time = time.time()
Explanation: Word prediction based on Quadgram
This program reads the corpus line by line so it is slower than the program which reads the corpus
in ... |
14,088 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anomaly detection
Anomaly detection is a machine learning task that consists in spotting so-called outliers.
“An outlier is an observation in a data set which appears to be inconsistent with... | Python Code:
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
Explanation: Anomaly detection
Anomaly detection is a machine learning task that consists in spotting so-called outliers.
“An outlier is an observation in a data set whi... |
14,089 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Library Bioinformatics Service
Jupyter Notebook Tutorial
This tutorial was built in a Jupyter notebook!
Various formats of this tutorial can be accessed at https
Step1: This is a text cell
... | Python Code:
# this is a code cell with no output
a=120
# this is a code cell with output
# all output to stdout / stderr will be displayed below the cell.
print(a)
Explanation: Library Bioinformatics Service
Jupyter Notebook Tutorial
This tutorial was built in a Jupyter notebook!
Various formats of this tutorial can b... |
14,090 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computing a covariance matrix
Many methods in MNE, including source estimation and some classification
algorithms, require covariance estimations from the recordings.
In this tutorial we cov... | Python Code:
import os.path as op
import mne
from mne.datasets import sample
Explanation: Computing a covariance matrix
Many methods in MNE, including source estimation and some classification
algorithms, require covariance estimations from the recordings.
In this tutorial we cover the basics of sensor covariance compu... |
14,091 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Examples of how to use the BCES fitting code
BCES python module available on Github.
Step1: Example 1
In this example, the data contains uncertainties on both $x$ and $y$; no correlation be... | Python Code:
%pylab inline
cd '/Users/nemmen/Dropbox/codes/python/bces'
import bces.bces as BCES
Explanation: Examples of how to use the BCES fitting code
BCES python module available on Github.
End of explanation
data=load('data.npz')
xdata=data['x']
ydata=data['y']
errx=data['errx']
erry=data['erry']
cov=data['cov']
... |
14,092 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First, some code. Scroll down.
Step4: Functionality that could be implemented in SparseBinaryMatrix
Step10: This SetMemory docstring is worth reading
Step11: Experiment code
Train an arra... | Python Code:
import itertools
import random
from collections import deque
from copy import deepcopy
import numpy
from nupic.bindings.math import SparseBinaryMatrix, GetNTAReal
Explanation: First, some code. Scroll down.
End of explanation
def makeSparseBinaryMatrix(numRows, numCols):
Construct a SparseBinaryMa... |
14,093 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Attention on MNIST (Saliency and grad-CAM)
Lets build the mnist model and train it for 5 epochs. It should get to about ~99% test accuracy.
Step1: Saliency
To visualize activation over fina... | Python Code:
from __future__ import print_function
import numpy as np
import keras
from keras.datasets import mnist
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten, Activation, Input
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
batch_size = 128... |
14,094 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interactive mapping
Alongside static plots, geopandas can create interactive maps based on the folium library.
Creating maps for interactive exploration mirrors the API of static plots in an... | Python Code:
import geopandas
nybb = geopandas.read_file(geopandas.datasets.get_path('nybb'))
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
cities = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities'))
Explanation: Interactive mapping
Alongside static plots, geopanda... |
14,095 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Build and test a Nearest Neighbors classifier.
Load the relevant packages.
Step1: Load the Iris data to use for experiments. The data include 50 observations of each of 3 types of irises (1... | Python Code:
# This tells matplotlib not to try opening a new window for each plot.
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_iris
Explanation: Build and test a Nearest Neighbors classifier.
Load the relevant packages.
End of explanation
# Load the data, whi... |
14,096 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kaggle Galaxy Zoo Competition
Step1: First Model
2 layer CNN
Step2: To Do | Python Code:
%matplotlib inline
path = "data/galaxy/sample/"
#path = "data/galaxy/"
train_path = path + 'train/'
valid_path = path + 'valid/'
test_path = path + 'test/'
results_path = path + 'results/'
model_path = path + 'model/'
from utils import *
batch_size = 32
num_epoch = 1
import pandas as pd
df = pd.read_csv(pa... |
14,097 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ilastik for 10/31/16 Week
From last week, I was able to generate 3D TIFF slices and image classifiers on Fear199 downsampled data. However, my problems were that
Step1: In a nutshell, meth... | Python Code:
## Script used to download nii run on Docker
from ndreg import *
import matplotlib
import ndio.remote.neurodata as neurodata
import nibabel as nb
inToken = "Fear199"
nd = neurodata()
print(nd.get_metadata(inToken)['dataset']['voxelres'].keys())
inImg = imgDownload(inToken, resolution=5)
imgWrite(inImg, "./... |
14,098 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example
of building a notebook-friendly object into the output of the data API
Author
Step1: Authorization
In the vanilla notebook, you need to manually set an auth. token. You'll need your... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import qgrid
qgrid.nbinstall()
from biokbase import data_api
from biokbase.data_api import display
display.nbviewer_mode(True)
Explanation: Example
of building a notebook-friendly object into the output of the data API
Author: Dan Gunter
Initialization
Imp... |
14,099 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generating Feature Descriptions
As features become more complicated, their names can become harder to understand. Both the describe_feature function and the graph_feature function can help e... | Python Code:
import featuretools as ft
es = ft.demo.load_mock_customer(return_entityset=True)
feature_defs = ft.dfs(entityset=es,
target_dataframe_name="customers",
agg_primitives=["mean", "sum", "mode", "n_most_common"],
trans_primitives=["month", "hour... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.