Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
9,100 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introducing the Keras Sequential API
Learning Objectives
1. Learn how to use feature columns in a Keras model
1. Build a DNN model using the Keras Sequential API
1. Learn how to train ... | Python Code:
# Ensure the right version of Tensorflow is installed.
!pip freeze | grep tensorflow==2.0 || pip install tensorflow==2.0
Explanation: Introducing the Keras Sequential API
Learning Objectives
1. Learn how to use feature columns in a Keras model
1. Build a DNN model using the Keras Sequential API
1. Le... |
9,101 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create the siamese net feature extraction model
Step1: Restore from checkpoint and calc the features from all of train data
Step2: Searching for similar test images from trainset based on ... | Python Code:
img_placeholder = tf.placeholder(tf.float32, [None, 28, 28, 1], name='img')
net = mnist_model(img_placeholder, reuse=False)
Explanation: Create the siamese net feature extraction model
End of explanation
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
... |
9,102 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Python Tour of Data Science
Step1: 2 Vectorization
First step
Step2: Exploration question
Step3: 3 Pre-processing
The independant variables $X$ are the bags of words.
The target $y$ is ... | Python Code:
import pandas as pd
import numpy as np
from IPython.display import display
import os.path
folder = os.path.join('..', 'data', 'social_media')
# Your code here.
Explanation: A Python Tour of Data Science: Data Acquisition & Exploration
Michaël Defferrard, PhD student, EPFL LTS2
Exercise: problem definition
... |
9,103 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setup
Locally store your Planet API key and start a session. Create a funciton to print json objects.
Step1: Stats
Here you will perform a statistics search of planets database, while getti... | Python Code:
import os
import json
import requests
PLANET_API_KEY = os.getenv('PL_API_KEY')
# Setup Planet Data API base URL
URL = "https://api.planet.com/data/v1"
# Setup the session
session = requests.Session()
# Authenticate
session.auth = (PLANET_API_KEY, "")
res = session.get(URL)
res.status_code
# Helper function... |
9,104 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Get the results of a single run
Step1: Done. Let's test the reshape_by_symbol function
Step2: So, the reshape_by_symbol function seems to work with run_single_val. It could be added to it.... | Python Code:
from predictor import evaluation as ev
from predictor.dummy_mean_predictor import DummyPredictor
predictor = DummyPredictor()
y_train_true_df, y_train_pred_df, y_val_true_df, y_val_pred_df = ev.run_single_val(x, y, ahead_days, predictor)
print(y_train_true_df.shape)
print(y_train_pred_df.shape)
print(y_val... |
9,105 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
General Imports
!! IMPORTANT !!
If you did NOT install opengrid with pip,
make sure the path to the opengrid folder is added to your PYTHONPATH
Step1: Houseprint
Step2: A Houseprint objec... | Python Code:
import os
import inspect
import sys
import pandas as pd
import charts
from opengrid.library import houseprint
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = 16,8
Explanation: General Imports
!! IMPORTANT !!
If you did NOT install opengrid with pip,
make sure the path t... |
9,106 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color='mediumblue'> Lists
<font color='midnightblue'> Example
Step1: <font color='midnightblue'> Example
Step2: <font color='midnightblue'> Example
Step3: <font color='mediumblue'> ... | Python Code:
list1 = [10, 12, 14, 16, 18]
print(list1[0]) # Index starts at 0
print(list1[-1]) # Last index at -1
Explanation: <font color='mediumblue'> Lists
<font color='midnightblue'> Example: Indexed
End of explanation
print(list1[0:3]) # Slicing: exclusive of end value
# i.e. get ... |
9,107 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Disaggregation - Hart Active data only
Customary imports
Step1: show versions for any diagnostics
Step2: Load dataset
Step3: Use 4 working days for training
Step4: Training
We'll now do ... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
from os.path import join
from pylab import rcParams
import matplotlib.pyplot as plt
rcParams['figure.figsize'] = (13, 6)
plt.style.use('ggplot')
#import nilmtk
from nilmtk import DataSet, TimeFrame, MeterGroup, HDFDataStore
from nilmtk.disaggregate.... |
9,108 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Arbitrary number of channels parametrization
This notebook uses the new param.image parametrization that takes any number of channels.
Step2: Testing params
The following params are introdu... | Python Code:
import numpy as np
import tensorflow as tf
import lucid.modelzoo.vision_models as models
from lucid.misc.io import show
import lucid.optvis.objectives as objectives
import lucid.optvis.param as param
import lucid.optvis.render as render
import lucid.optvis.transform as transform
model = models.InceptionV1(... |
9,109 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table class="ee-notebook-buttons" align="left"><td>
<a target="_blank" href="http
Step1: Authenticate and initialize
Run the ee.Authenticate function to authenticate your access to Earth ... | Python Code:
import ee
Explanation: <table class="ee-notebook-buttons" align="left"><td>
<a target="_blank" href="http://colab.research.google.com/github/google/earthengine-api/blob/master/python/examples/ipynb/ee-api-colab-setup.ipynb">
<img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Go... |
9,110 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating MNE's data structures from scratch
MNE provides mechanisms for creating various core objects directly from
NumPy arrays.
Step1: Creating
Step2: You can also supply more extensive... | Python Code:
import mne
import numpy as np
Explanation: Creating MNE's data structures from scratch
MNE provides mechanisms for creating various core objects directly from
NumPy arrays.
End of explanation
# Create some dummy metadata
n_channels = 32
sampling_rate = 200
info = mne.create_info(n_channels, sampling_rate)
... |
9,111 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Neural Network for Image Classification
Step1: 2 - Dataset
You will use the same "Cat vs non-Cat" dataset as in "Logistic Regression as a Neural Network" (Assignment 2). The model you ... | Python Code:
import time
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
from dnn_app_utils_v2 import *
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
p... |
9,112 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing IMDB Data in Keras - Solution
Step1: 1. Loading the data
This dataset comes preloaded with Keras, so one simple command will get us training and testing data. There is a parameter... | Python Code:
# Imports
import numpy as np
import keras
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.preprocessing.text import Tokenizer
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(42)
Explanation: Analyzing IMDB ... |
9,113 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulating Diffusion on Surfaces
The simulation scripts described in this chapter is available at STEPS_Example repository.
This chapter introduces how to model and simulate surface diffusio... | Python Code:
import steps.model as smodel
import steps.geom as stetmesh
import steps.utilities.meshio as smeshio
import steps.rng as srng
import steps.solver as solvmod
import pylab
import math
Explanation: Simulating Diffusion on Surfaces
The simulation scripts described in this chapter is available at STEPS_Example r... |
9,114 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Boundary value problem
Problem
We are going to solve ordinary differential equation of 2-nd order with boundary values of different types
$$
y'' + p(x)y' + q(x) = f(x),\
\alpha y'(a) + \beta... | Python Code:
def thomas(a, b, c, d):
n = len(d)
A = np.empty_like(d)
B = np.empty_like(d)
A[0] = -c[0]/b[0]
B[0] = d[0]/b[0]
for i in range(1, n):
A[i] = -c[i] / (b[i] + a[i]*A[i - 1])
B[i] = (d[i] - a[i]*B[i - 1])/(b[i] + a[i]*A[i - 1])
y = np.empty_like(d)
y[n - 1] = B[... |
9,115 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
dbcollection package usage tutorial
This tutorial shows how to use the dbcollection package to load and manage datasets in a simple and easy way. It is divided into two main topics
Step1: S... | Python Code:
# import tutorial packages
from __future__ import print_function
import os
import sys
import numpy as np
import dbcollection.manager as dbclt
Explanation: dbcollection package usage tutorial
This tutorial shows how to use the dbcollection package to load and manage datasets in a simple and easy way. It is ... |
9,116 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p style="text-align
Step1: Bad match dates
Step2: Setup MySQL connection
Login credentials for connecting to MySQL database.
Step3: All import statements here.
Step4: Try to connect to ... | Python Code:
import IPython as IP
IP.display.Image("example_of_name_matching_problems_mod.png",width=400,height=200,embed=True)
Explanation: <p style="text-align: center"> Merging "odds" and "player" data</p>
Author: Carl Toews
File: merge_datasets.ipynb
Description:
An obvious metric for assessing the quality ... |
9,117 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
感情 (肯定/否定) のラベル付けをされた,25,000のIMDB映画レビューのデータセット.レビューは前処理済みで,各レビューは単語のインデックス(整数)のシーケンスとしてエンコードされています.便宜上,単語はデータセットにおいての出現頻度によってインデックスされています.そのため例えば,整数"3"はデータの中で3番目に頻度が多い単語にエンコードされます.これによって"上位2... | Python Code:
print('Loading data...')
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
Explanation: 感情 (肯定/否定) のラベル付けをされた,25,000のIMDB映画レビューのデータセット.レビューは前処理済みで,各レビューは単語のインデックス(整数)のシーケンスとしてエンコードされています.便宜上,単語はデータセットにおいての出現頻度によってインデックスされています.そのため例えば,整数"3"はデータの中で3番目に頻度が多い単語にエンコードされます.これによって"上位20... |
9,118 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Probability Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: TensorFlow Probability의 가우시안 프로세스 회귀
<table class="tfo-notebook-but... | 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... |
9,119 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Word2Vec Tutorial
In case you missed the buzz, word2vec is a widely featured as a member of the “new wave” of machine learning algorithms based on neural networks, commonly referred to as "d... | Python Code:
# import modules & set up logging
import gensim, logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = [['first', 'sentence'], ['second', 'sentence']]
# train word2vec on the two sentences
model = gensim.models.Word2Vec(sentences, min_count=1)
Expla... |
9,120 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualing The Paradise Papers With Python And Neo4j
Connect to Neo4j from Python
Create some Pandas Dataframes from Cypher queries
Matplotlib visualizations from Dataframe
Bokeh chord diagra... | Python Code:
# !pip install neo4j-driver
# !pip install pandas
# !pip install bokeh
from neo4j.v1 import GraphDatabase
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline
plt.figure(dpi=300)
Explanation: Visualing The Paradise Papers With Python And Neo4j
Connect to Neo4j from Python
Create some Pand... |
9,121 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MLP for CIFAR10
Multi-Layer Perceptron (MLP) is a simple neural network model that can be used for classification tasks.
In this demo, we will train a 3-layer MLP on the CIFAR10 dataset. We... | Python Code:
import torch
import torchvision
import wandb
import math
from torch import nn
from einops import rearrange
from argparse import ArgumentParser
from pytorch_lightning import LightningModule, Trainer, Callback
from pytorch_lightning.loggers import WandbLogger
from torchmetrics.functional import accuracy
from... |
9,122 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Thermal equilibrium of interacting dimer
In this notebook we simulate the thermal equilibrium (Boltzmann distrubion) of two interacting magnetic nanoparticles (dimer), coupled with dipolar i... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
%matplotlib inline
Explanation: Thermal equilibrium of interacting dimer
In this notebook we simulate the thermal equilibrium (Boltzmann distrubion) of two interacting magnetic nanoparticles (dimer), coupled wi... |
9,123 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create Fake Index Data
Step1: Build and run ERC Strategy
You can read more about ERC here.
http | Python Code:
mean = np.array([0.05/252 + 0.02/252, 0.03/252 + 0.02/252])
volatility = np.array([0.2/np.sqrt(252), 0.05/np.sqrt(252)])
variance = np.power(volatility,2)
correlation = np.array(
[
[1, 0.25],
[0.25,1]
]
)
covariance = np.zeros((2,2))
for i in range(len(variance)):
for j in range... |
9,124 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: 유니코드 문자열
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: tf.string 데이터 타입
텐서플로의 기본 tf.strin... | 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... |
9,125 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Paillier Homomorphic Encryption Example
DISCLAIMER
Step1: Basic Ops
Step2: Key SerDe
Step3: Value SerDe | Python Code:
from syft.he.paillier import KeyPair, PaillierTensor
from syft import TensorBase
import numpy as np
Explanation: Paillier Homomorphic Encryption Example
DISCLAIMER: This is a proof-of-concept implementation. It does not represent a remotely product ready implementation or follow proper conventions for secu... |
9,126 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'mri', 'mri-esm2-0', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: MRI
Source ID: MRI-ESM2-0
Topic: Ocnbgchem
Sub-Topics: Tracers.
Prop... |
9,127 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring the TTC Subway Real-time API
The API we're pulling data from is what supports the TTC's Next Train Arrivals page. With a bit of exploration through your browser's developer console... | Python Code:
import requests #to handle http requests to the API
from psycopg2 import connect
stationid = 3
#We'll find out the full range of possible stations further down.
lineid = 1
#[1,2,4]
# The url for the request
base_url = "http://www.ttc.ca/Subway/loadNtas.action"
# Our query parameters for this API request
... |
9,128 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Post-training dynamic range quantization
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Tr... | 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... |
9,129 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
OIQ-Exam-Question-1 (Version 2)
Technical exam question from Ordre des ingénieurs du Québec. Obviously meant to be done using moment-distribution, but even easier using slope-deflection. T... | Python Code:
from sympy import *
init_printing(use_latex='mathjax')
from IPython import display
display.SVG('oiq-exam-1.svg')
from sdutil2 import SD, FEF
var('EI theta_a theta_b theta_c theta_d')
Mab,Mba,Vab,Vba = SD(6,EI,theta_a,theta_b) + FEF.p(6,180,4)
Mbc,Mcb,Vbc,Vcb = SD(8,2*EI,theta_b,theta_c) + FEF.udl(8,45)
Mcd... |
9,130 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep learning using fastai library
(https
Step1: Below picture is not an iceberg
Step2: Get rgb of image using color composite function
Thanks to MadScientist for color composite.
Here is ... | Python Code:
# Put these at the top of every notebook, to get automatic reloading and inline plotting
%reload_ext autoreload
%autoreload 2
%matplotlib inline
# This file contains all the main external libs we'll use
import numpy as np
import pandas as pd
from fastai.imports import *
from sklearn.model_selection import ... |
9,131 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting started with mne.Report
This tutorial covers making interactive HTML summaries with
Step1: Before getting started with
Step2: This report yields a textual summary of the
Step3: ... | Python Code:
import os
import mne
Explanation: Getting started with mne.Report
This tutorial covers making interactive HTML summaries with
:class:mne.Report.
:depth: 2
As usual we'll start by importing the modules we need and loading some
example data <sample-dataset>:
End of explanation
path = mne.datasets.sa... |
9,132 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Play Notebook
Import Data
The first dataset we will import is the Iris Dataset
Step1: Neural Network
First we train te network on x dataset
Step2: If you already trained the dataset there ... | Python Code:
from sklearn import datasets
X, y = datasets.make_hastie_10_2(n_samples=12000, random_state=1)
#make random test and train set
from sklearn import cross_validation
from sklearn.cross_validation import train_test_split
train_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.3, random_state=0)
... |
9,133 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Epidemics
During this seminar we will numerically solve systems of differential equations of SI, SIS and SIR models. <br> This experience is going to help us as we switch to network models. ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
%matplotlib inline
def si_model( z0, T, **kwargs) :
beta = kwargs['beta']
t = np.arange( T, step = 0.1 )
si = lambda z ,t, beta : np.array([
-beta * z[0] * z[1],
beta * z[0] * z[1]])
retur... |
9,134 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
English localization
Static list of correct answers in English.
Additional columns
Language column
Preparation for temporalities
Renaming
List of answers
Scientific questions
Demographic que... | Python Code:
%run "../Utilities/Preparation.ipynb"
processGFormEN = not ('gformEN' in globals())
if processGFormEN:
# tz='Europe/Berlin' time
dateparseGForm = lambda x: pd.Timestamp(x.split(' GMT')[0], tz='Europe/Berlin').tz_convert('utc')
if processGFormEN:
csvEncoding = 'utf-8'
gformPath = "../../data... |
9,135 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ncar', 'sandbox-3', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: NCAR
Source ID: SANDBOX-3
Topic: Atmoschem
Sub-Topics: Transport, Emi... |
9,136 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Recommender systems
Описание задачи
Небольшой интернет-магазин попросил вас добавить ранжирование товаров в блок "Смотрели ранее" - в нём теперь надо показывать не последние просмотренные по... | Python Code:
from __future__ import division, print_function
import numpy as np
import pandas as pd
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
Explanation: Recommender systems
Описание задачи
Небольшой интернет-магазин попросил вас добавить ранжирование то... |
9,137 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Unsupervised Learning
Davis SML
Step2: TFIDF vectorization
document vectorization counts the proportion of words in document
$X_{i,j}$ is the "proportion" of word j in document i
tfidf indi... | Python Code:
from lxml import html, etree
import numpy as np
from sklearn import cluster, feature_extraction, metrics, preprocessing, decomposition
import collections
import nltk
import pandas as pd
import plotnine as p9
# nltk.download()
# Download Corpora -> stopwords, Models -> punkt
from nltk.corpus import stopword... |
9,138 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Random Processes in Computational Physics
The contents of this Jupyter Notebook lecture notes are
Step1: Random Processes in Physics
Examples of physical processes that are/can be modelled ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Random Processes in Computational Physics
The contents of this Jupyter Notebook lecture notes are:
Introduction to Random Numbers in Physics
Random Number Generation
Python Packages for Random Numbers
Coding for Probability... |
9,139 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Load Boston Housing Dataset
Step2: Fit A Linear Regression
Step3: View Intercept Term
Step4: View Coefficients | Python Code:
# Load libraries
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston
import warnings
# Suppress Warning
warnings.filterwarnings(action="ignore", module="scipy", message="^internal gelsd")
Explanation: Title: Linear Regression Using Scikit-Learn
Slug: linear_regression... |
9,140 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generate a random (stable) IIR filter
Step1: Self Tuning Regulator
NLMS IIR System Identification
Step2: Let's try fixed regulation with the estimated filter
Step3: works with some bias
N... | Python Code:
B_len = np.random.randint(5, 10)
A_len = np.random.randint(5, 10)
B = np.random.randn(B_len)
A = np.random.randn(A_len)
def stable_poly(length):
# all roots inside unit circle and real valued polynomial
roots = np.random.rand((length - 1) // 2) * np.exp(np.random.rand((length - 1) // 2) * 2j *... |
9,141 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Is there any package in Python that does data transformation like Box-Cox transformation to eliminate skewness of data? | Problem:
import numpy as np
import pandas as pd
import sklearn
data = load_data()
assert type(data) == np.ndarray
from sklearn import preprocessing
pt = preprocessing.PowerTransformer(method="box-cox")
box_cox_data = pt.fit_transform(data) |
9,142 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Data
Step2: Select Name And Ages Only When The Name Is Known | Python Code:
# Ignore
%load_ext sql
%sql sqlite://
%config SqlMagic.feedback = False
Explanation: Title: Ignoring Null or Missing Values
Slug: ignoring_null_values
Summary: Ignoring Null or Missing Values in SQL.
Date: 2017-01-16 12:00
Category: SQL
Tags: Basics
Authors: Chris Albon
Note: This tutorial was written... |
9,143 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Few things to keep aware of.
People acessing things at the same time, take the earlier user's request, then discard the other guys request and then continue the chain.
Step2: create... | Python Code:
#Intialization - creates db and then sends an empty response
s = {
"Details": {
"Username" : "Anonymous",
"Story" : "Rabbit Story"
},
"Characters": [
{
"Name": "Rabbit",
"Position": "Right",
"Social" : 0.3,
"Emotion": "Happy"
},
{
"Name": "Turtle"... |
9,144 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PROV-O Diagram Rendering Example
This example takes a PROV-O activity graph and uses the PROV Python library, which is an implementation of the Provenance Data Model by the World Wide Web Co... | Python Code:
#if you need to install dependencies, do so in this cell
!pip install pydot prov
!conda install -y python-graphviz
Explanation: PROV-O Diagram Rendering Example
This example takes a PROV-O activity graph and uses the PROV Python library, which is an implementation of the Provenance Data Model by the World ... |
9,145 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dynamics of multiple spin enembles
Step1: 1) Collective processes only (QuTiP $\texttt{jmat}$)
System properties - QuTiP jmat()
QuTiP's jmat() functions span the symmetric (N+1)-dimensional... | Python Code:
from qutip import *
from qutip.piqs import *
import matplotlib.pyplot as plt
from scipy import constants
Explanation: Dynamics of multiple spin enembles: two driven-dissipative ensembles
Notebook author: Nathan Shammah (nathan.shammah at gmail.com)
We use the Permutational Invariant Quantum Solver (PIQS) l... |
9,146 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
week1 - Доверительные интервалы - quiz
1.
Давайте уточним правило трёх сигм. Утверждение
Step1: Task 5
Step2: Task 6, 7
Step3: Task 8 | Python Code:
import scipy.stats
scipy.stats.norm.ppf(0.9985)
Explanation: week1 - Доверительные интервалы - quiz
1.
Давайте уточним правило трёх сигм. Утверждение: 99.7% вероятностной массы случайной величины X∼N(μ,σ2) лежит в интервале μ±c⋅σ. Чему равно точное значение константы c? Округлите ответ до четырёх знаков по... |
9,147 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Methods for testing and plotting the functios in Potapov.py
Step1: Tests
In each of these tests, we construct a Blaschke-Potapov product. We apply our procedure on the resulting function an... | Python Code:
import Potapov as P
import numpy as np
import matplotlib.pyplot as plt
import numpy.linalg as la
%pylab inline
def plot(L,dx,func,(i,j),*args):
'''
This function plots func(F(z)) for z*1j from -L to L for each function
F in args.
'''
x = np.linspace(-L,L,2.*L/dx)
for arg in args:
... |
9,148 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dénes Csala
MCC, 2022
Based on Elements of Data Science (Allen B. Downey, 2021) and Python Data Science Handbook (Jake VanderPlas, 2018)
License
Step1: Introducing Principal Component Ana... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
plt.style.use('seaborn')
Explanation: Dénes Csala
MCC, 2022
Based on Elements of Data Science (Allen B. Downey, 2021) and Python Data Science Handbook (Jake Vander... |
9,149 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
pycellerator demo.ipynb
demonstrates some basic features of pycellerator
Step1: Read, Translate, and Solve a Cellerator Model
Step2: print first 10 values of t and s to demonstrate content... | Python Code:
from cellerator import cellerator as c
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
%matplotlib inline
Explanation: pycellerator demo.ipynb
demonstrates some basic features of pycellerator
End of explanation
model="Gold1.model"
c.PrintModel(model)
c.PrintODES(model)
t, v, s ... |
9,150 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
By listing the first six prime numbers
Step1: <!-- TEASER_END -->
Step2: This implementation scales quite well, and has good space and time complexity. | Python Code:
from itertools import count, islice
from collections import defaultdict
def _sieve_of_eratosthenes():
factors = defaultdict(set)
for n in count(2):
if factors[n]:
for m in factors.pop(n):
factors[n+m].add(m)
else:
factors[n*n].add(n)
... |
9,151 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Graph Neural Nets with JAX/jraph
Lisa Wang, DeepMind (wanglisa@deepmind.com), Nikola Jovanović, ETH Zurich (nikola.jovanovic@inf.ethz.ch)
Colab Runtime
Step2: Fundamental Gr... | Python Code:
!pip install git+https://github.com/deepmind/jraph.git
!pip install flax
!pip install dm-haiku
# Imports
%matplotlib inline
import functools
import matplotlib.pyplot as plt
import jax
import jax.numpy as jnp
import jax.tree_util as tree
import jraph
import flax
import haiku as hk
import optax
import pickle... |
9,152 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
https
Step1: Step 0 - hyperparams
vocab_size is all the potential words you could have (classification for translation case)
and max sequence length are the SAME thing
decoder RNN hidden un... | Python Code:
from __future__ import division
import tensorflow as tf
from os import path
import numpy as np
import pandas as pd
import csv
from sklearn.model_selection import StratifiedShuffleSplit
from time import time
from matplotlib import pyplot as plt
import seaborn as sns
from mylibs.jupyter_notebook_helper impor... |
9,153 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PerfForesightConsumerType
Step1: The module HARK.ConsumptionSaving.ConsIndShockModel concerns consumption-saving models with idiosyncratic shocks to (non-capital) income. All of the models... | Python Code:
# Initial imports and notebook setup, click arrow to show
from copy import copy
import matplotlib.pyplot as plt
import numpy as np
from HARK.ConsumptionSaving.ConsIndShockModel import PerfForesightConsumerType
from HARK.utilities import plot_funcs
mystr = lambda number: "{:.4f}".format(number)
Explanation:... |
9,154 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistic Regression with Hyperparameter Optimization (scikit-learn)
<a href="https
Step1: Prepare Data
Step2: Prepare Hyperparameters
Step3: Run Validation
Step4: Pick the best hyperpara... | Python Code:
import warnings
from sklearn.exceptions import ConvergenceWarning
warnings.filterwarnings("ignore", category=ConvergenceWarning)
import itertools
import time
import numpy as np
import pandas as pd
from sklearn import model_selection
from sklearn import linear_model
from sklearn import metrics
Explanation: ... |
9,155 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
There are a thousand movie reviews for both
positive and
negetive
reviews
Step1: Now I need to store it as
python
documents = [
('pos', ['good', 'awesome', ....]),
('neg', ['ridicu... | Python Code:
movie_reviews.categories()
Explanation: There are a thousand movie reviews for both
positive and
negetive
reviews
End of explanation
documents = [(list(word for word in movie_reviews.words(fileid) if word not in stop_words), category)
for category in movie_reviews.categories()
for ... |
9,156 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nasa-giss', 'sandbox-2', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: NASA-GISS
Source ID: SANDBOX-2
Topic: Ocnbgchem
Sub-Topics: Trac... |
9,157 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Oregon Curriculum Network <br />
Discovering Math with Python
All Aboard the S Train!
Those of us exploring the geometry of thinking laid out in Synergetics (subtitled explorations in the ge... | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo("1VXDejQcAWY")
Explanation: Oregon Curriculum Network <br />
Discovering Math with Python
All Aboard the S Train!
Those of us exploring the geometry of thinking laid out in Synergetics (subtitled explorations in the geometry of thinking) will be familia... |
9,158 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Identificação de Cargas através de Representação Visual de Séries Temporais
Artigo
Step1: Pré-processamento dos dados
Step2: Parâmetros gerais dos dados utilizados na modelagem (treino e t... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot')
plt.rc('text', usetex=False)
from matplotlib.image import imsave
import pandas as pd
import pickle as cPickle
import os, sys
from math import *
from pprint import pprint
from tqdm import tqdm_notebook
from mpl_too... |
9,159 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Pytorch-Introduction" data-toc-modified-id="Pytorch-Introduction-1"><span cl... | Python Code:
# code for loading the format for the notebook
import os
# path : store the current path to convert back to it later
path = os.getcwd()
os.chdir(os.path.join('..', '..', 'notebook_format'))
from formats import load_style
load_style(css_style='custom2.css', plot_style=False)
os.chdir(path)
# 1. magic for in... |
9,160 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BUG report
To keep track of bugs we report them here so that they can be reproduced easily. Additionally, as soon as they are fixed they should disappear in this notebook. To each bug report... | Python Code:
%pylab nbagg
import sygma as s
reload(s)
s.__file__
!echo $PYTHONPATH
Explanation: BUG report
To keep track of bugs we report them here so that they can be reproduced easily. Additionally, as soon as they are fixed they should disappear in this notebook. To each bug report add time and your name. Add new b... |
9,161 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Applying unvectorized functions with apply_ufunc
This example will illustrate how to conveniently apply an unvectorized function func to xarray objects using apply_ufunc. func expects 1D num... | Python Code:
import xarray as xr
import numpy as np
xr.set_options(display_style="html") # fancy HTML repr
air = (
xr.tutorial.load_dataset("air_temperature")
.air.sortby("lat") # np.interp needs coordinate in ascending order
.isel(time=slice(4), lon=slice(3))
) # choose a small subset for convenience
ai... |
9,162 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building the train object
The job of the YAML parser is to instantiate the train object and everything inside of it. Looking at an example YAML file
Step1: We want to know how to build a mo... | Python Code:
!cat yaml_templates/replicate_8aug_online.yaml
Explanation: Building the train object
The job of the YAML parser is to instantiate the train object and everything inside of it. Looking at an example YAML file:
End of explanation
import pylearn2.space
final_shape = (48,48)
input_space = pylearn2.space.Compo... |
9,163 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Wright-Fisher model of mutation and random genetic drift
A Wright-Fisher model has a fixed population size N and discrete non-overlapping generations. Each generation, each individual has a ... | Python Code:
import numpy as np
import itertools
Explanation: Wright-Fisher model of mutation and random genetic drift
A Wright-Fisher model has a fixed population size N and discrete non-overlapping generations. Each generation, each individual has a random number of offspring whose mean is proportional to the individ... |
9,164 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to ITK Segmentation in SimpleITK Notebooks <a href="https
Step1: Thresholding
Thresholding is the most basic form of segmentation. It simply labels the pixels of an image based... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
from ipywidgets import interact, FloatSlider
import SimpleITK as sitk
# Download data to work on
%run update_path_to_download_script
from downloaddata import fetch_data as fdata
from myshow import myshow, myshow3d
img_T1 = sitk.ReadImage(fdata("nac-hncma-a... |
9,165 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Image Classification
In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile
cifar10_dataset_folder_path = 'cifar-10-batches-py'
# Use Floyd's cifar-10 dataset if present
floyd_cifa... |
9,166 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistic regression
In this example, I classify a popular database of seeds of 2 cathegories using a logistic regression algorithm.
This is a first simple example to show how to apply learni... | Python Code:
import warnings # avoid a bunch of warnings that we'll ignore
warnings.filterwarnings("ignore")
Explanation: Logistic regression
In this example, I classify a popular database of seeds of 2 cathegories using a logistic regression algorithm.
This is a first simple example to show how to apply learning algor... |
9,167 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 12 - Bayesian Approaches to Testing a Point ("Null") Hypothesis
12.2.2 - Are different groups equal or not?
Step1: Data
Using R, I executed lines 18-63 from the script OneOddGroupMo... | Python Code:
import pandas as pd
import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
import theano.tensor as tt
from matplotlib import gridspec
%matplotlib inline
plt.style.use('seaborn-white')
color = '#87... |
9,168 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
troubleshooting optimization performance in wobble
Step1: viewing more optimization info
Step2: toggle on the save_history keyword (which is False by default) to generate a wobble.History ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import warnings
with warnings.catch_warnings(): # suppress annoying TensorFlow FutureWarnings
warnings.filterwarnings("ignore",category=FutureWarning)
import wobble
Explanation: troubleshooting optimization performance in wobble
End of explanat... |
9,169 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The following code will print the prime numbers between 1 and 100. Modify the code so it prints every other prime number from 1 to 100
Original Code
Step1: Modified Code
Step2: Extra Credi... | Python Code:
for num in range(1,101): # for-loop through the numbers
prime = True # boolean flag to check the number for being prime
for i in range(2,num): # for-loop to check for "primeness" by checking for divisors other than 1
if (num%i==0): # logical test for the number having a divisor other than 1... |
9,170 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--BOOK_INFORMATION-->
<a href="https
Step1: Running k-means
Setting up $k$-means works exactly the same as in the previous examples. We tell the
algorithm to perform at most 10 iterations... | Python Code:
from sklearn.datasets import load_digits
digits = load_digits()
digits.data.shape
Explanation: <!--BOOK_INFORMATION-->
<a href="https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv" target="_blank"><img align="left" src="data/cover.jpg" style="width: 76px; height: 100px; back... |
9,171 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST Image Classification with TensorFlow on Cloud ML Engine
This notebook demonstrates how to implement different image models on MNIST using Estimator.
Note the MODEL_TYPE; change it to ... | Python Code:
import os
PROJECT = "cloud-training-demos" # REPLACE WITH YOUR PROJECT ID
BUCKET = "cloud-training-demos-ml" # REPLACE WITH YOUR BUCKET NAME
REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1
MODEL_TYPE = "linear" # "linear", "dnn", "dnn_dropout", or "cnn"
# do not change these
os.e... |
9,172 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sandstone Model
First we make a GeMpy instance with most of the parameters default (except range that is given by the project). Then we also fix the extension and the resolution of the domai... | Python Code:
# Setting extend, grid and compile
# Setting the extent
sandstone = GeoMig.Interpolator(696000,747000,6863000,6950000,-20000, 2000,
range_var = np.float32(110000),
u_grade = 9) # Range used in geomodeller
# Setting resolution of the grid
sandst... |
9,173 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Shelter Animal Outcomes 1
Data visualization
Step1: Overall it seems not many animals died of natural causes.
Doesn't seem like cats have nine lives unfortunately.
Probably because of thei... | Python Code:
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv('train.csv')
df.head()
df['AnimalType'].unique()
df.groupby(['AnimalType']).get_group('Cat').shape[0]
df.groupby(['AnimalType']).get_group('Dog').shape[0]
df['OutcomeType'].unique()
f, (ax1, ax2) =... |
9,174 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I'm using tensorflow 2.10.0. | Problem:
import tensorflow as tf
a = tf.constant(
[[0.3232, -0.2321, 0.2332, -0.1231, 0.2435, 0.6728],
[0.2323, -0.1231, -0.5321, -0.1452, 0.5435, 0.1722],
[0.9823, -0.1321, -0.6433, 0.1231, 0.023, 0.0711]]
)
def g(a):
return tf.argmax(a,axis=1)
result = g(a.__copy__()) |
9,175 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time Series Data
Step1: Working with Datetime Objects
Step2: The Datetime Object
Step3: Making a datetime indexed dataframe
Step4: Time Resampling
Step5: Quicker (but less controlled) w... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Time Series Data
End of explanation
from datetime import datetime
my_year = 2017
my_month = 10
my_day = 14
my_hour = 15
my_minute = 30
my_second = 15
Explanation: Working with Datetime Objects
End of expl... |
9,176 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploratory Data Analysis
In this tutorial we focus on two popular methods for exploring high dimensional datasets.
Principal Component Analysis
Latent Semantic Analysis
The first method is... | Python Code:
# We will first read the wine data headers
f = open("wine.data")
header = f.readlines()[0]
Explanation: Exploratory Data Analysis
In this tutorial we focus on two popular methods for exploring high dimensional datasets.
Principal Component Analysis
Latent Semantic Analysis
The first method is a general s... |
9,177 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro
Step1: Step #1 - Exploring/Cleaning the data
Summary of Statistics
Step2: Summary of Statistics [separated by class]
Step3: Data Visualization & Exploratory Analysis
Libraries used
... | Python Code:
import numpy as np
import pandas as pd
data = pd.read_csv('xAPI-Edu-Data.csv') #columns = ['Gender','Nationality', 'PlaceofBirth','StageID','GradeID','SectionID'
#,'Topic','Semester','Relation','RaisedHands','VisitedResources'
... |
9,178 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FloPy
Quick demo on how FloPy handles external files for arrays
Step1: make an hk and vka array. We'll save hk to files - pretent that you spent months making this important model property... | Python Code:
import os
import shutil
import flopy
import numpy as np
# make a model
nlay,nrow,ncol = 10,20,5
model_ws = os.path.join("data","external_demo")
if os.path.exists(model_ws):
shutil.rmtree(model_ws)
# the place for all of your hand made and costly model inputs
array_dir = os.path.join("data","array_... |
9,179 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Census income classification with scikit-learn
This example uses the standard <a href="https
Step1: Load the census data
Step2: Train a k-nearest neighbors classifier
Here we just train di... | Python Code:
import sklearn
import shap
Explanation: Census income classification with scikit-learn
This example uses the standard <a href="https://archive.ics.uci.edu/ml/datasets/Adult">adult census income dataset</a> from the UCI machine learning data repository. We train a k-nearest neighbors classifier using sci-ki... |
9,180 | 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', 'inm', 'sandbox-1', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: INM
Source ID: SANDBOX-1
Topic: Land
Sub-Topics: Soil, Snow, Vegetation, Energy ... |
9,181 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
检索,查询数据
这一节学习如何检索pandas数据。
Step1: Python和Numpy的索引操作符[]和属性操作符‘.’能够快速检索pandas数据。
然而,这两种方式的效率在pandas中可能不是最优的,我们推荐使用专门优化过的pandas数据检索方法。而这些方法则是本节要介绍的。
多种索引方式
pandas支持三种不同的索引方式:
* .loc 基于label进行索... | Python Code:
import numpy as np
import pandas as pd
Explanation: 检索,查询数据
这一节学习如何检索pandas数据。
End of explanation
dates = pd.date_range('1/1/2000', periods=8)
dates
df = pd.DataFrame(np.random.randn(8,4), index=dates, columns=list('ABCD'))
df
panel = pd.Panel({'one':df, 'two':df-df.mean()})
panel
Explanation: Python和Nump... |
9,182 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python MinBLEP Generator
An iPython port of the MinBLEP generator from experimentalscene
This notebook takes a bottom-up approach to reconstructing the algorithms described there, and uses n... | Python Code:
pylab inline
from itertools import izip
Explanation: Python MinBLEP Generator
An iPython port of the MinBLEP generator from experimentalscene
This notebook takes a bottom-up approach to reconstructing the algorithms described there, and uses numpy where possible (most notably for sinc, fft/ifft, and automa... |
9,183 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exact explainer
This notebooks demonstrates how to use the Exact explainer on some simple datasets. The Exact explainer is model-agnostic, so it can compute Shapley values and Owen values ex... | Python Code:
import shap
import xgboost
# get a dataset on income prediction
X,y = shap.datasets.adult()
# train an XGBoost model (but any other model type would also work)
model = xgboost.XGBClassifier()
model.fit(X, y);
Explanation: Exact explainer
This notebooks demonstrates how to use the Exact explainer on some si... |
9,184 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Siphon to query the NetCDF Subset Service
First we construct a TDSCatalog instance pointing to our dataset of interest, in
this case TDS' "Best" virtual dataset for the GFS global 0.5 ... | Python Code:
from siphon.catalog import TDSCatalog
best_gfs = TDSCatalog('http://thredds.ucar.edu/thredds/catalog/grib/NCEP/GFS/Global_0p5deg/catalog.xml?dataset=grib/NCEP/GFS/Global_0p5deg/Best')
best_gfs.datasets
Explanation: Using Siphon to query the NetCDF Subset Service
First we construct a TDSCatalog instance poi... |
9,185 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
VHM python implemented model structure
Import libraries and set image properties
Step1: Load observations
Step2: Model simulation
Parameter values, initial conditions and constant values
S... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
from matplotlib.ticker import LinearLocator
sns.set_style('whitegrid')
mpl.rcParams['font.size'] = 16
mpl.rcParams['axes.labelsize'] = 16
mpl.rcParams['xtick.labelsize'] ... |
9,186 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome to the first SimpleITK Notebook demo
Step1: Image Construction
There are a variety of ways to create an image. All images' initial value is well defined as zero.
Step2: Pixel Types... | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
import SimpleITK as sitk
Explanation: Welcome to the first SimpleITK Notebook demo:
SimpleITK Image Basics
This document will give a brief orientation to the SimpleITK Image class.
First we import the SimpleITK Python module. By convention our module is im... |
9,187 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow运作方式入门
代码:tensorflow/examples/tutorials/mnist/
本篇教程的目的,是向大家展示如何利用TensorFlow使用(经典)MNIST数据集训练并评估一个用于识别手写数字的简易前馈神经网络(feed-forward neural network)。我们的目标读者,是有兴趣使用TensorFlow的资深机器学习人士。
因此... | Python Code:
data_sets = input_data.read_data_sets(FLAGS.train_dir, FLAGS.fake_data)
Explanation: TensorFlow运作方式入门
代码:tensorflow/examples/tutorials/mnist/
本篇教程的目的,是向大家展示如何利用TensorFlow使用(经典)MNIST数据集训练并评估一个用于识别手写数字的简易前馈神经网络(feed-forward neural network)。我们的目标读者,是有兴趣使用TensorFlow的资深机器学习人士。
因此,撰写该系列教程并不是为了教大家机器学习领域的基础知识。
在学习... |
9,188 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Rotations" data-toc-modified-id="Rotations-1"><span class="toc-item-num">1 </span>Rotations</a></div><div class="lev1 toc... | Python Code:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import xgboost as xgb
from sklearn.metrics import roc_curve, auc
from sklearn.metrics import precision_recall_curve
df = pd.read_csv("iris.csv")
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href=... |
9,189 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Loading packages
Step1: Discrete Random Variables
In this section we show a few example of discrete random variables using Python.
The documentation for these routines can be found at
Step2... | Python Code:
import numpy as np
import matplotlib.pylab as py
import pandas as pa
import scipy.stats as st
np.set_printoptions(precision=2)
%matplotlib inline
Explanation: Loading packages
End of explanation
X=st.bernoulli(p=0.3)
X.rvs(100)
# Note that "high" is not included.
X=st.randint(low=1,high=5)
X.rvs(100)
Expla... |
9,190 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create dataframe
Step2: Make plot | Python Code:
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Title: Pie Chart In MatPlotLib
Slug: matplotlib_pie_chart
Summary: Pie Chart In MatPlotLib
Date: 2016-05-01 12:00
Category: Python
Tags: Data Visualization
Authors: Chris Albon
Based on: Sebastian Raschka.
Preliminaries
E... |
9,191 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
So far, you've learned how to use several SQL clauses. For instance, you know how to use SELECT to pull specific columns from a table, along with WHERE to pull rows that meet s... | Python Code:
#$HIDE_INPUT$
from google.cloud import bigquery
# Create a "Client" object
client = bigquery.Client()
# Construct a reference to the "nhtsa_traffic_fatalities" dataset
dataset_ref = client.dataset("nhtsa_traffic_fatalities", project="bigquery-public-data")
# API request - fetch the dataset
dataset = client... |
9,192 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing interstellar reddening and calculating synthetic photometry
Authors
Kristen Larson, Lia Corrales, Stephanie T. Douglas, Kelle Cruz
Input from Emir Karamehmetoglu, Pey Lian Lim, Kar... | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import astropy.units as u
from astropy.table import Table
from dust_extinction.parameter_averages import CCM89, F99
from synphot import units, config
from synphot import SourceSpectrum,SpectralElement,Observation,ExtinctionModel1D
from s... |
9,193 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Uncertainty Analysis in Bayesian Deep Learning with Tensorflow Probability
Here is astroNN, please take a look if you are interested in astronomy or how neural network applied in ... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format='retina'
import numpy as np
import pylab as plt
import random
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Dense, InputLayer, Activation
from tensorflow.keras... |
9,194 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Background Removal with Robust PCA
视频数据集 BMC | Background Models Challenge
https
Step1: LU 分解
将一个矩阵分解为一个上三角和下三角矩阵的乘积
Step2: The LU factorization is useful!
Solving Ax = b becomes LUx = b
S... | Python Code:
# 多行结果输出支持
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
Explanation: Background Removal with Robust PCA
视频数据集 BMC | Background Models Challenge
https://www.cs.utexas.edu/~chaoyeh/web_action_data/dataset_list.html
Background Subtraction Website
E... |
9,195 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center">TensorFlow Neural Network Lab</h1>
<img src="image/notmnist.png">
In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl... | Python Code:
import hashlib
import os
import pickle
from urllib.request import urlretrieve
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils import resample
from tqdm import tqdm
from zipfile import ZipFile
p... |
9,196 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anna KaRNNa
In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.... | Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
Explanation: Anna KaRNNa
In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.
This network ... |
9,197 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Question I (a)
queue = [A]
next = A; queue = [B,C]
next = B; queue = [C,I,D,E]
next = C; queue = [I,D,E,F,G]
next = I -> STOP
There are 4 iterations needed to find the Node I in mi... | Python Code:
grapha = {"A":["B", "C"],
"B":["D", "I", "E"],
"C":["G", "F"],
"D":["E","H"],
"E":["I"],
"F":["G","A"],
"H":[],
"I":["F"],
"G":[]}
def dfs(connects, start, searched):
looks if a searched node is in a... |
9,198 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
San Diego Burrito Analytics
Step1: Load data
Step2: Linear model 1
Step3: Linear model 2
Step4: Linear model 3. Predicting Yelp ratings
Can also do this for Google ratings
Note, interest... | Python Code:
%config InlineBackend.figure_format = 'retina'
%matplotlib inline
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import pandas as pd
import statsmodels.api as sm
import seaborn as sns
sns.set_style("white")
Explanation: San Diego Burrito Analytics: Linear models
Scott Cole
21 May 201... |
9,199 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Running Tune experiments with Skopt
In this tutorial we introduce Skopt, while running a simple Ray Tune experiment. Tune’s Search Algorithms integrate with Skopt and, as a result, allow you... | Python Code:
# !pip install ray[tune]
!pip install scikit-optimize==0.8.1
!pip install sklearn==0.18.2
Explanation: Running Tune experiments with Skopt
In this tutorial we introduce Skopt, while running a simple Ray Tune experiment. Tune’s Search Algorithms integrate with Skopt and, as a result, allow you to seamlessly... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.