Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
5,400 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Keras for Text Classification
Learning Objectives
Learn how to create a text classification datasets using BigQuery.
Learn how to tokenize and integerize a corpus of text for training in Ker... | Python Code:
import os
from google.cloud import bigquery
import pandas as pd
%load_ext google.cloud.bigquery
Explanation: Keras for Text Classification
Learning Objectives
Learn how to create a text classification datasets using BigQuery.
Learn how to tokenize and integerize a corpus of text for training in Keras.
Lear... |
5,401 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Think Bayes
Step2: Improving Reading Ability
From DASL(http
Step3: Exercise
Step9: Paintball
Step10: Exercise
Step11: Exercise | Python Code:
from __future__ import print_function, division
% matplotlib inline
import warnings
warnings.filterwarnings('ignore')
import math
import numpy as np
from thinkbayes2 import Pmf, Cdf, Suite, Joint
import thinkplot
Explanation: Think Bayes: Chapter 9
This notebook presents code and exercises from Think Bayes... |
5,402 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Сравнение метрик качества бинарной классификации
Programming Assignment
В этом задании мы разберемся, в чем состоит разница между разными метриками качества. Мы остановимся на задаче бинарно... | Python Code:
import numpy as np
from matplotlib import pyplot as plt
import seaborn
%matplotlib inline
Explanation: Сравнение метрик качества бинарной классификации
Programming Assignment
В этом задании мы разберемся, в чем состоит разница между разными метриками качества. Мы остановимся на задаче бинарной классификаци... |
5,403 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
waLBerla Tutorial 01
Step1: We have created an empty playing field consisting of 8-bit integer values, all initialized with zeros.
Now we write a function iterating over all cells, applying... | Python Code:
import numpy as np
def makeGrid(shape):
return np.zeros(shape, dtype=np.int8)
print(makeGrid( [5,5] ))
Explanation: waLBerla Tutorial 01: Basic data structures
Preface
This is an interactive Python notebook. The grey cells contain runnable Python code which can be executed with Ctrl+Enter. Make sure to... |
5,404 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sensitivity analysis with SALib
We have got the single parts now for the sensitivity analysis. We are now using the global sensitivity analysis methods of the Python package SALib, available... | Python Code:
from IPython.core.display import HTML
css_file = 'pynoddy.css'
HTML(open(css_file, "r").read())
%matplotlib inline
import sys, os
import matplotlib.pyplot as plt
import numpy as np
# adjust some settings for matplotlib
from matplotlib import rcParams
# print rcParams
rcParams['font.size'] = 15
# determine ... |
5,405 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: Create a function to download and save SRTM images using BMI_topography.
Step2: Make function to plot DEMs and drainage accumulation with shaded relief.
Step3: Compa... | Python Code:
import sys, time, os
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
from landlab.components import FlowAccumulator, PriorityFloodFlowRouter, ChannelProfiler
from landlab.io.netcdf import read_netcdf
from landlab.utils import get_watershed_mask
from landlab import imshowhs_grid,... |
5,406 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
02. Fetching binary data with urllib and unzipping files with zipfile
If you can get the web address, or URL, of a specific binary file that you found on some website, you can usually downlo... | Python Code:
#Import the two modules
import urllib
import zipfile
#Specify the URL of the resource
theURL = 'https://www2.census.gov/geo/tiger/TIGER2017/TRACT/tl_2017_38_tract.zip'
#Set a local filename to save the file as
localFile = 'tl_2017_38_tract.zip'
#The urlretrieve function downloads a file, saving it as the f... |
5,407 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this recipe, we're going to build taxonomic classifiers for amplicon sequencing. We'll do this for 16S using some scikit-learn classifiers.
Step1: We're going to work with the qiime-defa... | Python Code:
%pylab inline
from __future__ import division
import numpy as np
import pandas as pd
import skbio
import qiime_default_reference
Explanation: In this recipe, we're going to build taxonomic classifiers for amplicon sequencing. We'll do this for 16S using some scikit-learn classifiers.
End of explanation
###... |
5,408 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Sequential model
Author
Step1: When to use a Sequential model
A Sequential model is appropriate for a plain stack of layers
where each layer has exactly one input tensor and one output ... | Python Code:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
Explanation: The Sequential model
Author: fchollet<br>
Date created: 2020/04/12<br>
Last modified: 2020/04/12<br>
Description: Complete guide to the Sequential model.
Setup
End of explanation
# Define Sequential model ... |
5,409 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Supplementary tables
Setup
Step1: Table of non-synonymous variants
One row per alternate allele.
Step2: Table of haplotype tracking variants
One row per variant. Only biallelic obviously b... | Python Code:
%run setup.ipynb
%matplotlib inline
# load haplotypes
callset_haps = np.load('../data/haps_phase1.npz')
haps = allel.HaplotypeArray(callset_haps['haplotypes'])
pos = allel.SortedIndex(callset_haps['POS'])
n_variants = haps.shape[0]
n_haps = haps.shape[1]
n_variants, n_haps
list(callset_haps)
callset_haps['... |
5,410 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
VARLiNGAM
Import and settings
In this example, we need to import numpy, pandas, and graphviz in addition to lingam.
Step1: Test data
We create test data consisting of 5 variables.
Step2: C... | Python Code:
import numpy as np
import pandas as pd
import graphviz
import lingam
from lingam.utils import make_dot, print_causal_directions, print_dagc
print([np.__version__, pd.__version__, graphviz.__version__, lingam.__version__])
np.set_printoptions(precision=3, suppress=True)
np.random.seed(0)
Explanation: VARLiN... |
5,411 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyze a large dataset with Google BigQuery
Learning Objectives
Access an ecommerce dataset
Look at the dataset metadata
Remove duplicate entries
Write and execute queries
Introduction
BigQ... | Python Code:
import os
import pandas as pd
PROJECT = "<YOUR PROJECT>" #TODO Replace with your project id
os.environ["PROJECT"] = PROJECT
pd.options.display.max_columns = 50
Explanation: Analyze a large dataset with Google BigQuery
Learning Objectives
Access an ecommerce dataset
Look at the dataset metadata
Remove dupli... |
5,412 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Plot dynamics functions
Step2: Sample data from the ARHMM
Step3: Below, we visualize each component of of the observation variable as a time series. The colors corre... | Python Code:
!pip install -qq git+git://github.com/lindermanlab/ssm-jax-refactor.git
try:
import ssm
except ModuleNotFoundError:
%pip install -qq ssm
import ssm
import copy
import jax.numpy as np
import jax.random as jr
try:
from tensorflow_probability.substrates import jax as tfp
except ModuleNotFound... |
5,413 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Agents
Agents are objects having a strategy, a vocabulary, and an ID (this last attribute is not important for the moment).
Step1: Let's create an agent. Vocabulary and strategy are created... | Python Code:
import lib.ngagent as ngagent
Explanation: Agents
Agents are objects having a strategy, a vocabulary, and an ID (this last attribute is not important for the moment).
End of explanation
ag_cfg = {
'agent_id':'test',
'voc_cfg':{
'voc_type':'sparse_matrix',
'M':5,
'W':10
... |
5,414 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
classify reviews
This notebook describes the binary classification of Yelp hotel reviews on whether or not they are dog related.
Step1: Connect to DB
Step2: Restore BF Reviews
Step3: Rest... | Python Code:
import numpy as np
from time import time
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.feature_selection import SelectKBest, chi2
from skl... |
5,415 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data cleaning
Because Domestic % and International % columns data end with %, and its data type are objects, it is necessary to transfer its data type to float.
Step1: for the score columns... | Python Code:
pixar_movies['Domestic %'] = pixar_movies['Domestic %'].str.rstrip('%').astype('float')
pixar_movies['International %'] = pixar_movies['International %'].str.rstrip('%').astype('float')
Explanation: Data cleaning
Because Domestic % and International % columns data end with %, and its data type are objects,... |
5,416 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In Codice Ratio Convolutional Neural Network - Test on words
In this notebook we are going to define 4 pipelines and test them on words. This is just a preliminary test on 3 words with 2 gro... | Python Code:
import os.path
from IPython.display import Image
import time
from util import Util
u = Util()
import image_utils as iu
import keras_image_utils as kiu
import numpy as np
# Explicit random seed for reproducibility
np.random.seed(1337)
from keras.models import Sequential
from keras.layers import Dense, Dropo... |
5,417 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reading Data with DLTK
To build a reader you have to define a read function. This is a function with a signature read_fn(file_references, mode, params=None), where
- file_references is a ar... | Python Code:
import SimpleITK as sitk
import os
from dltk.io.augmentation import *
from dltk.io.preprocessing import *
import tensorflow as tf
def read_fn(file_references, mode, params=None):
# We define a `read_fn` and iterate through the `file_references`, which
# can contain information about the data t... |
5,418 | 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', 'nerc', 'ukesm1-0-mmh', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: NERC
Source ID: UKESM1-0-MMH
Topic: Land
Sub-Topics: Soil, Snow, Vegetation,... |
5,419 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring precision and recall
The goal of this second notebook is to understand precision-recall in the context of classifiers.
Use Amazon review data in its entirety.
Train a logistic regr... | Python Code:
import graphlab
from __future__ import division
import numpy as np
graphlab.canvas.set_target('ipynb')
Explanation: Exploring precision and recall
The goal of this second notebook is to understand precision-recall in the context of classifiers.
Use Amazon review data in its entirety.
Train a logistic regre... |
5,420 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re going ... |
5,421 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Think Bayes
Step1: The Pmf class
I'll start by making a Pmf that represents the outcome of a six-sided die. Initially there are 6 values with equal probability.
Step2: To be true probabil... | Python Code:
from __future__ import print_function, division
% matplotlib inline
from thinkbayes2 import Hist, Pmf, Suite
Explanation: Think Bayes: Chapter 2
This notebook presents example code and exercise solutions for Think Bayes.
Copyright 2016 Allen B. Downey
MIT License: https://opensource.org/licenses/MIT
End of... |
5,422 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Trajectory Simulation
The simulation is done using a expected differentiation pattern along a timeline t. The differentiation pattern is generated doing randomly angled linear splits (like a... | Python Code:
seeds = [8971, 3551, 3279, 5001, 5081]
from topslam.simulation import qpcr_simulation
fig = plt.figure(figsize=(15,3), tight_layout=True)
gs = plt.GridSpec(6, 5)
axit = iter([fig.add_subplot(gs[1:, i]) for i in range(5)])
for seed in seeds:
Xsim, simulate_new, t, c, labels, seed = qpcr_simulation(seed=... |
5,423 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Querying portia - Data fetching with Python
Making HTTP requests using Python - Checking credentials
Unsucessfull request
Step1: Sucessfull request
Step2: Obtaining data from a specific ti... | Python Code:
# Library for HTTP requests
import requests
# Portia service URL for token authorization checking
url = "http://io.portia.supe.solutions/api/v1/accesstoken/check"
# Makes the request
response = requests.get(url)
# Shows response
if response.status_code == 200:
print("Success accessing Portia Service - ... |
5,424 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--BOOK_INFORMATION-->
<a href="https
Step1: Then, loading the dataset is a one-liner
Step2: This function returns a dictionary we call iris, which contains a bunch of different fields
St... | Python Code:
import numpy as np
import cv2
from sklearn import datasets
from sklearn import model_selection
from sklearn import metrics
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot')
Explanation: <!--BOOK_INFORMATION-->
<a href="https://www.packtpub.com/big-data-and-business-intelligence/mac... |
5,425 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Instrumental-Variables Estimation to Recover the Treatment Effect in Quasi-Experiments
This section is taken from Chapter 11 of Methods Matter by Richard Murnane and John Willett.
In ... | Python Code:
# THINGS TO IMPORT
# This is a baseline set of libraries I import by default if I'm rushed for time.
import codecs # load UTF-8 Content
import json # load JSON files
import pandas as pd # Pandas handles dataframes
import numpy as np # N... |
5,426 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
There are three main plot kinds; in addition to histograms and kernel density estimates (KDEs), you can also draw empirical cumulative distribution functions (ECDFs)
Step1: While in histogr... | Python Code:
sns.displot(data=penguins, x="flipper_length_mm", kind="ecdf")
Explanation: There are three main plot kinds; in addition to histograms and kernel density estimates (KDEs), you can also draw empirical cumulative distribution functions (ECDFs):
End of explanation
sns.displot(data=penguins, x="flipper_length_... |
5,427 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Build Adjacency Matrix
Step1: Queries
Step2: Step through every interaction.
If geneids1 not in matrix - insert it as dict.
If geneids2 not in matrix[geneids1] - insert it as []
If probabi... | Python Code:
import sqlite3
import json
DATABASE = "data.sqlite"
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
Explanation: Build Adjacency Matrix
End of explanation
# For getting the maximum row id
QUERY_MAX_ID = "SELECT id FROM interactions ORDER BY id DESC LIMIT 1"
# Get interaction data
QUERY_INTERACTION ... |
5,428 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Aula 05 - Lendo dados oceanográficos em diversos formatos (netCDF, OPeNDAP, ERDDAP etc) e dimensões (AKA além das tabelas)]
Objetivos
Exibir dados em várias dimensões (Satélites, Modelos, et... | Python Code:
t = 'Python'
t[0:2]
t[::2]
t[::-1]
import numpy as np
arr = np.array([[3, 6, 2, 1, 7],
[4, 1, 3, 2, 8],
[7, 9, 2, 1, 8],
[8, 6, 9, 6, 7],
[9, 1, 9, 2, 6],
[9, 8, 1, 5, 6],
[0, 4, 2, 0, 6],
[0, 3,... |
5,429 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing functions in epydemiology
Import epydemiology
(All other packages will be imported or reported missing.)
Step1: Some background details
Step2: FILE
Step3: FILE
Step4: FUNCTION
St... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import epydemiology as epy
Explanation: Testing functions in epydemiology
Import epydemiology
(All other packages will be imported or reported missing.)
End of explanation
help(epy)
print(dir(epy))
Explanation: Some background details
End of explana... |
5,430 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Minimal Example to Produce a Synthetic Light Curve
Setup
Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for yo... | Python Code:
!pip install -I "phoebe>=2.2,<2.3"
%matplotlib inline
Explanation: Minimal Example to Produce a Synthetic Light Curve
Setup
Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the lat... |
5,431 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An implicit feedback recommender for the Movielens dataset
Implicit feedback
For some time, the recommender system literature focused on explicit feedback
Step1: This gives us a dictionary ... | Python Code:
import numpy as np
from lightfm.datasets import fetch_movielens
movielens = fetch_movielens()
Explanation: An implicit feedback recommender for the Movielens dataset
Implicit feedback
For some time, the recommender system literature focused on explicit feedback: the Netflix prize focused on accurately repr... |
5,432 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic Metrics
When we think about summarizing data, what are the metrics that we look at?
In this notebook, we will look at the car dataset
To read how the data was acquired, please read thi... | Python Code:
#Import the required libraries
import numpy as np
import pandas as pd
from datetime import datetime as dt
from scipy import stats
Explanation: Basic Metrics
When we think about summarizing data, what are the metrics that we look at?
In this notebook, we will look at the car dataset
To read how the data was... |
5,433 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Design of Experiments
Unit 18, Lecture 1
Numerical Methods and Statistics
Prof. Andrew White, April 30, 2019
Goals
Know the vocubulary (treatment condition, factor, level, response, ANOVA, c... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
import scipy.stats as ss
import numpy.linalg as linalg
x1 = [1, 1, -1, -1]
x2 = [1, -1, 1, -1]
y = [1.2, 3.2, 4.1, 3.6]
Explanation: Design of Experiments
Unit 18, Lecture 1
Numerical Methods and Statistics
Prof. Andrew White, ... |
5,434 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introducción a Python
Step1: Con esta línea, ya tendremos en nuestro pequeño script el paquete listo para ser usado. Para acceder a los módulos tendremos que hacer numpy.nombre_de_la_funció... | Python Code:
import numpy
Explanation: Introducción a Python: nivel intermedio
Python es un lenguaje muy extendido, con una rica comunidad que abarca muchos aspectos, muy fácil de aprender y programar con él, y que nos permite realizar un montón de tareas diferentes. Pero, no solo de pan vive. Python tiene muchas libre... |
5,435 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
tulipy
Python bindings for Tulip Indicators
Tulipy requires numpy as all inputs and outputs are numpy arrays (dtype=np.float64).
Installation
You can install via pip install tulipy.
If a whe... | Python Code:
import numpy as np
import tulipy as ti
ti.TI_VERSION
DATA = np.array([81.59, 81.06, 82.87, 83, 83.61,
83.15, 82.84, 83.99, 84.55, 84.36,
85.53, 86.54, 86.89, 87.77, 87.29])
Explanation: tulipy
Python bindings for Tulip Indicators
Tulipy requires numpy as all inputs and ... |
5,436 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Traveling Salesman problem
Names of group members
// put your names here!
Goals of this assignment
The main goal of this assignment is to use Monte Carlo methods to find the shortest pat... | Python Code:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
from IPython.display import display, clear_output
def calc_total_distance(table_of_distances, city_order):
'''
Calculates distances between a sequence of cities.
Inputs: N x N table containing distances between each pair... |
5,437 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistic Regression for Banknote Authentication
<hr>
Overview
Choosing a classification algorithm
First steps with scikit-learn
Loading the Dataset
Logistic regression
Training a logistic re... | Python Code:
import numpy as np
import pandas as pd
# read .csv from provided dataset
csv_filename="data_banknote_authentication.txt"
# We assign the collumn names ourselves and load the data in a Pandas Dataframe
df=pd.read_csv(csv_filename,names=["Variance","Skewness","Curtosis","Entropy","Class"])
Explanation: Logis... |
5,438 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial - Distributed training in a notebook!
Using Accelerate to launch a training script from your notebook
Step1: Overview
In this tutorial we will see how to use Accelerate to launch a... | Python Code:
#|all_multicuda
Explanation: Tutorial - Distributed training in a notebook!
Using Accelerate to launch a training script from your notebook
End of explanation
#hide
from fastai.vision.all import *
from fastai.distributed import *
from fastai.vision.models.xresnet import *
from accelerate import notebook_la... |
5,439 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling and Simulation in Python
Rabbit example
Copyright 2017 Allen Downey
License
Step1: Rabbit Redux
This notebook starts with a version of the rabbit population growth model and walks ... | Python Code:
%matplotlib inline
from modsim import *
Explanation: Modeling and Simulation in Python
Rabbit example
Copyright 2017 Allen Downey
License: Creative Commons Attribution 4.0 International
End of explanation
system = System(t0 = 0,
t_end = 10,
adult_pop0 = 10,
... |
5,440 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Weighted Least Squares
Step1: WLS Estimation
Artificial data
Step2: WLS knowing the true variance ratio of heteroscedasticity
In this example, w is the standard deviation of the error. WL... | Python Code:
%matplotlib inline
import numpy as np
from scipy import stats
import statsmodels.api as sm
import matplotlib.pyplot as plt
from statsmodels.sandbox.regression.predstd import wls_prediction_std
from statsmodels.iolib.table import (SimpleTable, default_txt_fmt)
np.random.seed(1024)
Explanation: Weighted Leas... |
5,441 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cube multidimensionnel - énoncé
Ce notebook aborde différentes solutions pour traiter les données qu'on représente plus volontiers en plusieurs dimensions. Le mot-clé associé est OLAP ou cub... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import pyensae
from pyquickhelper.helpgen import NbImage
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: Cube multidimensionnel - énoncé
Ce notebook aborde différentes solutions pour traiter les données ... |
5,442 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bokeh Charts Attributes
One of Bokeh Charts main contributions is that it provides a flexible interface for applying unique attributes based on the unique values in column(s) of a DataFrame.... | Python Code:
from bokeh.charts.attributes import AttrSpec, ColorAttr, MarkerAttr
Explanation: Bokeh Charts Attributes
One of Bokeh Charts main contributions is that it provides a flexible interface for applying unique attributes based on the unique values in column(s) of a DataFrame.
Internally, the bokeh chart uses th... |
5,443 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Think Bayes
Step1: Improving Reading Ability
From DASL(http
Step2: And use groupby to compute the means for the two groups.
Step4: The Normal class provides a Likelihood function that com... | Python Code:
from __future__ import print_function, division
% matplotlib inline
import warnings
warnings.filterwarnings('ignore')
import math
import numpy as np
from thinkbayes2 import Pmf, Cdf, Suite, Joint
import thinkplot
Explanation: Think Bayes: Chapter 9
This notebook presents code and exercises from Think Bayes... |
5,444 | 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', 'cnrm-cerfacs', 'sandbox-1', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: CNRM-CERFACS
Source ID: SANDBOX-1
Topic: Aerosol
Sub-Topics: Tran... |
5,445 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
연습문제
아래 문제들을 해결하는 코드를 lab06.py 파일에 작성하여 제출하라.
연습 1
아래 코드를 실행하고 23.5입력하면 ValueError 오류가 발생한다.
======
n = int(raw_input("Please enter a number
Step1: 견본 단안 2
Step2: 연습 2
아래 코드를 실행하면 왜 어떤 결과... | Python Code:
while True:
try:
n = int(raw_input("Please enter a number: "))
print("정확히 입력되었습니다.")
break
except ValueError:
print("정수를 입력하시오.")
Explanation: 연습문제
아래 문제들을 해결하는 코드를 lab06.py 파일에 작성하여 제출하라.
연습 1
아래 코드를 실행하고 23.5입력하면 ValueError 오류가 발생한다.
======
n = int(raw_input("Plea... |
5,446 | 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="#Spark-PCA" data-toc-modified-id="Spark-PCA-1"><span class="toc-item-num">1&n... | 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(plot_style = False)
os.chdir(path)
# 1. magic for inline plot
# 2. magic to print... |
5,447 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Vision Transformer without Attention
Author
Step1: Hyperparameters
These are the hyperparameters that we have chosen for the experiment.
Please feel free to tune them.
Step2: Load the CI... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow_addons as tfa
# Setting seed for reproducibiltiy
SEED = 42
keras.utils.set_random_seed(SEED)
Explanation: A Vision Transformer without Attention
Auth... |
5,448 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GP Regression with Uncertain Inputs
Introduction
In this notebook, we're going to demonstrate one way of dealing with uncertainty in our training data. Let's say that we're collecting traini... | Python Code:
import math
import torch
import tqdm
import gpytorch
from matplotlib import pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
Explanation: GP Regression with Uncertain Inputs
Introduction
In this notebook, we're going to demonstrate one way of dealing with uncertainty in our training data... |
5,449 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
Step1: Introduction
In this tutorial, you will learn how to do statistical analysis of your simulation data.
This is an important topic, because the statistics of your data determi... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 18})
import sys
import logging
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
np.random.seed(43)
def ar_1_process(n_samples, c, phi, eps):
'''
Generate a correlated random sequence with the AR(1) proces... |
5,450 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deskew the MNIST training and test images
This set of scripts serves several purposes
Step1: OpenCV deskew function
Step3: Read MNIST binary-file data and convert to numpy.ndarray
thanks t... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import cv2
print cv2.__version__
Explanation: Deskew the MNIST training and test images
This set of scripts serves several purposes:
* it provides two functions
- a function to read the binary MNIST data into numpy.ndarray
- a f... |
5,451 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sequential Domain Reduction
Background
Sequential domain reduction is a process where the bounds of the optimization problem are mutated (typically contracted) to reduce the time required to... | Python Code:
import numpy as np
from bayes_opt import BayesianOptimization
from bayes_opt import SequentialDomainReductionTransformer
import matplotlib.pyplot as plt
Explanation: Sequential Domain Reduction
Background
Sequential domain reduction is a process where the bounds of the optimization problem are mutated (typ... |
5,452 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Impact of Scattered Moonlight on Exposure Times
Step1: Simulation Config
Step2: ELG Fiducial Target
Look up the expected redshift distribution of ELG targets. Note that the ELG doublet fa... | Python Code:
%pylab inline
import os
import os.path
import astropy.table
import astropy.constants
import astropy.units as u
import sklearn.linear_model
Explanation: Impact of Scattered Moonlight on Exposure Times
End of explanation
import specsim.simulator
desi = specsim.simulator.Simulator('desi')
Explanation: Simulat... |
5,453 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multi-label prediction with Planet Amazon dataset
Step1: Getting the data
The planet dataset isn't available on the fastai dataset page due to copyright restrictions. You can download it fr... | Python Code:
%reload_ext autoreload
%autoreload 2
%matplotlib inline
from fastai.vision import *
Explanation: Multi-label prediction with Planet Amazon dataset
End of explanation
# ! {sys.executable} -m pip install kaggle --upgrade
Explanation: Getting the data
The planet dataset isn't available on the fastai dataset p... |
5,454 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gaia
Real data!
gully
Sept 14, 2016
Outline
Step1: 1. Retrieve existing catalogs
Retrieve Data file from here
Step2: 2. Read in the Gaia data
Step3: This takes a finite amount of RAM, but... | Python Code:
#! cat /Users/gully/.ipython/profile_default/startup/start.ipy
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%config InlineBackend.figure_format = 'retina'
%matplotlib inline
import pandas as pd
from astropy import units as u
from astropy.coordinates import SkyCoord
Explanation: ... |
5,455 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook shows you step by step how you can transform text data from vmstat output file into a pandas DataFrame.
Step1: Data Input
In this version, I'll guide you through data parsing ... | Python Code:
%less ../datasets/vmstat_loadtest.log
Explanation: This notebook shows you step by step how you can transform text data from vmstat output file into a pandas DataFrame.
End of explanation
import pandas as pd
raw = pd.read_csv("../datasets/vmstat_loadtest.log", skiprows=1)
raw.head()
columns = raw.columns.s... |
5,456 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Repetition Codes on the BSC, BEC, and BI-AWGN Channel
This code is provided as supplementary material of the lecture Channel Coding 2 - Advanced Methods.
This code illustrates
* The decoding... | Python Code:
import numpy as np
from scipy.stats import norm
from scipy.special import comb
import matplotlib.pyplot as plt
Explanation: Repetition Codes on the BSC, BEC, and BI-AWGN Channel
This code is provided as supplementary material of the lecture Channel Coding 2 - Advanced Methods.
This code illustrates
* The d... |
5,457 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ODM2 API
Step1: odm2api version used to run this notebook
Step2: Connect to the ODM2 SQLite Database
This example uses an ODM2 SQLite database file loaded with a sensor-based, high-frequen... | Python Code:
import os
import datetime
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
import pandas as pd
import odm2api
from odm2api.ODMconnection import dbconnection
import odm2api.services.readService as odm2rs
"{} UTC".format(datetime.datetime.utcnow())
pd.__version__
Explanation: ODM2 ... |
5,458 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
3.1 Correction of symmetry distortion using thin plate spline
3.1.0 Retrieve experimental data
Step1: 3.1.1 Calculate coordinate deformation from selected or detected landmarks and their sy... | Python Code:
fpath = r'../data/data_114_4axis_100x100x200x50.h5'
fbinned = fp.readBinnedhdf5(fpath)
V = fbinned['V']
V.shape
Eslice = V[15:20, :, :, 35:41].sum(axis=(0,3))
plt.imshow(Eslice, origin='lower', cmap='terrain_r')
mc = aly.MomentumCorrector(V[15:20, :, :, :].sum(axis=0), rotsym=6)
Explanation: 3.1 Correction... |
5,459 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Minist retrainning(finetuning)
Minist 예제에서 Network를 구조를 마지막 fully connected (linear) 부분의 차원을 수정한 다음 재훈련을 하도록 하겠습니다.
이것을 수행하기 위해서는 다음과 같은 방법이 있는데, finetuning에 해당하는 방법3을 구현하도록 하겠습니다.
방법1
Ste... | Python Code:
%matplotlib inline
Explanation: Minist retrainning(finetuning)
Minist 예제에서 Network를 구조를 마지막 fully connected (linear) 부분의 차원을 수정한 다음 재훈련을 하도록 하겠습니다.
이것을 수행하기 위해서는 다음과 같은 방법이 있는데, finetuning에 해당하는 방법3을 구현하도록 하겠습니다.
방법1 : Minist Network를 새로 작성한다.
python
self.fc1 = nn.Linear(64*7*7, 1024)
self.fc2 = nn.Linear... |
5,460 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling and Simulation in Python
Copyright 2017 Allen Downey
License
Step1: Low pass filter
The following circuit diagram (from Wikipedia) shows a low-pass filter built with one resistor a... | Python Code:
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import functions from the modsim.py module
from modsim import *
Explanation: Modeling and Si... |
5,461 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ReGraph tutorial
Step1: I. Simple graph rewriting
1. Initialization of a graph
ReGraph works with NetworkX graph objects, both undirected graphs (nx.Graph) and directed ones (nx.DiGraph). T... | Python Code:
import copy
import networkx as nx
from regraph.hierarchy import Hierarchy
from regraph.rules import Rule
from regraph.plotting import plot_graph, plot_instance, plot_rule
from regraph.primitives import find_matching, print_graph, equal, add_nodes_from, add_edges_from
from regraph.utils import keys_by_valu... |
5,462 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Figure 1. Sketch of a cell (top left) with the horizontal (red) and vertical (green) velocity nodes and the cell-centered node (blue). Definition of the normal vector to "surface" (segment) ... | Python Code:
%matplotlib inline
# plots graphs within the notebook
%config InlineBackend.figure_format='svg' # not sure what this does, may be default images to svg format
import matplotlib.pyplot as plt #calls the plotting library hereafter referred as to plt
import numpy as np
Explanation: Figure 1. Sketch of a cell... |
5,463 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Part 1
Step1: (2) Plot of the means $\mathbf{\mu}$ of the learnt mixture
Step2: (3) It is not possible to have one center per class with only 10 components even though there are only 10 di... | Python Code:
# settings
data_path = '/home/data/ml/mnist'
k = 10
# we load pre-calculated k-means
import kmeans as kmeans_
kmeans = kmeans_.load_kmeans('kmeans-20.dat')
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import scipy
import bmm
import visualize
# loading the data
fro... |
5,464 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problem Set 8 Review & Transfer Learning with word2vec
Import various modules that we need for this notebook (now using Keras 1.0.0)
Step1: I. Problem Set 8, Part 1
Let's work through a sol... | Python Code:
%pylab inline
import copy
import numpy as np
import pandas as pd
import sys
import os
import re
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD, RMSprop
from keras.layers.normalization import BatchNormalization
from keras.layers.... |
5,465 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic MEG and EEG data processing
MNE-Python reimplements most of MNE-C's (the original MNE command line utils)
functionality and offers transparent scripting.
On top of that it extends MNE-... | Python Code:
import mne
Explanation: Basic MEG and EEG data processing
MNE-Python reimplements most of MNE-C's (the original MNE command line utils)
functionality and offers transparent scripting.
On top of that it extends MNE-C's functionality considerably
(customize events, compute contrasts, group statistics, time-f... |
5,466 | 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', 'ec-earth-consortium', 'sandbox-2', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: EC-EARTH-CONSORTIUM
Source ID: SANDBOX-2
Topic: Aerosol
Su... |
5,467 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2. Gender Detection
Figuring out genders from names
We're going to use 3 different methods, all of which use a similar philosophy. Essentially, each of these services have build databases fr... | Python Code:
import os
os.chdir("../data/pubs")
names = []
with open("git.csv") as infile:
for line in infile:
names.append(line.split(",")[3])
Explanation: 2. Gender Detection
Figuring out genders from names
We're going to use 3 different methods, all of which use a similar philosophy. Essentially, each of... |
5,468 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setup
Step1: Adapted from http
Step2: Image from https
Step3: Label Encoding
Step4: Multiclass Classification
Data subset (1 feature only)
Step5: Plotting
Step6: Model (Logistic Regres... | Python Code:
from __future__ import print_function, unicode_literals, absolute_import, division
from six.moves import range, zip, map, reduce, filter
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import seaborn as sns
sns... |
5,469 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: In the below cell, import pandas and make a DataFrame object using the above poll data and using the dates list as the index.
Then, display the data by printing your D... | Python Code:
num_respondents = 1156
dates = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan2020']
data = {}
data['approve'] = [37, 40, 42, 43, 43, 43, 40, 39, 41, 42, 43, 43]
data['disapprove'] = [57, 55, 51, 52, 52, 52, 54, 55, 57, 54, 53, 53]
data['no_opinion'] = [7, 5, 8, 5, 5, 5,... |
5,470 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Running MSAF
The main MSAF functionality is demonstrated here.
Step1: Single File Mode
This mode analyzes one audio file at a time.
Note
Step2: Using different Algorithms
MSAF includes mul... | Python Code:
from __future__ import print_function
import msaf
import librosa
import seaborn as sns
# and IPython.display for audio output
import IPython.display
# Setup nice plots
sns.set(style="dark")
%matplotlib inline
Explanation: Running MSAF
The main MSAF functionality is demonstrated here.
End of explanation
# C... |
5,471 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using ROOT to bind Python and C++
What is PyROOT?
PyROOT is the name of the Python bindings offered by ROOT
All the ROOT C++ functions and classes are accessible from Python via PyROOT
Pytho... | Python Code:
import ROOT
Explanation: Using ROOT to bind Python and C++
What is PyROOT?
PyROOT is the name of the Python bindings offered by ROOT
All the ROOT C++ functions and classes are accessible from Python via PyROOT
Python façade, C++ performance
But PyROOT is not just for ROOT!
It can also call into user-define... |
5,472 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computing basic semantic similarities between GO terms
Adapted from book chapter written by Alex Warwick Vesztrocy and Christophe Dessimoz
In this section we look at how to compute semantic ... | Python Code:
%load_ext autoreload
%autoreload 2
import sys
sys.path.insert(0, "..")
from goatools import obo_parser
go = obo_parser.GODag("../go-basic.obo")
go_id3 = 'GO:0048364'
go_id4 = 'GO:0044707'
print(go[go_id3])
print(go[go_id4])
Explanation: Computing basic semantic similarities between GO terms
Adapted from bo... |
5,473 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Download RetinaNet code to notebook instance
Step1: Create API Key on Kaggle
Please go https | Python Code:
!pip install --user --upgrade kaggle
import IPython
IPython.Application.instance().kernel.do_shutdown(True) #automatically restarts kernel
Explanation: Download RetinaNet code to notebook instance
End of explanation
!ls ./kaggle.json
import os
current_dir=!pwd
current_dir=current_dir[0]
os.environ['KAGGLE_... |
5,474 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualizing Networks
The following demonstrates basic use of nupic.frameworks.viz.NetworkVisualizer to visualize a network.
Before you begin, you will need to install the otherwise optional ... | Python Code:
from nupic.engine import Network, Dimensions
# Create Network instance
network = Network()
# Add three TestNode regions to network
network.addRegion("region1", "TestNode", "")
network.addRegion("region2", "TestNode", "")
network.addRegion("region3", "TestNode", "")
# Set dimensions on first region
region1 ... |
5,475 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interfaces
In Nipype, interfaces are python modules that allow you to use various external packages (e.g. FSL, SPM or FreeSurfer), even if they themselves are written in another programming ... | Python Code:
%pylab inline
from nilearn.plotting import plot_anat
plot_anat('/data/ds102/sub-01/anat/sub-01_T1w.nii.gz', title='original',
display_mode='ortho', dim=-1, draw_cross=False, annotate=False)
Explanation: Interfaces
In Nipype, interfaces are python modules that allow you to use various external pac... |
5,476 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Session 02 - Chromosome $k$-mers <img src="data/JHI_STRAP_Web.png" style="width
Step1: Sequence data
Like Session 01, we will be dealing with sequence data directly, but there are again hel... | Python Code:
%matplotlib inline
from Bio import SeqIO # For working with sequence data files
from Bio.Seq import Seq # Seq object, needed for the last activity
from Bio.Alphabet import generic_dna # sequence alphabet, for the last activity
from bs32010 import ex02 # Local fun... |
5,477 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Optimizing the SVM Classifier
Machine learning models are parameterized so that their behavior can be tuned for a given problem. Models can have many parameters and finding the best combinat... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
#Load libraries for data processing
import pandas as pd #data processing, CSV file I/O (e.g. pd.read_csv)
import numpy as np
from scipy.stats import norm
## Supervised learning.
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing im... |
5,478 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Win/Loss Betting Model
Same as other one but I now filter by teams that have a ranking
Step1: Obtain results of teams within the past year
Step2: Pymc Model
Determining Binary Win Loss
Ste... | Python Code:
import pandas as pd
import numpy as np
import datetime as dt
from scipy.stats import norm, bernoulli
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
from spcl_case import *
plt.style.use('fivethirtyeight')
Explanation: Win/Loss Betting Model
Same as other one but I now filter by te... |
5,479 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ThreatExchange Data Dashboard
Purpose
The ThreatExchange APIs are designed to make consuming threat intelligence from multiple sources easy. This notebook will walk you through
Step1: Opti... | Python Code:
from pytx.access_token import access_token
from pytx.logger import setup_logger
from pytx.vocabulary import PrivacyType as pt
# Specify the location of your token via one of several ways:
# https://pytx.readthedocs.org/en/latest/pytx.access_token.html
access_token()
Explanation: ThreatExchange Data Dashboa... |
5,480 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kaggle's Predicting Red Hat Business Value
This is a first quick & dirty attempt at Kaggle's Predicting Red Hat Business Value competition.
Loading in the data
Step1: Joining together to ge... | Python Code:
import pandas as pd
people = pd.read_csv('people.csv.zip')
people.head(3)
actions = pd.read_csv('act_train.csv.zip')
actions.head(3)
Explanation: Kaggle's Predicting Red Hat Business Value
This is a first quick & dirty attempt at Kaggle's Predicting Red Hat Business Value competition.
Loading in the data
E... |
5,481 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning
Step1: Workflow for each analysis type (e.g basic, 1 Dense layer...)
Step2: Linear Model
Step3: Single Dense Layer
Step4: VGG-Style CNN
Step5: Data Augmentation
Step6: Ba... | Python Code:
%matplotlib inline
import math
import numpy as np
import utils; reload(utils)
from utils import *
from sympy import Symbol
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Lambda, Dense
from matplotlib import pyplot as plt
Explanation: Deep Learning: Mnist Analy... |
5,482 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Enter Team Member Names here (double click to edit)
Step1: <a id="linearnumpy"></a>
<a href="#top">Back to Top</a>
Using Linear Regression
In the videos, we derived the formula for calculat... | Python Code:
from sklearn.datasets import load_diabetes
import numpy as np
from __future__ import print_function
ds = load_diabetes()
# this holds the continuous feature data
# because ds.data is a matrix, there are some special properties we can access (like 'shape')
print('features shape:', ds.data.shape, 'format is:... |
5,483 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Latent Semantic Indexing
Here, we apply the technique Latent Semantic Indexing to capture the similarity of words. We are given a list of words and their frequencies in 9 documents, found on... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing
plt.rcParams['font.size'] = 16
words_list = list()
with open('lsiWords.txt') as f:
for line in f:
words_list.append(line.strip())
words = pd.Series(words_list, name="words... |
5,484 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python 内置排序方法
Python 提供两种内置排序方法,一个是只针对 List 的原地(in-place)排序方法 list.sort(),另一个是针对所有可迭代对象的非原地排序方法 sorted()。
所谓原地排序是指会立即改变被排序的列表对象,就像 append()/pop() 等方法一样:
Step1: sorted() 不限于列表,而且会生成并返回一个新的排序... | Python Code:
from random import randrange
lst = [randrange(1, 100) for _ in range(10)]
print(lst)
lst.sort()
print(lst)
Explanation: Python 内置排序方法
Python 提供两种内置排序方法,一个是只针对 List 的原地(in-place)排序方法 list.sort(),另一个是针对所有可迭代对象的非原地排序方法 sorted()。
所谓原地排序是指会立即改变被排序的列表对象,就像 append()/pop() 等方法一样:
End of explanation
lst = [randrang... |
5,485 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
本章以第 9 章定义的二维向量 Vector2d 类为基础,向前迈出一大步,定义表示多维向量的 Vector 类。这个类的行为与 Python 标准中的不可变扁平序列一样。Vector 实例中的元素是浮点数,本章结束后 Vector2d 类将支持以下功能
基本的序列协议 -- __len__ 和 __getitem__
正确表述拥有很多元素的实例
适当的切片支持,用于生成新的 ... | Python Code:
from array import array
import reprlib
import math
class Vector:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components) # 把 Vector 分量保存到一个数组中('d' 表示 double)
def __iter__(self):
return iter(self._components)
def __rep... |
5,486 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
automaton.is_coaccessible
Whether all its states are coaccessible, i.e., its transposed automaton is accessible, in other words, all its states cab reach a final state.
Preconditions
Step1: ... | Python Code:
import vcsn
Explanation: automaton.is_coaccessible
Whether all its states are coaccessible, i.e., its transposed automaton is accessible, in other words, all its states cab reach a final state.
Preconditions:
- None
See also:
- automaton.coaccessible
- automaton.is_accessible
- automaton.trim
Examples
End ... |
5,487 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multiple Stripe Analysis (MSA) for Single Degree of Freedom (SDOF) Oscillators
In this method, a single degree of freedom (SDOF) model of each structure is subjected to non-linear time histo... | Python Code:
import numpy as np
from rmtk.vulnerability.common import utils
from rmtk.vulnerability.derivation_fragility.NLTHA_on_SDOF import MSA_on_SDOF
from rmtk.vulnerability.derivation_fragility.NLTHA_on_SDOF import MSA_utils
from rmtk.vulnerability.derivation_fragility.NLTHA_on_SDOF.read_pinching_parameters import... |
5,488 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Checking the model with superclass hierarchy with no augmentation. (It was manually switched off in the .json file)
Step1: Run the modification of check_test_score.py so that it can work wi... | Python Code:
cd ..
Explanation: Checking the model with superclass hierarchy with no augmentation. (It was manually switched off in the .json file)
End of explanation
import numpy as np
import pylearn2.utils
import pylearn2.config
import theano
import neukrill_net.dense_dataset
import neukrill_net.utils
import sklearn.... |
5,489 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Turing machine computation
Tape
We will represent the tape as a list of tape symbols and we will represent tape symbols as Python strings.
The string ' ' represents the blank symbol.
... | Python Code:
def run(transitions, input, steps):
simulate Turing machine for the given number of steps and the given input
# convert input from string to list of symbols
# we use '|>' as a symbol to indicate the beginning of the tape
input = ['|>'] + list(input) + [' ']
# sanitize transitions for 'a... |
5,490 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Arxiv summary auto translation
Set up
import modules.
Step1: Set credentials.<br>
Need to prepare the credentials file form GCP console.
Step2: Set the dates.<br>
No argument leads to set ... | Python Code:
import os
from modules.DataArxiv import get_date
from modules.DataArxiv import execute_query
from modules.Translate import Translate
Explanation: Arxiv summary auto translation
Set up
import modules.
End of explanation
CREDENTIALS_JSON = "credentials.json"
CREDENTIALS_PATH = os.path.normpath(
os.path.j... |
5,491 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Text Processing
Table of Contents
<p><div class="lev1 toc-item"><a href="#Text-Processing" data-toc-modified-id="Text-Processing-1"><span class="toc-item-num">1 </span>Text Proces... | Python Code:
# This is the path to our file
bigsourcefile = 'Solorzano/Sections_I.1_TA.txt'
# We use a variable 'input' for keeping its contents.
input = open(bigsourcefile, encoding='utf-8').readlines()
# Just for information, let's see the first 10 lines of the file.
input[0:10] # actually, since python starts coun... |
5,492 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example of Liftingline Analysis
Step1: Creating wing defintion
Step2: Lift calculation using LiftAnalysis object
The LiftAnalysis object calculates base lift distributions (e.q. for aerody... | Python Code:
# numpy and matplotlib imports
import numpy as np
from matplotlib import pyplot as plt
# import of wingstructure submodels
from wingstructure import data, aero
Explanation: Example of Liftingline Analysis
End of explanation
# create wing object
wing = data.Wing()
# add sections to wing
# leading edge posit... |
5,493 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework #1
This notebook contains the first homework for this class, and is due on Friday, October 23rd, 2016 at 11
Step1: Answers to questions (based on this model)
Step2: Note
Step3: F... | Python Code:
# write any code you need here!
# Create additional cells if you need them by using the
# 'Insert' menu at the top of the browser window.
import numpy as np
C_gas = [2.0, 3.0, 4.0, 5.0]
M_drive = [1.0e+5, 2.0e+5, 3.0e+5, 4.0e+5, 5.0e+5]
M_pg = [8,15,25,35,45,60]
V1g = 0.003785 # in m^3
M1g = 2.9 # in ... |
5,494 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Having difficulty generating a tridiagonal matrix from numpy arrays. I managed to replicate the results given here, but I'm not able to apply these techniques to my problem. I may a... | Problem:
from scipy import sparse
import numpy as np
matrix = np.array([[3.5, 13. , 28.5, 50. , 77.5],
[-5. , -23. , -53. , -95. , -149. ],
[2.5, 11. , 25.5, 46. , 72.5]])
result = sparse.spdiags(matrix, (1, 0, -1), 5, 5).T.A |
5,495 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
https
Step1: 3
Step2: 4
Step3: 5
Step4: 6 | Python Code:
# %sh
# wget https://raw.githubusercontent.com/fivethirtyeight/data/master/avengers/avengers.csv
# ls -l
Explanation: https://www.dataquest.io/mission/114/challenge-cleaning-data/
2: Life And Death Of Avengers
The Avengers are a well-known and widely loved team of superheroes in the Marvel universe that we... |
5,496 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This example will setup the required electronic structures for usage in TBtrans.
You will also learn the importance of perform $k$-point convergence tests for systems using TBtrans.
We will ... | Python Code:
graphene = sisl.geom.graphene(orthogonal=True)
H = sisl.Hamiltonian(graphene)
H.construct([[0.1, 1.43], [0., -2.7]])
Explanation: This example will setup the required electronic structures for usage in TBtrans.
You will also learn the importance of perform $k$-point convergence tests for systems using TBtr... |
5,497 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
QuTiP example
Step1: Two-level system
Step2: Harmonic oscillator
Step3: Zero temperature
Step4: Finite temperature
Step5: Storing states instead of expectation values
Step6: Atom-Cavi... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from qutip import *
Explanation: QuTiP example: Bloch-Redfield Master Equation
End of explanation
delta = 0.0 * 2 * np.pi
epsilon = 0.5 * 2 * np.pi
gamma = 0.25
times = np.linspace(0, 10, 100)
H = delta/2 * sigmax() + epsilon/2 * sigmaz... |
5,498 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transfer Learning
Most of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instea... | Python Code:
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
vgg_dir = 'tensorflow_vgg/'
# Make sure vgg exists
if not isdir(vgg_dir):
raise Exception("VGG directory doesn't exist!")
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=... |
5,499 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
You are a bird conservation expert and want to understand migration patterns of purple martins. In your research, you discover that these birds typically spend the summer breed... | Python Code:
import pandas as pd
import geopandas as gpd
from shapely.geometry import LineString
from learntools.core import binder
binder.bind(globals())
from learntools.geospatial.ex2 import *
Explanation: Introduction
You are a bird conservation expert and want to understand migration patterns of purple martins. In... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.