Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
12,500 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Physique
Mini Table of Contents
Create or refresh data files
Using Physique from a working directory not containing Physique itself
NIST Fundamental Constants
NIST Official Conversions (to m... | Python Code:
import os
print(os.getcwd())
os.chdir(os.getcwd() + "/Physique/") # change current working directory
print(os.getcwd())
%run -i ./Scripts/Refresh.py # this is the main, important, command to run
import Physique
import sys
sys.executable # Check which Python you are running in case you have ImportError's
pr... |
12,501 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Handwritten Number Recognition with TFLearn and MNIST
In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9.
This kind of neural network is used in a ... | Python Code:
# Import Numpy, TensorFlow, TFLearn, and MNIST data
import numpy as np
import tensorflow as tf
import tflearn
import tflearn.datasets.mnist as mnist
Explanation: Handwritten Number Recognition with TFLearn and MNIST
In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-... |
12,502 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regularization
Welcome to the second assignment of this week. Deep Learning models have so much flexibility and capacity that overfitting can be a serious problem, if the training dataset is... | Python Code:
# import packages
import numpy as np
import matplotlib.pyplot as plt
from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec
from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters
import sklearn
impo... |
12,503 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Imports and data
Step1: These data (~71 million rows) were taken from https
Step2: Apply any function in the fastest available manner
When possible, vectorized form of function is used for... | Python Code:
import pandas as pd
import numpy as np
import modin.pandas as md
import swifter
Explanation: Imports and data
End of explanation
trips = pd.read_csv('trip.csv')
data = pd.read_csv('status.csv')
print(data.shape)
data.head()
Explanation: These data (~71 million rows) were taken from https://www.kaggle.com/b... |
12,504 | 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
print(tf.__version__)
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 t... |
12,505 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Autoencoder
In this example we will demonstrate how you can create a convolutional autoencoder in Gluon
Step1: Data
We will use the FashionMNIST dataset, which is of a similar... | Python Code:
import random
import matplotlib.pyplot as plt
import mxnet as mx
from mxnet import autograd, gluon
Explanation: Convolutional Autoencoder
In this example we will demonstrate how you can create a convolutional autoencoder in Gluon
End of explanation
batch_size = 512
ctx = mx.gpu() if len(mx.test_utils.list_... |
12,506 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1.3 NumPy - Algebra liniowa
NumPy jest pakietem szczególnie przydatnym do obliczeń w dziedzinie algebry liniowej. W uczeniu maszynowym algebra liniowa będzie miała duże znaczenie.
Wektor o ... | Python Code:
import numpy as np
x = np.array([[1,2,3]]).T
xt = x.T
x.shape
xt.shape
Explanation: 1.3 NumPy - Algebra liniowa
NumPy jest pakietem szczególnie przydatnym do obliczeń w dziedzinie algebry liniowej. W uczeniu maszynowym algebra liniowa będzie miała duże znaczenie.
Wektor o wymiarach $1 \times N$
$$
X ... |
12,507 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Read HIV Data
Step1: Read in Clinical Data
Step2: Update clinical data with new data provided by Howard Fox
Step3: Clean up diabetes across annotation files
Step4: All of the patients ar... | Python Code:
import os
if os.getcwd().endswith('Setup'):
os.chdir('..')
import NotebookImport
from Setup.Imports import *
Explanation: Read HIV Data
End of explanation
c1 = pd.read_excel(ucsd_path + 'DESIGN_Fox_v2_Samples-ChipLAyout-Clinical UNMC-UCSD methylomestudy.xlsx',
'HIV- samples from Old... |
12,508 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to NumPy
Numpy is a library that provides multi-dimensional array objects. You can think of these somewhat like normal Python lists, except they have a number of qualities that ... | Python Code:
x = [1,2,3]
y = [4,5,6]
x + y
Explanation: Introduction to NumPy
Numpy is a library that provides multi-dimensional array objects. You can think of these somewhat like normal Python lists, except they have a number of qualities that make them better for numeric computations.
Let's try adding two lists toge... |
12,509 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to generate batches from a dataset and work with batch components
Step1: Create a dataset
A dataset is defined by an index (a sequence of item ids) and a batch class (see the documentat... | Python Code:
import sys
import numpy as np
# the following line is not required if BatchFlow is installed as a python package.
sys.path.append("../..")
from batchflow import Dataset, DatasetIndex, Batch
# number of items in the dataset
NUM_ITEMS = 10
# number of items in a batch when iterating
BATCH_SIZE = 3
Explanatio... |
12,510 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Specify sample data csv paths. See the files listed here for expected structure. Marginal tables require multi-indexed columns with category name and category value in levels 0 and 1 of the ... | Python Code:
hh_marginal_file = 'input_data/hh_marginals.csv'
person_marginal_file = 'input_data/person_marginals.csv'
hh_sample_file = 'input_data/household_sample.csv'
person_sample_file = 'input_data/person_sample.csv'
Explanation: Specify sample data csv paths. See the files listed here for expected structure. Marg... |
12,511 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PJRC's receive test
(host in C, variable buffer size, receiving in 64 Byte chunks)
Anything below 64 bytes is not a full USB packet and waits for transmission. Above, full speed is achieved.... | Python Code:
result_path = '../src/USB_Virtual_Serial_Rcv_Speed_Test/usb_serial_receive/host_software/'
print [f for f in os.listdir(result_path) if f.endswith('.txt')]
def read_result(filename):
results = {}
current_blocksize = None
with open(os.path.join(result_path, filename)) as f:
for line in f... |
12,512 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 4
Imports
Step2: Line with Gaussian noise
Write a function named random_line that creates x and y data for a line with y direction random noise that has a normal distribut... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
Explanation: Interact Exercise 4
Imports
End of explanation
def random_line(m, b, sigma, size=10):
Create a line y = m*x + b + N(0,sigm... |
12,513 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In the previous example we investigated if it was possible to query the NGDC CSW Catalog to extract records matching an IOOS RA acronym.
However, we could not trust the results.
Some RAs res... | Python Code:
from owslib.csw import CatalogueServiceWeb
endpoint = 'http://www.ngdc.noaa.gov/geoportal/csw'
csw = CatalogueServiceWeb(endpoint, timeout=30)
Explanation: In the previous example we investigated if it was possible to query the NGDC CSW Catalog to extract records matching an IOOS RA acronym.
However, we co... |
12,514 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data generation
Step1: Preparing data set sweep
First, we're going to define the data sets that we'll sweep over. The following cell does not need to be modified unless if you wish to chang... | Python Code:
from os.path import join, expandvars
from joblib import Parallel, delayed
from glob import glob
from os import system
from tax_credit.framework_functions import (parameter_sweep,
generate_per_method_biom_tables,
move_re... |
12,515 | Given the following text description, write Python code to implement the functionality described.
Description:
Given a positive integer, obtain its roman numeral equivalent as a string,
and return it in lowercase.
Restrictions: 1 <= num <= 1000
Examples:
This is how the function will work:
int_to_... | Python Code:
def int_to_mini_roman(number):
num = [1, 4, 5, 9, 10, 40, 50, 90,
100, 400, 500, 900, 1000]
sym = ["I", "IV", "V", "IX", "X", "XL",
"L", "XC", "C", "CD", "D", "CM", "M"]
i = 12
res = ''
while number:
div = number // num[i]
number %= num... |
12,516 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quickstart
This notebook was made with the following version of emcee
Step1: The easiest way to get started with using emcee is to use it for a project. To get you started, here’s an annota... | Python Code:
import emcee
emcee.__version__
Explanation: Quickstart
This notebook was made with the following version of emcee:
End of explanation
import numpy as np
Explanation: The easiest way to get started with using emcee is to use it for a project. To get you started, here’s an annotated, fully-functional example... |
12,517 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow
Step1: Download the Data
Step2: Dataset Metadata
Step3: Building a TensorFlow Custom Estimator
Creating feature columns
Creating model_fn
Create estimator using the model_fn
De... | Python Code:
import math
import os
import pandas as pd
import numpy as np
from datetime import datetime
import tensorflow as tf
from tensorflow import data
print("TensorFlow : {}".format(tf.__version__))
SEED = 19831060
Explanation: TensorFlow: From Estimators to Keras
Building a custom TensorFlow estimator (as a refer... |
12,518 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tensorflow
Step1: In it's essence, tensorflow is a generic computing framework that allows you to define compute graphs (=definitions)
without running them at the same time - essentially sp... | Python Code:
import tensorflow as tf
import numpy as np
Explanation: Tensorflow
End of explanation
hello = tf.constant('Hello, TensorFlow!')
# To do anything useful in TF, you have the create a session and then run it
# This is also true for just outputting the value of a TF variable/constant/placeholder.
# While this ... |
12,519 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python for Everyone!<br/>Oregon Curriculum Network
VPython inside Jupyter Notebooks
The Vector, Edge and Polyhedron types
The Vector class below is but a thin wrapper around VPython's built-... | Python Code:
from vpython import *
class Vector:
def __init__(self, x, y, z):
self.v = vector(x, y, z)
def __add__(self, other):
v_sum = self.v + other.v
return Vector(*v_sum.value)
def __neg__(self):
return Vector(*((-self.v).value))
def __sub__(s... |
12,520 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Weather Data
Daily ocean temperature data since 1981. http
Step1: Plots!
Step2: Computations
Step3: Note that this only builds up a graph of the computations, but doesn't actually run any... | Python Code:
import zarr
import dask.array as da
a = zarr.open_array("sst.day.mean.v2.zarr/", mode='r')
data = da.from_array(a, chunks=a.chunks)
data
data.nbytes / 1e9
Explanation: Weather Data
Daily ocean temperature data since 1981. http://www.esrl.noaa.gov/psd/data/gridded/data.noaa.oisst.v2.html. This is roughly 52... |
12,521 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
arrows
Step1: Just adding some imports and setting graph display options.
Step2: Let's look at our data!
load_df loads it in as a pandas.DataFrame, excellent for statistical analysis and ... | Python Code:
from arrows.preprocess import load_df
Explanation: arrows: Yet Another Twitter/Python Data Analysis
Geospatially, Temporally, and Linguistically Analyzing Tweets about Top U.S. Presidential Candidates with Pandas, TextBlob, Seaborn, and Cartopy
Hi, I'm Raj. For my internship this summer, I've been using da... |
12,522 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
filter
The function filter(function, list) offers a convenient way to filter out all the elements of an iterable, for which the function returns True.
The function filter(function(),l) need... | Python Code:
#First let's make a function
def even_check(num):
if num%2 ==0:
return True
Explanation: filter
The function filter(function, list) offers a convenient way to filter out all the elements of an iterable, for which the function returns True.
The function filter(function(),l) needs a function as ... |
12,523 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solving an integer linear programming problem with linprog
Step1: Objective function
$$z(max) = 7x_1 + 6x_2$$
Constraints
Step2: In this case this problem is not giving Integer Variables.
... | Python Code:
from scipy.optimize import linprog
import numpy as np
Explanation: Solving an integer linear programming problem with linprog
End of explanation
z = np.array([ 7, 6])
C = np.array([
[ 2, 3], #C1
[ 6, 5] #C2
])
b = np.array([12, 30])
x1 = (0, None)
x2 = (0, None)
sol = linprog(-z,... |
12,524 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Review of Numerical Differentiation
Q. What orders are the errors?
Step2: Integration
Step3: Test case
Step4: Q. What should we get if we integrate from 0 to 1?
We can verify this analyti... | Python Code:
def forward_difference(f, x, h):
return (f(x + h) - f(x)) / h
def central_difference(f, x, h):
return (f(x + h) - f(x - h)) / (2. * h)
Explanation: Review of Numerical Differentiation
Q. What orders are the errors?
End of explanation
def trapezoidal(f, x_L, x_U, n):
Integrate function f fr... |
12,525 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CAPITOLO 1.1
Step1: Iterazione nelle liste e cicli for su indice
Step2: DIZIONARI
Step3: Iterazione nei dizionari
ATTENZIONE
Step4: DYI
Step5: WARNING / DANGER / EXPLOSION / ATTENZIONE!... | Python Code:
# creazione
l = [1,2,3,10,"a", -12.333, 1024, 768, "pippo"]
# concatenazione
l += ["la", "concatenazione", "della", "lista"]
# aggiunta elementi in fondo
l.append(32)
l.append(3)
print(u"la lista è {}".format(l))
l.remove(3) # rimuove la prima occorrenza
print(u"la lista è {}".format(l))
i = l.index(10) ... |
12,526 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An Exclusive Guide to Exclusion Limits
In this notebook we will place exclusion limits using Python, it's the companion piece to an an introduction to exclusion limits we wrote that explains... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import poisson, norm, chi2
from scipy.optimize import minimize, brentq
import warnings; warnings.simplefilter('ignore') # ignore some numerical errors
Explanation: An Exclusive Guide to Exclusion Limits
In this notebook ... |
12,527 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BCycle Austin stations
This notebook looks at the stations that make up the Austin BCycle network. For each station we have the following information
Step1: Plot the stations on a map of Au... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import folium
import seaborn as sns
from bcycle_lib.utils import *
%matplotlib inline
# for auto-reloading external modules
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autorelo... |
12,528 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Question 1
Compute the average temperature by season ('season_desc'). (The temperatures are numbers between 0 and 1, but don't worry about that. Let's say that's the Shellman temperature sca... | Python Code:
from pandas import DataFrame, Series
import pandas as pd
import numpy as np
weather_data = pd.read_table('data/daily_weather.tsv')
season_mapping = {'Spring': 'Winter', 'Winter': 'Fall', 'Fall': 'Summer', 'Summer': 'Spring'}
def fix_seasons(x):
return season_mapping[x]
weather_data['season_desc'] = wea... |
12,529 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nasa-giss', 'giss-e2-1h', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: NASA-GISS
Source ID: GISS-E2-1H
Topic: Atmoschem
Sub-Topics: Tr... |
12,530 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Le TD a commencé par un petit contrôle... que nous avons ensuite (partiellement) corrigé.
Correction de l'exercice mystère.
Rappel du sujet initial
Step1: 1
Step2: 2
Step3: Étape 2. B... | Python Code:
def mystere(unparametre)
unevariable = True
uneautrevariable = 0
while unevariable:
truc = unparametre // 10
uneautrevariable+=1
if truc = 0:
print("truc 0")
if truc > 0:
unparametre = truc
else:
unevariable = False
ret... |
12,531 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: Módulo 2
Step5: Scatter Plot
Variáveis
Step6: Plot dos datasets
scatter plot simples
Step7: Customizando formas, cores e tamanho
Step8: Adicionando mais um dataset
Step12: Facili... | Python Code:
import numpy as np
import os
import pandas as pd
habilitando plots no notebook
%matplotlib inline
plot libs
import matplotlib.pyplot as plt
import seaborn as sns
Configurando o Matplotlib para o modo manual
plt.interactive(False)
Explanation: Módulo 2: Scatter Plot + Text
Tutorial
Imports
End of expl... |
12,532 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hacking for heat
In this series, I'm going to be posting about the process that goes on behind some of the blog posts we end up writing. In this first entry, I'm going to be exploring a numb... | Python Code:
import pandas as pd
litigation = pd.read_csv("Housing_Litigations.csv")
litigation.head()
Explanation: Hacking for heat
In this series, I'm going to be posting about the process that goes on behind some of the blog posts we end up writing. In this first entry, I'm going to be exploring a number of datsets.... |
12,533 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The previous GenerateProbs and GenerateProbsPart2 focused on creating a CDF that can be indexed with a uniform random number to determine the coupon draw. But what if we went the other way?... | Python Code:
%matplotlib inline
import numpy as np
from numpy.random import beta as npbeta
from random import betavariate as pybeta
from scipy.stats import beta as scibeta
from matplotlib import pyplot as plt
from numpy import arange, vectorize
import timeit
start = timeit.default_timer()
for i in np.arange(1000000):
... |
12,534 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--BOOK_INFORMATION-->
<img align="left" style="padding-right
Step1: Visualizing a Three-Dimensional Function
We'll start by demonstrating a contour plot using a function $z = f(x, y)$, us... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
Explanation: <!--BOOK_INFORMATION-->
<img align="left" style="padding-right:10px;" src="figures/PDSH-cover-small.png">
This notebook contains an excerpt from the Python Data Science Handbook by Jake VanderP... |
12,535 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Read in the .csv data file
Use pandas pd.read_csv() function to read in the .csv file
Step2: Build the violin plot
Use seaborns built-in violin plot function to make the plot.... | Python Code:
# seaborn violin plot
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Title: Violin Plot using Python, matplotlib and seaborn
Date: 2017-10-21 16:00
Import the necessary packages
Pandas is used to read in the .csv data. Seaborn to build the plot and... |
12,536 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kalman filter for altitude estimation from GPS, sonar, baro. Input with accelerometer. Estimation of acceleometer bias and baro bias.
I) TRAJECTORY
We assume sinusoidal trajectory
Step1: I... | Python Code:
m = 50000 # timesteps
dt = 1/ 250.0 # update loop at 250Hz
t = np.arange(m) * dt
freq = 0.05 # Hz
amplitude = 5.0 # meter
alt_true = 405 + amplitude * np.cos(2 * np.pi * freq * t)
height_true = 6 + amplitude * np.cos(2 * np.pi * freq * t)
vel_true = - amplitude * (2 * np.pi * freq) * np.sin(2 ... |
12,537 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DICS for power mapping
In this tutorial, we'll simulate two signals originating from two
locations on the cortex. These signals will be sinusoids, so we'll be looking
at oscillatory activity... | Python Code:
# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
#
# License: BSD (3-clause)
Explanation: DICS for power mapping
In this tutorial, we'll simulate two signals originating from two
locations on the cortex. These signals will be sinusoids, so we'll be looking
at oscillatory activity (as opposed to evoked a... |
12,538 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: Theano exercises
This notebook contains Theano exercises not related to machine learning.
The exercises work in the following way
Step4: Solution
Step9: Exercise 2
This exercise req... | Python Code:
import numpy as np
from theano import function
raise NotImplementedError("TODO: add any other imports you need")
def make_scalar():
Returns a new Theano scalar.
raise NotImplementedError("TODO: implement this function.")
def log(x):
Returns the logarithm of a Theano scalar x.
... |
12,539 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Scan Examples
By Rob DiPietro – Version 0.32 – April 28, 2016.
<a href="https
Step1: This example shows how scan is used
Step3: <a id="generating-inputs-and-targets"></a>
Genera... | Python Code:
from __future__ import division, print_function
import tensorflow as tf
def fn(previous_output, current_input):
return previous_output + current_input
elems = tf.Variable([1.0, 2.0, 2.0, 2.0])
elems = tf.identity(elems)
initializer = tf.constant(0.0)
out = tf.scan(fn, elems, initializer=initializer)
wi... |
12,540 | 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 ... |
12,541 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Get Data
Step1: Basic Heat map
Step2: Hide tick_labels and color axis using 'axes_options'
Step3: Non Uniform Heat map
Step4: Alignment of the data with respect to the grid
For a N-by-N ... | Python Code:
np.random.seed(0)
data = np.random.randn(10, 10)
Explanation: Get Data
End of explanation
from ipywidgets import *
fig = plt.figure(padding_y=0.0)
grid_map = plt.gridheatmap(data)
fig
grid_map.display_format = ".2f"
grid_map.font_style = {"font-size": "16px", "fill": "blue", "font-weight": "bold"}
Explanat... |
12,542 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Linear regression
Linear regression in Python can be done in different ways. From coding it yourself to using a function from a statistics module.
Here we will do both.
Coding with nu... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.arange(10.)
y = 5*x+3
np.random.seed(3)
y+= np.random.normal(scale=10,size=x.size)
plt.scatter(x,y);
def lin_reg(x,y):
Perform a linear regression of x vs y.
x, y are 1 dimensional numpy arrays
returns alpha and b... |
12,543 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Význam nízkých a vysokých harmonických složek
Obdélníkový časový průběh
Amplitudy jednotlivých hramonických složek obdélníkového časového průběhu lze vyjádřit vztahem
Step1: Součet všech ha... | Python Code:
Um=1
DCL=0.25
f=linspace(0,1000,1001)
U=2.*Um*DCL*sinc(f*DCL)
U[0]=U[0]/2.
figure(figsize=(10,7))
minorticks_on()
xlabel(r'$\rightarrow$ \\f [Hz]',fontsize=16, x=0.9 )
ylabel(r'U [V] $\uparrow$',fontsize=16, y=0.9, rotation=0)
title(u"Amplitudové frekvenční spektrum -- obdélník DCL=25\%)")
grid(True, 'majo... |
12,544 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinary Differential Equations Exercise 1
Imports
Step2: Lorenz system
The Lorenz system is one of the earliest studied examples of a system of differential equations that exhibits chaotic... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
from IPython.html.widgets import interact, fixed
Explanation: Ordinary Differential Equations Exercise 1
Imports
End of explanation
def lorentz_derivs(yvec, t, sigma, rho, beta):
Compute the the der... |
12,545 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Word prediction using Quadgram
This program reads the corpus line by line.This reads the corpus one line at a time loads it into the memory
Time Complexity for word prediction
Step1: <u>Do... | Python Code:
from nltk.util import ngrams
from collections import defaultdict
from collections import OrderedDict
import string
import time
import gc
start_time = time.time()
Explanation: Word prediction using Quadgram
This program reads the corpus line by line.This reads the corpus one line at a time loads it into the... |
12,546 | 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
Step3: 1. UI界面
Step4: 从回测结果中可以看到最终收益为正值,由于使用较高的止盈位,偏倚重盈亏比值,胜率不高,最终策略是否应该使用这组参数,即最优参数的选择在‘第7节-寻找策略最... | 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安装的... |
12,547 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ipsl', 'sandbox-3', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: IPSL
Source ID: SANDBOX-3
Topic: Ocnbgchem
Sub-Topics: Tracers.
Prop... |
12,548 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Landcover factor exploration
This notebook explores the relationship between the soundscape power and contributing land cover area for sounds in a pumilio database.
Required packages
pandas ... | Python Code:
import pandas
from Pymilio import database
import numpy as np
from colour import Color
import matplotlib.pylab as plt
%matplotlib inline
Explanation: Landcover factor exploration
This notebook explores the relationship between the soundscape power and contributing land cover area for sounds in a pumilio da... |
12,549 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exclusive OR
Following symbol are used to explain Exclusive OR in logic, or mathematics.
$A{\veebar}B \ A{\oplus}B$
logical operation
| A | B | $A{\oplus}B$ |
|---|---|---|
| F | F | F |
| F... | Python Code:
# In Python, XOR operator is ^
for a in (False, True):
for b in (False,True):
for c in (False, True):
# print (a, b, c, a^(b^c), (a^b)^c)
print ("{!r:5} {!r:5} {!r:5} | {!r:5} {!r:5}".format(a, b, c, a^(b^c), (a^b)^c))
Explanation: Exclusive OR
Following symbol are used ... |
12,550 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The purpose of this notebook is twofold. First, it demonstrates the basic functionality of PyLogit for estimatin Mixed Logit models. Secondly, it compares the estimation results for a Mixed ... | Python Code:
from collections import OrderedDict # For recording the model specification
import pandas as pd # For file input/output
import numpy as np # For vectorized math operations
import pylogit as pl # For choice model estimation
Explanation: The purpos... |
12,551 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Facies Classification Solution By Team_BGC
Cheolkyun Jeong and Ping Zhang From Team_BGC
Import Header
Step1: 1. Data Prepocessing
1) Filtered data preparation
After the initial data validat... | Python Code:
##### import basic function
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
##### import stuff from scikit learn
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.metrics import confusion_matrix, make_scor... |
12,552 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Digit Classification using K-Neighbours and Logistic Regression
http
Step1: What does our data look like?
This is how we represent a handwritten '0' character - values with a 0 are dark, an... | Python Code:
from sklearn import datasets, neighbors, linear_model
digits = datasets.load_digits() # Retrieves digits dataset from scikit-learn
print(digits['DESCR'])
Explanation: Digit Classification using K-Neighbours and Logistic Regression
http://scikit-learn.org/stable/auto_examples/exercises/plot_digits_classific... |
12,553 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Departamento de Física - Faculdade de Ciências e Tecnologia da Universidade de Coimbra
Física Computacional - Ficha 4 - Sistemas de equações Lineares
Rafael Isaque Santos - 2012144694 - Lice... | Python Code:
import numpy as np
Explanation: Departamento de Física - Faculdade de Ciências e Tecnologia da Universidade de Coimbra
Física Computacional - Ficha 4 - Sistemas de equações Lineares
Rafael Isaque Santos - 2012144694 - Licenciatura em Física
1 - Resolução de um sistema de equações lineares $Ax = b$ pelo mét... |
12,554 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Euler Bernoulli Beam "solver"
The Euler-Bernoulli equation describes the relationship between the beam's deflection and the applied load
$$\frac{d^2}{dx^2}\left(EI\frac{d^2w}{dx^2}\right) = ... | Python Code:
from sympy import *
%matplotlib notebook
init_printing()
x = symbols('x')
E, I = symbols('E I', positive=True)
C1, C2, C3, C4 = symbols('C1 C2 C3 C4')
w, M, q, f = symbols('w M q f', cls=Function)
EI = symbols('EI', cls=Function, nonnegative=True)
M_eq = -diff(M(x), x, 2) - q(x)
M_eq
M_sol = dsolve(M_eq, M... |
12,555 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification
$$
\renewcommand{\like}{{\cal L}}
\renewcommand{\loglike}{{\ell}}
\renewcommand{\err}{{\cal E}}
\renewcommand{\dat}{{\cal D}}
\renewcommand{\hyp}{{\cal H}}
\renewcommand{\Ex}[... | Python Code:
%matplotlib inline
import numpy as np
import scipy as sp
import matplotlib as mpl
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import pandas as pd
pd.set_option('display.width', 500)
pd.set_option('display.max_columns', 100)
pd.set_option('display.notebook_repr_html', True)
import seaborn as ... |
12,556 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: 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... |
12,557 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
用Python 3开发网络爬虫
By Terrill Yang (Github
Step1: urllib.request是一个库, 隶属urllib. 点此打开官方相关文档. 官方文档应该怎么使用呢? 首先点刚刚提到的这个链接进去的页面有urllib的几个子库, 我们暂时用到了request, 所以我们先看urllib.request部分. 首先看到的是一句话介绍这个库是干... | Python Code:
#encoding:UTF-8
import urllib.request
url = "http://www.pku.edu.cn"
data = urllib.request.urlopen(url).read()
data = data.decode('UTF-8')
print(data)
Explanation: 用Python 3开发网络爬虫
By Terrill Yang (Github: https://github.com/yttty)
由你需要这些:Python3.x爬虫学习资料整理 - 知乎专栏整理而来。
用Python 3开发网络爬虫 - Chapter 01
1. 一个简单的伪... |
12,558 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Partial Dependence Plots with categorical values
Sigurd Carlsen Feb 2019
Holger Nahrstaedt 2020
.. currentmodule
Step1: objective function
Here we define a function that we evaluate.
Step2... | Python Code:
print(__doc__)
import sys
from skopt.plots import plot_objective
from skopt import forest_minimize
import numpy as np
np.random.seed(123)
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_sel... |
12,559 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Rough outline brainstorm
Reading in data
briefly address encoding issues. I believe pandas default to ASCII? (-- it's acutally UTF-8)
basic manipulations
Subsetting
Accessing rows/columns/in... | Python Code:
# Import the packages we will use
import pandas as pd
import numpy as np
from IPython.display import display, HTML
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
Explanation: Rough outline brainstorm
Reading in data
briefly address encoding issues. I believe pand... |
12,560 | 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', 'cmcc', 'cmcc-cm2-hr4', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: CMCC
Source ID: CMCC-CM2-HR4
Sub-Topics: Radiative Forcings.
Proper... |
12,561 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow IO Authors.
Step1: Prometheus 서버에서 메트릭 로드하기
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: CoreDNS 및 Prometheus... | 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... |
12,562 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ateliers
Step1: 1. Importation des données
Définition du répertoir de travail, des noms des différents fichiers utilisés et des variables globales.
Dans un premier temps, il vous faut téléc... | Python Code:
#Importation des librairies utilisées
import unicodedata
import time
import pandas as pd
import numpy as np
import random
import nltk
import collections
import itertools
import csv
import warnings
from sklearn.cross_validation import train_test_split
Explanation: Ateliers: Technologies de l'intelligence A... |
12,563 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Parsing Citations
With AnyStyle.io and Crossref's search api
Step1: ok, we got a pile of citations. But they aren't in shape. When we look at the cites, they are a collection of 1,505 strin... | Python Code:
import pandas as pd
citations = pd.read_csv("cites.csv")
citations
citations.iloc[0]
len(citations)
Explanation: Parsing Citations
With AnyStyle.io and Crossref's search api
End of explanation
citations.iloc[0:5]
Explanation: ok, we got a pile of citations. But they aren't in shape. When we look at the cit... |
12,564 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Titanic Survival Analysis
Step1: The next step is to explore the dataset
Step2: We can see that Passenger ID, Name and Cabin have little value to the analysis, so we drop these columns off... | Python Code:
# Import the libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy
# Read the csv file
titanic = pd.read_csv("titanic-data.csv")
Explanation: Titanic Survival Analysis:
Questions:
According to Wikipedia, "Women and children first" is a code of c... |
12,565 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualization of Bus Bunching
When we are working on spatio-temporal data sets, it will be handy if we can visualize the spatial components of data while understanding their relations with t... | Python Code:
import pandas as pd
import numpy as np
df = pd.read_csv("mta_1706.csv")
# Set to datetime object
df['RecordedAtTime'] = pd.to_datetime(df['RecordedAtTime'])
df = df[(df['RecordedAtTime'] < pd.Timestamp('2017-06-02')) & (df['RecordedAtTime'] > pd.Timestamp('2017-05-31'))]
# filter missing values
df = df.dro... |
12,566 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
.. _tut_stats_cluster_sensor_rANOVA_tfr
Mass-univariate twoway repeated measures ANOVA on single trial power
This script shows how to conduct a mass-univariate repeated measures
ANOVA. As th... | Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
# Eric Larson <larson.eric.d@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.time_frequency ... |
12,567 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fortran cython i numpy
Porównanie różnych podejść - do rozwiązywanie równania dyfuzji jawnym algorytmem.
Obliczanie operatora Laplace'a na siatce z f2py, stosując wektorowy kod w f90 działa ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
%load_ext Cython
%%cython
cimport cython
cimport numpy as np
@cython.wraparound(False)
@cython.boundscheck(False)
def cython_diff2d(np.ndarray[double, ndim=2] u,np.ndarray[double, ndim=2] v, double dx2, double dy2, double c):
cdef un... |
12,568 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fitting a diagonal covariance Gaussian mixture model to text data
In a previous assignment, we explored k-means clustering for a high-dimensional Wikipedia dataset. We can also model this da... | Python Code:
import graphlab
'''Check GraphLab Create version'''
from distutils.version import StrictVersion
assert (StrictVersion(graphlab.version) >= StrictVersion('1.8.5')), 'GraphLab Create must be version 1.8.5 or later.'
Explanation: Fitting a diagonal covariance Gaussian mixture model to text data
In a previous ... |
12,569 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling and Simulation in Python
Rabbit example
Copyright 2017 Allen Downey
License
Step1: Rabbit is Rich
This notebook starts with a version of the rabbit population growth model. You wi... | Python Code:
%matplotlib inline
from modsim import *
Explanation: Modeling and Simulation in Python
Rabbit example
Copyright 2017 Allen Downey
License: Creative Commons Attribution 4.0 International
End of explanation
system = System(t0 = 0,
t_end = 20,
juvenile_pop0 = 0,
... |
12,570 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Automatic Hyperparameter tuning
This notebook will show you how to extend the code in the cloud-ml-housing-prices notebook to take advantage of Cloud ML Engine's automatic hyperparameter tun... | Python Code:
%%bash
mkdir trainer
touch trainer/__init__.py
%%writefile trainer/task.py
import argparse
import pandas as pd
import tensorflow as tf
import os #NEW
import json #NEW
from tensorflow.contrib.learn.python.learn import learn_runner
from tensorflow.contrib.learn.python.learn.utils import saved_model_export_ut... |
12,571 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Rejecting bad data spans
This tutorial covers manual marking of bad spans of data, and automated
rejection of data spans based on signal amplitude.
Step1: Annotating bad spans of data
^... | Python Code:
import os
import mne
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
'sample_audvis_filt-0-40_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)
events_file = os.path.join... |
12,572 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST Image Classification with TensorFlow on Cloud ML Engine
This notebook demonstrates how to implement different image models on MNIST using Estimator.
Note the MODEL_TYPE; change it to ... | Python Code:
import os
PROJECT = "cloud-training-demos" # REPLACE WITH YOUR PROJECT ID
BUCKET = "cloud-training-demos-ml" # REPLACE WITH YOUR BUCKET NAME
REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1
MODEL_TYPE = "dnn" # "linear", "dnn", "dnn_dropout", or "cnn"
# Do not change these
os.envi... |
12,573 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting started
Step1: One of the essential paradigms of do-mpc is a modular architecture, where individual building bricks can be used independently our jointly, depending on the applicati... | Python Code:
import numpy as np
# Add do_mpc to path. This is not necessary if it was installed via pip.
import sys
sys.path.append('../../')
# Import do_mpc package:
import do_mpc
Explanation: Getting started: MPC
In this Jupyter Notebook we illustrate the core functionalities of do-mpc.
Open an interactive online Jup... |
12,574 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning
Assignment 1
The objective of this assignment is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later.
This notebook ... | Python Code:
# Config the matlotlib backend as plotting inline in IPython
%matplotlib inline
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import t... |
12,575 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Network Traffic Forecasting with AutoTSEstimator
In telco, accurate forecast of KPIs (e.g. network traffic, utilizations, user experience, etc.) for communication networks ( 2G/3G/4G/5G/wire... | Python Code:
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
raw_df = pd.read_csv("data/data.csv")
Explanation: Network Traffic Forecasting with AutoTSEstimator
In telco, accurate forecast of KPIs (e.g. network traffic, utilizations, user experience, etc.) for commun... |
12,576 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 9</font>
Download
Step1: Preço médio de um veículo por marca, bem como tipo de veículo | Python Code:
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())
# Imports
import os
import subprocess
import stat
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib as mat
import matplotlib.pypl... |
12,577 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Breaking MCMC
Step1: Here's the Rosenbrock function in code. Since we're pretending it's the log-posterior, I've introduced a minus sign that doesn't normally appear.
Step2: Let's plot "st... | Python Code:
from IPython.display import Image
Image(filename="DifficultDensities_banana_eg.png", width=350)
Explanation: Breaking MCMC: difficult densities
We're fortunate that much of the time the posterior functions we care about are relatively simple, i.e. unimodal and roughly Gaussian shaped. But not always! So, l... |
12,578 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example
Step1: 1
Step2: The input parameter
sele_atoms
enables the user to choose which atoms she/he wants to use as beads when constructing the ENM.
Standard options are
Step3: We can s... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
# import barnaba
import barnaba.enm as enm
# define the input file
fname = "../test/data/sample1.pdb"
Explanation: Example: Elastic Network Model
Here we show how to use BaRNAba to construct an elastic network model (ENM) of an RNA molec... |
12,579 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Catigorical Columns Don't just One-Hot, They Count.
Step1: Here we have 3 examples, each containing 5 strings.
Note
Step2: Now we define a categorical column to represent it.
Step3: Use i... | Python Code:
tf.reset_default_graph()
Explanation: Catigorical Columns Don't just One-Hot, They Count.
End of explanation
strings = np.array([['a','a','','b','c'],['a','c','zz','',''],['b','qq','qq','b','']])
Explanation: Here we have 3 examples, each containing 5 strings.
Note: empty strings are ignored, and can be us... |
12,580 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Analyzing convention speeches with Google Language API </h1>
This notebook accompanies my Medium article
Step1: <b> Note
Step2: <h2> Sentiment analysis with Language API </h2>
Let's e... | Python Code:
APIKEY="AIzaSyBNa0Hw5_SZpmQP2-iXgUfchVHa4Ot956M"
Explanation: <h1> Analyzing convention speeches with Google Language API </h1>
This notebook accompanies my Medium article: <a href="https://medium.com/@lakshmanok/is-this-presidential-election-more-negative-than-years-past-yes-ca254e35eb9#.krrlhkryr"> Is th... |
12,581 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Now that we have created and saved a configuration file, let’s read it back and explore the data it holds.
Step1: Please note that default values have precedence over fallback values. For i... | Python Code:
config = configparser.ConfigParser()
config.sections()
config.read('example.ini')
config.sections()
'bitbucket.org' in config
'bytebong.com' in config
config['bitbucket.org']['User']
config['DEFAULT']['Compression']
topsecret = config['topsecret.server.com']
topsecret['ForwardX11']
topsecret['Port']
for ke... |
12,582 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Units and Quantities
Objectives
Use units
Create functions that accept quantities as arguments
Create new units
Basics
How do we define a Quantity and which parts does it have?
Step1: Quant... | Python Code:
from astropy import units as u
# Define a quantity length
length = 26.2 * u.meter
# print it
print(length) # length is a quantity
# Type of quantity
type(length)
# Type of unit
type(u.meter)
# Quantity
length
# value
length.value
# unit
length.unit
# information
length.info
Explanation: Units and Quantitie... |
12,583 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quick Start
This quick start will show how to do the following
Step1: Now let's import a GAM that's made for regression problems.
Let's fit a spline term to the first 2 features, and a fact... | Python Code:
from pygam.datasets import wage
X, y = wage()
Explanation: Quick Start
This quick start will show how to do the following:
Install everything needed to use pyGAM.
fit a regression model with custom terms
search for the best smoothing parameters
plot partial dependence functions
Install pyGAM
Pip
pip instal... |
12,584 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: A simple classification model using Keras with Cloud TPUs
Overview
This not... | 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... |
12,585 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Models
By Saurabh Mahindre - <a href="https
Step1: Training and generating weights
LeastSquaresRegression has to be initialised with the training features and training labels. On... | Python Code:
%pylab inline
%matplotlib inline
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
from cycler import cycler
# import all shogun classes
from shogun import *
import shogun as sg
slope = 3
X_train = rand(30)*10
y_train = slope*(X_train)+random.randn(30)*2+2
y_true = slope*(X_train)+2
X... |
12,586 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generic Android viewer
Step1: Test environment setup
For more details on this please check out examples/utils/testenv_example.ipynb.
devlib requires the ANDROID_HOME environment variable co... | Python Code:
from conf import LisaLogging
LisaLogging.setup()
%pylab inline
import json
import os
# Support to access the remote target
import devlib
from env import TestEnv
# Import support for Android devices
from android import Screen, Workload, System, ViewerWorkload
from target_script import TargetScript
# Support... |
12,587 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook has some profiling of Dask used to make a selection along both first and second axes of a large-ish multidimensional array. The use case is making selections of genotype data, ... | Python Code:
import zarr; print('zarr', zarr.__version__)
import dask; print('dask', dask.__version__)
import dask.array as da
import numpy as np
Explanation: This notebook has some profiling of Dask used to make a selection along both first and second axes of a large-ish multidimensional array. The use case is making ... |
12,588 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
OLGA ppl files, examples and howto
For an tpl file the following methods are available
Step1: Profile selection
As for tpl files, a ppl file may contain hundreds of profiles, in particular ... | Python Code:
ppl_path = '../../pyfas/test/test_files/'
fname = 'FC1_rev01.ppl'
ppl = fa.Ppl(ppl_path+fname)
Explanation: OLGA ppl files, examples and howto
For an tpl file the following methods are available:
<b>filter_data</b> - return a filtered subset of trends
<b>extract</b> - extract a single trend variable
<b>to_... |
12,589 | 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: Running an SBML model
If you have run your genome through RA... | Python Code:
import sys
import copy
import PyFBA
from __future__ import print_function
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.
T... |
12,590 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Identify Coupled Patterns between SLP and SST through Maximum Covariance Analysis
Maximum Correlation Analysis (MCA; Bretherton et al., 1992) is similar to Empirical Orthogonal Function Anal... | Python Code:
%matplotlib inline
import numpy as np
import xarray as xr
import cartopy.crs as ccrs
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.gridspec as gridspec
import matplotlib.dates as mdates
mpl.rcParams['figure.figsize'] = 8.0, 4.0
mpl.rcParams['font.size'] =... |
12,591 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
5. Basic Numerical Analysis
5.1. NumPy
5.1.1. The standard Python library for linear algebra is numpy. In this section, we cover just enough of the numpy API to implement a few algorithms in... | Python Code:
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([[1, 2, 3, 4]])
c = np.array([[1], [2], [3], [4]])
d = np.array([[1, 2], [3, 4]])
print(a)
print('shape of a: {}'.format(a.shape))
print()
print(b)
print('shape of b: {}'.format(b.shape))
print()
print(c)
print('shape of c: {}'.format(c.shape))
pri... |
12,592 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learn the alphabet
http
Step1: Naive LSTM for Learning One-Char to One-Char Mapping
Let’s start off by designing a simple LSTM to learn how to predict the next character in the alphabet giv... | Python Code:
import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.utils import np_utils
# fix random seed for reproducibility
numpy.random.seed(7)
# define the raw dataset
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# create mapping of characters to intege... |
12,593 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pixels to Tabular Data
Agricultural Statistical Analysis Use Case
Talk about pixels and tabular data.
The use case addressed in this tutorial is
Step1: Get Field and Sample Blocks AOIs
Step... | Python Code:
import datetime
import json
import os
from pathlib import Path
from pprint import pprint
import shutil
import time
from zipfile import ZipFile
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from planet import api
from planet.api import downloader, filters
import pyproj
from rasterio... |
12,594 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
计算传播应用
推荐系统简介
王成军
wangchengjun@nju.edu.cn
计算传播网 http
Step1: 1. User-based filtering
1.0 Finding similar users
Step2: This formula calculates the distance, which will be smaller for people ... | Python Code:
# A dictionary of movie critics and their ratings of a small
# set of movies
critics={'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,
'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,
'The Night Listener': 3.0},
'Gene Seymour': {'Lady in the Water':... |
12,595 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pyomo - Stock problem v1
Pyomo installation
Step1: Version 1 (P1)
$x_t < 0$ = buy $|x|$ at time $t$
$x_t > 0$ = sell $|x|$ at time $t$
$s_t$ = the battery level at time $t$
$$
\begin{align}... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
from pyomo.environ import *
Explanation: Pyomo - Stock problem v1
Pyomo installation: see http://www.pyomo.org/installation
pip install pyomo
End of explanation
# Cost of energy on the market
#cost = [10, 30, 20] # -> -100, 100, 0
#cost = [10, 30,... |
12,596 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
List - Dictionary - Tuples
<font color='red'>What will be Covered?</font>
<OL>
<LI> List
<LI> Tuples
<LI> Dictionary
</OL>
<font color='red'>Reference Documents</font>
<OL>
<LI> <A HREF="htt... | Python Code:
myList = []
myList = ["The", "earth", "revolves", "around", "sun"]
myList[5]
myList[4]
myList[-1]
Explanation: List - Dictionary - Tuples
<font color='red'>What will be Covered?</font>
<OL>
<LI> List
<LI> Tuples
<LI> Dictionary
</OL>
<font color='red'>Reference Documents</font>
<OL>
<LI> <A HREF="http://ef... |
12,597 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
12,598 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<figure>
<IMG SRC="../../logo/logo.png" WIDTH=250 ALIGN="right">
</figure>
IHE Python course, 2017
Three-doors quiz (famous statistical fallacy)
T.N.Olsthoorn,
April 18, 2017
The famous t... | Python Code:
import random
verbose = True
N = 1 if verbose else 10000
verbose = True
Explanation: <figure>
<IMG SRC="../../logo/logo.png" WIDTH=250 ALIGN="right">
</figure>
IHE Python course, 2017
Three-doors quiz (famous statistical fallacy)
T.N.Olsthoorn,
April 18, 2017
The famous three doors fallacy goes like thi... |
12,599 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center">TensorFlow Neural Network Lab</h1>
<img src="image/notmnist.png">
In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl... | Python Code:
import hashlib
import os
import pickle
from urllib.request import urlretrieve
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils import resample
from tqdm import tqdm
from zipfile import ZipFile
p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.