Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
6,200 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tigergraph Bindings
Step1: Dynamic user-defined GSQL endpoints
Step3: On-the-fly GSQL interpreted queries | Python Code:
import graphistry
# !pip install graphistry -q
# To specify Graphistry account & server, use:
# graphistry.register(api=3, username='...', password='...', protocol='https', server='hub.graphistry.com')
# For more options, see https://github.com/graphistry/pygraphistry#configure
g = graphistry.tigergraph(
... |
6,201 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The model
This style of modeling is often called the "piecewise exponential model", or PEM. It is the simplest case where we estimate the hazard of an event occurring in a time period as the... | Python Code:
print(survivalstan.models.pem_survival_model)
Explanation: The model
This style of modeling is often called the "piecewise exponential model", or PEM. It is the simplest case where we estimate the hazard of an event occurring in a time period as the outcome, rather than estimating the survival (ie, time to... |
6,202 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 by D. Koehn, heterogeneous models are from this Jupyter notebook by Heiner Igel (@heiner... | Python Code:
# Execute this cell to load the notebook's style sheet, then ignore it
from IPython.core.display import HTML
css_file = '../../style/custom.css'
HTML(open(css_file, "r").read())
Explanation: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 by D. Koehn, h... |
6,203 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Histogrammar basic tutorial
Histogrammar is a Python package that allows you to make histograms from numpy arrays, and pandas and spark dataframes. (There is also a scala backend for Histogr... | Python Code:
%%capture
# install histogrammar (if not installed yet)
import sys
!"{sys.executable}" -m pip install histogrammar
import histogrammar as hg
import pandas as pd
import numpy as np
import matplotlib
Explanation: Histogrammar basic tutorial
Histogrammar is a Python package that allows you to make histograms ... |
6,204 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
02. Connect datalab
datalab은 Google Cloud에서 서비스하는 Jupyter notebook이라고 보면 됩니다
최근 20170818 버전부터 python2, python3 커널을 사용할 수 있습니다 (기존에는 python2만 해당)
datalab은 Google Cloud Storage / BigQuery 등에서 ... | Python Code:
import google.datalab.bigquery as bq
# Query 생성
query_string = '''
#standardSQL
SELECT corpus AS title, COUNT(*) AS unique_words
FROM `publicdata.samples.shakespeare`
GROUP BY title
ORDER BY unique_words DESC
LIMIT 10
... |
6,205 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
linear regression
解析式直接求解
Step1: $y = Xw$
$ w = (X^TX)^[-1]X^T*y$
Step2: Results
w1 = 2.97396653
w2 = -0.54139002
w3 = 0.97132913
b = 2.03076198
Step3: 梯度下降法求解
目标函数选取要合适一些, 前边乘以适当的系数.
注意检... | Python Code:
df['x4'] = 1
X = df.iloc[:,(0,1,2,4)].values
y = df.y.values
Explanation: linear regression
解析式直接求解
End of explanation
inv_XX_T = inv(X.T.dot(X))
w = inv_XX_T.dot(X.T).dot(df.y.values)
w
Explanation: $y = Xw$
$ w = (X^TX)^[-1]X^T*y$
End of explanation
qr(inv_XX_T)
X.shape
#solve(X,y)##只能解方阵
Explanation: Re... |
6,206 | 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... |
6,207 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Section 0
Step1: Section 1
Step2: Section 2
Step3: Section 3
Step4: Section 4
Recommendation and predictions for Articles
Recommendation method
Step5: Testing data for cluster assigning... | Python Code:
dataset= sf.SFrame('Dataset/KO_data.csv')
dataset.remove_column('X1')
dataset= dataset.add_row_number()
dataset.rename({'id':'X1'})
tfidfvec= TfidfVectorizer(stop_words='english')
tf_idf_matrix= tfidfvec.fit_transform(dataset['text'])
tf_idf_matrix = normalize(tf_idf_matrix)
Explanation: Section 0:
Dataset... |
6,208 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the Licen... | Python Code:
import os
import numpy
import pandas
from six.moves import zip
from sklearn import mixture
import gzip
!pip install python-Levenshtein
import Levenshtein
Explanation: Copyright 2020 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance wi... |
6,209 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using the library
This code tutorial shows how to estimate a 1-RDM and perform variational optimization
Step1: Generate the input files, set up quantum resources, and set up the OpdmFunctio... | Python Code:
# Import library functions and define a helper function
import numpy as np
import cirq
from openfermioncirq.experiments.hfvqe.gradient_hf import rhf_func_generator
from openfermioncirq.experiments.hfvqe.opdm_functionals import OpdmFunctional
from openfermioncirq.experiments.hfvqe.analysis import (compute_o... |
6,210 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building a pandas Cheat Sheet, Part 1
Import pandas with the right name
Step1: Set all graphics from matplotlib to display inline
Step2: Display the names of the columns in the csv
Step3: ... | Python Code:
import pandas as pd
df = pd.read_csv("07-hw-animals.csv")
Explanation: Building a pandas Cheat Sheet, Part 1
Import pandas with the right name
End of explanation
#!pip install matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
#This lets your graph show you in your notebook
df
Explanation: Set a... |
6,211 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The Cirq Developers
Step1: Notebook template
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Make a copy of this template
... | 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... |
6,212 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create test datasets
In this case we are making a n=5 of "gaussian blobs" with st_dev=1.
We will look at 2 cases,
* easy case
Step1: Create ko
Step2: Create a Collection and add ko
Step3... | Python Code:
# Blobs with 4 -- slight overlaps
num_centers = 5
st_dev = 1
n_samples = 1000
noise = 0.12
#Easy Case
#x,y = make_blobs(n_samples=n_samples, centers=num_centers, cluster_std=st_dev, random_state=10)
#Medium Case
x,y = make_blobs(n_samples=n_samples, centers=num_centers, cluster_std=st_dev, random_state=0)
... |
6,213 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="AW&H2015.tiff" style="float
Step1: Setup a New Directory and Change Paths
For this tutorial, we will work in the 21_FlopyIntro directory, which is located up one folder and over t... | Python Code:
%matplotlib inline
import sys
import os
import shutil
import numpy as np
from subprocess import check_output
# Import flopy
import flopy
Explanation: <img src="AW&H2015.tiff" style="float: left">
<img src="flopylogo.png" style="float: center">
Problem P4.1 Flopy Background and Toth (1962) Flow System
Pages... |
6,214 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<H2>Complex sine waves</H2>
To have an imaginary wave, we simply need to multiply the wave by the imaginary operator, as we do with the real numbers to have the equivalent imaginary numbers.... | Python Code:
t = np.arange(0,np.pi, 1/30000)
freq = 2 # in Hz
phi = 0
amp = 1
k = 2*np.pi*freq*t + phi
cwv = amp * np.exp(-1j* k) # complex sine wave
fig, ax = plt.subplots(2,1, figsize=(8,4), sharex=True)
ax[0].plot(t, np.real(cwv), lw=1.5)
ax[0].plot(t, np.imag(cwv), lw=0.5, color='orange')
ax[0].set_title('real (cos... |
6,215 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Word2Vec trained on recipe instructions
Objectives
Create word embeddings for recipe.
Use word vectors for (traditional) segmentation, classification, and retrieval of recipes.
Data Preparat... | Python Code:
import re # Regular Expressions
import pandas as pd # DataFrames & Manipulation
from gensim.models.word2vec import Word2Vec
train_input = "../data/recipes.tsv.bz2"
# preserve empty strings (http://pandas-docs.github.io/pandas-docs-travis/io.html#n... |
6,216 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cheat Sheet
Step1: To print multiple strings, import print_function to prevent Py2 from interpreting it as a tuple
Step2: Raising exceptions
Step3: Raising exceptions with a traceback
Ste... | Python Code:
# Python 2 only:
print 'Hello'
# Python 2 and 3:
print('Hello')
Explanation: Cheat Sheet: Writing Python 2-3 compatible code
Copyright (c): 2013-2019 Python Charmers Pty Ltd, Australia.
Author: Ed Schofield.
Licence: Creative Commons Attribution.
A PDF version is here: http://python-future.org/compatible_i... |
6,217 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numba Demo 2
Fibonacci Series
Lets try with the classic Fibonacci series
Step1: But the recursive implementation is not efficient, it is recursive, and at each recursion call itself twice
S... | Python Code:
def fibonacci_r(x):
assert x >= 0, 'x must be a positive integer'
if x <= 1: # First 2 cases.
return x
return fibonacci_r(x - 1) + fibonacci_r(x - 2)
X = [x for x in range(10)]
print('X = ' + repr(X))
Y = [fibonacci_r(x) for x in X]
print('Y = ' + repr(Y))
Explanation: Nu... |
6,218 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analysis with median derived value. Checking for jump between (blue to green) and (green to red) chips
Method of persistence determination
Step1: First let's examine the range of persisten... | Python Code:
f = '/home/spiffical/data/stars/apStar_visits_quantifypersist_med.txt'
persist_vals_med1=[]
persist_vals_med2=[]
fibers_med = []
snr_combined_med = []
starflags_indiv_med = []
loc_ids_med = []
ap_ids_med = []
fi = open(f)
for j, line in enumerate(fi):
# Get values
line = line.split()
persi... |
6,219 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
text plot
This notebook is designed to demonstrate (and so document) how to use the shap.plots.text function. It uses a distilled PyTorch BERT model from the transformers package to do senti... | Python Code:
import shap
import transformers
import nlp
import torch
import numpy as np
import scipy as sp
# load a BERT sentiment analysis model
tokenizer = transformers.DistilBertTokenizerFast.from_pretrained("distilbert-base-uncased")
model = transformers.DistilBertForSequenceClassification.from_pretrained(
"dis... |
6,220 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
In the previous two lessons, we learned about the three operations that carry out feature extraction from an image
Step1: Stride
The distance the window moves at each step is c... | Python Code:
from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential([
layers.Conv2D(filters=64,
kernel_size=3,
strides=1,
padding='same',
activation='relu'),
layers.MaxPool2D(pool_size=2,
... |
6,221 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with auxi's Ideal Gas Models
Purpose
The purpose of this example is to introduce and demonstrate the idealgas model classes in auxi's material physical property tools package.
Backgr... | Python Code:
# import some tools to use in this example
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Working with auxi's Ideal Gas Models
Purpose
The purpose of this example is to introduce and demonstrate the idealgas model classes in auxi's material physical property tools packa... |
6,222 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Motivation
<br>
<font color=red size=+3>Know what you eat, </font>
<font color=green size=+3> Gain insight into food.</font>
<a href=https
Step1: Import libraries
Step7: User-defined funct... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: Motivation
<br>
<font color=red size=+3>Know what you eat, </font>
<font color=green size=+3> Gain insight into food.</font>
<a href=https://world.openfoodfacts.org/>
<img src=https://static.openfoodfacts.org/images/misc/openfoodf... |
6,223 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to Build a RuleBasedProfiler
This Notebook will demonstrate the steps we need to take to generate a simple RuleBasedProfiler by initializing the components in memory.
We will start from ... | Python Code:
import great_expectations as ge
from ruamel import yaml
from great_expectations.core.batch import BatchRequest
from great_expectations.rule_based_profiler.rule.rule import Rule
from great_expectations.rule_based_profiler.rule_based_profiler import RuleBasedProfiler, RuleBasedProfilerResult
from great_expec... |
6,224 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Q2
In this question, we'll explore the basics of using NumPy arrays. We'll also start using functions as they were intended
Step1: Part B
Write a function which takes a NumPy array and retu... | Python Code:
import numpy as np
np.random.seed(578435)
x11 = np.random.random(10)
x12 = np.random.random(10)
d1 = np.array([ 0.24542374, 0.19098998, 0.20645088, 0.49097139, -0.56594091,
-0.13363814, 0.46859546, -0.32476466, -0.35938731, 0.17459786])
np.testing.assert_allclose(d1, difference(x11, x12))
np.ra... |
6,225 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id='top'> </a>
Author
Step1: Data-MC comparison
Table of contents
Data preprocessing
Weight simulation events to spectrum
S125 verification
$\log_{10}(\mathrm{dE/dX})$ verification
Step2... | Python Code:
%load_ext watermark
%watermark -u -d -v -p numpy,scipy,pandas,sklearn,mlxtend
Explanation: <a id='top'> </a>
Author: James Bourbeau
End of explanation
from __future__ import division, print_function
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec ... |
6,226 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing the community activity for version control systems
Context
You are a new team member in a software company
The developers there are using CVS (Concurrent Versions System)
You propo... | Python Code:
import pandas as pd
vcs_data = pd.read_csv('../dataset/stackoverflow_vcs_data_subset.gz')
vcs_data.head()
Explanation: Analyzing the community activity for version control systems
Context
You are a new team member in a software company
The developers there are using CVS (Concurrent Versions System)
You pro... |
6,227 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create 3D boolean masks
In this tutorial we will show how to create 3D boolean masks for arbitrary latitude and longitude grids. It uses the same algorithm to determine if a gridpoint is in ... | Python Code:
import regionmask
regionmask.__version__
Explanation: Create 3D boolean masks
In this tutorial we will show how to create 3D boolean masks for arbitrary latitude and longitude grids. It uses the same algorithm to determine if a gridpoint is in a region as for the 2D mask. However, it returns a xarray.Datas... |
6,228 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Your first steps with Python
1.1 Introduction
Python is a general purpose programming language. It is used extensively for scientific computing, data analytics and visualization, web deve... | Python Code:
# change this cell into a Markdown cell. Then type something here and execute it (Shift-Enter)
Explanation: 1. Your first steps with Python
1.1 Introduction
Python is a general purpose programming language. It is used extensively for scientific computing, data analytics and visualization, web development a... |
6,229 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Categorical Data
Categoricals are a pandas data type, which correspond to categorical variables in statistics
Step1: Change data type
change data type for "Grade" column to category
documen... | Python Code:
import pandas as pd
import numpy as np
file_name_string = 'C:/Users/Charles Kelly/Desktop/Exercise Files/02_07/Begin/EmployeesWithGrades.xlsx'
employees_df = pd.read_excel(file_name_string, 'Sheet1', index_col=None, na_values=['NA'])
Explanation: Categorical Data
Categoricals are a pandas data type, which ... |
6,230 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Clustering Algorithms
Step1: Proof of Concept
Step2: The above block creates 400 points evenly distributed between two clusters around the coordinates (1,1) and (6,6) on the x-y plane with... | Python Code:
%matplotlib inline
import numpy as np
from sklearn.cluster import MeanShift
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")
Explanation: Clustering Algorithms: Mean Shift
Very often datasets contain information about... |
6,231 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
LightGBM Custom Loss Function
| Python Code::
import LightGBM as lgb
def custom_loss(y_pred, data):
y_true = data.get_label()
error = y_pred-y_true
#1st derivative of loss function
grad = 2 * error
#2nd derivative of loss function
hess = 0 * error + 2
return grad, hess
params = {"learning_rate" : 0.1}
training_da... |
6,232 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
word2vec
<img src="images/book.png" style="width
Step1: Why is word2vec so popular?
Creates a word "cloud", organized by semantic meaning.
Converts text into a numerical form that machine l... | Python Code:
output = {'fox': [-0.00449447, -0.00310097]}
input_text = "The quick brown fox"
print(output['fox'])
Explanation: word2vec
<img src="images/book.png" style="width: 300px;" align="middle"/>
Slides: bit.ly/word2vec_talk
Agenda
0) Welcome!
1) What is word2vec?
2) How does word2vec work?
3) What can you do w... |
6,233 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using the scipy Kolmogorov–Smirnov test
A short note on how to use the scipy Kolmogorov–Smirnov test because quite frankly the documentation was not compelling and I always forget how the s... | Python Code:
xvals = np.linspace(0, 0.5, 500)
args = [0.5, 20]
d1 = ss.beta.rvs(args[0], args[1], size=1000)
noise = ss.norm.rvs(0.4, 0.1, size=50)
d2 = np.append(d1[:len(d1)-len(noise)], noise)
fig, (ax1, ax2) = plt.subplots(nrows = 2)
ax1.plot(xvals, ss.gaussian_kde(d1).evaluate(xvals), "-k",
label="d1")
ax1... |
6,234 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center> Problema zilei de nastere</center>
In acest notebook calculam probabilitatile evenimentelor $E_n$, ca intr-un grup de n persoane, $2\leq n\leq 365$, sa existe cel putin doua cu acee... | Python Code:
from __future__ import division
def prob_theor(n):
if n==2:
return (1-1/365)
else:
return prob_theor(n-1)*(1-(n-1)/365)
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('ggplot') # setam stilul de afisare a plot-urilor.
# Incepand cu matp... |
6,235 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Likelihood-free Inference of Stable Distribution Parameters
1. Stable Distribution
Stable distributions, also known as $\alpha$-stable distributions and Lévy (alpha) stable distribution, are... | Python Code:
import elfi
import scipy.stats as ss
import numpy as np
import matplotlib.pyplot as plt
import pickle
# http://www.ams.sunysb.edu/~yiyang/research/presentation/proof_simulate_stable_para_estimate.pdf
def stable_dist_rvs(alpha,beta,mu,sig,Ns=200,batch_size=1,random_state=None):
'''
generates random ... |
6,236 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
bsym – a basic symmetry module
bsym is a basic Python symmetry module. It consists of some core classes that describe configuration vector spaces, their symmetry operations, and specific con... | Python Code:
from bsym import SymmetryOperation
SymmetryOperation([[ 1, 0, 0 ],
[ 0, 1, 0 ],
[ 0, 0, 1 ]])
Explanation: bsym – a basic symmetry module
bsym is a basic Python symmetry module. It consists of some core classes that describe configuration vector spaces, their symmetr... |
6,237 | Given the following text description, write Python code to implement the functionality described.
Description:
I think we all remember that feeling when the result of some long-awaited
event is finally known. The feelings and thoughts you have at that moment are
definitely worth noting down and comparing.
Y... | Python Code:
def compare(game,guess):
return [abs(x-y) for x,y in zip(game,guess)] |
6,238 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ipsl', 'sandbox-1', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: IPSL
Source ID: SANDBOX-1
Topic: Atmos
Sub-Topics: Dynamical Core, Radiation,... |
6,239 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Unsupervised learning
AutoEncoders
An autoencoder, is an artificial neural network used for learning efficient codings.
The aim of an autoencoder is to learn a representation (encoding) for... | Python Code:
from keras.layers import Input, Dense
from keras.models import Model
from keras.datasets import mnist
import numpy as np
# this is the size of our encoded representations
encoding_dim = 32 # 32 floats -> compression of factor 24.5, assuming the input is 784 floats
# this is our input placeholder
input_img... |
6,240 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p><font size="6"><b>01 - Pandas
Step1: Introduction
Let's directly start with importing some data
Step2: Starting from reading such a tabular dataset, Pandas provides the functionalities ... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
Explanation: <p><font size="6"><b>01 - Pandas: Data Structures </b></font></p>
© 2021, Joris Van den Bossche and Stijn Van Hoey (jorisvandenbossche@gm	... |
6,241 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: On-Device Training with TensorFlow Lite
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Not... | 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... |
6,242 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
glob contains function glob that finds files that match a pattern
* matches 0+ characters; ? matches any one char
Step1: results in a list of strings, we can loop oer
we want to create sets... | Python Code:
print(glob.glob('data/inflammation*.csv'))
Explanation: glob contains function glob that finds files that match a pattern
* matches 0+ characters; ? matches any one char
End of explanation
# loop here
counter = 0
for filename in glob.glob('data/*.csv'):
#counter+=1
counter = counter + 1
print("numb... |
6,243 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example of use of Package PVSystems
Author
Step1: Extraterrestrial radiation
Extraterrestrial radiation. Computation for a specific day
Define input variable (day of the year)
i.e.
2nd of ... | Python Code:
import sys
print(sys.version)
from pvsystems import PVSystems as PVS
import math
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Example of use of Package PVSystems
Author: Mario Mañana. University of Cantabria
Email: mananam@unican.es
Version: 1.0
End of explanation
S1=... |
6,244 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Converting masks back to annotations
Overview
Step1: 1. Connect girder client and set parameters
Step2: Let's inspect the ground truth codes file
This contains the ground truth codes and i... | Python Code:
import os
CWD = os.getcwd()
import girder_client
from pandas import read_csv
from imageio import imread
from histomicstk.annotations_and_masks.masks_to_annotations_handler import (
get_contours_from_mask,
get_single_annotation_document_from_contours,
get_annotation_documents_from_contours)
impo... |
6,245 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: CSE 6040, Fall 2015 [05, Part A]
Step6: Exercise
Step8: Putting it all together
Step9: Exercise | Python Code:
# === Sparse vector: definition ===
from collections import defaultdict
def sparse_vector ():
return defaultdict (int)
def print_sparse_vector (x):
for key, value in x.items ():
print ("%s: %d" % (key, value))
# === Sparse vector demo ===
def alpha_chars (text):
(Generator) Yields ... |
6,246 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Probability Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: TFP Release Notes notebook (0.13.0)
The intent of this notebook is ... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# 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... |
6,247 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: Uncertainty-aware Deep Language Learning with BERT-SNGP
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="h... | 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... |
6,248 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Class Coding Lab
Step1: Types Matter
Python's built in functions and operators work differently depending on the type of the variable.
Step2: Switching Types
there are built-in Python func... | Python Code:
a = "4"
type(a) # should be str
a = 4
type(a) # should be int
Explanation: Class Coding Lab: Variables And Types
The goals of this lab are to help you to understand:
Python data types
Getting input as different types
Formatting output as different types
Basic arithmetic operators
How to create a program fr... |
6,249 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting histograms from the "Z path" analysis
Initial set-up
These commands give us access to some tools for plotting histograms and other graphs. We only need to run these once at the begi... | Python Code:
import pylab
import matplotlib.pyplot as plt
%matplotlib inline
pylab.rcParams['figure.figsize'] = 8,6
Explanation: Plotting histograms from the "Z path" analysis
Initial set-up
These commands give us access to some tools for plotting histograms and other graphs. We only need to run these once at the begin... |
6,250 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Airbnb User Data Exploration
Step1: I wanted to take a look at the user data we have for this competition so I made this little notebook to share my findings and discuss about those. At the... | Python Code:
# Draw inline
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
# Set figure aesthetics
sns.set_style("white", {'ytick.major.size': 10.0})
sns.set_context("poster", font_scale=1.1)
Explanation: Airbnb User Data Exploration
End of... |
6,251 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tiny offset from zero here, but overall it looks pretty good.
Step1: With default analogRead settings, 12-bit resolution, we see 4 µA measured current noise on 10 mA full scale, with no eff... | Python Code:
np.std(df.y_scaled[np.logical_and(df.x_scaled < 1, df.x_scaled > 0.5)], ddof=1)*1000
Explanation: Tiny offset from zero here, but overall it looks pretty good.
End of explanation
(4./10000)**-1
Explanation: With default analogRead settings, 12-bit resolution, we see 4 µA measured current noise on 10 mA ful... |
6,252 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Overview
In this notebook the full dataset is broken into 26 subsets for each of the unique values of the kinase key. A random forest is fit to each of the subsets and evaluated using $k=5$-... | Python Code:
import pandas as pd
import time
import glob
import numpy as np
from scipy.stats import randint as sp_randint
from prettytable import PrettyTable
from sklearn.preprocessing import Imputer
from sklearn.model_selection import train_test_split, cross_val_score, RandomizedSearchCV
from sklearn.metrics import f1... |
6,253 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Motivation
We can view pretty much all of machine learning (ML) (and this is one of many possible views) as an optimization exercise. Our challenge in supervized learning is to find a functi... | Python Code:
def func(x): return -2. * x**2 + 6. * x + 9.
Explanation: Motivation
We can view pretty much all of machine learning (ML) (and this is one of many possible views) as an optimization exercise. Our challenge in supervized learning is to find a function that maps the inputs of a certain system to its outputs.... |
6,254 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Benign or not?
Predicting the incidence of breast cancer diagnosis using multiple cytological characteristics
Kyle Willett (12 Jul 2016)
This project focuses on analyzing results of a study ... | Python Code:
# Load some basic plotting and data analysis packages from Python
%matplotlib inline
from matplotlib import pyplot as plt
import pandas as pd
import seaborn as sns;
Explanation: Benign or not?
Predicting the incidence of breast cancer diagnosis using multiple cytological characteristics
Kyle Willett (12 Ju... |
6,255 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Microbiome experiment step-by-step analysis
This is a jupyter notebook example of how to load, process and plot data from a microbiome experiment using Calour.
Setup
Import the calour module... | Python Code:
import calour as ca
Explanation: Microbiome experiment step-by-step analysis
This is a jupyter notebook example of how to load, process and plot data from a microbiome experiment using Calour.
Setup
Import the calour module
End of explanation
ca.set_log_level(11)
Explanation: (optional) Set the level of fe... |
6,256 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Aerosol
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ipsl', 'sandbox-3', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: IPSL
Source ID: SANDBOX-3
Topic: Aerosol
Sub-Topics: Transport, Emissions... |
6,257 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: If the conflict is active print a statement
Step2: If the conflict is active print a statement, if not, print a different statement
Step3: If the conflict is active print a s... | Python Code:
conflict_active = 1
Explanation: Title: if and if else
Slug: if_and_if_else_statements
Summary: if and if else
Date: 2016-05-01 12:00
Category: Python
Tags: Basics
Authors: Chris Albon
Create a variable with the status of the conflict.
1 if the conflict is active
0 if the conflict is not active
unknown i... |
6,258 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinary Differential Equations Exercise 3
Imports
Step1: Damped, driven nonlinear pendulum
The equations of motion for a simple pendulum of mass $m$, length $l$ are
Step4: Write a functio... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy.integrate import odeint
from IPython.html.widgets import interact, fixed
Explanation: Ordinary Differential Equations Exercise 3
Imports
End of explanation
g = 9.81 # m/s^2
l = 0.5 # length of pendul... |
6,259 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Leverage
Make sure to watch the video and slides for this lecture for the full explanation!
$ Leverage Ratio = \frac{Debt + Capital Base}{Capital Base}$
Leverage from Algorithm
Make sure to ... | Python Code:
def initialize(context):
context.amzn = sid(16841)
context.ibm = sid(3766)
schedule_function(rebalance,
date_rules.every_day(),
time_rules.market_open())
schedule_function(record_vars,
date_rules.every_day(),
... |
6,260 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DV360 Bulk Targeting Editor
Allows bulk targeting DV360 through Sheets and BigQuery.
License
Copyright 2020 Google LLC,
Licensed under the Apache License, Version 2.0 (the "License");
you ma... | Python Code:
!pip install git+https://github.com/google/starthinker
Explanation: DV360 Bulk Targeting Editor
Allows bulk targeting DV360 through Sheets and BigQuery.
License
Copyright 2020 Google LLC,
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the... |
6,261 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cross-validation for parameter tuning, model selection, and feature selection
From the video series
Step1: Question
Step2: Dataset contains 25 observations (numbered 0 through 24)
5-fold c... | Python Code:
from sklearn.datasets import load_iris
from sklearn.cross_validation import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
# read in the iris data
iris = load_iris()
# create X (features) and y (response)
X = iris.data
y = iris.target
# use train/test split ... |
6,262 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Regression
In the nature (or in a real life situation), it is unusual to observe a variable, let's say $y$, and its exact mathematical relationship with another variables $x$. Suppose... | Python Code:
import numpy as np
n=200
x_tr = np.linspace(0.0, 2.0, n)
y_tr = np.exp(3*x_tr)
import random
mu, sigma = 0,50
random.seed(1)
y = y_tr + np.random.normal(loc=mu, scale= sigma, size=len(x_tr))
import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(x_tr,y,".",mew=3);
plt.plot(x_tr, y_tr,"--r",lw=3);
plt.... |
6,263 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced indexing
Step1: Functionality and API
Indexing a 1D array with a Boolean (mask) array
Supported via get/set_mask_selection() and .vindex[]. Also supported via get/set_orthogonal_se... | Python Code:
import sys
sys.path.insert(0, '..')
import zarr
import numpy as np
np.random.seed(42)
import cProfile
zarr.__version__
Explanation: Advanced indexing
End of explanation
a = np.arange(10)
za = zarr.array(a, chunks=2)
ix = [False, True, False, True, False, True, False, True, False, True]
# get items
za... |
6,264 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
12-752 Course Project
Xiaowen Gu (xiaoweng), Kenan Zhang (kenanz)
Step1: 1. Load Data
1.1 Energy Data of Gates
Step2: As is shown in the figure, the load data is cumulated energy consumpti... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
%matplotlib inline
Explanation: 12-752 Course Project
Xiaowen Gu (xiaoweng), Kenan Zhang (kenanz)
End of explanation
gatesDateConverter = lambda d : dt.datetime.strptime(d,'%m/%d/%Y %H:%M')
gates_elect = np.genfromtxt('pointData_gates... |
6,265 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook illustrates the TubeTK tube NumPy array data structure and how to create histograms of the properties of a VesselTube.
First, import the function for reading a tube file in as ... | Python Code:
import os
import sys
# Path for TubeTK libs
TubeTK_BUILD_DIR=None
if 'TubeTK_BUILD_DIR' in os.environ:
TubeTK_BUILD_DIR = os.environ['TubeTK_BUILD_DIR']
if not os.path.exists(TubeTK_BUILD_DIR):
print('TubeTK_BUILD_DIR not found!')
print(' Set environment variable')
sys.exit(1)
sys.path.app... |
6,266 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Minimum count of indices to be skipped for every index of Array to keep sum till that index at most T Function to calculate minimum indices to be skipped so that sum till i remai... | Python Code::
def skipIndices(N , T , arr):
sum = 0
count = { }
for i in range(N):
d = sum + arr[i]- T
k = 0
if(d > 0):
for u in list(count . keys())[: : - 1]:
j = u
x = j * count[j]
if(d <= x):
k +=(d + j - 1)// j
break
k += count[j]
d -= x
sum += arr[i]
count[arr[i]] = count . g... |
6,267 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
Glossary
3. Positional Astronomy
Previous
Step1: 3.1 Equatorial Coordinates (RA,DEC)
3.1.1 The Celestial Sphere
We can use a geographical coordinate system to uniquely identify a ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import HTML
HTML('../style/course.css') #apply general CSS
from IPython.display import HTML
HTML('../style/code_toggle.html')
import healpy as hp
%pylab inline
pylab.rcParams['figure.figsize'] = (15, 10)
import matp... |
6,268 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Aula 10 Discrete Wavelets Transform
Exercícios
isccsym
Não é fácil projetar um conjunto de testes para garantir que o seu programa esteja correta.
No caso em que o resultado é Falso, i.e., ... | Python Code:
import numpy as np
import sys,os
import matplotlib.image as mpimg
ia898path = os.path.abspath('../../')
if ia898path not in sys.path:
sys.path.append(ia898path)
import ia898.src as ia
Explanation: Aula 10 Discrete Wavelets Transform
Exercícios
isccsym
Não é fácil projetar um conjunto de testes para ga... |
6,269 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sparsified K-means Heuristic Plots
This file generates a bunch of figures showing heuristically how sparsified k-means works.
Step2: Data Matrices
X is the data matrix, U is the centroid ma... | Python Code:
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from scipy.linalg import hadamard
from scipy.fftpack import dct
%matplotlib inline
n = 10 #dimension of data (rows in plot)
K = 3 #number of centroids
m = 4 #subsampling dimension
p = 6 #number of obs... |
6,270 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
enterprise Data Structures
This guide will give an introduction to the unique data structures used in enterprise. These are all designed with the goal of making this code as user-friendly as... | Python Code:
% matplotlib inline
%config InlineBackend.figure_format = 'retina'
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import enterprise
from enterprise.pulsar import Pulsar
import enterprise.signals.parameter as parameter
from enterprise.signals import utils
from enterprise.... |
6,271 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Attribution
Step1: Vectors and Matrices
Linear algebra is the study of vectors and matrices and how they can be manipulated to perform various calculations.
Consider functions which take s... | Python Code:
%matplotlib notebook
# Note that this is the usual way that I import Numpy and Matplotlib
import numpy as np
import matplotlib.pyplot as plt
Explanation: Attribution:
Most material based on Sam Roweis' Linear Algebra Review
End of explanation
a = np.array([1, 2, 3])
b = np.ones(3,)
print a
print b
print a... |
6,272 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Tutorial
Welcome to this week's programming assignment. Until now, you've always used numpy to build neural networks. Now we will step you through a deep learning framework that w... | Python Code:
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict
%matplotlib inline
np.random.seed(1)
Explanation: TensorFlow Tutorial
Welcome to... |
6,273 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example - Plotting timetraces with bursts
This notebook is part of smFRET burst analysis software FRETBursts.
In this notebook shows how to plot timetraces with burst information.
For a comp... | Python Code:
from fretbursts import *
sns = init_notebook(apionly=True)
print('seaborn version: ', sns.__version__)
# Tweak here matplotlib style
import matplotlib as mpl
mpl.rcParams['font.sans-serif'].insert(0, 'Arial')
mpl.rcParams['font.size'] = 12
%config InlineBackend.figure_format = 'retina'
from IPython.display... |
6,274 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib example (https
Step1: Pandas examples (https
Step2: Seaborn examples (https
Step3: Cartopy examples (https
Step4: Xarray examples (http | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.show()
# to save
# plt.savefig('test_nb.png')
Explanation: Matplotlib example (https://matplotlib.org/gallery/index.html)
End of explanation
import pandas as pd
import numpy as np
ts = pd.Series(np.random.randn(1000), index=pd.date_... |
6,275 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GPyTorch regression with derivative information
Introduction
In this notebook, we show how to train a GP regression model in GPyTorch of an unknown function given function value and derivati... | Python Code:
import torch
import gpytorch
import math
from matplotlib import pyplot as plt
import numpy as np
%matplotlib inline
%load_ext autoreload
%autoreload 2
Explanation: GPyTorch regression with derivative information
Introduction
In this notebook, we show how to train a GP regression model in GPyTorch of an unk... |
6,276 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'pcmdi', 'sandbox-1', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: PCMDI
Source ID: SANDBOX-1
Topic: Land
Sub-Topics: Soil, Snow, Vegetation, Ene... |
6,277 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
深度学习在早期一度被认为是无监督的特征学习。
1. 无监督学习,即不需要标注数据就可以对数据进行一定程度的学习,这种学习是对数据内容的组织形式的学习,提取的是频繁出现的特征;
2. 逐层抽象,特征是需要不断抽象的,就像人总是从简单基础的概念开始学习,再到复杂的概念。
对于那些特征并不明确的领域,人工的提取特征需要行业相关的专业知识。比如图像识别,图像是有像素点构成。像素点数值是... | Python Code:
%matplotlib inline
import numpy as np
from sklearn import preprocessing
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials import mnist
from __future__ import division
Explanation: 深度学习在早期一度被认为是无监督的特征学习。
1. 无监督学习,即不需要标注数据就可以对数据进行一定程度的学习,这种学习是对数据内容的组织形式的学习,提取的是频繁出现的特征... |
6,278 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: 权重聚类综合指南
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 定义聚类模型
聚类整个模型(序贯模型和函数式模型)
提高模型准确率的提示:
您... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
6,279 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
On souhaite prédire la colonne "SalePrice". Donc toutes les autres colonnes sont des variables à faire apprendre
Step1: Le model peux prendre en entré que des chiffre, il faut donc transfor... | Python Code:
features = [col for col in data.columns if col not in "SalePrice"]
features
train = data[features]
y = data.SalePrice
#y = data['SalePrice']
train.head()
y.head()
sns.distplot(y)
# Modele pour la regression
from sklearn.linear_model import Ridge
import sklearn
sklearn.__version__
# Initialisation du model... |
6,280 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transfer Learning
Using the high level transfer learning APIs, you can easily customize pretrained models for feature extraction or fine-tuning.
In this notebook, we will use a pre-trained ... | Python Code:
import re
from bigdl.dllib.nn.criterion import CrossEntropyCriterion
from pyspark.ml import Pipeline
from pyspark.sql.functions import col, udf
from pyspark.sql.types import DoubleType, StringType
from bigdl.dllib.nncontext import *
from bigdl.dllib.feature.image import *
from bigdl.dllib.keras.layers impo... |
6,281 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Assigning particles unique IDs and removing particles from the simulation
For some applications, it is useful to keep track of which particle is which, and this can get jumbled up when parti... | Python Code:
import rebound
import numpy as np
def setupSimulation(Nplanets):
sim = rebound.Simulation()
sim.integrator = "ias15" # IAS15 is the default integrator, so we don't need this line
sim.add(m=1.,id=0)
for i in range(1,Nbodies):
sim.add(m=1e-5,x=i,vy=i**(-0.5),id=i)
sim.move_to_com(... |
6,282 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time Series Prediction with BQML and AutoML
Objectives
1. Learn how to use BQML to create a classification time-series model using CREATE MODEL.
2. Learn how to use BQML to create a linear... | Python Code:
PROJECT = !(gcloud config get-value core/project)
PROJECT = PROJECT[0]
%env PROJECT = {PROJECT}
%env REGION = "us-central1"
Explanation: Time Series Prediction with BQML and AutoML
Objectives
1. Learn how to use BQML to create a classification time-series model using CREATE MODEL.
2. Learn how to use BQM... |
6,283 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Librairies
Step1: read file content
Step2: Dots seem to follow a line, we could have done a correlation test to check if the two variabes are linked. Now we transform the data matrix into ... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Librairies
End of explanation
data = pd.read_csv('ex1data1.txt', header=None, names=['population', 'profit'])
data.head()
data.plot.scatter('population', 'profit')
Explanation: read file content
End of ex... |
6,284 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Corpus callosum's shape signature for segmentation error detection in large datasets
Abstract
Corpus Callosum (CC) is a subcortical, white matter structure with great importance in clinical ... | Python Code:
## Functions
import sys,os
import copy
path = os.path.abspath('../dev/')
if path not in sys.path:
sys.path.append(path)
import bib_mri as FW
import numpy as np
import scipy as scipy
import scipy.misc as misc
import matplotlib as mpl
import matplotlib.pyplot as plt
from numpy import genfromtxt
import p... |
6,285 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Implementing a Neural Network
In this exercise we will develop a neural network with fully-connected layers to perform classification, and test it out on the CIFAR-10 dataset.
Step2: ... | Python Code:
import os
os.chdir(os.getcwd() + '/..')
# Run some setup code for this notebook
import random
import numpy as np
import matplotlib.pyplot as plt
from utils.data_utils import load_CIFAR10
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpol... |
6,286 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The multi-armed bandit problem
Step1: The Bandits
Here we define our bandits. For this example we are using a four-armed bandit. The pullBandit function generates a random number from a nor... | Python Code:
import tensorflow as tf
import numpy as np
Explanation: The multi-armed bandit problem
End of explanation
bandits = [0.2, 0, -0.2, -5] # Random order
num_bandits = len(bandits)
def pullBandit(bandit):
# Get a random number
result = np.random.randn(1)
if result > bandit:
# return a posi... |
6,287 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Customising static orbit plots
The default styling for plots works pretty well however sometimes you may need to change things. The following will show you how to change the style of your pl... | Python Code:
from astropy.time import Time
import matplotlib.pyplot as plt
from poliastro.plotting import StaticOrbitPlotter
from poliastro.frames import Planes
from poliastro.bodies import Earth, Mars, Jupiter, Sun
from poliastro.twobody import Orbit
epoch = Time("2018-08-17 12:05:50", scale="tdb")
plotter = StaticOrb... |
6,288 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load Data
We will load the sociopatterns network data for this notebook. From the Konect website
Step1: Hubs
Step2: API Note
Step3: Approach 2
Step4: If you inspect the dictionary closel... | Python Code:
# Load the sociopatterns network data.
G = cf.load_sociopatterns_network()
# How many nodes and edges are present?
len(G.nodes()), len(G.edges())
Explanation: Load Data
We will load the sociopatterns network data for this notebook. From the Konect website:
This network describes the face-to-face behavior o... |
6,289 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<figure>
<IMG SRC="https
Step1: Load the head observations
The first step in time series analysis is to load a time series of head observations. The time series needs to be stored as a pa... | Python Code:
import pandas as pd
import pastas as ps
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: <figure>
<IMG SRC="https://raw.githubusercontent.com/pastas/pastas/master/doc/_static/TUD_logo.png" WIDTH=250 ALIGN="right">
</figure>
Time Series Analysis with Pastas
Developed by M... |
6,290 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This Jupyter notebook should be used in conjunction with pypeoutgoing.ipynb.
Run through the following cells...
Step1: Then run the following cell and send some values from pypeoutgoing.ipy... | Python Code:
import os, sys
sys.path.append(os.path.abspath('../../main/python'))
import thalesians.tsa.pypes as pypes
pype = pypes.Pype(pypes.Direction.INCOMING, name='EXAMPLE', port=5758); pype
Explanation: This Jupyter notebook should be used in conjunction with pypeoutgoing.ipynb.
Run through the following cells...... |
6,291 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Template for test
Step1: Controlling for Random Negatve vs Sans Random in Imbalanced Techniques using K acytelation.
Training data is from CUCKOO group and benchmarks are from dbptm.
Step2:... | Python Code:
from pred import Predictor
from pred import sequence_vector
from pred import chemical_vector
Explanation: Template for test
End of explanation
par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"]
for i in par:
print("y", i)
y = Predictor()
y.load_data(file="Data/Train... |
6,292 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Aprendizaje de variedades
Una de las debilidades del PCA es que no puede detectar características no lineales. Un conjunto de algoritmos que evitan este problema son los algoritmos de aprend... | Python Code:
from sklearn.datasets import make_s_curve
X, y = make_s_curve(n_samples=1000)
from mpl_toolkits.mplot3d import Axes3D
ax = plt.axes(projection='3d')
ax.scatter3D(X[:, 0], X[:, 1], X[:, 2], c=y)
ax.view_init(10, -60);
Explanation: Aprendizaje de variedades
Una de las debilidades del PCA es que no puede dete... |
6,293 | 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... |
6,294 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
Step1: In order to get you familiar with graph ideas,
I have deliberately chosen to steer away from
the more pedantic matters
of loading graph data to and from disk.
That said,... | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo(id="3sJnTpeFXZ4", width="100%")
Explanation: Introduction
End of explanation
from pyprojroot import here
Explanation: In order to get you familiar with graph ideas,
I have deliberately chosen to steer away from
the more pedantic matters
of loading graph... |
6,295 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Crime
Boilerplate
Step1: Read the Data
Step2: ## Transforming the Original Data Using a Mapped Dictionary
Step3: Linear Regression through Ordinary Least Squares
Step4: So only in Distri... | Python Code:
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.formula.api import ols
from statsmodels.formula.api import logit
import pylab as pl
import seaborn as sns
mpl.style.use('fivethirtyeight')
%matplotlib inline
Explana... |
6,296 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Registration Initialization
Step1: Loading Data
Note
Step2: Register using centered transform initializer (assumes orientation is similar)
Step3: Visually evaluate the results using a li... | Python Code:
import SimpleITK as sitk
# If the environment variable SIMPLE_ITK_MEMORY_CONSTRAINED_ENVIRONMENT is set, this will override the ReadImage
# function so that it also resamples the image to a smaller size (testing environment is memory constrained).
%run setup_for_testing
import os
import numpy as np
from ip... |
6,297 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Algo - Calculs de surface et autres calculs
C'est l'histoire d'une boucle, puis d'une autre, puis enfin d'un couple de boucles, voire d'un triplé.
Step1: Enoncé
Exercice 1
Step2: 1.1 En u... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: Algo - Calculs de surface et autres calculs
C'est l'histoire d'une boucle, puis d'une autre, puis enfin d'un couple de boucles, voire d'un triplé.
End of explanation
def surface_cerle(r):
# ...
return 0.
Explanation: Enonc... |
6,298 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: ODE to joy
Jens Hahn - 27/05/2016
Countinuous deterministic modelling with differential equations
Numerical integration
Every numerical procedure to solve an ODE is based on the dis... | Python Code:
import numpy as np
# Lotka Volterra model
# initialise parameters
k1 = 1.5
k2 = 1.
k3 = 3.
k4 = 1.
def my_dxdt(s,t):
Function returns values of derivatives of Lotka Volterra model
return [k1*s[0] - k2*s[0]*s[1], - k3*s[1]+k4*s[0]*s[1]]
def my_euler_solver(dxdt, s0, timegrid):
Imp... |
6,299 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Jupyter Notebook é uma ferramenta excelente para
Step1: Como você viu, uma célula de código pode ter várias linhas de código em Python (ou de outra linguagem suportada), incluindo definiçõe... | Python Code:
def fatorial(n):
return 1 if n < 2 else n * fatorial(n-1)
fatorial(42)
Explanation: Jupyter Notebook é uma ferramenta excelente para:
Exploração interativa de dados;
Análise de dados (i.e. Analytics);
Aprender Python, R, Julia e dezenas de outras linguagens suportadas
O nome Jupyter é mistura de Julia,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.