Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
14,300 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
My first precipitation nowcast
In this example, we will use pysteps to compute and plot an extrapolation nowcast using the NSSL's Multi-Radar/Multi-Sensor System
(MRMS) rain rate product.
Th... | Python Code:
# These libraries are needed for the pygrib library in Colab.
# Note that is needed if you install pygrib using pip.
# If you use conda, the libraries will be installed automatically.
! apt-get install libeccodes-dev libproj-dev
# Install the python packages
! pip install pyproj
! pip install pygrib
# Uni... |
14,301 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ground Penetrating Radar Lab 6 Notebook
This notebook contains two apps, which are used to complete part 3 in GPR Lab 6
Step1: Pipe Fitting App
<img style="float
Step2: Slab Fitting App
<i... | Python Code:
from geoscilabs.gpr.GPRlab1 import downloadRadargramImage, PipeWidget, WallWidget
from SimPEG.utils import download
Explanation: Ground Penetrating Radar Lab 6 Notebook
This notebook contains two apps, which are used to complete part 3 in GPR Lab 6:
Pipe Fitting App: This app simulates the radargram signat... |
14,302 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
How to convert a numpy array of dtype=object to torch Tensor? | Problem:
import pandas as pd
import torch
import numpy as np
x_array = load_data()
x_tensor = torch.from_numpy(x_array.astype(float)) |
14,303 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stellar mass profiles based on sg_fluxtable
Preliminary stellar mass profiles of the HST sample based on the radial aperture photometry sg_fluxtable_nm.txt generated in July 2017 at Bates.
S... | Python Code:
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import fitsio
import astropy.units as u
from astropy.io import ascii
from astropy.table import Table
from astropy.cosmology import FlatLambdaCDM
%pylab inline
mpl.rcParams.update({'font.size': 18})
cosmo = FlatLambdaCDM(H... |
14,304 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
Welcome to my analysis on who died during the sinking of the Titanic. In this notebook I will be exploring some basic trends to see what are the best predictors of who survived ... | Python Code:
# IMPORT STATEMENTS.
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import seaborn as sns # data visualisation
import matplotlib.pyplot as plt # data visualisation
import random # Used to sample survival.
# DEFINE GLOBALS.
NUM_OF_ROLLS = 3
df = pd... |
14,305 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t... |
14,306 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced indexing
Step1: This dataset is borrowed from the PyCon tutorial of Brandon Rhodes (so all credit to him!). You can download these data from here
Step2: Setting columns as the ind... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
try:
import seaborn
except ImportError:
pass
pd.options.display.max_rows = 10
Explanation: Advanced indexing
End of explanation
cast = pd.read_csv('data/cast.csv')
cast.head()
titles = pd.read_csv('data/titles... |
14,307 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Traffic flow
Step1: The LWR model
Recall the continuity equation for any density that is advected with a flow
Step2: Combining the two equations above, our conservation law says
$$\rho_t +... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
from ipywidgets import interact
from ipywidgets import FloatSlider, fixed
from exact_solvers import traffic_LWR
from exact_solvers import traffic_demos
from IPython.display import Image
Explanation: Traffic flow: the Lighthill-Whitham-Richards ... |
14,308 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Playing atari with advantage actor-critic
This time we're going to learn something harder then CartPole
Step3: Processing game image
Raw atari images are large, 210x160x3 by default. Howev... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
#setup theano/lasagne. Prefer GPU
%env THEANO_FLAGS=device=gpu,floatX=float32
#If you are running on a server, launch xvfb to record game videos
#Please make sure you have xvfb installed (apt-get install xvfb, see gym readme on xvfb)
imp... |
14,309 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing the 1-D DVR
Use matplotlib inline so that plots show up in the notebook.
Step1: Next import the dvr_1d module. We import dvr_1d using a series of ipython notebook magic commands so ... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.sparse as sp
import scipy.sparse.linalg as sla
Explanation: Testing the 1-D DVR
Use matplotlib inline so that plots show up in the notebook.
End of explanation
# autoreload the lattice module so that we can make changes to i... |
14,310 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multitask GP Regression
Introduction
Multitask regression, introduced in this paper learns similarities in the outputs simultaneously. It's useful when you are performing regression on multi... | Python Code:
import math
import torch
import gpytorch
from matplotlib import pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
Explanation: Multitask GP Regression
Introduction
Multitask regression, introduced in this paper learns similarities in the outputs simultaneously. It's useful when you are pe... |
14,311 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear classifier on sensor data with plot patterns and filters
Here decoding, a.k.a MVPA or supervised machine learning, is applied to M/EEG
data in sensor space. Fit a linear classifier wi... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Romain Trachel <trachelr@gmail.com>
# Jean-Remi King <jeanremi.king@gmail.com>
#
# License: BSD-3-Clause
import mne
from mne import io, EvokedArray
from mne.datasets import sample
from mne.decoding import Vectorizer, get_coef
f... |
14,312 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring the Lorenz System of Differential Equations
Downloaded 10/2017 from the ipywidgets docs
In this Notebook we explore the Lorenz system of differential equations
Step2: Computing th... | Python Code:
%matplotlib inline
from ipywidgets import interact, interactive
from IPython.display import clear_output, display, HTML
import numpy as np
from scipy import integrate
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
from matplotlib import ani... |
14,313 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predictiong with SLM
In this notebook we compare how accurate is a SVM prediction using SLM as its features when the latter are normalized (its values are only 0, 1) in opposition to the cur... | Python Code:
import numpy as np
import h5py
from sklearn import svm, cross_validation, preprocessing
Explanation: Predictiong with SLM
In this notebook we compare how accurate is a SVM prediction using SLM as its features when the latter are normalized (its values are only 0, 1) in opposition to the current state where... |
14,314 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
License
Copyright (C) 2017 J. Patrick Hall, jphall@gwu.edu
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (t... | Python Code:
import pandas as pd # pandas for handling mixed data sets
import numpy as np # numpy for basic math and matrix operations
import matplotlib.pyplot as plt # pyplot for plotting
# scikit-learn for machine learning and data preprocessing
from sklearn.decomposition import PCA
Expla... |
14,315 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a part-of-speech tagger with transformers (BERT)
This example shows how to use Thinc and Hugging Face's transformers library to implement and train a part-of-speech tagger on the Un... | Python Code:
!pip install "thinc>=8.0.0" transformers torch "ml_datasets>=0.2.0" "tqdm>=4.41"
Explanation: Training a part-of-speech tagger with transformers (BERT)
This example shows how to use Thinc and Hugging Face's transformers library to implement and train a part-of-speech tagger on the Universal Dependencies An... |
14,316 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
word2vec
This notebook is equivalent to demo-word.sh, demo-analogy.sh, demo-phrases.sh and demo-classes.sh from the Google examples.
Step1: Training
Download some data, for example
Step2: ... | Python Code:
%load_ext autoreload
%autoreload 2
Explanation: word2vec
This notebook is equivalent to demo-word.sh, demo-analogy.sh, demo-phrases.sh and demo-classes.sh from the Google examples.
End of explanation
import word2vec
Explanation: Training
Download some data, for example: http://mattmahoney.net/dc/text8.zip
... |
14,317 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Control Flow
Step1: NOTE on notation
* _x, _y, _z, ...
Step2: Q5. Given x, return the truth value of NOT x element-wise. | Python Code:
from __future__ import print_function
import tensorflow as tf
import numpy as np
from datetime import date
date.today()
author = "kyubyong. https://github.com/Kyubyong/tensorflow-exercises"
tf.__version__
np.__version__
sess = tf.InteractiveSession()
Explanation: Control Flow
End of explanation
x = tf.cons... |
14,318 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transfer Learning
Most of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instea... | Python Code:
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
vgg_dir = 'tensorflow_vgg/'
# Make sure vgg exists
if not isdir(vgg_dir):
raise Exception("VGG directory doesn't exist!")
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=... |
14,319 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
本章讨论的话题是接口,从鸭子类型代表特征动态协议,到使接口更明确,能验证是否符合规定的抽象基类(Abstract Base Class,ABC)
在 Python 中 上章所说的鸭子类型是接口的常规方式,新只是是抽象基类和类型检查。Python 语言诞生 15 年之后,Python 2.6 才引入抽象基类。
本章先说明 Python 社区以往对接口的不严谨理解:部分实现接口通常... | Python Code:
class Vector2d:
typecode = 'd'
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __iter__(self):
return (i for i in (self.x, self.y))
Explanation: 本章讨论的话题是接口,从鸭子类型代表特征动态协议,到使接口更明确,能验证是否符合规定的抽象基类(Abstract Base Class,ABC)
在 Python 中 上章所说的鸭子类型是... |
14,320 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Laplace transform
This notebook is a short tutorial of Laplace transform using SymPy.
The main functions to use are laplace_transform and inverse_laplace_transform.
Step1: Let us compute th... | Python Code:
from sympy import *
init_session()
Explanation: Laplace transform
This notebook is a short tutorial of Laplace transform using SymPy.
The main functions to use are laplace_transform and inverse_laplace_transform.
End of explanation
t = symbols("t", real=True, positive=True)
s = symbols("s")
Explanation: Le... |
14,321 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bootstrap
Import and settings
In this example, we need to import numpy, pandas, and graphviz in addition to lingam.
Step1: Test data
We create test data consisting of 6 variables.
Step2: B... | Python Code:
import numpy as np
import pandas as pd
import graphviz
import lingam
from lingam.utils import print_causal_directions, print_dagc, make_dot
print([np.__version__, pd.__version__, graphviz.__version__, lingam.__version__])
np.set_printoptions(precision=3, suppress=True)
np.random.seed(0)
Explanation: Bootst... |
14,322 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Concepts and data from "An Introduction to Statistical Learning, with applications in R" (Springer, 2013) with permission from the authors
Step1: Acquiring and seeing trends in multidimens... | Python Code:
# HIDDEN
# For Tables reference see http://data8.org/datascience/tables.html
# This useful nonsense should just go at the top of your notebook.
from datascience import *
%matplotlib inline
import matplotlib.pyplot as plots
import numpy as np
from sklearn import linear_model
plots.style.use('fivethirtyeight... |
14,323 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using MinBLEP to generate a Saw
Step1: Picking up from where we left off with the MinBlep notebook
Step2: The above saw algorithm goes from -1 to 1, but the blep is from 0 to 1, so it need... | Python Code:
pylab inline
import numpy as np
from minblep import generate_min_blep
sample_rate = 44100
Explanation: Using MinBLEP to generate a Saw
End of explanation
plot(generate_min_blep(15, 400))
def gen_pure_saw(osc_freq, sample_rate, num_samples, initial_phase=0):
peak_amplitude = 1.0
two_pi = 2.0 * np.pi... |
14,324 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color="#04B404"><h1 align="center">Machine Learning 2017-2018</h1></font>
<font color="#6E6E6E"><h2 align="center">Práctica 4
Step1: 1.1. Kernel lineal
Completa el código de la funció... | Python Code:
# Imports
import numpy as np
import svm as svm
from sklearn.metrics.pairwise import polynomial_kernel
from sklearn.metrics.pairwise import rbf_kernel
# Datos de prueba:
n = 10
m = 8
d = 4
x = np.random.randn(n, d)
y = np.random.randn(m, d)
print x.shape
print y.shape
Explanation: <font color="#04B404"><h1... |
14,325 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div style='background-image
Step1: 1. Initialization of setup
Step2: 2. The Mass Matrix
Now we initialize the mass and stiffness matrices. In general, the mass matrix at the elemental lev... | Python Code:
# Import all necessary libraries, this is a configuration step for the exercise.
# Please run it before the simulation code!
import numpy as np
import matplotlib.pyplot as plt
from gll import gll
from lagrange1st import lagrange1st
from ricker import ricker
# Show the plots in the Notebook.
plt.switch_bac... |
14,326 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Read input from JSON records.
Step1: Create a pandas DataFrame
Step2: Create new features
Step3: Filter for PostTypeId == 1 or PostTypeId == 2
Step4: Are any relationships apparent in th... | Python Code:
lines = []
for part in ("00000", "00001"):
with open("../output/2017-01-03_13.57.34/part-%s" % part) as f:
lines += f.readlines()
print(lines[0])
Explanation: Read input from JSON records.
End of explanation
import pandas as pd
df = pd.read_json('[%s]' % ','.join(lines))
print(df.info())
df.head()
Ex... |
14,327 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
In group efforts, there is sometimes the impression that there are those who work, and those who talk. A naive question to ask is whether or not the people that tend to talk a l... | Python Code:
# Load the raw email and git data
url = "http://mail.python.org/pipermail/scipy-dev/"
arx = Archive(url,archive_dir="../archives")
mailInfo = arx.data
repo = repo_loader.get_repo("bigbang")
gitInfo = repo.commit_data;
Explanation: Introduction
In group efforts, there is sometimes the impression that there ... |
14,328 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computing source space SNR
This example shows how to compute and plot source space SNR as in
Step1: EEG
Next we do the same for EEG and plot the result on the cortex | Python Code:
# Author: Padma Sundaram <tottochan@gmail.com>
# Kaisu Lankinen <klankinen@mgh.harvard.edu>
#
# License: BSD-3-Clause
import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
import numpy as np
import matplotlib.pyplot as plt
print(__doc__)
data_p... |
14,329 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
XPCS fitting with lmfit
The experimentatl X-ray Photon Correlation Sepectroscopy(XPCS) data
are fitted with Intermediate Scattering Factor(ISF) using
lmfit Model (http
Step1: Easily switch ... | Python Code:
# analysis tools from scikit-beam (https://github.com/scikit-beam/scikit-beam/tree/master/skbeam/core)
import skbeam.core.roi as roi
import skbeam.core.correlation as corr
import skbeam.core.utils as utils
from lmfit import Model
# plotting tools from xray_vision (https://github.com/Nikea/xray-vision/blob/... |
14,330 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Limits
You can use algebraeic methods to calculate the rate of change over a function interval by joining two points on the function with a secant line and measuring its slope. For example, ... | Python Code:
%matplotlib inline
# Here's the function
def f(x):
return x**2 + x
from matplotlib import pyplot as plt
# Create an array of x values from 0 to 10 to plot
x = list(range(0, 11))
# Get the corresponding y values from the function
y = [f(i) for i in x]
# Set up the graph
plt.xlabel('x')
plt.ylabel('f(x)... |
14,331 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p style="text-align
Step1: To define a floating point number, you may use one of the following notations
Step2: Arithmetic operations
We can arithmetic operations that are common in many ... | Python Code:
myint = 7
print myint
print type(myint)
Explanation: <p style="text-align:right;color:red;font-weight:bold;font-size:16pt;padding-bottom:20px">Please, rename this notebook before editing!</p>
The Programming Language Python
References
Here are some references to freshen up on concepts:
- Self-paced online ... |
14,332 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Forensic Intelligence Applications
In this section we will explore the use of similar source, score-based, non-anchored LRs for forensic intelligence applications. Score-based LRs can be a v... | Python Code:
from IPython.core.display import HTML
import os
#def css_styling():
#response = urllib.request.urlopen('https://dl.dropboxusercontent.com/u/24373111/custom.css')
#desktopFile = os.path.expanduser("~\Desktop\EAFS_LR_software\ForensicIntelligence\custom.css")
# styles = open(desktopFile, "r").read... |
14,333 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
T-Tests and P-Values
Let's say we're running an A/B test. We'll fabricate some data that randomly assigns order amounts from customers in sets A and B, with B being a little bit higher
Step1... | Python Code:
import numpy as np
from scipy import stats
A = np.random.normal(25.0, 5.0, 10000)
B = np.random.normal(26.0, 5.0, 10000)
stats.ttest_ind(A, B)
Explanation: T-Tests and P-Values
Let's say we're running an A/B test. We'll fabricate some data that randomly assigns order amounts from customers in sets A and B,... |
14,334 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pole-Zero (PZ) simulation example
In this short example we will simulate a simple RLC circuit with the ahkab simulator.
In particular, we consider a series resonant RLC circuit. If you need ... | Python Code:
%pylab inline
figsize = (10, 7)
# libraries we need
import ahkab
print "We're using ahkab %s" % ahkab.__version__
Explanation: Pole-Zero (PZ) simulation example
In this short example we will simulate a simple RLC circuit with the ahkab simulator.
In particular, we consider a series resonant RLC circuit. If... |
14,335 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step4: Let me work through CSS Tutorial, while consulting Cascading Style Sheets - Wikipedia, the free encyclopedia.
CSS as a collection of
Step6: Box model
CSS box model - Wikipedia, the f... | Python Code:
from nbfiddle import Fiddle
# http://www.w3schools.com/css/tryit.asp?filename=trycss_default
Fiddle(
div_css =
background-color: #d0e4fe;
h1 {
color: orange;
text-align: center;
}
p {
font-family: "Times New Roman";
font-size: 20px;
}
,
html =
<h1>My First CSS Example</h1>
<p>This is... |
14,336 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First Order Filters
This notebook goes through calculations of first order low- and high-pass filters.
To start, lets import the libraries that will be used during this tutorial.
Step1: Tim... | Python Code:
import numpy as np
import plotly.plotly as py
import plotly.graph_objs as go
Explanation: First Order Filters
This notebook goes through calculations of first order low- and high-pass filters.
To start, lets import the libraries that will be used during this tutorial.
End of explanation
# inputs
R = 1000 ... |
14,337 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
July 2, 2020
Step1: Define prog constants
Step2: Define dirs, cats, etc
Step3: Define header, format, etc
NOTE
Step4: Read in the matched 2020 SSC + PS1 cat
Step5: Print out header and ... | Python Code:
# GENERAL PURPOSE PACKAGES
import os
import glob
import tarfile
from urllib.request import urlretrieve
from datetime import date
import timeit
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Import ZI tools
%load_ext autoreload
%autoreload 2
# importing ZI tools:
# import ZItools... |
14,338 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License").
Text Generation using a RNN
<table class="tfo-notebook-buttons" align="left"><td>
<a ta... | Python Code:
!pip install unidecode
Explanation: Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License").
Text Generation using a RNN
<table class="tfo-notebook-buttons" align="left"><td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/tensorfl... |
14,339 | 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,340 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="http
Step1: Market Environment and Portfolio Object
We start by instantiating a market environment object which in particular contains a list of ticker symbols in which we are int... | Python Code:
from dx import *
import seaborn as sns; sns.set()
Explanation: <img src="http://hilpisch.com/tpq_logo.png" alt="The Python Quants" width="45%" align="right" border="4">
Mean-Variance Portfolio Class
Without doubt, the Markowitz (1952) mean-variance portfolio theory is a cornerstone of modern financial theo... |
14,341 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is a tutorial on how to compare machine learning methods with the python library scikit-learn. We'll be using the Indian Liver Disease dataset (found here https
Step1: We'll use all co... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (20,10)
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier... |
14,342 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Convolutional Networks
So far we have worked with deep fully-connected networks, using them to explore different optimization strategies and network architectures. Fully-connected net... | Python Code:
# As usual, a bit of setup
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.cnn import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient_array, eval_numerical_gradient
from cs231n.layers import *
from cs231n.fast_layers impo... |
14,343 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Update for PyTorch 0.4
Step1: Simplicity of using backward()
Step2: The simple operations defined a forward path $z=(2x)^3$, $z$ will be the final output tensor we would like to compute gr... | Python Code:
import torch as T
import torch.autograd
import numpy as np
Explanation: Update for PyTorch 0.4:
Earlier versions used Variable to wrap tensors with different properties. Since version 0.4, Variable is merged with tensor, in other words, Variable is NOT needed anymore. The flag require_grad can be directly ... |
14,344 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Youtube videos
Step1: Closures
A closure closes over free variables from their environment.
Step2: Decorators
Decorators are a way to dynamically alter the functionality of your functions.... | Python Code:
def square(x):
return x*x
def cube(x):
return x*x*x
# This is custom-built map function which is going to behave like in-bulit map function.
def my_map(func, arg_list):
result = []
for i in arg_list:
result.append(func(i))
return result
squares = my_map(square, [1,2,3,4])
print(... |
14,345 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Making New Layers and Models via Subclassing
Learning Objectives
Use Layer class as the combination of state (weights) and computation.
Defer weight creation until the shape of the inputs is... | Python Code:
# Import necessary libraries
import tensorflow as tf
from tensorflow import keras
Explanation: Making New Layers and Models via Subclassing
Learning Objectives
Use Layer class as the combination of state (weights) and computation.
Defer weight creation until the shape of the inputs is known.
Build recursiv... |
14,346 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demonstrate impact of whitening on source estimates
This example demonstrates the relationship between the noise covariance
estimate and the MNE / dSPM source amplitudes. It computes source ... | Python Code:
# Author: Denis A. Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import os
import os.path as op
import numpy as np
from scipy.misc import imread
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.datasets import spm_face
from mne.minimum_norm import apply_inverse, make... |
14,347 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib Exercise 2
Imports
Step1: Exoplanet properties
Over the past few decades, astronomers have discovered thousands of extrasolar planets. The following paper describes the propertie... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Matplotlib Exercise 2
Imports
End of explanation
!head -n 30 open_exoplanet_catalogue.txt
Explanation: Exoplanet properties
Over the past few decades, astronomers have discovered thousands of extrasolar planets. The followin... |
14,348 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Minimizing KL Divergence
Let’s see how we could go about minimizing the KL divergence between two probability distributions using gradient descent. To begin, we create a probability distribu... | Python Code:
import os
import warnings
warnings.filterwarnings('ignore')
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (4,4) # Make the figures a bit bigger
plt.style.use('fivethirtyeight')
import numpy as np
from scipy.stats import norm
import tensorflow as tf
import seaborn as sns
sns.set()
import... |
14,349 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
内容索引
相关性分析 --- cov函数、diagonal函数、trace函数、corrcoef函数
多项式拟合 --- polyfit函数、polyval函数、roots函数、polyder函数
计算净额成交量 --- sign函数、piecewise函数
Step1: 1. 股票相关性分析
本例子中, 我们使用2个示例数据集提供收盘价数据,第一家公司是BHP Billit... | Python Code:
%matplotlib inline
import numpy as np
from matplotlib.pyplot import plot
from matplotlib.pyplot import show
Explanation: 内容索引
相关性分析 --- cov函数、diagonal函数、trace函数、corrcoef函数
多项式拟合 --- polyfit函数、polyval函数、roots函数、polyder函数
计算净额成交量 --- sign函数、piecewise函数
End of explanation
# 首先读入两只股票的收盘价,并计算收益率
bhp_cp = np.loa... |
14,350 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: Known coordinates of rectangle
Step2: Define the area inside x and y coordinates
Step3: Define boundaries as CLOSED
Step4: Make a new elevation field for display | Python Code:
from landlab import RasterModelGrid
import numpy as np
from landlab.plot.imshow import imshow_grid_at_node
from matplotlib.pyplot import show
%matplotlib inline
mg = RasterModelGrid((10, 10))
Explanation: <a href="http://landlab.github.io"><img style="float: left" src="../../landlab_header.png"></a>
Settin... |
14,351 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Estimating Counts
Think Bayes, Second Edition
Copyright 2020 Allen B. Downey
License
Step1: In the previous chapter we solved problems that involve estimating proportions.
In the Euro probl... | Python Code:
# If we're running on Colab, install empiricaldist
# https://pypi.org/project/empiricaldist/
import sys
IN_COLAB = 'google.colab' in sys.modules
if IN_COLAB:
!pip install empiricaldist
# Get utils.py
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(... |
14,352 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computer Vision for Image Feature Extraction
Step1: A smaller size allows computation intensive algoritms to run reasonably on a PC
Step2: Part of the canny edge detection algorithm is a g... | Python Code:
%pylab inline
from skimage import io
import matplotlib.pyplot as plt
Explanation: Computer Vision for Image Feature Extraction
End of explanation
image = io.imread('uploads/df947b7905ec613a239a1c4d531e8eab45ccbd6d.jpg')
from skimage.transform import rescale
small = rescale(image, 0.1)
imshow(small)
from sk... |
14,353 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial "Algorithmic Methods for Network Analysis with NetworKit" (Part 1)
Welcome to the hands-on session of our tutorial! This tutorial is based on the user guide of NetworKit, our networ... | Python Code:
from networkit import *
%matplotlib inline
Explanation: Tutorial "Algorithmic Methods for Network Analysis with NetworKit" (Part 1)
Welcome to the hands-on session of our tutorial! This tutorial is based on the user guide of NetworKit, our network analysis software. You will learn in this tutorial how to u... |
14,354 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Experimento de Young con trenes de ondas
Consideraciones iniciales
Step1: Cuando estudiamos el experimento de Young, asumimos que iluminábamos con radiación monocromática. En este caso, la ... | Python Code:
from IPython.display import Image
Image(filename="EsquemaYoung.png")
Explanation: Experimento de Young con trenes de ondas
Consideraciones iniciales
End of explanation
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
plt.style.use('fivethirtyeight')
#import ipywidgets as widg
#from IPy... |
14,355 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predicting house prices using k-nearest neighbors regression
In this notebook, you will implement k-nearest neighbors regression. You will
Step1: Load in house sales data
For this notebook,... | Python Code:
import graphlab
graphlab.product_key.set_product_key("C0C2-04B4-D94B-70F6-8771-86F9-C6E1-E122")
Explanation: Predicting house prices using k-nearest neighbors regression
In this notebook, you will implement k-nearest neighbors regression. You will:
* Find the k-nearest neighbors of a given query input
... |
14,356 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
If, else, Logic, and Laziness
These commands are Pythons bread and butter! You would do well to pay attention to this lecture because 'if statements' are both very common and very very usefu... | Python Code:
# Takes a number as input, prints whether that number is divisible by 4.
text = input("Give me integer... ")
result = "{} is{}divisible by 4".format(text, "" if int(text) % 4 == 0 else " NOT ")
# ^ this is the important bit ... |
14,357 | Given the following text description, write Python code to implement the functionality described.
Description:
Sort the character array based on ASCII % N
This function takes last element as pivot , places the pivot element at its correct position in sorted array , and places all smaller ( smaller than pivot ) to left ... | Python Code:
def partition(arr , low , high , mod ) :
pivot = ord(arr[high ] ) ;
i =(low - 1 ) ;
piv = pivot % mod ;
for j in range(low , high ) :
a = ord(arr[j ] ) % mod ;
if(a <= piv ) :
i += 1 ;
arr[i ] , arr[j ] = arr[j ] , arr[i ]
arr[i + 1 ] , arr[high ] = arr[high ] , arr[i + 1 ]
retur... |
14,358 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook was created by Sergey Tomin for Workshop
Step1: If you want to see injector_lattice.py file you can run following command (lattice file is very large)
Step2: 1. Design optics... | Python Code:
# the output of plotting commands is displayed inline within frontends,
# directly below the code cell that produced it
%matplotlib inline
# this python library provides generic shallow (copy) and deep copy (deepcopy) operations
from copy import deepcopy
# import from Ocelot main modules and functions
fr... |
14,359 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Slicing with pandas, gurobipy.tuplelist, and O(n) slicing
Run a little python script that sets up the performance comparisons.
Step1: The slicing will be over small, medium, and large table... | Python Code:
run prep_for_different_slicings.py
Explanation: Slicing with pandas, gurobipy.tuplelist, and O(n) slicing
Run a little python script that sets up the performance comparisons.
End of explanation
[len(getattr(td, "childTable")) for td in (smallTd, medTd, bigTd)]
Explanation: The slicing will be over small, m... |
14,360 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyGSLIB
Draw
The GSLIb equivalent parameter file is
```
Parameters for DRAW
***
START OF PARAMETERS
Step1: Getting the data ready for work
If the data is... | Python Code:
#general imports
import matplotlib.pyplot as plt
import pygslib
import numpy as np
import pandas as pd
#make the plots inline
%matplotlib inline
Explanation: PyGSLIB
Draw
The GSLIb equivalent parameter file is
```
Parameters for DRAW
***
START OF PARAMETERS:
data/... |
14,361 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training on Cifar 10 Using MXNet and H2O
https
Step1: Step 1
Step2: Let's turn the class label into a factor
Step3: Anytime, especially during training, you can inspect the model in Flow ... | Python Code:
%matplotlib inline
import matplotlib
import scipy.io
import matplotlib.pyplot as plt
import cPickle
import numpy as np
from scipy.misc import imsave
from IPython.display import Image, display, HTML
Explanation: Training on Cifar 10 Using MXNet and H2O
https://www.cs.toronto.edu/~kriz/cifar.html
The CIFAR-1... |
14,362 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create a set of pings from "saved-session" to build a set of core client data.
Step1: Remove any pings without a clientId.
Step2: Sanitize the pings and reduce the set of pings to one ping... | Python Code:
update_channel = "beta"
now = dt.datetime.now()
start = now - dt.timedelta(30)
end = now - dt.timedelta(1)
pings = get_pings(sc, app="Fennec", channel=update_channel,
submission_date=(start.strftime("%Y%m%d"), end.strftime("%Y%m%d")),
build_id=("20100101000000", "9999999... |
14,363 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lasso regression with block updating
Sometimes, it is very useful to update a set of parameters together. For example, variables that are highly correlated are often good to update together.... | Python Code:
%pylab inline
from matplotlib.pylab import *
from pymc3 import *
import numpy as np
d = np.random.normal(size=(3, 30))
d1 = d[0] + 4
d2 = d[1] + 4
yd = .2*d1 +.3*d2 + d[2]
Explanation: Lasso regression with block updating
Sometimes, it is very useful to update a set of parameters together. For example, v... |
14,364 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Optimization Exercise 1
Imports
Step1: Hat potential
The following potential is often used in Physics and other fields to describe symmetry breaking and is often known as the "hat potential... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
Explanation: Optimization Exercise 1
Imports
End of explanation
def hat(x,a,b):
return -a*x**2+b*x**4
assert hat(0.0, 1.0, 1.0)==0.0
assert hat(0.0, 1.0, 1.0)==0.0
assert hat(1.0, 10.0, 1.0)==-9.0
Explana... |
14,365 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LDA and NMF on New Job-Skill Matrix
Step1: LDA and NMF
Global arguments
Step2: Trainning LDA
Step3: Saved results of trainning
Step4: Evaluation of LDA on test set by perplexity
Step5: ... | Python Code:
import ja_helpers as ja_helpers; from ja_helpers import *
HOME_DIR = 'd:/larc_projects/job_analytics/'; DATA_DIR = HOME_DIR + 'data/clean/'
RES_DIR = HOME_DIR + 'results/skill_cluster/new/'
skill_df = pd.read_csv(DATA_DIR + 'skill_index.csv')
doc_skill = mmread(DATA_DIR + 'doc_skill.mtx')
skills = skill_df... |
14,366 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 12
Modeling and Simulation in Python
Copyright 2021 Allen Downey
License
Step4: Code
Here's the code from the previous notebook that we'll need.
Step5: In the previous chapter I pr... | Python Code:
# install Pint if necessary
try:
import pint
except ImportError:
!pip install pint
# download modsim.py if necessary
from os.path import exists
filename = 'modsim.py'
if not exists(filename):
from urllib.request import urlretrieve
url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/... |
14,367 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
News Categorization using Multinomial Naive Bayes
The objective of this site is to show how to use Multinomial Naive Bayes method to classify news according to some predefined classes.
The ... | Python Code:
import pandas as pd
Explanation: News Categorization using Multinomial Naive Bayes
The objective of this site is to show how to use Multinomial Naive Bayes method to classify news according to some predefined classes.
The News Aggregator Data Set comes from the UCI Machine Learning Repository.
Lichman, M... |
14,368 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Multiplying Numpy Arrays
Step2: LAB CHALLENGE | Python Code:
import numpy as np
one_dimensional = np.array([1,1,1,2,3,3,3,3,3])
one_dimensional
one_dimensional.shape # not yet rows & columns
one_dimensional.reshape((9,-1)) # let numpy figure out how many columns
one_dimensional # still the same
one_dimensional.ndim
two_dimensional = one_dimensional.reshape(1,9) #... |
14,369 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import important modules and declare important directories
Step1: This is a function that we'll use later to plot the results of a linear SVM classifier
Step2: Load in the sample JSON file... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
import json
import pandas as pd
import csv
import os
import re
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import svm
from sklearn.linear_model import SGDClassifie... |
14,370 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Index - Back - Next
Output widgets
Step1: The Output widget can capture and display stdout, stderr and rich output generated by IPython. You can also append output directly to an output wid... | Python Code:
import ipywidgets as widgets
Explanation: Index - Back - Next
Output widgets: leveraging Jupyter's display system
End of explanation
out = widgets.Output(layout={'border': '1px solid black'})
out
Explanation: The Output widget can capture and display stdout, stderr and rich output generated by IPython. You... |
14,371 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating MNE's data structures from scratch
MNE provides mechanisms for creating various core objects directly from
NumPy arrays.
Step1: Creating
Step2: You can also supply more extensive... | Python Code:
import mne
import numpy as np
Explanation: Creating MNE's data structures from scratch
MNE provides mechanisms for creating various core objects directly from
NumPy arrays.
End of explanation
# Create some dummy metadata
n_channels = 32
sampling_rate = 200
info = mne.create_info(n_channels, sampling_rate)
... |
14,372 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GLM
Step1: Load and Prepare Data
We'll use the Hogg 2010 data available at https
Step2: Observe
Step3: Sample
Step4: View Traces
NOTE
Step5: NOTE
Step6: Sample
Step7: View Traces
Ste... | Python Code:
%matplotlib inline
%qtconsole --colors=linux
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import optimize
import pymc3 as pm
import theano as thno
import theano.tensor as T
# configure some basic o... |
14,373 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load an AIA image
Step1: I then go to JPL Horizons (https
Step2: This is assuming the target is at 1 ly away (very far!) | Python Code:
aiamap=sunpy.map.Map('/Users/kkozarev/sunpy/data/sample_data/AIA20110319_105400_0171.fits')
Explanation: Load an AIA image
End of explanation
sunc_1au=SkyCoord(ra='23h53m53.47',dec='-00d39m44.3s', distance=1.*u.au,frame='icrs').transform_to(aiamap.coordinate_frame)
Explanation: I then go to JPL Horizons (h... |
14,374 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
APS - new snow
Imports
Step1: Parameters, categories and scores
Main control factors
Step2: Weighting
Weights are added if they are independent of the value of the core factor or multiplie... | Python Code:
# -*- coding: utf-8 -*-
%matplotlib inline
from __future__ import print_function
import pylab as plt
import datetime
import numpy as np
plt.rcParams['figure.figsize'] = (14, 6)
Explanation: APS - new snow
Imports
End of explanation
# New snow amount last 24 h 0-60 cm [10 cm intervals]
new_snow_24h_cat = np... |
14,375 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook provides a couple examples for how to convert long $\LaTeX$ expression into sympy format, via Mathematica.
EMRI terms
The first step is to select the equation you want from the... | Python Code:
%%bash
perl -nlw \
-e 's/\\begin\{eqnarray\*\}//g; s/\\end\{eqnarray\*\}//g; ' `# remove environment for Mathematica` \
-e 's/\{dE\\over dt\}=&&\\left\(\{dE\\over dt\}\\right\)_N//;' `# remove definition statement` \
-e 's/\{\\rm ln\}/\\ln/g;' `# Correct bad notation for logarithm` \
-e 's/... |
14,376 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 10
Python Basic, Lesson 4, v1.0.1, 2016.12 by David.Yi
Python Basic, Lesson 4, v1.0.2, 2017.03 modified by Yimeng.Zhang
v1.1, 2020.4 5,edit by David Yi
本次内容要点
函数不同参数形式
匿名函数
思考一下... | Python Code:
# 函数默认参数
def cal_0(money, rate=0.1):
return money + money * rate
print(cal_0(100))
print(cal_0(100,0.2))
print(cal_0(rate=0.3,money=100))
# 函数默认参数
def cal_1(money, bonus=1000, month=12,a=1, b=2):
i = money * month + bonus
return i
print(cal_1(5000))
print(cal_1(5000, 2000))
print(cal_1(5000, ... |
14,377 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 6
Step1: Setup an identical instance of NPTFit to Example 5
Firstly we initialize an instance of nptfit identical to that used in the previous example.
Step2: Evaluate the Likeliho... | Python Code:
# Import relevant modules
%matplotlib inline
%load_ext autoreload
%autoreload 2
import numpy as np
import healpy as hp
import matplotlib.pyplot as plt
from NPTFit import nptfit # module for performing scan
from NPTFit import create_mask as cm # module for creating the mask
from NPTFit import psf_correction... |
14,378 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Collate outside the notebook
Python files, input files, output file
Set up a PyCharm project
Create a Python file
Run a script
In PyCharm
In the terminal
Input files
Output file
Exercise
Her... | Python Code:
from collatex import *
collation = Collation()
collation.add_plain_witness( "A", "The quick brown fox jumped over the lazy dog.")
collation.add_plain_witness( "B", "The brown fox jumped over the dog." )
collation.add_plain_witness( "C", "The bad fox jumped over the lazy dog.")
table = collate(collation)
pr... |
14,379 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Remote Service Control Manager Handle
Metadata
| Metadata | Value |
|
Step1: Download & Process Security Dataset
Step2: Analytic I
Detects non-system users failing to get a hand... | Python Code:
from openhunt.mordorutils import *
spark = get_spark()
Explanation: Remote Service Control Manager Handle
Metadata
| Metadata | Value |
|:------------------|:---|
| collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] |
| creation date | 2019/08/26 |
| modification date | 2020/09/20 |
| play... |
14,380 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 16 - Metric-Predicted Variable on One or Two Groups
16.1 - Estimating the mean and standard deviation of a normal distribution
16.2 - Outliers and robust estimation
Step1: Data
Step... | Python Code:
import pandas as pd
import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
from scipy.stats import norm, t
from IPython.display import Image
%matplotlib inline
plt.style.use('seaborn-white')
color... |
14,381 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In Class Exercise
Step1: In Class Exercise
Returning to the programme you just wrote to calculate the integral of $f(x) = \sin^2 [\frac{1}{x(2-x)}]$, please now add an estimate of the accur... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
#This just needed for the Notebook to show plots inline.
%matplotlib inline
#Define the function
def f(x):
fx = (np.sin(1/(x*(2-x))))**2
return fx
#Integrate the function from x=0-2
#Note that you need to know the maximum value of the function
#o... |
14,382 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This notebook is a very basic and simple introductory primer to the method of ensembling models, in particular the variant of ensembling known as Stacking. In a nutshell stackin... | Python Code:
# Load in our libraries
import pandas as pd
import numpy as np
import re
import sklearn
import xgboost as xgb
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
import plotly.offline as py
py.init_notebook_mode(connected=True)
import plotly.graph_objs as go
import plotly.tools as tls
... |
14,383 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This notebook gives examples for processing spins monitor data.
Logging data is stored in monitors that are defined within the optimization plan. Every iteration of the optimiza... | Python Code:
## Import libraries necessary for monitor data processing. ##
from matplotlib import pyplot as plt
import numpy as np
import os
import pandas as pd
import pickle
from spins.invdes.problem_graph import log_tools
## Define filenames. ##
# `save_folder` is the full path to the directory containing the Pickle ... |
14,384 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Esta será una microentrada para presentar una extensión para el notebook que estoy usando en un curso interno que estoy dando en mi empresa.
Si a alguno más os puede valer para mostrar cosas... | Python Code:
%load_ext tutormagic
Explanation: Esta será una microentrada para presentar una extensión para el notebook que estoy usando en un curso interno que estoy dando en mi empresa.
Si a alguno más os puede valer para mostrar cosas básicas de Python (2 y 3, además de Java y Javascript) para muy principiantes me a... |
14,385 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Today, we'll sample a spatially-varying coefficient model, like that discussed in Gelfand (2003). These models are of the form
Step1: This reflects a gradient from left to right, and from b... | Python Code:
side = np.arange(0,10,1)
grid = np.tile(side, 10)
beta1 = grid.reshape(10,10)
beta2 = np.fliplr(beta1).T
fig, ax = plt.subplots(1,2, figsize=(12*1.6, 6))
sns.heatmap(beta1, ax=ax[0])
sns.heatmap(beta2, ax=ax[1])
plt.show()
Explanation: Today, we'll sample a spatially-varying coefficient model, like that di... |
14,386 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Procrustes Analysis
Step1: PCA
Step2: Solving b vector
$$b = \Phi^T \left(x - \bar{x}\right)$$ | Python Code:
import pandas
df = pandas.read_csv('muct76-opencv.csv', header=0, usecols=np.arange(2,154), dtype=float)
df.head()
X = df.iloc[:, ::2].values
Y = df.iloc[:, 1::2].values
d = np.hstack((X,Y))
d.shape
import sys
threshold = 1.0e-8
def center(vec):
pivot = int(vec.shape[0]/2)
meanx = np.mean(vec[:pivo... |
14,387 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bokeh Visualization Demo
Recreating Han's Rosling's "The Health and Wealth of Nations"
This notebook is intended to illustrate the some of the utilities of the Python Bokeh visualization lib... | Python Code:
import numpy as np
import pandas as pd
from bokeh.embed import file_html
from bokeh.io import output_notebook, show
from bokeh.layouts import layout
from bokeh.models import (
ColumnDataSource, Plot, Circle, Range1d, LinearAxis, HoverTool,
Text, SingleIntervalTicker, Slider, CustomJS)
from bokeh.p... |
14,388 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implement Logistic Classification for classifying tweets / text
Given a tweet we will have to decide whether a tweet is positive and negative
Step1: Load and Analyse the dataset
Step2: Pro... | Python Code:
import numpy as np
import pandas as pd
import nltk
from nltk.corpus import twitter_samples
nltk.download('twitter_samples')
nltk.download('stopwords')
Explanation: Implement Logistic Classification for classifying tweets / text
Given a tweet we will have to decide whether a tweet is positive and negative
E... |
14,389 | 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... |
14,390 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Storing and loading questions as a serialized object.
As questinos.csv is not easy to use itself, it might be healpful to make the csv file into a serialized object. In this case, we can use... | Python Code:
import csv
import gzip
import cPickle as pickle
from collections import defaultdict
import yaml
question_reader = csv.reader(open("../data/questions.csv"))
question_header = ["answer", "group", "category", "question", "pos_token"]
questions = defaultdict(dict)
for row in question_reader:
question = {}
... |
14,391 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NDArray Tutorial
In MXNet, NDArray is the core datastructure for all mathematical computations.
An NDArray represents a multidimensional, fixed-size homogenous array.
If you're familiar with... | Python Code:
import mxnet as mx
# create a 1-dimensional array with a python list
a = mx.nd.array([1,2,3])
# create a 2-dimensional array with a nested python list
b = mx.nd.array([[1,2,3], [2,3,4]])
{'a.shape':a.shape, 'b.shape':b.shape}
Explanation: NDArray Tutorial
In MXNet, NDArray is the core datastructure for al... |
14,392 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: \title{myHDL Combinational Logic Elements
Step2: Demultiplexers
\begin{definition}\label{def
Step4: myHDL Module
Step6: myHDL Testing
Step7: Verilog Conversion
Step9: \begin{figu... | Python Code:
#This notebook also uses the `(some) LaTeX environments for Jupyter`
#https://github.com/ProfFan/latex_envs wich is part of the
#jupyter_contrib_nbextensions package
from myhdl import *
from myhdlpeek import Peeker
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
fr... |
14,393 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Imputation
Step1: Create data frame
Step2: Add some missing values
Step3: Confirm the presence of null values
Step4: Create categorical variables
Step5: Create dummy variables
Step6: I... | Python Code:
import pandas as pd
import numpy as np
import statsmodels
from statsmodels.imputation import mice
import random
random.seed(10)
Explanation: Imputation
End of explanation
df = pd.read_csv("http://goo.gl/19NKXV")
df.head()
original = df.copy()
original.describe().loc['count',:]
Explanation: Create data fram... |
14,394 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computing various MNE solutions
This example shows example fixed- and free-orientation source localizations
produced by the minimum-norm variants implemented in MNE-Python
Step1: Fixed orie... | Python Code:
# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
print(__doc__)
data_path = sample.data_path()
subjects_dir = data_path / 'subjects'
# Read data (just MEG here for speed, th... |
14,395 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Method 2
Step2: Method 3 | Python Code:
# Create a list of casualties from battles
battleDeaths = [482, 93, 392, 920, 813, 199, 374, 237, 244]
# Create a function that updates all battle deaths by adding 100
def updated(x): return x + 100
# Create a list that applies updated() to all elements of battleDeaths
list(map(updated, battleDeaths))
Expl... |
14,396 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Optimierung des fachlichen Schnitts
Vorgehen
Subdomains sind bereits anhand von Namensschemata gebildet
Abhängigkeiten zwischen Subdomains werden über die Abhängigkeitsbeziehung der z... | Python Code:
import py2neo
import pandas as pd
graph= py2neo.Graph()
query=
MATCH
(s1:Subdomain)<-[:BELONGS_TO]-
(type:Type)-[r:DEPENDS_ON*0..1]->
(dependency:Type)-[:BELONGS_TO]->(s2:Subdomain)
RETURN s1.name as from, s2.name as to, COUNT(r) as x_number
result = graph.run(query).data()
df = pd.DataFrame(r... |
14,397 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Autoencoder
Sticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. Again, loading modules and the data.
Step1: Network Archit... | Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
img = mnist.train.images[2]
plt.imshow(img.reshape((28, 28)), cmap='Greys_r')
Explanati... |
14,398 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I'm using tensorflow 2.10.0. | Problem:
import tensorflow as tf
import numpy as np
np.random.seed(10)
a = tf.constant(np.random.rand(50, 100, 512))
def g(a):
return tf.expand_dims(a, 2)
result = g(a.__copy__()) |
14,399 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Symbolic derivation qubit-cavity Hamiltonian
<style>
p {
font-family
Step1: The Jaynes-Cummings model
The Jaynes-Cummings model is one of the most elementary quantum mechanical models l... | Python Code:
from sympy import *
init_printing()
from sympsi import *
from sympsi.boson import *
from sympsi.pauli import *
Explanation: Symbolic derivation qubit-cavity Hamiltonian
<style>
p {
font-family: "Liberation Serif", serif;
font-size: 12pt;
}
</style>
Based on: J. R. Johansson (robert@riken.jp), http:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.