Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
12,900 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced Sounding
Plot a sounding using MetPy with more advanced features.
Beyond just plotting data, this uses calculations from metpy.calc to find the lifted
condensation level (LCL) and t... | Python Code:
import matplotlib.pyplot as plt
import pandas as pd
import metpy.calc as mpcalc
from metpy.cbook import get_test_data
from metpy.plots import add_metpy_logo, SkewT
from metpy.units import units
Explanation: Advanced Sounding
Plot a sounding using MetPy with more advanced features.
Beyond just plotting data... |
12,901 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Explorando as despesas da cidade de São Paulo
Um tutorial de primeiros passos para acessar a execução orçamentária do município usando Python e a biblioteca de análise de dados Pandas *
Pass... | Python Code:
import pandas as pd
import requests
import json
import numpy as np
TOKEN = '198f959a5f39a1c441c7c863423264'
base_url = "https://gatewayapi.prodam.sp.gov.br:443/financas/orcamento/sof/v2.1.0"
headers={'Authorization' : str('Bearer ' + TOKEN)}
Explanation: Explorando as despesas da cidade de São Paulo
Um tut... |
12,902 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time-frequency beamforming using LCMV
Compute LCMV source power in a grid of time-frequency windows and display
results.
The original reference is
Step1: Read raw data, preload to allow fil... | Python Code:
# Author: Roman Goj <roman.goj@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne import compute_covariance
from mne.datasets import sample
from mne.event import make_fixed_length_events
from mne.beamformer import tf_lcmv
from mne.viz import plot_source_spectrogram
print(__doc__)
data_path = sample... |
12,903 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center>
<h1>Simple Py-ART Usage </h1>
</center>
Step1: Data available by FigShare Here
Step2: Take a read of the BAMS article by Zirnic and Ryzhkov | Python Code:
#first we do some imports and check the version of Py-ART for consistency
import pyart
from matplotlib import pyplot as plt
import numpy as np
%matplotlib inline
print pyart.__version__
#you can grab the data here: http://figshare.com/articles/Data_for_AMS_Short_Course_on_Open_Source_Radar_Software/1537461... |
12,904 | 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... |
12,905 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Thanksgiving Survey Analysis
Every year Thanksgiving is celebrated in United States all around the country. Some people travel to their hometown while others celebrate with friends. In this ... | Python Code:
# this line is required to see visualizations inline for Jupyter notebook
%matplotlib inline
# importing modules that we need for analysis
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# read the data from file and print out first few rows and columns
thanksgiving = pd.read_csv("th... |
12,906 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Manipulating pages
pikepdf presents the pages in a PDF through the Pdf.pages property, which
follows the list protocol. As such page numbers begin at 0.
Let's look at a simple PDF that conta... | Python Code:
from pikepdf import Pdf
pdf = Pdf.open('../../tests/resources/fourpages.pdf')
Explanation: Manipulating pages
pikepdf presents the pages in a PDF through the Pdf.pages property, which
follows the list protocol. As such page numbers begin at 0.
Let's look at a simple PDF that contains four pages.
End of exp... |
12,907 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook is show how to use Q2-DSFDR in command line interface
convert feature table to qiime2 qza artifact
Step1: select interested category to compare using DS-FDR
Step2: output the... | Python Code:
!qiime tools import \
--input-path ../data/deblur-feature-table.biom \
--type 'FeatureTable[Frequency]' \
--source-format BIOMV210Format \
--output-path ../data/dblr_haddad.qza
Explanation: This notebook is show how to use Q2-DSFDR in command line interface
convert feature table to qiime2 qza artifact
End ... |
12,908 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Attitude Control System (ACS)
This assignment is broken up into the following sections
Step2: Solar Torques
Step4: Magnetic Torques
Step5: Since both the magnetic torques are less than th... | Python Code:
import math
q = 0.6
P_mars = 2.0 * 10 ** -6
A_left = 7.6 # cm^2
L_left = 131.2 # cm
A_right = 6.3 # cm^2
L_right = 126.1 # cm
Explanation: Attitude Control System (ACS)
This assignment is broken up into the following sections:
Mission Attitude Control modes
Selection of the ACS system-type
Minimum Th... |
12,909 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolution
As the name implies, convolution operations are an important component of convolutional neural networks. The ability for a CNN to accurately match diverse patterns can be attribu... | Python Code:
# setup-only-ignore
import tensorflow as tf
import numpy as np
# setup-only-ignore
sess = tf.InteractiveSession()
input_batch = tf.constant([
[ # First Input
[[0.0], [1.0]],
[[2.0], [3.0]]
],
[ # Second Input
[[2.0], [4.0]],
[[6.0], ... |
12,910 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Week 5
Step1: Load in house sales data
Dataset is from house sales in King County, the region where the city of Seattle, WA is located.
Step2: If we want to do any "feature engi... | Python Code:
import graphlab
Explanation: Regression Week 5: LASSO (coordinate descent)
In this notebook, you will implement your very own LASSO solver via coordinate descent. You will:
* Write a function to normalize features
* Implement coordinate descent for LASSO
* Explore effects of L1 penalty
Fire up graphlab cre... |
12,911 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
lingam.utils
In this example, we need to import numpy, pandas, and lingam.
Step1: We define utility functions to draw the directed acyclic graph.
Step2: print_causal_directions
We create t... | Python Code:
import numpy as np
import pandas as pd
import graphviz
import lingam
from lingam.utils import make_dot
np.set_printoptions(precision=3, suppress=True)
np.random.seed(0)
Explanation: lingam.utils
In this example, we need to import numpy, pandas, and lingam.
End of explanation
def make_prior_knowledge_graph(... |
12,912 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
How can I know the (row, column) index of the minimum(might not be single) of a numpy array/matrix? | Problem:
import numpy as np
a = np.array([[1, 0], [0, 2]])
result = np.argwhere(a == np.min(a)) |
12,913 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demonstration
The following demonstration includes basic and intermediate uses of the LamAna Project library. It is intended to exhaustively reference all API features, therefore some advan... | Python Code:
#------------------------------------------------------------------------------
import pandas as pd
import lamana as la
#import LamAna as la
%matplotlib inline
#%matplotlib nbagg
# PARAMETERS ------------------------------------------------------------------
# Build dicts of geometric and material paramete... |
12,914 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step2: Environment
Step3: Try out Environment
Step4: Train model
random has lower total reward than version with dense customers
total cost when travelling all paths (back... | Python Code:
!pip install git+https://github.com/openai/baselines >/dev/null
!pip install gym >/dev/null
Explanation: <a href="https://colab.research.google.com/github/DJCordhose/ai/blob/master/notebooks/rl/berater-v7.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open ... |
12,915 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color = blue>Primer examen parcial </font>
<font color= #8A0829> Simulación matemática.</font>
<Strong> Lázaro Alonso </Strong>
<Strong> Año </Strong>
Step1: Ahora si gráficamos al pé... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def theta_t(theta_0, theta_0_dot, g, l, t):
omega_0 = np.sqrt(g/l)
return theta_0 * np.cos(omega_0 * t) + theta_0_dot * np.sin(omega_0 * t)/omega_0
Explanation: <font color = blue>Primer examen parcial </font>
<font color= #8A082... |
12,916 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook will explore the Ridge property data as modeled by FVS and the Ecotrust Growth-Yield-Batch system. Also serves as a demonstration of pandas and associated python libraries.
Fir... | Python Code:
%matplotlib inline
from matplotlib.pylab import plt
import pandas as pd
from sqlalchemy import create_engine
from matplotlib import cm
import seaborn as sns
Explanation: This notebook will explore the Ridge property data as modeled by FVS and the Ecotrust Growth-Yield-Batch system. Also serves as a demonst... |
12,917 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: <a href="https
Step3: Step by Step Code Order
#1. How to find the order of differencing (d) in ARIMA model
p is the order of the AR term
q is the order of the MA term
d is the number... | Python Code:
#sign:max: MAXBOX8: 03/02/2021 18:34:41
# optimal moving average OMA for market index signals ARIMA study- Max Kleiner
# v2 shell argument forecast days - 4 lines compare - ^GDAXI for DAX
# pip install pandas-datareader
# C:\maXbox\mX46210\DataScience\princeton\AB_NYC_2019.csv AB_NYC_2019.csv
#https://m... |
12,918 | 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: Introducing Principal Component Analysis
Principal component analysis is a fast and flexible unsupervised method for di... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
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 Vande... |
12,919 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Part 1
Step2: pandas is an open source, BSD-licensed library providing high-performance,
easy-to-use data structures and data analysis tools for the Python programming language.
htt... | Python Code:
----------------------------------------------------------------------
Filename : 01_basic_data_structs.py
Date : 12th Dec, 2013
Author : Jaidev Deshpande
Purpose : To get started with basic data structures in Pandas
Libraries: Pandas 0.12 and its dependencies
---------------------------------------... |
12,920 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Saving your iPython notebook
File -> Save and Checkpoint
Can change the name also in that menu. But also possible via clicking the name above.
Talk about command mode and edit mode of cells.... | Python Code:
10 / 3 # We provide integers
# What will the output be?
Explanation: Saving your iPython notebook
File -> Save and Checkpoint
Can change the name also in that menu. But also possible via clicking the name above.
Talk about command mode and edit mode of cells. And the help window.
Data Types: Integers vs.... |
12,921 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Iris introduction course
4. Joining Cubes Together
Learning outcome
Step1: 4.1 Merge<a id='merge'></a>
When Iris loads data it tries to reduce the number of cubes returned by collecting tog... | Python Code:
import iris
import numpy as np
Explanation: Iris introduction course
4. Joining Cubes Together
Learning outcome: by the end of this section, you will be able to apply Iris functionality to combine multiple Iris cubes into a new larger cube.
Duration: 30 minutes
Overview:<br>
4.1 Merge<br>
4.2 Concatenate<b... |
12,922 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step4: The inspect module provides functions for learning about live objects, classes, instances, and methods. The functions in this module can be used to retrieve the original source code f... | Python Code:
# %load example.py
def module_level_function(arg1, arg2='default', *args, **kwargs):
This function is declared in the module.
local_variable = arg1 * 2
return local_variable
class A(object):
The A class.
def __init__(self, name):
self.name = name
def get_name(self):
... |
12,923 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
facebook-scraper
This is a short introduction to using the scraper to fully scrape a public FB page
Requirements
You need to register yourself as a developer on Facebook
You create an App on... | Python Code:
import fb_scraper.prodcons
APP_ID = ''
APP_ID_SECRET = ''
ACCESS_TOKEN = ''
Explanation: facebook-scraper
This is a short introduction to using the scraper to fully scrape a public FB page
Requirements
You need to register yourself as a developer on Facebook
You create an App on your Facebook developer pag... |
12,924 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
For high dpi displays.
Step1: 0. General note
This notebook shows an example of how to conduct equation of state fitting for the pressure-volume-temperature data using pytheos.
Advantage of... | Python Code:
%config InlineBackend.figure_format = 'retina'
Explanation: For high dpi displays.
End of explanation
import numpy as np
import uncertainties as uct
import pandas as pd
from uncertainties import unumpy as unp
import matplotlib.pyplot as plt
import pytheos as eos
Explanation: 0. General note
This notebook s... |
12,925 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
Brief Overview
Is a training set something immutable and unexpandable? Active learning relates to situations where the answer is no. The training set size can be increased, but,... | Python Code:
import math
from copy import copy
from typing import List
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
from sklearn.base import BaseEstimator
from sklearn.metrics import accuracy_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.calibratio... |
12,926 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: Topographic grids
For this tutorial we will consider one topographic surface. Here it is plotted in three dimensions.
Step2: Initalizing and running the FlowAccumulato... | Python Code:
%matplotlib inline
# import plotting tools
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib as mpl
# import numpy
import numpy as np
# import necessary landlab components
from ... |
12,927 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An MNIST example for tensorflow-cloud on Google Colab
This colab shows an example for using Keras to build a simple ConvNet model for MNIST, and utilize tensorflow-cloud to train the model ... | Python Code:
import os
import sys
try:
import tensorflow_cloud as tfc
except:
os.system('pip install -U --quiet tensorflow-cloud')
import tensorflow_cloud as tfc
import tensorflow_datasets as tfds
import tensorflow as tf
print(tf.__version__)
Explanation: An MNIST example for tensorflow-cloud on Google Colab
Thi... |
12,928 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ABC calibration of $I_\text{CaL}$ in standardised model to unified dataset.
Step1: Initial set-up
Load experiments used for unified dataset calibration
Step2: Plot steady-state and tau fun... | Python Code:
import os, tempfile
import logging
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from ionchannelABC import theoretical_population_size
from ionchannelABC import IonChannelDistance, EfficientMultivariateNormalTransition, IonChannelAcceptor
from ionchannelA... |
12,929 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Cesta ke kořenům</h1>
<p>Moto
Step1: <p>Vykreslení dat do grafu zajistí <t>plot(x,y)</t>
Step2: <p>Fakt je tam... jen není vidět.</p>
Step3: <p>Žádáme-li víc bodů, musíme je uzavřít d... | Python Code:
import matplotlib.pyplot as plt # plt je vseobecne uzivana zkratka, grafy si kreslime primo do notebookove stranky:
%matplotlib inline
Explanation: <h1>Cesta ke kořenům</h1>
<p>Moto: panda v koruně pevného stromu</p>
<ul>
<li>Grafy bodů</li>
<li>Seznamy</li>
<li>Vektory v numpy</li>
<li>Grafy funkcí</li... |
12,930 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
groupby
With groupby, you can group data in a DataFrame and apply calculations on those groups in various ways.
This Cheatbook (Cheatsheet + Notebook) introduces you to the core functionalit... | Python Code:
import pandas as pd
df = pd.DataFrame({
"file" : ['hello.java', 'tutorial.md', 'controller.java', "build.sh", "deploy.sh"],
"dir" : ["src", "docs", "src", "src", "src"],
"bytes" : [54, 124, 36, 78, 62]
})
df
Explanation: groupby
With groupby, you can group data in a DataFrame and apply calc... |
12,931 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Goal
A basic, full run of the SIPSim pipeline with the whole bacterial genome dataset to see
Step1: Init
Step2: Creating a community file
2 communities
control vs treatment
Step3: Plottin... | Python Code:
workDir = '/home/nick/notebook/SIPSim/dev/bac_genome1147/Meselson_diff/validation/'
genomeDir = '/var/seq_data/ncbi_db/genome/Jan2016/bac_complete_spec-rep1_rn/'
R_dir = '/home/nick/notebook/SIPSim/lib/R/'
#figureDir = '/home/nick/notebook/SIPSim/figures/bac_genome_n1147/'
bandwidth = 0.8
DBL_scaling = 0.5... |
12,932 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Probabilidades
La matemática es la lógica de la certeza mientras que la probabilidad es la lógica de la incerteza, dice Joseph K. Blitzstein condensando el pensamiento de cientos de personas... | Python Code:
distri = stats.randint(1, 7) # límite inferior, límite superior + 1
x = np.arange(0, 8)
x_pmf = distri.pmf(x) # la pmf evaluada para todos los "x"
media, varianza = distri.stats(moments='mv')
plt.vlines(x, 0, x_pmf, colors='C0', lw=5,
label='$\mu$ = {:3.1f}\n$\sigma$ = {:3.1f}'.format(float(... |
12,933 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logic functions
Step1: Truth value testing
Q1. Let x be an arbitrary array. Return True if none of the elements of x is zero. Remind that 0 evaluates to False in python.
Step2: Q2. Let x b... | Python Code:
import numpy as np
np.__version__
Explanation: Logic functions
End of explanation
x = np.array([1,2,3])
#
x = np.array([1,0,3])
#
Explanation: Truth value testing
Q1. Let x be an arbitrary array. Return True if none of the elements of x is zero. Remind that 0 evaluates to False in python.
End of explanatio... |
12,934 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
My tutorial
This section describes a tool or operation that is desirable for someone. The title above should describe what is happening, and this paragraph explains in what situation the too... | Python Code:
from scipy import misc as scm
import os.path as op
import matplotlib.pyplot as plt
% matplotlib inline
datadir = '/tmp/113_1/'
im = scm.imread(op.join(datadir,'0090.png'))
plt.imshow(im, cmap='gray')
plt.show()
Explanation: My tutorial
This section describes a tool or operation that is desirable for someon... |
12,935 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Think Bayes
This notebook presents example code and exercise solutions for Think Bayes.
Copyright 2016 Allen B. Downey
MIT License
Step2: Here's a problem from Joyce, "How probabilities ref... | Python Code:
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import classes from thinkbayes2
from thinkbayes2 import Pmf, Suite
import thinkplot as tplt
... |
12,936 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SINGA Model Classes
<img src="http
Step1: Common layers
Step2: Dense Layer
Step3: Convolution Layer
Step4: Pooling Layer
Step5: Branch layers
Step6: Metric and Loss
Step7: Optimizer
S... | Python Code:
from singa import tensor, device, layer
#help(layer.Layer)
layer.engine='singacpp'
Explanation: SINGA Model Classes
<img src="http://singa.apache.org/en/_static/images/singav1-sw.png" width="500px"/>
Layer
Typically, the life cycle of a layer instance includes:
1. construct layer without input_sample_shap... |
12,937 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Section 7.3
Step1: Load data
Step3: Final data format
Step4: How long did this take to run? | Python Code:
user_agent_email = "REPLACE THIS WITH YOUR EMAIL plz kthxbye"
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import glob
import pickle
import numpy as np
import mwapi
%matplotlib inline
import datetime
start = datetime.datetime.now()
Explanation: Section 7.3: S... |
12,938 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sparse Linear Inverse with EM Learning
In the sparse linear inverse demo, we saw how to set up a solve a simple sparse linear inverse problem using the vamp method in the vampyre package. S... | Python Code:
# Import vampyre
import os
import sys
vp_path = os.path.abspath('../../')
if not vp_path in sys.path:
sys.path.append(vp_path)
import vampyre as vp
# Import the other packages
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Sparse Linear Inverse with... |
12,939 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Naive Bayes
by Chiyuan Zhang
This notebook illustrates <a href="http
Step1: A helper function is defined to generate samples
Step2: Then we train the GNB model with SHOGUN
Step3: Run clas... | Python Code:
%matplotlib inline
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
import numpy as np
import pylab as pl
np.random.seed(0)
n_train = 300
models = [{'mu': [8, 0], 'sigma':
np.array([[np.cos(-np.pi/4),-np.sin(-np.pi/4)],
[np.sin(-np.pi/4), np.cos(-np.pi... |
12,940 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Below path is a shared directory, swap to own
Step1: Replication of 'csv_to_hdf5.py'
Original repo used some bizarre tuple method of reading in data to save in a hdf5 file using fuel. The f... | Python Code:
data_path = "/data/datasets/taxi/"
Explanation: Below path is a shared directory, swap to own
End of explanation
meta = pd.read_csv(data_path+'metaData_taxistandsID_name_GPSlocation.csv', header=0)
meta.head()
train = pd.read_csv(data_path+'train/train.csv', header=0)
train.head()
train['ORIGIN_CALL'] = pd... |
12,941 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Twitter Data Analysis
Predict inter-tweet times for a single user
An implementation of the "Question", "Model", "Validate" process for data science.
Step1: Load Data
Step2: Feature Selecti... | Python Code:
%pylab inline
# Import libraries
from __future__ import print_function
import scipy
import numpy as np
import pandas as pd
import matplotlib.pyplot as pyplt
import seaborn as sns
pyplt.rcParams['figure.figsize'] = (4, 3)
import datetime
from datetime import datetime
from datetime import timedelta
from date... |
12,942 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Sklearn Principle Component Analysis - PCA Example
| Python Code::
from sklearn.decomposition import PCA
# Step 1: Initalise and fit PCA for 4 dimensions
pca = PCA(n_components=4)
pca.fit(X_train)
# Step 2: Transform data
X_train = pd.DataFrame(pca.transform(X_train))
X_test = pd.DataFrame(pca.transform(X_test))
# Step 3: Print out explained variance ratio
print(pca.expl... |
12,943 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Files
Python uses file objects to interact with external files on your computer. These file objects can be any sort of file you have on your computer, whether it be an audio file, a text fil... | Python Code:
%%writefile test.txt
Hello, this is a quick test file
Explanation: Files
Python uses file objects to interact with external files on your computer. These file objects can be any sort of file you have on your computer, whether it be an audio file, a text file, emails, Excel documents, etc. Note: You will pr... |
12,944 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Extending Development Patterns with Tails
Getting Started
This tutorial focuses on extending the developent patterns beyond the tail.
Note that a lot of the examples shown here might not be... | Python Code:
# Black linter, optional
%load_ext lab_black
import pandas as pd
import numpy as np
import chainladder as cl
import os
print("pandas: " + pd.__version__)
print("numpy: " + np.__version__)
print("chainladder: " + cl.__version__)
Explanation: Extending Development Patterns with Tails
Getting Started
This tut... |
12,945 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Beyond Least Squares
Measuring the size of the error with different norms
We define the error as
\begin{eqnarray}
e = y - Aw
\end{eqnarray}
Least Squares measures the Euclidian norm of the ... | Python Code:
# A toy data set with outliers
x = np.matrix('[0,1,2,3,4,5]').T
y = np.matrix('[2,4,6,-1,10,12]').T
# Degree of the fitted polynomial
degree = 1
N = len(x)
A = np.hstack((np.power(x,i) for i in range(degree+1)))
xx = np.matrix(np.arange(-1,6,0.1)).T
A2 = np.hstack((np.power(xx,i) for i in range(degree+1)))... |
12,946 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Uisng Random Forest Regression
| Python Code::
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor()
model.fit(X_train, Y_train)
pred = model.predict(X_test)
|
12,947 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: Implementing MapReduce
The Pool class can be used to create a simple single-server MapReduce implementation. Although it does not give the full benefits of distributed processing, it ... | Python Code:
import collections
import itertools
import multiprocessing
class SimpleMapReduce:
def __init__(self, map_func, reduce_func, num_workers=None):
map_func
Function to map inputs to intermediate data. Takes as
argument one input value and returns a tuple with the
... |
12,948 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Subreddit Mapping using t-SNE
This was my first effort at subreddit mapping to test if the idea was vaiable. It turns out that this was mostly quite similar to the final analysis, but I spen... | Python Code:
import pandas as pd
import scipy.sparse as ss
import numpy as np
from sklearn.decomposition import TruncatedSVD
import sklearn.manifold
import tsne
import re
raw_data = pd.read_csv('subreddit-overlap')
raw_data.head()
subreddit_popularity = raw_data.groupby('t2_subreddit')['NumOverlaps'].sum()
subreddits =... |
12,949 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classifying movie reviews
Step1: The argument num_words=10000 means that we will only keep the top 10,000 most frequently occurring words in the training data. Rare words
will be discarded... | Python Code:
from keras.datasets import imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
Explanation: Classifying movie reviews: a binary classification example
This notebook contains the code samples found in Chapter 3, Section 5 of Deep Learning with Python. Note that the or... |
12,950 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fitting Models Exercise 2
Imports
Step1: Fitting a decaying oscillation
For this problem you are given a raw dataset in the file decay_osc.npz. This file contains three arrays
Step2: Now, ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
Explanation: Fitting Models Exercise 2
Imports
End of explanation
f = np.load('decay_osc.npz', mmap_mode='r')
list(f)
ydata = f['ydata']
dy = f['dy']
tdata = f['tdata']
plt.figure(figsize=(10,5))
plt.errorbar... |
12,951 | 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... |
12,952 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h3>Step 1
Step1: <h3>Step 2
Step2: <h3>Step 3
Step3: <h3>Step 4
Step4: <h4>Problem
Step5: <h2>JSON</h2>
<li>The python library - json - deals with converting text to and from JSON
Step... | Python Code:
import requests
Explanation: <h3>Step 1: Import the requests library</h3>
End of explanation
response = requests.get("http://www.epicurious.com/search/Tofu+Chili")
Explanation: <h3>Step 2: Send an HTTP request, get the response, and save in a variable</h3>
End of explanation
print(response.status_code)
Exp... |
12,953 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Skip-gram word2vec
In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about emb... | Python Code:
import time
import numpy as np
import tensorflow as tf
import utils
Explanation: Skip-gram word2vec
In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural lang... |
12,954 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: Ragged Tensors
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Overview
Your data comes in ... | 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,955 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introducing curiosity-driven learning
Random exploration is not enough
In the last tutorials, we compared the motor and goal babbling strategies on the simple arm environment. We saw that th... | Python Code:
from __future__ import print_function
from explauto.environment import environments
env_cls, env_configs, _ = environments['simple_arm']
print("'high_dimensional' configuration sensory bounds:")
print('s_mins = {} ; s_maxs = {}'.format(env_configs['high_dimensional']['s_mins'], env_configs['high_dimensiona... |
12,956 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A preliminary look at sensor data
The general idea of the project is to get a handle on how the house heats and cools so that we can better program the thermostat.
To gather data, I've assem... | Python Code:
!head -5 temps.csv
Explanation: A preliminary look at sensor data
The general idea of the project is to get a handle on how the house heats and cools so that we can better program the thermostat.
To gather data, I've assembled and programmed 5 probes using inexpensive hardware (Wemos D1 Mini ESP8266 Wifi b... |
12,957 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparing surrogate models
Tim Head, July 2016.
Reformatted by Holger Nahrstaedt 2020
.. currentmodule
Step1: Toy model
We will use the
Step2: This shows the value of the two-dimensional ... | Python Code:
print(__doc__)
import numpy as np
np.random.seed(123)
import matplotlib.pyplot as plt
Explanation: Comparing surrogate models
Tim Head, July 2016.
Reformatted by Holger Nahrstaedt 2020
.. currentmodule:: skopt
Bayesian optimization or sequential model-based optimization uses a surrogate
model to model the ... |
12,958 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multi-Layer Perceptron, MNIST
In this notebook, we will train an MLP to classify images from the MNIST database hand-written digit database.
The process will be broken down into the followin... | Python Code:
# import libraries
import torch
import numpy as np
Explanation: Multi-Layer Perceptron, MNIST
In this notebook, we will train an MLP to classify images from the MNIST database hand-written digit database.
The process will be broken down into the following steps:
Load and visualize the data
Define a neural ... |
12,959 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
Objective
Step1: Objective
Step2: Figure out what makeARGB is doing
Step3: Make a semi-transparent rectangle (image)
Step4: What is np.vstack.transpose() doing?
Step5: ... | Python Code:
%%javascript
IPython.load_extensions('calico-document-tools');
!date
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
import pyqtgraph as pg
import numpy as np
Explanation: Table of Contents
Objective: propagating plane wave visualization
How to get docstrings for a class definition
Fig... |
12,960 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Define problem, hparams, model, encoder and decoder
Definition of this model (as well as many more) can be found on tensor2tensor github page.
Step1: Define path to checkpoint
In this demo ... | Python Code:
problem_name = "librispeech_clean"
asr_problem = problems.problem(problem_name)
encoders = asr_problem.feature_encoders(None)
model_name = "transformer"
hparams_set = "transformer_librispeech_tpu"
hparams = trainer_lib.create_hparams(hparams_set,data_dir=data_dir, problem_name=problem_name)
asr_model = reg... |
12,961 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CORDEX ESGF submission form
.. outdated .. needs adaption to future use ..
General Information
Data to be submitted for ESGF data publication must follow the rules outlined in the Cordex A... | Python Code:
# Evaluate this cell to identifiy your form
from dkrz_forms import form_widgets, form_handler, checks
form_infos = form_widgets.show_selection()
# Evaluate this cell to generate your personal form instance
form_info = form_infos[form_widgets.FORMS.value]
sf = form_handler.init_form(form_info)
form = sf.su... |
12,962 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Autobatching log-densities example
This notebook demonstrates a simple Bayesian inference example where autobatching makes user code easier to write, easier to read, and less likely to inclu... | Python Code:
import functools
import itertools
import re
import sys
import time
from matplotlib.pyplot import *
import jax
from jax import lax
import jax.numpy as jnp
import jax.scipy as jsp
from jax import random
import numpy as np
import scipy as sp
Explanation: Autobatching log-densities example
This notebook demons... |
12,963 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
如何爬取Facebook粉絲頁資料 (posts) ?
基本上是透過 Facebook Graph API 去取得粉絲頁的資料,但是使用 Facebook Graph API 還需要取得權限,有兩種方法
Step1: 第一步 - 要先取得應用程式的帳號,密碼 (app_id, app_secret)
第二步 - 輸入要分析的粉絲團的 id (page_id)
[教學]如何申... | Python Code:
# 載入python 套件
import requests
import datetime
import time
import pandas as pd
Explanation: 如何爬取Facebook粉絲頁資料 (posts) ?
基本上是透過 Facebook Graph API 去取得粉絲頁的資料,但是使用 Facebook Graph API 還需要取得權限,有兩種方法 :
第一種是取得 Access Token
第二種是建立 Facebook App的應用程式,用該應用程式的帳號,密碼當作權限
兩者的差別在於第一種會有時效限制,必須每隔一段時間去更新Access Token,才能使用
Acce... |
12,964 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
UK schools cluster analysis
This notebook explores some potential correlations between the features of our UK school datasets and then performs an agglomerative clustering saving the labelin... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn.cluster import KMeans, AgglomerativeClustering
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
Explanation: UK schools cluster analysis
This notebook explores some potential c... |
12,965 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quelques rappels sur les chaînes de caractères
Les chaînes de caractères s'écrivent entre guillemets (quotes en anglais), simples ou doubles. Elles peuvent être comparées entre elles avec le... | Python Code:
txt1 = "Ceci est un texte"
txt2 = 'ceci est un autre texte'
print("A" < txt1)
print("B" < txt2)
print("A" >"a")
print("Z" < "a" and "z" < "é")
print(txt1 + txt2)
print(len(txt1))
print(len(txt2))
print(txt1[2])
Explanation: Quelques rappels sur les chaînes de caractères
Les chaînes de caractères s'écrive... |
12,966 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chainer basic module introduction
Advanced memo is written as "Note". You can skip reading this for the first time reading.
In this tutorial, basic chainer modules are introduced and explain... | Python Code:
# Initial setup following
import numpy as np
import chainer
from chainer import cuda, Function, gradient_check, report, training, utils, Variable
from chainer import datasets, iterators, optimizers, serializers
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links a... |
12,967 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
5368175 function calls (5360007 primitive calls) in 17.618 seconds
Ordered by
Step1: Computing occupancy statistics
Need to compute a bunch of output stats to use for visualization, metamod... | Python Code:
hm.run_hillmaker(scenario_name,stops_df,in_fld_name, out_fld_name,cat_fld_name,start_analysis,end_analysis,tot_fld_name,bin_size_mins,categories=includecats,outputpath='./testing')
occ_df = pd.read_csv(fn_occ_summary)
bydt_df = pd.read_csv(fn_bydatetime)
def num_gt_0(column):
return (column != 0).sum()... |
12,968 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Conditional Probability Solution
First we'll modify the code to have some fixed purchase probability regardless of age, say 40%
Step1: Next we will compute P(E|F) for some age group, let's ... | Python Code:
from numpy import random
random.seed(0)
totals = {20:0, 30:0, 40:0, 50:0, 60:0, 70:0}
purchases = {20:0, 30:0, 40:0, 50:0, 60:0, 70:0}
totalPurchases = 0
for _ in range(100000):
ageDecade = random.choice([20, 30, 40, 50, 60, 70])
purchaseProbability = 0.4
totals[ageDecade] += 1
if (random.r... |
12,969 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
pysgrid only works with raw netCDF4 (for now!)
Step1: The sgrid object
Step2: The object knows about sgrid conventions
Step3: Being generic is nice! This is an improvement up on my first... | Python Code:
from netCDF4 import Dataset
url = ('http://geoport.whoi.edu/thredds/dodsC/clay/usgs/users/'
'jcwarner/Projects/Sandy/triple_nest/00_dir_NYB05.ncml')
nc = Dataset(url)
Explanation: pysgrid only works with raw netCDF4 (for now!)
End of explanation
import pysgrid
# The object creation is a litt... |
12,970 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Parameter identification example
Here is a simple toy model that we use to demonstrate the working of the inference package
$\emptyset \xrightarrow[]{k_1} X \; \; \; \; X \xrightarrow[]{d_1}... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = "retina"
from matplotlib import rcParams
rcParams["savefig.dpi"] = 100
rcParams["figure.dpi"] = 100
rcParams["font.size"] = 20
Explanation: Parameter identification example
Here is a simple toy model that we use to demonstrate the working of the infe... |
12,971 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
numpy.vectorize
Step1: Multi-core processing
Step2: Single core
Step3: Threads
```python
%%time
args = [(x, i) for i, x in enumerate(data)]
def plot_one_(arg)
Step4: Parallel comprehensi... | Python Code:
def in_unit_circle(x, y):
if x**2 + y**2 < 1:
return 1
else:
return 0
@numba.vectorize('int64(float64, float64)',target='cpu')
def in_unit_circle_serial(x, y):
if x**2 + y**2 < 1:
return 1
else:
return 0
@numba.vectorize('int64(float64, float64)',target='para... |
12,972 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: TensorFlow の NumPy API
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https
Step2: NumPy 動作の有効化
tnp を N... | 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,973 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The atmosphere and its layers
The World Meteorological Organization (WMO) defines the atmosphere as
Step1: Comparing coesa62 and coesa76
Also known as U.S. Standard Atmosphere, the atmosphe... | Python Code:
from poliastro.atmosphere import COESA62, COESA76
from astropy import units as u
import numpy as np
import matplotlib.pyplot as plt
Explanation: The atmosphere and its layers
The World Meteorological Organization (WMO) defines the atmosphere as:
A hypotetical vertical distribution of atmospheric temperatur... |
12,974 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stopword Removal from Media Unit & Annotation
In this tutorial, we will show how dimensionality reduction can be applied over both the media units and the annotations of a crowdsourcing task... | Python Code:
import pandas as pd
test_data = pd.read_csv("data/person-video-highlight.csv")
test_data["taggedinsubtitles"][0:30]
Explanation: Stopword Removal from Media Unit & Annotation
In this tutorial, we will show how dimensionality reduction can be applied over both the media units and the annotations of a crowds... |
12,975 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Running EnergyPlus from Eppy
It would be great if we could run EnergyPlus directly from our IDF wouldn’t it?
Well here’s how we can.
Step1: if you are in a terminal, you will see something ... | Python Code:
# you would normaly install eppy by doing
# python setup.py install
# or
# pip install eppy
# or
# easy_install eppy
# if you have not done so, uncomment the following three lines
import sys
# pathnameto_eppy = 'c:/eppy'
pathnameto_eppy = '../'
sys.path.append(pathnameto_eppy)
from eppy.modeleditor import ... |
12,976 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
切片
为了计算 seq[start
Step1: 对列表使用 + 与 *
要连接多个同一列表副本,只需要将列表乘上一个整数
Step2: 用 * 构建内含多个列表的列表
如果我们想初始化列表中有一定数量的列表,最适合使用列表生成式,例如下面就可以表示井字的棋盘列表,里面有 3 个长度为 3 的列表
Step3: 上面很吸引人,并且是一种标准的做法,不过要注意,如果你在 a... | Python Code:
l = list(range(10))
l
l[2:5] = 100 #当赋值对象是切片时候,即使只有一个元素,等式右面也必须是一个可迭代元素
l[2:5] = [100]
l
Explanation: 切片
为了计算 seq[start:stop:step],Python 会调用 seq.__getitem__(slice(start, stop, step))。
多维切片
[ ] 运算符也可以接收以逗号分隔的多个索引或切片,举例来说,Numpy 中,你可以使用 a[i, j] 取得二维的 numpy.ndarray,以及使用 a[m:n, k:l] 这类的运算符获取二维的切片。处理 [ ] 运算符的 _... |
12,977 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Models
Timothy Helton
Imports
Step1: Load Data
Step2: Batting
Step3: Player
Step4: Salary
Step5: Team
Step6: Exercise 1
Step7: Exercise 2
Step8: Exercise 3
Step9: Exercise 4
... | Python Code:
import os
import os.path as osp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
import seaborn as sns
import statsmodels.formula.api as smf
from statsmodels.graphics.regressionplots import influ... |
12,978 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
STA 208
Step3: The response variable is quality. | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import LeaveOneOut
from sklearn import linear_model, neighbors
%matplotlib inline
plt.style.use('ggplot')
# dataset path
data_dir = "."
sample_data = pd.read_csv(data_dir+"/hw1.csv", delimiter=',')
sample_da... |
12,979 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex SDK
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Restart the kernel
Once you've installed the additional packages, you need to restart the no... | Python Code:
import os
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG
Explanation: Vertex SDK: AutoML training image object detection model for export to edge
<table align=... |
12,980 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Jupyter Notebook & Python Intro
Zuerst navigieren wir mit der Kommandozeile in den Folder, wo wir das Jupyter Notebook abspeichern wollen. Dann gehen wir in unser virtual environment und sta... | Python Code:
#dsfdskjfbskjdfbdkjbfkjdbf
#asdasd
Explanation: Jupyter Notebook & Python Intro
Zuerst navigieren wir mit der Kommandozeile in den Folder, wo wir das Jupyter Notebook abspeichern wollen. Dann gehen wir in unser virtual environment und starten mit "jupyter notebook" unser Notebook auf. Jupyter Notebook ist ... |
12,981 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Forest Fire Model
A rapid introduction to Mesa
The Forest Fire Model is one of the simplest examples of a model that exhibits self-organized criticality.
Mesa is a new, Pythonic agent-ba... | Python Code:
import random
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from mesa import Model, Agent
from mesa.time import RandomActivation
from mesa.space import Grid
from mesa.datacollection import DataCollector
from mesa.batchrunner import BatchRunner
Explanation: The Forest Fire Model
A ra... |
12,982 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Preprocessing
... but you can't access it! So MDR has done, it, below...
Download and unzip the data - MDR
(Don't re-run the below unless needed - it's >800Mb, and takes about 3-4 min to dow... | Python Code:
import zipfile
with zipfile.ZipFile(path + "glove.6B.zip","r") as zip_ref:
zip_ref.extractall(path)
%ls $path
Explanation: Preprocessing
... but you can't access it! So MDR has done, it, below...
Download and unzip the data - MDR
(Don't re-run the below unless needed - it's >800Mb, and takes about 3-4 ... |
12,983 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TUTORIAL 05 - Exact Parametrized Functions for non-affine elliptic problems
Keywords
Step1: 3. Affine decomposition
The parametrized bilinear form $a(\cdot, \cdot; \boldsymbol{\mu})$ is tri... | Python Code:
from dolfin import *
from rbnics import *
Explanation: TUTORIAL 05 - Exact Parametrized Functions for non-affine elliptic problems
Keywords: exact parametrized functions
1. Introduction
In this Tutorial, we consider steady heat conduction in a two-dimensional square domain $\Omega = (-1, 1)^2$.
The boundar... |
12,984 | 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
Step1: 下面先获取沙盒数据中美股一年的数据,为之后的分析做数据准备:
Step2: 1. 传统的双均线择时策略
双均线策略是量化策略中经典的策略之一,其属于趋势跟踪策略,基本实现思想如下
预... | 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,985 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PCA Python vs R
Originally, R was used to calculate PCA using both princomp and prcomp. However, rpy2 stopped was intorducing some issues on the galaxy server. I decided to switch the calcul... | Python Code:
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
Explanation: PCA Python vs R
Originally, R was used to calculate PCA using both princomp and prcomp. However, rpy2 stopped was intorducing some issues on the galaxy server. I decided to switch the calculation over to a pure python... |
12,986 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<hr>
<h1>Detecting Abnormalities in Mammograms</h1>
<p>Jay Narhan</p>
May 2017
Screening for breast cancer will often make use of mammography as the primary imaging modality for early detect... | Python Code:
import os
import sys
import time
import numpy as np
from tqdm import tqdm
import sklearn.metrics as skm
from sklearn import metrics
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from skimage import color
import keras.callbacks as cb
import keras.utils.np_utils as np_utils... |
12,987 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
how split dataset into training and testing sets
| Python Code::
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(ds.data, ds.target, test_size = 0.20)
|
12,988 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Laboratory 02
Requirements
For the second part of the exercises you will need the wikipedia package. On Windows machines, use the following command in the Anaconda Prompt (Start --> Anaco... | Python Code:
def is_symmetric(l):
for i in range(len(l) // 2):
if l[i] != l[len(l)-i-1]:
return False
return True
# idiomatic solution
def is_symmetric(l):
return all(l[i] == l[len(l)-i-1] for i in range(len(l) // 2))
assert(is_symmetric([1]) == True)
assert(is_symmetric([]) == True)
ass... |
12,989 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial 1
Step1: Spots magic
I wrote an %imaris_pull shortcut to pull spots, cells, filaments and surfaces. Typing the following create a spots dictionary with spot objects names as keys a... | Python Code:
%reload_ext XTIPython
import numpy as np
Explanation: Tutorial 1: Number of cells vs time
NOTE: This tutorials works with the R18Demo.ims dataset. You will also need to create some spot data.
Create a new spot object in Imaris, and just use the defaults until you reach the end of the spots creation wizard.... |
12,990 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification on the Titanic Dataset
The following example gives an idea about how you could run basic classification using a Gaussian mixture model on the Titanic dataset, using a latent n... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import re
import sys
sys.path.append("../../../bayesianpy")
import bayesianpy
import bayesianpy.visual
import logging
import os
from sklearn.cross_validation import KFold
from sklearn.metrics import accuracy_score
pattern = re.compile("([A-Z]{1})([0... |
12,991 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FastAI models.validate CUDA Tensor Issue
WNixalo – 2018/6/11
I ran into trouble trying to reimplement a CIFAR-10 baseline notebook. The notebook used PyTorch dataloaders fed into a ModelData... | Python Code:
import torch
from fastai.conv_learner import *
x = torch.FloatTensor([[[1,1,],[1,1]]]); x
VV(x)
VV(VV(x))
torch.equal(VV(x), VV(VV(x)))
Explanation: FastAI models.validate CUDA Tensor Issue
WNixalo – 2018/6/11
I ran into trouble trying to reimplement a CIFAR-10 baseline notebook. The notebook used PyTorch ... |
12,992 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python_중간발표
데이터사이언스학과 M2015228 조재환
'key
Step1: 이전 제출물
Step2: 이전에 제출한 것은 출력하면 알파벳과 모스부호가 정렬되지 않았습니다. 입력한 문장대로 모스부호를 나타내고 싶었었는데 조금 더 공부하다보니 코드를 만들 수 있어서 다시 한번 제출합니다.
수정 | Python Code:
drinks={
'martini' : {'vodka', 'vermouth'},
'black russian' : {'vodka', 'kahlua'},
'white russian' : {'cream', 'kahlua', 'vodka'},
'manhattan' : {'rye', 'vermouth', 'bitters'},
'screwdriver': {'orange juice', 'vodka'},
'verorange' : {'orange juice', 'vermouth'},
'kahlua milk' : ... |
12,993 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This is the central location where all variables should be defined, and any relationships between them should be given. Having all definitions collected in one file is useful b... | Python Code:
# Make sure division of integers does not round to the nearest integer
from __future__ import division
# Make everything in python's symbolic math package available
from sympy import * # Make sure sympy functions are used in preference to numpy
import sympy # Make sympy. constructions available
from sympy ... |
12,994 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Circuit optimization, gate alignment, and spin echoes
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step3: Preparing circuits to run on ... | Python Code:
try:
import cirq
except ImportError:
print("installing cirq...")
!pip install --quiet cirq --pre
print("installed cirq.")
import matplotlib.pyplot as plt
import numpy as np
import cirq
import cirq_google as cg
import os
# The Google Cloud Project id to use.
project_id = '' #@param {type:"st... |
12,995 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting Started With TensorFlow
Reference
To get the most out of this guide, you should know the following
Step1: TensorFlow Core tutorial
Importing TensorFlow
The canonical import statemen... | Python Code:
3 # a rank 0 tensor; this is a scalar with shape []
[1. ,2., 3.] # a rank 1 tensor; this is a vector with shape [3]
[[1., 2., 3.], [4., 5., 6.]] # a rank 2 tensor; a matrix with shape [2, 3]
[[[1., 2., 3.]], [[7., 8., 9.]]] # a rank 3 tensor with shape [2, 1, 3]
Explanation: Getting Started With TensorFlow... |
12,996 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas DataFrame
Step1: V4 grade (범주형 데이터형)
LC assigned loan grade
A,B,C,D,E,F,G = {1, 2, 3, 4, 5, 6, 7}
Step2: V5 sub_grade (범주형 데이터형)
LC assigned loan subgrade
1, 2, 3, 4, 5
Step3: V6 e... | Python Code:
lc_data = pd.DataFrame.from_csv('./lc_dataframe(cleaning).csv')
lc_data = lc_data.reset_index()
lc_data.tail()
Explanation: Pandas DataFrame
End of explanation
x = lc_data['grade']
sns.distplot(x, color = 'r')
plt.show()
Explanation: V4 grade (범주형 데이터형)
LC assigned loan grade
A,B,C,D,E,F,G = {1, 2, 3, 4, 5... |
12,997 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Downloading Overlays
This notebook demonstrates how to download an FPGA overlay and examine programmable logic state.
1. Instantiating an overlay
With the following overlay bundle present ... | Python Code:
import os, warnings
from pynq import PL
from pynq import Overlay
if not os.path.exists(PL.bitfile_name):
warnings.warn('There is no overlay loaded after boot.', UserWarning)
Explanation: Downloading Overlays
This notebook demonstrates how to download an FPGA overlay and examine programmable logic state... |
12,998 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture 10
Step1: With NumPy arrays, all the same functionality you know and love from lists is still there.
Step2: These operations all work whether you're using Python lists or NumPy arr... | Python Code:
li = ["this", "is", "a", "list"]
print(li)
print(li[1:3]) # Print element 1 (inclusive) to 3 (exclusive)
print(li[2:]) # Print element 2 and everything after that
print(li[:-1]) # Print everything BEFORE element -1 (the last one)
Explanation: Lecture 10: Array Indexing, Slicing, and Broadcasting
CSCI 1... |
12,999 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Distributions
Step1: Ex 2. LINEARITY OF THE NORMAL DISTRIBUTION.
Repeat the exercise using random normal variables with mean 3 and standard deviation 0.4, using now 3 times each of 4,20... | Python Code:
fig = plt.figure(1,figsize=(8,8))
for ii in range(1, 10):
rv = scipy.stats.norm.rvs(0, 1, size = 200)
ax = fig.add_subplot(3,3,ii)
sm.qqplot(rv, line = 's', ax = ax)
ax.set_xlabel('')
ax.set_ylabel('')
fig.text(0.5, 0.02, 'Theoretical Quantiles', ha='center',size=16)
fig.text(0.02, 0.5,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.