Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
10,400 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: 图像分类
在此项目中,你将对 CIFAR-10 数据集 中的图片进行分类。该数据集包含飞机、猫狗和其他物体。你需要预处理这些图片,然后用所有样本训练一个卷积神经网络。图片需要标准化(normalized),标签需要采用 one-hot 编码。你需要应用所学的知识构建卷积的、最大池化(max pooling)、丢弃(dropout)和完全连接(fully conne... | 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... |
10,401 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Atmospherically Corrected Earth Engine Time Series
Overview
This notebook creates atmospherically corrected time series of satellite imagery using Google Earth Engine and the 6S emulator.
S... | Python Code:
# standard modules
import os
import sys
import ee
import colorsys
from IPython.display import display, Image
%matplotlib inline
ee.Initialize()
# custom modules
# base_dir = os.path.dirname(os.getcwd())
# sys.path.append(os.path.join(base_dir,'atmcorr'))
from atmcorr.timeSeries import timeSeries
from atmco... |
10,402 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import Data
Step1: I downloaded the Zillow codes dataset
Step2: API Reference
Step3: Percent of homes increasing in value
Step4: Using Prophet for time series forecasting
Step5: Creatin... | Python Code:
import quandl
quandl.ApiConfig.api_key = '############'
Explanation: Import Data:
Explore the data.
Pick a starting point and create visualizations that might help understand the data better.
Come back and explore other parts of the data and create more visualizations and models.
Quandl is a great place to... |
10,403 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Keyboard shortcuts
In this notebook, you'll get some practice using keyboard shortcuts. These are key to becoming proficient at using notebooks and will greatly increase your work speed.
Fir... | Python Code:
# mode practice
Explanation: Keyboard shortcuts
In this notebook, you'll get some practice using keyboard shortcuts. These are key to becoming proficient at using notebooks and will greatly increase your work speed.
First up, switching between edit mode and command mode. Edit mode allows you to type into c... |
10,404 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Content and Objective
Showing results of fading on ber
Method
Step1: Parameters
Step2: Simulation
Step3: Plotting | Python Code:
# importing
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib
# showing figures inline
%matplotlib inline
# plotting options
font = {'size' : 30}
plt.rc('font', **font)
#plt.rc('text', usetex=True)
matplotlib.rc('figure', figsize=(30, 12) )
Explanation: Content... |
10,405 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyEarthScience
Step1: Generate x- and y-values.
Step2: Draw data, set title and axis labels.
Step3: Show the plot in this notebook. | Python Code:
import numpy as np
import Ngl, Nio
Explanation: PyEarthScience: Python examples for Earth Scientists
XY-plots
Using PyNGL
Line plot with
- marker
- different colors
- legend
- title
- x-axis label
- y-axis label
End of explanation
x2 = np.arange(100)
data = np.arange(1,40,5)
linear = np.arange(100)
squa... |
10,406 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small>
Challenge Notebook
Problem
Step1: Unit Test
The following unit test is expected to fa... | Python Code:
class Item(object):
def __init__(self, key, value):
# TODO: Implement me
pass
class HashTable(object):
def __init__(self, size):
# TODO: Implement me
pass
def hash_function(self, key):
# TODO: Implement me
pass
def set(self, key, value):
... |
10,407 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise 2
Step4: (a)
Let $f(x)=x^7$. Evaluate the derivative matrix and the derivatives at quadrature points using Gauss-Lobatto-Legendre quadrature with $Q=7,\ 8,\ 9$.
Step6: (b)
The sam... | Python Code:
import numpy
import re
from matplotlib import pyplot
from IPython.display import Latex, Math, display
% matplotlib inline
import os, sys
sys.path.append(os.path.split(os.path.split(os.getcwd())[0])[0])
import utils.quadrature as quad
import utils.poly as poly
Explanation: Exercise 2
End of explanation
def ... |
10,408 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
easysnmp
Step1: The type of .value is always a Python string but the string returned in .snmp_type can be used to convert to the correct Python type.
* INTEGER32
* INTEGER
* UNSIGNED32
* GA... | Python Code:
import easysnmp
session = easysnmp.Session(hostname='localhost', community='public', version=2,
timeout=1, retries=1, use_sprint_value=True)
# IMPORTANT: use_sprint_value=True for proper formatting of values
location = session.get('sysLocation.0')
location.oid, location.oid_inde... |
10,409 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
The goal of this Artificial Neural Network (ANN) 101 session is twofold
Step1: Get the data
Step2: Build the artificial neural-network
Step3: Train the artificial neural-netw... | Python Code:
# library to store and manipulate neural-network input and output data
import numpy as np
# library to graphically display any data
import matplotlib.pyplot as plt
# library to manipulate neural-network models
import torch
import torch.nn as nn
import torch.optim as optim
# the code is compatible with Tens... |
10,410 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Recursion (Recursive Program)
Recursion is a very important way of thinking in programming. It is a function that calls itself. Typical examples are Factorial and Fibonacchi Function.
5 out ... | Python Code:
def factorial(n):
'''
n: integer (n>=1)
returns n! (1*2*3*..*n)
'''
if n==1:
return 1
else:
return n * factorial(n-1) # n * (n-1)!
print('4!=', factorial(4))
print('10!=', factorial(10))
def fibonacchi(n):
'''
n: integer
return Fibonacchi numbe... |
10,411 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="images/logo.jpg" style="display
Step1: <p style="text-align
Step2: <p style="text-align
Step3: <p style="text-align
Step4: <p style="text-align
Step5: <p style="text-align
Ste... | Python Code:
items = ['banana', 'apple', 'carrot']
stock = [2, 3, 4]
Explanation: <img src="images/logo.jpg" style="display: block; margin-left: auto; margin-right: auto;" alt="לוגו של מיזם לימוד הפייתון. נחש מצויר בצבעי צהוב וכחול, הנע בין האותיות של שם הקורס: לומדים פייתון. הסלוגן המופיע מעל לשם הקורס הוא מיזם חינמי ... |
10,412 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gas-Phase Calculations
https
Step2: Add Master, Solution Species and Phases by executing PHREEQC input code
Step3: Run Calculation
Step4: Total Gas Pressure and Volume
Step5: Fixed Press... | Python Code:
%pylab inline
import phreeqpython
import pandas as pd
pp = phreeqpython.PhreeqPython(database='phreeqc.dat')
Explanation: Gas-Phase Calculations
https://wwwbrr.cr.usgs.gov/projects/GWC_coupled/phreeqc/phreeqc3-html/phreeqc3-62.htm#50528271_44022
End of explanation
pp.ip.run_string(
SOLUTION_MASTER_SPECIES
... |
10,413 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Figure 17, Plot of overall Froude number vs dimensionless amplitude
Start by loading some boiler plate
Step1: And some more specialized dependencies
Step2: Helper routines
Step3: Configur... | Python Code:
%matplotlib inline
import matplotlib
matplotlib.rcParams['figure.figsize'] = (10.0, 8.0)
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline
from scipy.interpolate import UnivariateSpline
import json
import pandas as pd
from functools import partial... |
10,414 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Get the data
2MASS => effective resolution of the 2MASS system is approximately 5"
WISE => 3.4, 4.6, 12, and 22 μm (W1, W2, W3, W4) with an angular resolution of 6.1", 6.4", 6.5", & 12.0"
G... | Python Code:
obj = ["PKS J0006-0623", 1.55789, -6.39315, 1]
# name, ra, dec, radius of cone
obj_name = obj[0]
obj_ra = obj[1]
obj_dec = obj[2]
cone_radius = obj[3]
obj_coord = coordinates.SkyCoord(ra=obj_ra, dec=obj_dec, unit=(u.deg, u.deg), frame="icrs")
data_2mass = Irsa.query_region(obj_coord, catalog="fp_psc", ... |
10,415 | Given the following text description, write Python code to implement the functionality described.
Description:
Sort a nearly sorted array using STL
Given an array of size n , where every element is k away from its target position , sorts the array in O ( n Log n ) time . ; Sort the array using inbuilt function ; An uti... | Python Code:
def sortK(arr , n , k ) :
arr . sort()
def printArray(arr , size ) :
for i in range(size ) :
print(arr[i ] , end = "▁ ")
print()
k = 3
arr =[2 , 6 , 3 , 12 , 56 , 8 ]
n = len(arr )
sortK(arr , n , k )
print("Following ▁ is ▁ sorted ▁ array ")
printArray(arr , n )
|
10,416 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cookbook recipe
Step1: Either create a new ipyrad assembly or load an existing one
Step2: Or load a finished assembly from its JSON file
Step3: Look at the stats summary for this assembly... | Python Code:
## import ipyrad and give it a shorter name
import ipyrad as ip
Explanation: Cookbook recipe: Access and plot ipyrad stats in R
Jupyter notebooks provide a convenient interface for sharing data and functions between Python and R through use of the Python rpy2 module. By combining all of your code from acro... |
10,417 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this example, we will use tensorflow.keras package to create a keras image classification application using model MobileNetV2, and transfer the application to Cluster Serving step by step... | Python Code:
import tensorflow as tf
import os
import PIL
tf.__version__
# Obtain data from url:"https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip"
zip_file = tf.keras.utils.get_file(origin="https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip",
... |
10,418 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Dataset Preparation
Overview
In this phase, a startups dataset will be properly created and prepared for further feature analysis. Different features will be created here by combining inf... | Python Code:
#All imports here
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing
from datetime import datetime
from dateutil import relativedelta
%matplotlib inline
#Let's start by importing our csv files into dataframes
df_companies = pd.read_csv('data/companies.c... |
10,419 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The series, $1^1 + 2^2 + 3^3 + ... + 10^{10} = 10405071317$.
Find the last ten digits of the series, $1^1 + 2^2 + 3^3 + ... + 1000^{1000}$.
Version 1
Step1: <!-- TEASER_END -->
This leaves ... | Python Code:
from six.moves import map, range, reduce
sum(map(lambda k: k**k, range(1, 1000+1))) % 10**10
Explanation: The series, $1^1 + 2^2 + 3^3 + ... + 10^{10} = 10405071317$.
Find the last ten digits of the series, $1^1 + 2^2 + 3^3 + ... + 1000^{1000}$.
Version 1: The obvious way
End of explanation
def prod_mod(nu... |
10,420 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hardware simulators - gem5 target support
The gem5 simulator is a modular platform for computer-system architecture research, encompassing system-level architecture as well as processor micr... | Python Code:
from conf import LisaLogging
LisaLogging.setup()
# One initial cell for imports
import json
import logging
import os
from env import TestEnv
# Suport for FTrace events parsing and visualization
import trappy
from trappy.ftrace import FTrace
from trace import Trace
# Support for plotting
# Generate plots in... |
10,421 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear regression homework with Yelp votes
Introduction
This assignment uses a small subset of the data from Kaggle's Yelp Business Rating Prediction competition.
Description of the data
Ste... | Python Code:
# access yelp.csv using a relative path
import pandas as pd
yelp = pd.read_csv('../data/yelp.csv')
yelp.head(1)
Explanation: Linear regression homework with Yelp votes
Introduction
This assignment uses a small subset of the data from Kaggle's Yelp Business Rating Prediction competition.
Description of the ... |
10,422 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Craftcans.com - cleaning
Craftcans.com provides a database of 2692 crafted canned beers. The data on beers includes the following variables
Step1: As it can be seen above, the header row is... | Python Code:
import pandas, re
data = pandas.read_excel("craftcans.xlsx")
data.head()
Explanation: Craftcans.com - cleaning
Craftcans.com provides a database of 2692 crafted canned beers. The data on beers includes the following variables:
Name
Style
Size
Alcohol by volume (ABV)
IBU’s
Brewer name
Brewer location
Howeve... |
10,423 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistic Regression with L2 regularization
The goal of this second notebook is to implement your own logistic regression classifier with L2 regularization. You will do the following
Step1: ... | Python Code:
from __future__ import division
import graphlab
Explanation: Logistic Regression with L2 regularization
The goal of this second notebook is to implement your own logistic regression classifier with L2 regularization. You will do the following:
Extract features from Amazon product reviews.
Convert an SFrame... |
10,424 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generating the phase diagram
To generate a phase diagram, we obtain entries from the Materials Project and call the PhaseDiagram class in pymatgen.
Step1: Plotting the phase diagram
To plot... | Python Code:
#This initializes the REST adaptor. You may need to put your own API key in as an arg.
a = MPRester()
#Entries are the basic unit for thermodynamic and other analyses in pymatgen.
#This gets all entries belonging to the Ca-C-O system.
entries = a.get_entries_in_chemsys(['Ca', 'C', 'O'])
#With entries, you ... |
10,425 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learning Unsupervised Embeddings for Molecules
In this tutorial, we will use a SeqToSeq model to generate fingerprints for classifying molecules. This is based on the following paper, altho... | Python Code:
!pip install --pre deepchem
import deepchem
deepchem.__version__
Explanation: Learning Unsupervised Embeddings for Molecules
In this tutorial, we will use a SeqToSeq model to generate fingerprints for classifying molecules. This is based on the following paper, although some of the implementation details ... |
10,426 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FloPy
MODFLOW-USG $-$ Discontinuous water table configuration over a stairway impervious base
One of the most challenging numerical cases for MODFLOW arises from drying-rewetting problems of... | Python Code:
%matplotlib inline
import os
import sys
import platform
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import flopy
print(sys.version)
print('numpy version: {}'.format(np.__version__))
print('matplotlib version: {}'.format(mpl.__version__))
print('flopy version: {}'.format(flop... |
10,427 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Singular Value Decomposition Notes
Code examples from andrew.gibiansky.com tutorial
Step1: Step 1
Step2: Step 2
Step4: Step 3 | Python Code:
%matplotlib inline
Explanation: Singular Value Decomposition Notes
Code examples from andrew.gibiansky.com tutorial
End of explanation
from scipy import ndimage, misc
import matplotlib.pyplot as plt
tiger = misc.imread('tiger.jpg', flatten=True)
def show_grayscale(values):
plt.gray()
plt.imshow(va... |
10,428 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Continuous Factors
Base Class for Continuous Factors
Joint Gaussian Distributions
Canonical Factors
Linear Gaussian CPD
In many situations, some variables are best modeled as taking values i... | Python Code:
import numpy as np
from scipy.special import beta
# Two variable drichlet ditribution with alpha = (1,2)
def drichlet_pdf(x, y):
return (np.power(x, 1)*np.power(y, 2))/beta(x, y)
from pgmpy.factors import ContinuousFactor
drichlet_factor = ContinuousFactor(['x', 'y'], drichlet_pdf)
drichlet_factor.sco... |
10,429 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 1
Step1: 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 dom... | Python Code:
# Importing
import theano.tensor as T
import sys, os
sys.path.append("../GeMpy")
# Importing GeMpy modules
import GeMpy_core
import Visualization
# Reloading (only for development purposes)
import importlib
importlib.reload(GeMpy_core)
importlib.reload(Visualization)
# Usuful packages
import numpy as np
im... |
10,430 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deploy and predict with Keras model on Cloud AI Platform.
Learning Objectives
Setup up the environment
Deploy trained Keras model to Cloud AI Platform
Online predict from model on Cloud AI P... | Python Code:
import os
Explanation: Deploy and predict with Keras model on Cloud AI Platform.
Learning Objectives
Setup up the environment
Deploy trained Keras model to Cloud AI Platform
Online predict from model on Cloud AI Platform
Batch predict from model on Cloud AI Platform
Introduction
Verify that you have previo... |
10,431 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DM_08_04
Import packages
We'll create a hidden Markov model to examine the state-shifting in the dataset.
Step1: Import data
Read CSV file into "df."
Step2: Drop the row number and "corr" ... | Python Code:
% matplotlib inline
import pylab
import numpy as np
import pandas as pd
from hmmlearn.hmm import GaussianHMM
Explanation: DM_08_04
Import packages
We'll create a hidden Markov model to examine the state-shifting in the dataset.
End of explanation
df = pd.read_csv("speed.csv", sep = ",")
df.head(5)
Explanat... |
10,432 | 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', 'mohc', 'sandbox-3', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: MOHC
Source ID: SANDBOX-3
Topic: Atmoschem
Sub-Topics: Transport, Emi... |
10,433 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mitchell-Schaeffer - First Version
This is my first pass, which ended up somewhat similar to the rat data Ian showed.
Model is Mitchell-Schaeffer as shown in Eqn 3.1 from Ian's thesis
Step1:... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
# h steady-state value
def h_inf(Vm=0.0):
return 0.0 # TODO??
# Input stimulus
def Id(t):
if 5.0 < t < 6.0:
return 1.0
elif 20.0 < t < 21.0:
return 1.0
return 0.0
# Compute derivative... |
10,434 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to NLTK
NLTK is the Natural Language Toolkit, a fairly large Python library for doing many sorts of linguistic analysis of text. NLTK comes with a selection of sample texts that... | Python Code:
from nltk.book import *
Explanation: Introduction to NLTK
NLTK is the Natural Language Toolkit, a fairly large Python library for doing many sorts of linguistic analysis of text. NLTK comes with a selection of sample texts that we'll use to day, to get yourself familiar with what sorts of analysis you can ... |
10,435 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Variational Equations With the Chain Rule
For a complete introduction to variational equations, please read the paper by Rein and Tamayo (2016).
Variational equations can be used to ca... | Python Code:
import rebound
import numpy as np
Explanation: Using Variational Equations With the Chain Rule
For a complete introduction to variational equations, please read the paper by Rein and Tamayo (2016).
Variational equations can be used to calculate derivatives in an $N$-body simulation. More specifically, give... |
10,436 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Modify Module
Step1: The last row of this data set repeats the labels. We're going to go ahead and omit it.
Step2: We're going to predict whether a job is still open, so our label will... | Python Code:
import diogenes
data = diogenes.read.open_csv_url('https://data.cityofchicago.org/api/views/mab8-y9h3/rows.csv?accessType=DOWNLOAD',
parse_datetimes=['Creation Date', 'Completion Date'])
Explanation: The Modify Module
:mod:diogenes.modify provides tools for manipulating a... |
10,437 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div id="toc"></div>
Step1: Method
Step2: Load det_df, channel lists
Step3: Load bhp data
Do I have a bhp distribution saved that I can load directly? I would rather not have to load and ... | Python Code:
%%javascript
$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')
Explanation: <div id="toc"></div>
End of explanation
import numpy as np
import scipy.io as sio
import os
import sys
import matplotlib.pyplot as plt
import matplotlib.colors
from matplotlib.pyplot import... |
10,438 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook contains a simple image classification convolutional neural network using the MNIST data. <br>
It is highly recommended to read the following blog post while going through the ... | Python Code:
## Keras related imports
from keras.datasets import mnist
from keras.models import Sequential, model_from_json
from keras.layers import Activation, Dropout, Flatten, Dense, Convolution2D, MaxPooling2D
from keras.utils import np_utils, data_utils, visualize_util
from keras.preprocessing.image import load_im... |
10,439 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
JointAnalyzer assumes the individual audio analysis and score analysis is applied earlier.
Step1: First we compute the input score and audio features for joint analysis.
Step2: Next, you c... | Python Code:
data_folder = os.path.join('..', 'sample-data')
# score inputs
symbtr_name = 'ussak--sazsemaisi--aksaksemai----neyzen_aziz_dede'
txt_score_filename = os.path.join(data_folder, symbtr_name, symbtr_name + '.txt')
mu2_score_filename = os.path.join(data_folder, symbtr_name, symbtr_name + '.mu2')
# instantiate
... |
10,440 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Collective intelligence
Step1: Build models
Lookin' good! Let's convert the data into a nice format. We rearrange some columns, check out what the columns are.
Step2: 4) Majority vote on c... | Python Code:
import wget
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
# Import the dataset
data_url = 'https://raw.githubusercontent.com/nslatysheva/data_science_blogging/master/datasets/wine/winequality-red.csv'
dataset = wget.download(data_url)
dataset = pd.read_csv(dat... |
10,441 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing Data using Python and SQLite3
SQLite basics
Create a connection
conn = sqlite3.connect('database_file')
cur = conn.curser()
Execute SQL commands
execute
Step1: Setup/create a tabl... | Python Code:
import sqlite3
conn = sqlite3.connect('election_tweets.sqlite')
cur = conn.cursor()
Explanation: Analyzing Data using Python and SQLite3
SQLite basics
Create a connection
conn = sqlite3.connect('database_file')
cur = conn.curser()
Execute SQL commands
execute: cur.execute('SQL COMMANDS')
commit to save cha... |
10,442 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This notebook compares the annotated results of the "blocked" vs. "random" dataset of wikipedia talk pages. The "blocked" dataset consists of the few last comments before a user... | Python Code:
%matplotlib inline
from __future__ import division
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
pd.set_option('display.width', 1000)
pd.set_option('display.max_colwidth', 1000)
# Download data from google drive (Respect Eng / Wiki Collab): wikipdia data/v2_annotated
blocked_dat = ... |
10,443 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Goal
Simulating fullCyc Day1 control gradients
Not simulating incorporation (all 0% isotope incorp.)
Don't know how much true incorporatation for emperical data
Using parameters inferred fro... | Python Code:
import os
import glob
import re
import nestly
%load_ext rpy2.ipython
%load_ext pushnote
%%R
library(ggplot2)
library(dplyr)
library(tidyr)
library(gridExtra)
library(phyloseq)
## BD for G+C of 0 or 100
BD.GCp0 = 0 * 0.098 + 1.66
BD.GCp100 = 1 * 0.098 + 1.66
Explanation: Goal
Simulating fullCyc Day1 control... |
10,444 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture 22
Step1: We start by using the ordinary free energy of the pure components
Step2: $$L(\phi,\nabla\phi) = \int_V \Big[ ~~f(\phi,T) + \frac{\epsilon^2_\phi}{2}|\nabla \phi|^2~\Big]~... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook
def plot_p_and_g():
phi = np.linspace(-0.1, 1.1, 200)
g=phi**2*(1-phi)**2
p=phi**3*(6*phi**2-15*phi+10)
# Changed 3 to 1 in the figure call.
plt.figure(1, figsize=(12,6))
plt.subplot(121)
plt.plot(phi, g, li... |
10,445 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Usage
Basic usage example, where the code table is built based on given symbol frequencies
Step1: You can also "train" the codec by providing it data directly
Step2: Non-string sequences
U... | Python Code:
codec = dahuffman.HuffmanCodec.from_frequencies({'e': 100, 'n':20, 'x':1, 'i': 40, 'q':3})
encoded = codec.encode('exeneeeexniqneieini')
print(encoded)
print(encoded.hex())
print(len(encoded))
codec.decode(encoded)
codec.print_code_table()
Explanation: Usage
Basic usage example, where the code table is bui... |
10,446 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: About Python
Created in 1991 by Guido van Rossum
Step2: Control flow
Built-in functions and types
Sequence types
References and mutability
Dicts and sets
Comprehensions
Functions are... | Python Code:
def fibonacci(n):
return Nth number in the Fibonacci series
a, b = 0, 1
while n:
a, b = b, a + b
n -= 1
return a
for n in range(20):
print(fibonacci(n))
for i, n in enumerate(range(20)):
print('%2d -> %4d' % (i, fibonacci(n)))
Explanation: About Python
Created in 199... |
10,447 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Titanic Dataset
Step1: Preprocessing
Cleaning
Step2: Feature Engineering
We can also generate new features. Here are some ideas
Step3: Using The Title
We can extract the title of the pass... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn import cross_validation
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
Explanation: Titanic Dataset
End of explanation
titanic = pd.read_csv("data/trai... |
10,448 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: 勾配ブースティング木
Step2: 特徴量の説明については、前のチュートリアルをご覧ください。
特徴量カラム、input_fn、を作成して Estimator をトレーニングする
データを処理する
元の数値カラムをそのまま、そして One-Hot エンコーディングカテゴリ変数を使用し... | 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... |
10,449 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This IPython Notebook illustrates the use of the openmc.mgxs.Library class. The Library class is designed to automate the calculation of multi-group cross sections for use cases with one or ... | Python Code:
import math
import pickle
from IPython.display import Image
import matplotlib.pyplot as plt
import numpy as np
import openmc
import openmc.mgxs
import openmoc
import openmoc.process
from openmoc.opencg_compatible import get_openmoc_geometry
from openmoc.materialize import load_openmc_mgxs_lib
%matplotlib i... |
10,450 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Setup
Step2: Data and model
Step3: HMC
Step4: Blackjax | Python Code:
import jax
print(jax.devices())
!git clone https://github.com/google-research/google-research.git
%cd /content/google-research
!ls bnn_hmc
!pip install optax
Explanation: <a href="https://colab.research.google.com/github/probml/probml-notebooks/blob/main/notebooks/bnn_hmc_gaussian.ipynb" target="_parent"><... |
10,451 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas 데이터 입출력
이 노트북의 예제를 실행하기 위해서는 datascienceschool/rpython 도커 이미지의 다음 디렉토리로 이동해야 한다.
Step1: pandas 데이터 입출력 종류
CSV
Clipboard
Excel
JSON
HTML
Python Pickling
HDF5
SAS
STATA
SQL
Google BigQ... | Python Code:
%cd /home/dockeruser/data/pydata-book-master/
Explanation: Pandas 데이터 입출력
이 노트북의 예제를 실행하기 위해서는 datascienceschool/rpython 도커 이미지의 다음 디렉토리로 이동해야 한다.
End of explanation
!cat ../../pydata-book-master/ch06/ex1.csv
!cat ch06/ex1.csv
df = pd.read_csv('../../pydata-book-master/ch06/ex1.csv')
df
Explanation: pandas... |
10,452 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with Projections
This section of the tutorial discusses map projections. If you don't know what a projection is, or are looking to learn more about how they work in geoplot, this pag... | Python Code:
import geopandas as gpd
import geoplot as gplt
%matplotlib inline
# load the example data
contiguous_usa = gpd.read_file(gplt.datasets.get_path('contiguous_usa'))
gplt.polyplot(contiguous_usa)
Explanation: Working with Projections
This section of the tutorial discusses map projections. If you don't know wh... |
10,453 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
오류 및 예외 처리
개요
코딩할 때 발생할 수 있는 다양한 오류 살펴 보기
오류 메시지 정보 확인 방법
예외 처리, 즉 오류가 발생할 수 있는 예외적인 상황을 미리 고려하는 방법 소개
오늘의 주요 예제
아래 코드는 raw_input() 함수를 이용하여 사용자로부터 숫자를 입력받아 그 숫자의 제곱을 리턴하고자 하는 내용을 담고 있다. 코드를... | Python Code:
from __future__ import print_function
input_number = raw_input("A number please: ")
number = int(input_number)
print("제곱의 결과는", number**2, "입니다.")
Explanation: 오류 및 예외 처리
개요
코딩할 때 발생할 수 있는 다양한 오류 살펴 보기
오류 메시지 정보 확인 방법
예외 처리, 즉 오류가 발생할 수 있는 예외적인 상황을 미리 고려하는 방법 소개
오늘의 주요 예제
아래 코드는 raw_input() 함수를 이용하여 사용자로부터... |
10,454 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
Step1: 1. Multiplication
The product of Gaussians comes up, for example, when the sampling distributions for different data points are independent Gaussians, or when the sampling d... | Python Code:
exec(open('tbc.py').read()) # define TBC and TBC_above
import numpy as np
import scipy.stats as st
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Tutorial: Gaussians and Least Squares
So far in the notes and problems, we've mostly avoided one of th... |
10,455 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Landice
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', 'ncc', 'noresm2-mm', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: NCC
Source ID: NORESM2-MM
Topic: Landice
Sub-Topics: Glaciers, Ice.
Prop... |
10,456 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2. Crear vocabulario
En un principio partiremos de las características de HoG para crear nuestro vocabulario, aunque se podría hacer con cualquier otras.
Importamos las características
Step... | Python Code:
import pickle
path = '../../rsc/obj/'
X_train_path = path + 'X_train.sav'
train_features = pickle.load(open(X_train_path, 'rb'))
# import pickle # Módulo para serializar
# import numpy as np
# path = '..//..//rsc//obj//BoW_features//'
# for i in (15000,30000,45000,53688):
# daisy_features_path = path +... |
10,457 | 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', 'mohc', 'sandbox-3', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: MOHC
Source ID: SANDBOX-3
Topic: Aerosol
Sub-Topics: Transport, Emissions... |
10,458 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sveučilište u Zagrebu<br>
Fakultet elektrotehnike i računarstva
Strojno učenje
<a href="http
Step1: Sadržaj
Step2: Nagib sigmoide može se regulirati množenjem ulaza određenim faktorom
Step... | Python Code:
import scipy as sp
import scipy.stats as stats
import matplotlib.pyplot as plt
import pandas as pd
%pylab inline
Explanation: Sveučilište u Zagrebu<br>
Fakultet elektrotehnike i računarstva
Strojno učenje
<a href="http://www.fer.unizg.hr/predmet/su">http://www.fer.unizg.hr/predmet/su</a>
Ak. god. 2015./201... |
10,459 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time Series Forecast with Basic RNN
Dataset is downloaded from https
Step2: Note
Scaling the variables will make optimization functions work better, so here going to scale the variable into... | Python Code:
import pandas as pd
import numpy as np
import datetime
from matplotlib import pyplot as plt
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler
df = pd.read_csv('data/pm25.csv')
print(df.shape)
df.head()
df.isnull().sum()*100/df.shape[0]
df.dropna(subset=['pm2.5'], axis=0, inplace=True)
df... |
10,460 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: <table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" ... | Python Code:
#@title Copyright 2020 The TensorFlow Hub Authors. All Rights Reserved.
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... |
10,461 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Query Meta data in database Groups [v1.1]
Step1: Setup
Step2: Check one of the meta tables
Step3: Query meta with Query dict
A simple example
Step4: Another example
Step5: One more
Step... | Python Code:
# imports
from astropy import units as u
from astropy.coordinates import SkyCoord
import specdb
from specdb.specdb import SpecDB
from specdb import specdb as spdb_spdb
from specdb.cat_utils import flags_to_groups
Explanation: Query Meta data in database Groups [v1.1]
End of explanation
db_file = specdb.__p... |
10,462 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome!
Let's start by assuming you have downloaded the code, and ran the setup.py . This demonstration will show the user how predict the time constant of their trEFM data using the method... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from trEFMlearn import data_sim
%matplotlib inline
Explanation: Welcome!
Let's start by assuming you have downloaded the code, and ran the setup.py . This demonstration will show the user how predict the time constant of their trEFM data using the methods ... |
10,463 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Grade
Step1: print a list of Lil's that are more popular than Lil's Kim
Step2: Pick two of your favorite Lils to fight it out, and use their IDs to print out their top tracks
Step3: Will ... | Python Code:
import requests
!pip3 install requests
response = requests.get("https://api.spotify.com/v1/search?q=Lil&type=artist&market=US&limit=50")
print(response.text)
data = response.json()
type(data)
data.keys()
data['artists'].keys()
artists=data['artists']
type(artists['items'])
artist_info = artists['items']
fo... |
10,464 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Strings
Step1: <font color="red"><i>Note
Step2: <img src="../images/string_indices.png">
Step3: Formatting | Python Code:
# this is an empty string
empty_str = ''
# create a string
str1 = ' the quick brown fox jumps over the lazy dog. '
str1
# strip whitespaces from the beginning and ending of the string
str2=str1.strip()
print str2
print str1
# this capitalizes the 1st letter of the string
str2.capitalize()
# count the num... |
10,465 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Time series prediction using RNNs, with TensorFlow and Cloud ML Engine </h1>
This notebook illustrates
Step1: <h2> RNN </h2>
For more info, see
Step2: <h3> Input Fn to read CSV </h3>
... | Python Code:
!pip install --upgrade tensorflow
import tensorflow as tf
print tf.__version__
import numpy as np
import tensorflow as tf
import seaborn as sns
import pandas as pd
SEQ_LEN = 10
def create_time_series():
freq = (np.random.random()*0.5) + 0.1 # 0.1 to 0.6
ampl = np.random.random() + 0.5 # 0.5 to 1.5
... |
10,466 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sistemas de ecuaciones lineales
En este notebook vamos a ver conceptos básicos para resolver sistemas de ecuaciones lineales.
La estructura de esta presentación está basada en http
Step1: S... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Sistemas de ecuaciones lineales
En este notebook vamos a ver conceptos básicos para resolver sistemas de ecuaciones lineales.
La estructura de esta presentación está basada en http://nbviewer.ipython.org/github/mbakker7/expl... |
10,467 | Given the following text description, write Python code to implement the functionality described.
Description:
Same Number Of Set Bits As N
; function ; __builtin_popcount function that count set bits in n ; Iterate from n - 1 to 1 ; check if the number of set bits equals to temp increment count ; Driver Code
| Python Code:
/ * returns number of set bits in a number * /
def __builtin_popcount(n ) :
t = 0
while(n > 0 ) :
d = n % 2
n = int(n / 2 )
if(d == 1 ) :
t = t + 1
return t
def smallerNumsWithSameSetBits(n ) :
temp = __builtin_popcount(n )
count = 0
for i in range(n - 1 , 0 , - 1 ) :
i... |
10,468 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Exploring deaths of notable people by year in Wikipedia
By R. Stuart Geiger, last updated 2016-12-28
Dual-licensed under CC-BY-SA 4.0 and the MIT License.
How many articles are in the... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
%matplotlib inline
matplotlib.style.use('seaborn-darkgrid')
import pywikibot
site = pywikibot.Site('en', 'wikipedia')
def yearly_death_counts(startyear,endyear):
years = np.arange(startyear,endyear+1) # add 1 to en... |
10,469 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TOC trends October 2016 (part 2)
This notebook continues the work described here, where my latest trends code was modified and tested. My aim here is to use the code to generate trends resul... | Python Code:
# Import custom functions
# Connect to db
resa2_basic_path = (r'C:\Data\James_Work\Staff\Heleen_d_W\ICP_Waters\Upload_Template'
r'\useful_resa2_code.py')
resa2_basic = imp.load_source('useful_resa2_code', resa2_basic_path)
engine, conn = resa2_basic.connect_to_resa2()
# Import code for ... |
10,470 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Collection - Crawling Flight Crash Data
This is the first step in our project. The code below shows a crawler (written using BeautifulSoup, the old school way) that gets raw HTML data f... | Python Code:
__author__ = 'shivam_gaur'
import requests
from bs4 import BeautifulSoup
import re
import os
import pymongo
from pymongo import MongoClient
import datetime
Explanation: Data Collection - Crawling Flight Crash Data
This is the first step in our project. The code below shows a crawler (written using Beautifu... |
10,471 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: STACKING DECORATORS
Lets look at decorators again. They're related to what we call "function composition" in that the decorator "eats" what's defined just below it, and returns a pro... | Python Code:
def plus(char):
returns a prepped adder to eat the target, and to
build a little lambda that does the job.
def adder(f):
return lambda s: f(s) + char
return adder
@plus('R')
def ident(s):
return s
ident('X') # do the job!
Explanation: STACKING DECORATORS
Lets loo... |
10,472 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Image Segmentation with Convolutional Neural Networks (CNNs)
Image segmentation
Here, we focus on using Convolutional Neural Networks or CNNs for segmenting images. Specifically, we us... | Python Code:
import os
import numpy as np
np.random.seed(123)
import pandas as pd
from glob import glob
import matplotlib.pyplot as plt
%matplotlib inline
import keras.backend as K
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D, BatchNormalization,... |
10,473 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Batch Normalization – Practice
Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll create a convolutional neural network with 20 convolutional l... | Python Code:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False)
Explanation: Batch Normalization – Practice
Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll crea... |
10,474 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Batch Normalization – Practice
Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll create a convolutional neural network with 20 convolutional l... | Python Code:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False)
Explanation: Batch Normalization – Practice
Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll crea... |
10,475 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A simple pipeline using hypergroup to perform community detection and network analysis
A social network of a karate club was studied by Wayne W. Zachary [1] for a period of three years from ... | Python Code:
import swat
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
# Also import networkx used for rendering a network
import networkx as nx
%matplotlib inline
Explanation: A simple pipeline using hypergroup to perfo... |
10,476 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework 14 (or so)
Step1: You can explore the files if you'd like, but we're going to get the ones from convote_v1.1/data_stage_one/development_set/. It's a bunch of text files.
Step2: So... | Python Code:
# If you'd like to download it through the command line...
!curl -O http://www.cs.cornell.edu/home/llee/data/convote/convote_v1.1.tar.gz
# And then extract it through the command line...
!tar -zxf convote_v1.1.tar.gz
Explanation: Homework 14 (or so): TF-IDF text analysis and clustering
Hooray, we kind of f... |
10,477 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Embedded Operator Splitting (EOS) Methods
This examples shows how to use the Embedded Operator Splitting (EOS) Methods described in Rein (2019). The idea is to embedded one operator splittin... | Python Code:
import rebound
%matplotlib inline
import matplotlib.pylab as plt
import numpy as np
import time
linestyles = ["--","-","-.",":"]
labels = {"LF": "LF", "LF4": "LF4", "LF6": "LF6", "LF8": "LF8", "LF4_2": "LF(4,2)", "LF8_6_4": "LF(8,6,4)", "PLF7_6_4": "PLF(7,6,4)", "PMLF4": "PMLF4", "PMLF6": "PMLF6"}
Explanat... |
10,478 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The following code will take the CLI commands produced in 01-JJA-L2V-Configuration-Files notebook
You need to install aws cli
http
Step1: This function will format the AWS CLI commands so... | Python Code:
from load_config import params_to_cli
llr, emb, pred,evaluation = params_to_cli("CONFIGS/ex1-ml-1m-config.yml", "CONFIGS/ex4-du04d100w10l80n10d30p1q1-1000-081417-params.yml")
llr
evaluation
Explanation: The following code will take the CLI commands produced in 01-JJA-L2V-Configuration-Files notebook
Yo... |
10,479 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I am trying to vectorize some data using | Problem:
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
corpus = [
'We are looking for Java developer',
'Frontend developer with knowledge in SQL and Jscript',
'And this is the third one.',
'Is this the first document?',
]
vectorizer = CountVectorizer(... |
10,480 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring the trajectory of a single patient
Import Python libraries
We first need to import some tools for working with data in Python.
- NumPy is for working with numbers
- Pandas is for ... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sqlite3
%matplotlib inline
Explanation: Exploring the trajectory of a single patient
Import Python libraries
We first need to import some tools for working with data in Python.
- NumPy is for working with numbers
- Pandas is for... |
10,481 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cluster Analysis
This notebook prototypes the cluster analysis visualizers that I'm currently putting together.
NOTE
Step1: Elbow Method
This method runs multiple clustering instances and c... | Python Code:
import sys
sys.path.append("../..")
import numpy as np
import yellowbrick as yb
import matplotlib.pyplot as plt
from functools import partial
from sklearn.datasets import make_blobs as sk_make_blobs
from sklearn.datasets import make_circles, make_moons
# Helpers for easy dataset creation
N_SAMPLES = 10... |
10,482 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Prepare Datasets
Once the datasets are obtained, they must be aligned and cropped to the same region. In this notebook, we crop the Planet scene and ground truth data to the aoi.
The section... | Python Code:
from collections import namedtuple
import copy
import json
import os
import pathlib
import shutil
import subprocess
import tempfile
import ipyleaflet as ipyl
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import rasterio
from shapely.geometry import shape, mapping
%matplotlib inline
E... |
10,483 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ch 09
Step1: Define the placeholders and variables for the CNN model
Step2: Define helper functions for the convolution and maxpool layers
Step3: The CNN model is defined all within the f... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import cifar_tools
import tensorflow as tf
learning_rate = 0.001
names, data, labels = \
cifar_tools.read_data('./cifar-10-batches-py')
Explanation: Ch 09: Concept 03
Convolution Neural Network
Load data from CIFAR-10.
End of explanation
x = tf.placeho... |
10,484 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
How can I get get the indices of the largest value in a multi-dimensional NumPy array `a`? | Problem:
import numpy as np
a = np.array([[10,50,30],[60,20,40]])
result = np.unravel_index(a.argmax(), a.shape) |
10,485 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with Streaming Data
Learning Objectives
1. Learn how to process real-time data for ML models using Cloud Dataflow
2. Learn how to serve online predictions using real-time data
Intr... | Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
import os
import googleapiclient.discovery
import shutil
from google.cloud import bigquery
from google.api_core.client_options import ClientOptions
from matplotlib import pyplot as plt
import numpy as np
import tensorflow as tf
from tensorf... |
10,486 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ansible is
configuration manager
simple
extensible via modules
written in python
broad community
many external tools
playbook repository
used by openstack, openshift & tonns of project
# C... | Python Code:
cd /notebooks/exercise-00/
# Let's check our ansible directory
!tree
Explanation: Ansible is
configuration manager
simple
extensible via modules
written in python
broad community
many external tools
playbook repository
used by openstack, openshift & tonns of project
# Configuration Manager
Explain infras... |
10,487 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinary Differential Equations Exercise 1
Imports
Step2: Euler's method
Euler's method is the simplest numerical approach for solving a first order ODE numerically. Given the differential ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy.integrate import odeint
from IPython.html.widgets import interact, fixed
Explanation: Ordinary Differential Equations Exercise 1
Imports
End of explanation
def solve_euler(derivs, y0, x):
Solve a 1d O... |
10,488 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TODO
Step1: Коэффициент для учета вклада гелия в массу газа (см. Notes)
Step2: Коэффициент, с которым пересчитывается масса молекулярного газа
Step3: Путь для картинок в статью
Step4: Пу... | Python Code:
%run ../../utils/load_notebook.py
from instabilities import *
import numpy as np
Explanation: TODO: сделать так, чтобы можно было импортировать
End of explanation
He_coeff = 1.36
Explanation: Коэффициент для учета вклада гелия в массу газа (см. Notes):
End of explanation
X_CO = 1.9
Explanation: Коэффициент... |
10,489 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Locality Sensitive Hashing
Locality Sensitive Hashing (LSH) provides for a fast, efficient approximate nearest neighbor search. The algorithm scales well with respect to the number of data p... | Python Code:
import numpy as np
import graphlab
from scipy.sparse import csr_matrix
from scipy.sparse.linalg import norm
from sklearn.metrics.pairwise import pairwise_distances
import time
from copy import copy
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Locality Sensitive Hashing
Locality Sensitive... |
10,490 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced Visualizations with TensorFlow Data Validaiton
Learning Objectives
Install TFDV
Compute and visualize statistics
Infer a schema
Check evaluation data for errors
Check for evaluation... | Python Code:
!pip install pyarrow==5.0.0
!pip install numpy==1.19.2
!pip install tensorflow-data-validation
Explanation: Advanced Visualizations with TensorFlow Data Validaiton
Learning Objectives
Install TFDV
Compute and visualize statistics
Infer a schema
Check evaluation data for errors
Check for evaluation anomalie... |
10,491 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This module helps solve systems of linear equations. There are several ways of doing this. The first is to just pass the coefficients as a list of lists. Say we want to solve the system of e... | Python Code:
import linear_solver as ls
xs = ls.solve_linear_system(
[[1, -1, 5],
[1, 1, -1]])
print(xs)
Explanation: This module helps solve systems of linear equations. There are several ways of doing this. The first is to just pass the coefficients as a list of lists. Say we want to solve the system of equ... |
10,492 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ROP Exam Analysis for NIRS and Pulse Ox
Finalized notebook to combine Masimo and NIRS Data into one iPython Notebook.
Select ROP Subject Number and Input Times
Step1: Baseline Average Calcu... | Python Code:
from ROP import *
#Takes a little bit, wait a while.
#ROP Number syntax: ###
#Eye Drop syntax: HH MM HH MM HH MM
#Exam Syntax: HH MM HH MM
Explanation: ROP Exam Analysis for NIRS and Pulse Ox
Finalized notebook to combine Masimo and NIRS Data into one iPython Notebook.
Select ROP Subject Number and Input T... |
10,493 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting topographic arrowmaps of evoked data
Load evoked data and plot arrowmaps along with the topomap for selected time
points. An arrowmap is based upon the Hosaka-Cohen transformation a... | Python Code:
# Authors: Sheraz Khan <sheraz@khansheraz.com>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne.datasets import sample
from mne.datasets.brainstorm import bst_raw
from mne import read_evokeds
from mne.viz import plot_arrowmap
print(__doc__)
path = sample.data_path()
fname = path + '/MEG/s... |
10,494 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introductory tutorial
pydov provides machine access to the data that can be visualized with the DOV viewer.
All the pydov functionalities rely on the existing DOV webservices. An in-depth ov... | Python Code:
%matplotlib inline
import inspect, sys
import pydov
import pandas as pd
Explanation: Introductory tutorial
pydov provides machine access to the data that can be visualized with the DOV viewer.
All the pydov functionalities rely on the existing DOV webservices. An in-depth overview of the available services... |
10,495 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Wilkinson Power Divider
In this notebook we create a Wilkinson power divider, which splits an input signal into two equals phase output signals. Theoretical results about this circuit are ex... | Python Code:
# standard imports
import numpy as np
import matplotlib.pyplot as plt
import skrf as rf
rf.stylely()
# frequency band
freq = rf.Frequency(start=0, stop=2, npoints=501, unit='GHz')
# characteristic impedance of the ports
Z0_ports = 50
# resistor
R = 100
line_resistor = rf.media.DefinedGammaZ0(frequency=freq... |
10,496 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: TensorFlow execution
Colaboratory allows you to execute TensorFlow code in your browser with a single click. The example below adds two matrices.
$\begin{bmatrix}
1.... | Python Code:
Hi. Can it be saved?
Explanation: <a href="https://colab.research.google.com/github/jiaqi-w/CoreNLPExampleCode/blob/master/Hello%2C_Colaboratory.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
Getting Started
Overview of Colaboratory
Loa... |
10,497 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Работа 1.3. Изучение колебаний на примере физического маятника
Цель работы
Step1: Определение величины свободного падения и длины стержня с помощью физического маятника
Обозначим через $l$ ... | Python Code:
import numpy as np
import scipy as ps
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Работа 1.3. Изучение колебаний на примере физического маятника
Цель работы: исследовать физический и математический маятники как колебательные системы, измерить зависимость периода коле... |
10,498 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MRC Gain
This notebook illustrates the gains obtained when using MRC in a SIMO system. It reproduces the results found here.
Initializations
First we set the Python path and import some libr... | Python Code:
%matplotlib inline
import numpy as np
from pyphysim.util.conversion import linear2dB
from pyphysim.util.misc import randn_c
Explanation: MRC Gain
This notebook illustrates the gains obtained when using MRC in a SIMO system. It reproduces the results found here.
Initializations
First we set the Python path ... |
10,499 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
License
Copyright (C) 2017 J. Patrick Hall, jphall@gwu.edu
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (t... | Python Code:
import h2o
from h2o.estimators.glrm import H2OGeneralizedLowRankEstimator
from h2o.estimators.glm import H2OGeneralizedLinearEstimator
from h2o.grid.grid_search import H2OGridSearch
h2o.init(max_mem_size='12G') # give h2o as much memory as possible
h2o.no_progress() # turn off h2o progress bars
import mat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.