Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
2,700 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pregunta 2
a) Carga de datos de NORB
Carga de datos de entrenamiento. En este caso debido a limitaciones de hardware se modificó la función original para cargar un solo batch de datos NORB.
... | Python Code:
import os
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import SGD
from keras.utils import np_utils
def unpickle(file):
import cPickle
fo = open(file, 'rb')
dict = cPickle.load(fo)
fo.c... |
2,701 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Introduction to Signal Processing</h1>
<h3>Lecture 1</h3>
<h2 class="title_stuff">Sivakumar Balasubramanian</h2>
<h4 class="title_stuff">Lecturer in Bioengineering</h4>
<h4 class="title_... | Python Code:
def continuous_discrete_time_signals():
t = np.arange(-10, 10.01, 0.01)
n = np.arange(-10, 11, 1.0)
x_t = np.exp(-0.1 * (t ** 2)) # continuous signal
x_n = np.exp(-0.1 * (n ** 2)) # discrete signal
fig = figure(figsize=(17,5))
plot(t, x_t, label="$e^{-0.1*t^{2}}$")
stem(n, x_n... |
2,702 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Naive Bayes and Bayes Classifiers
Step1: The data seems like it comes from two normal distributions, with the cyan class being more prevalent than the magenta class. A natural way to model ... | Python Code:
X = numpy.concatenate((numpy.random.normal(3, 1, 200), numpy.random.normal(10, 2, 1000)))
y = numpy.concatenate((numpy.zeros(200), numpy.ones(1000)))
x1 = X[:200]
x2 = X[200:]
plt.figure(figsize=(16, 5))
plt.hist(x1, bins=25, color='m', edgecolor='m', label="Class A")
plt.hist(x2, bins=25, color='c', edgec... |
2,703 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute source power using DICS beamformer
Compute a Dynamic Imaging of Coherent Sources (DICS)
Step1: Reading the raw data and creating epochs
Step2: We are interested in the beta band. ... | Python Code:
# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
# Roman Goj <roman.goj@gmail.com>
# Denis Engemann <denis.engemann@gmail.com>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD-3-Clause
import os.path as op
import numpy as np
import mne
from mne.datasets import s... |
2,704 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Propriedades-da-Convolução" data-toc-modified-id="Propriedades-da-Convolução-1"><span class="toc-item-num">1 </span>Propr... | Python Code:
# importando a função a ser utilizada nesse tutorial
import numpy as np
import sys,os
ia898path = os.path.abspath('../../')
if ia898path not in sys.path:
sys.path.append(ia898path)
import ia898.src as ia
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Propriedades-da-Convolução" ... |
2,705 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow IO Authors.
Step1: BigQuery TensorFlow 리더의 엔드 투 엔드 예제
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 인증합니다.
Ste... | 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... |
2,706 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modules, Imports and Packages
Dr. Chris Gwilliams
gwilliamsc@cardiff.ac.uk
Python Modules
We have seen that there are many things one can do using Python, but this barely touches the surface... | Python Code:
import random
dir(random)
Explanation: Modules, Imports and Packages
Dr. Chris Gwilliams
gwilliamsc@cardiff.ac.uk
Python Modules
We have seen that there are many things one can do using Python, but this barely touches the surface.
Python uses modules (a.ka. libraries) to extend the basic functionality and... |
2,707 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Graph format
The EDeN library allows the vectorization of graphs, i.e. the transformation of graphs into sparse vectors.
The graphs that can be processed by the EDeN library have the followi... | Python Code:
%matplotlib inline
import pylab as plt
import networkx as nx
G=nx.Graph()
G.add_node(0, label='A')
G.add_node(1, label='B')
G.add_node(2, label='C')
G.add_edge(0,1, label='x')
G.add_edge(1,2, label='y')
G.add_edge(2,0, label='z')
from eden.util import display
print display.serialize_graph(G)
from eden.util... |
2,708 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Taylor series expansion for the trigonometric function $\sin{x}$ around the point $a=0$ (also known as the Maclaurin series in this case) is given by
Step1: The factorial generator func... | Python Code:
def factorial():
a = b = 1
while True:
yield a
a *= b
b += 1
Explanation: The Taylor series expansion for the trigonometric function $\sin{x}$ around the point $a=0$ (also known as the Maclaurin series in this case) is given by:
$$
\sin{x} = x - \frac{x^3}{3!} + \frac{x^5}{5... |
2,709 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ARCH and GARCH Models
By Delaney Granizo-Mackenzie and Andrei Kirilenko.
This notebook developed in collaboration with Prof. Andrei Kirilenko as part of the Masters of Finance curriculum at ... | Python Code:
import cvxopt
from functools import partial
import math
import numpy as np
import scipy
from scipy import stats
import statsmodels as sm
from statsmodels.stats.stattools import jarque_bera
import matplotlib.pyplot as plt
Explanation: ARCH and GARCH Models
By Delaney Granizo-Mackenzie and Andrei Kirilenko.
... |
2,710 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Update BIOM file with data from STOQS
Given a .biom file and multiple STOQS databases, explore Next Generation Sequence and associated STOQS data
Executing this Notebook requires a personal ... | Python Code:
from campaigns import campaigns
dbs = [c for c in campaigns if 'simz' in c]
print dbs
Explanation: Update BIOM file with data from STOQS
Given a .biom file and multiple STOQS databases, explore Next Generation Sequence and associated STOQS data
Executing this Notebook requires a personal STOQS server. Foll... |
2,711 | 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:
# To enable Tensorflow 2 instead of TensorFlow 1.15, uncomment the next 4 lines
#try:
# %tensorflow_version 2.x
#except Exception:
# pass
# 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
#... |
2,712 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Verifying the MLOps environment on GCP
This notebook verifies the MLOps environment provisioned on GCP
1. Test using the local MLflow server in AI Notebooks instance in log entries to the Cl... | Python Code:
import os
import re
import mlflow
import mlflow.sklearn
import numpy as np
from sklearn.linear_model import LogisticRegression
import pymysql
from IPython.core.display import display, HTML
mlflow_tracking_uri = mlflow.get_tracking_uri()
MLFLOW_EXPERIMENTS_URI = os.environ['MLFLOW_EXPERIMENTS_URI']
print("M... |
2,713 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PYT-DS SAISOFT
Overview 1
Overview 3
<a data-flickr-embed="true" href="https
Step1: People needing to divide a fiscal year starting in July, into quarters, are in luck with pandas. I've b... | Python Code:
import pandas as pd
import numpy as np
rng_years = pd.period_range('1/1/2000', '1/1/2018', freq='Y')
Explanation: PYT-DS SAISOFT
Overview 1
Overview 3
<a data-flickr-embed="true" href="https://www.flickr.com/photos/kirbyurner/27963484878/in/album-72157693427665102/" title="Barry at Large"><img src="https:... |
2,714 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interacting with web APIs
Overview. We introduce the basics of interacting with web APIs using the requests package. We discuss the basics of how web APIs are usually constructed and show h... | Python Code:
import pandas as pd # data package
import matplotlib.pyplot as plt # graphics
import datetime as dt # date tools, used to note current date
import sys
# these are new
import requests
%matplotlib inline
print('\nPython version: ', sys.version)
print('Pandas version: ', pd.__versi... |
2,715 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Rejecting bad data (channels and segments)
Step1: Marking bad channels
Sometimes some MEG or EEG channels are not functioning properly
for various reasons. These channels should be excluded... | Python Code:
# sphinx_gallery_thumbnail_number = 3
import numpy as np
import mne
from mne.datasets import sample
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read_raw_fif(raw_fname) # already has an EEG ref
Explanation: Rejecting bad data (channels a... |
2,716 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Project Euler
Step2: Now write a set of assert tests for your number_to_words function that verifies that it is working as expected.
Step4: Now define a count_letters(n) that return... | Python Code:
def round_down(n):
s = str(n)
if n <= 20:
return n
elif n < 100:
return int(s[0] + '0'), int(s[1])
elif n<1000:
return int(s[0] + '00'),int(s[1]),int(s[2])
assert round_down(5) == 5
assert round_down(55) == (50,5)
assert round_down(222) == (200,2,2)
def numb... |
2,717 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'mpi-m', 'mpi-esm-1-2-lr', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: MPI-M
Source ID: MPI-ESM-1-2-LR
Sub-Topics: Radiative Forcings.
... |
2,718 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Support Vector Machines
This notebook discusses <em style="color
Step1: We construct a small data set containing just three points.
Step2: To proceed, we will plot the data points using a ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn.linear_model as lm
Explanation: Support Vector Machines
This notebook discusses <em style="color:blue;">support vector machines</em>. In order to understand why we need support vector mac... |
2,719 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have two numpy arrays x and y | Problem:
import numpy as np
x = np.array([0, 1, 1, 1, 3, 1, 5, 5, 5])
y = np.array([0, 2, 3, 4, 2, 4, 3, 4, 5])
a = 1
b = 4
idx_list = ((x == a) & (y == b))
result = idx_list.nonzero()[0] |
2,720 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute MxNE with time-frequency sparse prior
The TF-MxNE solver is a distributed inverse method (like dSPM or sLORETA)
that promotes focal (sparse) sources (such as dipole fitting technique... | Python Code:
# Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
from mne.inverse_s... |
2,721 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Speech Recognition using Graphs
Team members
Step1: Recompute
WARNING If you set recompute to True this will reextract all featrues, which will take approiximately a days, so we do not reco... | Python Code:
import os
from os.path import isdir, join
from pathlib import Path
import pandas as pd
from tqdm import tqdm
# Math
import numpy as np
import scipy.stats
from scipy.fftpack import fft
from scipy import signal
from scipy.io import wavfile
import librosa
import librosa.display
from scipy import sparse, stats... |
2,722 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Noise model diagnostics
Step1: Visualisation of the data
After obtaining these parameters, it is useful to visualise the data and the fit.
Step2: Plotting autocorrelation of the residuals
... | Python Code:
import pints
import pints.toy as toy
import pints.plot
import numpy as np
import matplotlib.pyplot as plt
# Use the toy logistic model
model = toy.LogisticModel()
real_parameters = [0.015, 500]
times = np.linspace(0, 1000, 100)
org_values = model.simulate(real_parameters, times)
# Add independent Gaussian ... |
2,723 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Create TensorFlow wide-and-deep model </h1>
This notebook illustrates
Step1: <h2> Create TensorFlow model using TensorFlow's Estimator API </h2>
<p>
First, write an input_fn to read th... | Python Code:
# change these to try this notebook out
BUCKET = 'cloud-training-demos-ml'
PROJECT = 'cloud-training-demos'
REGION = 'us-central1'
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJECT
os.environ['REGION'] = REGION
%%bash
if ! gsutil ls | grep -q gs://${BUCKET}/; then
gsutil mb -l ${REG... |
2,724 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MLE with exponential distribution
Step1: Draw exponential density
$$f\left(y_{i},\theta\right)=\theta\exp\left(-\theta y_{i}\right),\quad y_{i}>0,\quad\theta>0$$
Step2: Draw several densit... | Python Code:
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
np.set_printoptions(precision=4, suppress=True)
sns.set_context('notebook')
%matplotlib inline
Explanation: MLE with exponential distribution
End of explanation
theta = 1
y = np.linspace(0, 10, 100)
f = theta * np.exp(-theta * y)
# plo... |
2,725 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Left Handed Sister Problem
Think Bayes, Second Edition
Copyright 2021 Allen B. Downey
License
Step1: To compute the proportion of each type of family, I'll use Scipy to compute the bino... | Python Code:
import pandas as pd
qs = [(2, 0),
(1, 1),
(0, 2),
(3, 0),
(2, 1),
(1, 2),
(0, 3),
(4, 0),
(3, 1),
(2, 2),
(1, 3),
(0, 4),
]
index = pd.MultiIndex.from_tuples(qs, names=['Boys', 'Girls'])
Explanation: The Left Handed Sister Problem
Think ... |
2,726 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Name
Deploying a trained model to Cloud Machine Learning Engine
Label
Cloud Storage, Cloud ML Engine, Kubeflow, Pipeline
Summary
A Kubeflow Pipeline component to deploy a trained model from... | Python Code:
%%capture --no-stderr
!pip3 install kfp --upgrade
Explanation: Name
Deploying a trained model to Cloud Machine Learning Engine
Label
Cloud Storage, Cloud ML Engine, Kubeflow, Pipeline
Summary
A Kubeflow Pipeline component to deploy a trained model from a Cloud Storage location to Cloud ML Engine.
Details
... |
2,727 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First we import some datasets of interest
Step1: Now we separate the winners from the losers and organize our dataset
Step2: Now we match the detailed results to the merge dataset above
St... | Python Code:
#the seed information
#df_seeds = pd.read_csv('../input/NCAATourneySeeds.csv')
#print(df_seeds.shape)
#print(df_seeds.head())
#print(df_seeds.Season.value_counts())
#the seed information
df_seeds = pd.read_csv('../input/NCAATourneySeeds_SampleTourney2018.csv')
print(df_seeds.shape)
print(df_seeds.head())
#... |
2,728 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Calculate an average spectrum to ID peaks
Step1: 2. Make a feature matrix, n x p, where n = number of samples, p = number of features
Step2: 3. Standardize
Step3: 4. Sklearn PCA
Step4:... | Python Code:
averagespectrum = PCAsynthetic.get_hyper_peaks(spectralmatrix, threshold = 0.01)
plt.plot(averagespectrum)
Explanation: 1. Calculate an average spectrum to ID peaks
End of explanation
featurematrix = PCAsynthetic.makefeaturematrix(spectralmatrix, averagespectrum)
featurematrix[10:13,:]
Explanation: 2. Make... |
2,729 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Domain, Halo and Padding regions
In this tutorial we will learn about data regions and how these impact the Operator construction. We will use a simple time marching example.
Step1: At this... | Python Code:
from devito import Eq, Grid, TimeFunction, Operator
grid = Grid(shape=(3, 3))
u = TimeFunction(name='u', grid=grid)
u.data[:] = 1
Explanation: Domain, Halo and Padding regions
In this tutorial we will learn about data regions and how these impact the Operator construction. We will use a simple time marchin... |
2,730 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linked Structures
Arrays are basic sequence containe with easy and direct access to the individual elements however they are limited in their functionality
Python lists implemented using an ... | Python Code:
class ListNode:
def __init__(self, data):
self.data = data
Explanation: Linked Structures
Arrays are basic sequence containe with easy and direct access to the individual elements however they are limited in their functionality
Python lists implemented using an array structure, which extends ar... |
2,731 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Custom Kernels
In this tutorial we will learn
Step1: 1 - Write the nonlinearity and its symbolic form
Step2: 2 - Define a dcgp.kernel with our new callables
Step3: 3 - Profiling the speed... | Python Code:
# Some necessary imports.
import dcgpy
from time import time
import pyaudi
# Sympy is nice to have for basic symbolic manipulation.
from sympy import init_printing
from sympy.parsing.sympy_parser import *
init_printing()
# Fundamental for plotting.
from matplotlib import pyplot as plt
%matplotlib inline
Ex... |
2,732 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Handwritten Number Recognition with TFLearn and MNIST
In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9.
This kind of neural network is used in a ... | Python Code:
# Import Numpy, TensorFlow, TFLearn, and MNIST data
import numpy as np
import tensorflow as tf
import tflearn
import tflearn.datasets.mnist as mnist
Explanation: Handwritten Number Recognition with TFLearn and MNIST
In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-... |
2,733 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create TensorFlow Deep Neural Network Model
Learning Objective
- Create a DNN model using the high-level Estimator API
Introduction
We'll begin by modeling our data using a Deep Neural Netw... | Python Code:
PROJECT = "cloud-training-demos" # Replace with your PROJECT
BUCKET = "cloud-training-bucket" # Replace with your BUCKET
REGION = "us-central1" # Choose an available region for Cloud MLE
TFVERSION = "1.14" # TF version for CMLE to use
import os
os.environ["BUCKET"] = BUCKET
os.e... |
2,734 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We are using splu in scipy package. This is bit slow, but on the cluster you can use mumps, which might a lot faster. We can think about having better iterative solver.
Step1: I want to vis... | Python Code:
%%time
es_px = Ainv*rhs_px
es_py = Ainv*rhs_py
# Need to sum the ep and es to get the total field.
e_x = es_px #+ ep_px
e_y = es_py #+ ep_py
Explanation: We are using splu in scipy package. This is bit slow, but on the cluster you can use mumps, which might a lot faster. We can think about having better it... |
2,735 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step5: Copyright 2021 DeepMind Technologies Limited.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may ... | Python Code:
# @title Installation
!pip install dm-acme
!pip install dm-acme[reverb]
!pip install dm-acme[tf]
!pip install dm-sonnet
!pip install dopamine-rl==3.1.2
!pip install atari-py
!pip install dm_env
!git clone https://github.com/deepmind/deepmind-research.git
%cd deepmind-research
!git clone https://github.com/... |
2,736 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
P4J Periodogram demo
A simple demonstration of P4J's information theoretic periodogram
Step1: Generating a simple synthetic light curve
We create an irregulary sampled time series using a h... | Python Code:
from __future__ import division
import numpy as np
%matplotlib inline
import matplotlib.pylab as plt
import P4J
print("P4J version:")
print(P4J.__version__)
Explanation: P4J Periodogram demo
A simple demonstration of P4J's information theoretic periodogram
End of explanation
fundamental_freq = 2.0
lc_gener... |
2,737 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A simple demo of reparameterizing the gamma distribution
First, check out our blog post for the complete scoop. Once you've read that, the
functions below will make sense.
Step1: Define a ... | Python Code:
import autograd.numpy as np
import autograd.numpy.random as npr
from autograd.scipy.special import gammaln, psi
from autograd import grad
from autograd.optimizers import adam, sgd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context("talk")
sns.set_style("white")
%matplotlib inline
npr.see... |
2,738 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Node2Vec showcase
This notebook is about showcasing the qualities of the node2vec algorithm aswell which can be found and pip installed through this link.
Data is taken from https
Step1: Da... | Python Code:
%matplotlib inline
import warnings
from text_unidecode import unidecode
from collections import deque
warnings.filterwarnings('ignore')
import pandas as pd
from sklearn.manifold import TSNE
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import... |
2,739 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GLM
Step1: Here, 'log_radon_t' is a dependent variable, while 'floor_t' and 'county_idx_t' determine independent variable.
Step2: Random variable 'radon_like', associated with 'log_radon_t... | Python Code:
%matplotlib inline
import theano
theano.config.floatX = 'float64'
import matplotlib.pyplot as plt
import numpy as np
import pymc3 as pm
import pandas as pd
data = pd.read_csv('../data/radon.csv')
county_names = data.county.unique()
county_idx = data['county_code'].values
n_counties = len(data.county.uniqu... |
2,740 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Coding in Python, Part 2
Investigative Reporters and Editors Conference, New Orleans, June 2016<br />
By Aaron Kessler and Christopher Schnaars<br />
Lists
A list is a mutabl... | Python Code:
my_friends
Explanation: Introduction to Coding in Python, Part 2
Investigative Reporters and Editors Conference, New Orleans, June 2016<br />
By Aaron Kessler and Christopher Schnaars<br />
Lists
A list is a mutable (meaning it can be changed), ordered collection of objects. Everything in Python is an obje... |
2,741 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import CMIP5 from the module and start a session
The latest ARCCSSive stable version is available from the conda analysis27 environment
Anyone can load them both from raijin and the remote d... | Python Code:
! module use /g/data3/hh5/public/modules
! module load conda/analysis27
Explanation: Import CMIP5 from the module and start a session
The latest ARCCSSive stable version is available from the conda analysis27 environment
Anyone can load them both from raijin and the remote desktop.
End of explanation
! e... |
2,742 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
KNN (K-Nearest-Neighbors)
KNN is a simple concept
Step1: Now, we'll group everything by movie ID, and compute the total number of ratings (each movie's popularity) and the average rating fo... | Python Code:
import pandas as pd
r_cols = ['user_id', 'movie_id', 'rating']
ratings = pd.read_csv('e:/sundog-consult/udemy/datascience/ml-100k/u.data', sep='\t', names=r_cols, usecols=range(3))
ratings.head()
Explanation: KNN (K-Nearest-Neighbors)
KNN is a simple concept: define some distance metric between the items i... |
2,743 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chem 30324, Spring 2020, Homework 8
Due April 3, 2020
Chemical bonding
The electron wavefunctions (molecular orbitals) in molecules can be thought of as coming from combinations of atomic or... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
r = np.linspace(0,12,100) # r=R/a0
P = (1+r+1/3*r**2)*np.exp(-r)
plt.plot(r,P)
plt.xlim(0)
plt.ylim(0)
plt.xlabel('Internuclear Distance $R/a0$')
plt.ylabel('Overlap S')
plt.title('The Overlap Between Two 1s Orbitals')
plt.show()
Explanation: Chem 30324, S... |
2,744 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Order of magnitude faster training for image classification
Step1: Preprocess
Preprocessing uses a Dataflow pipeline to convert the image format, resize images, and run the converted image ... | Python Code:
import mltoolbox.image.classification as model
from google.datalab.ml import *
bucket = 'gs://' + datalab_project_id() + '-lab'
preprocess_dir = bucket + '/flowerpreprocessedcloud'
model_dir = bucket + '/flowermodelcloud'
staging_dir = bucket + '/staging'
!gsutil mb $bucket
Explanation: Order of magnitude ... |
2,745 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building and running a preprocessing pipeline
In this example, an image processing pipeline is created and then executed in a manner that maximize throughput.
Step1: Initial data loading
Se... | Python Code:
from PIL import Image, ImageOps
import seqtools
! [[ -f owl.jpg ]] || curl -s "https://cdn.pixabay.com/photo/2017/04/07/01/05/owl-2209827_640.jpg" -o owl.jpg
! [[ -f rooster.jpg ]] || curl -s "https://cdn.pixabay.com/photo/2018/08/26/14/05/hahn-3632299_640.jpg" -o rooster.jpg
! [[ -f duck.jpg ]] || curl -s... |
2,746 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fickian Diffusion and Tortuosity
In this example, we will learn how to perform Fickian diffusion on a Cubic network. The algorithm works fine with every other network type, but for now we wa... | Python Code:
import numpy as np
import openpnm as op
%config InlineBackend.figure_formats = ['svg']
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(10)
ws = op.Workspace()
ws.settings["loglevel"] = 40
np.set_printoptions(precision=5)
Explanation: Fickian Diffusion and Tortuosity
In this example, we wi... |
2,747 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Threshold, Dynamic Time Warping
DW (2016.01.04)
Step1: Comparison between fastDTW and normal DTW
Step2: Fast DTW is about 3 times faster then the normal DTW. Using an interpolation with 10... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import medfilt
import gitInformation
from neo.io.neuralynxio import NeuralynxIO
import quantities as pq
import sklearn
from scipy.interpolate import Rbf
import fastdtw
#import dtw
% matplotlib inline
gitInformation.printInformation()
# Se... |
2,748 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning with TensorFlow
Credits
Step2: Download the data from the source website if necessary.
Step3: Read the data into a string.
Step4: Build the dictionary and replace rare words... | Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
import collections
import math
import numpy as np
import os
import random
import tensorflow as tf
import urllib
import zipfile
from matplotlib import pylab
from sklearn.manifold import TSNE
Explanat... |
2,749 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="tmva_logo.gif" height="20%" width="20%">
TMVA Higgs Classification Example in Python
In this example we will still do Higgs classification but we will use together with the native ... | Python Code:
import ROOT
from ROOT import TMVA
Explanation: <img src="tmva_logo.gif" height="20%" width="20%">
TMVA Higgs Classification Example in Python
In this example we will still do Higgs classification but we will use together with the native TMVA methods also methods from Keras and scikit-learn.
End of explanat... |
2,750 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Training - Lesson 1 - Variables and Data Types
Variables
A variable refers to a certain value with specific type. For example, we may want to store a number, a fraction, or a name, da... | Python Code:
my_name = 'Adam'
print my_name
my_age = 92
your_age = 23
age_difference = my_age - your_age
print age_difference
Explanation: Python Training - Lesson 1 - Variables and Data Types
Variables
A variable refers to a certain value with specific type. For example, we may want to store a number, a fraction, or a... |
2,751 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise
Step1: Task 1
Read the iris data into a pandas DataFrame, including column names. Name the dataframe iris.
Step2: Task 2
Gather some basic information about the data such as
Step... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
# display plots in the notebook
%matplotlib inline
# increase default figure and font sizes for easier viewing
plt.rcParams['figure.figsize'] = (8, 6)
plt.rcParams['font.size'] = 14
Explanation: Exercise: "Human learning" with iris data
Question: Can you ... |
2,752 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vectorized Operations
not necessary to write loops for element-by-element operations
pandas' Series objects can be passed to MOST NumPy functions
documentation
Step1: add Series without loo... | Python Code:
import pandas as pd
import numpy as np
my_dictionary = {'a' : 45., 'b' : -19.5, 'c' : 4444}
my_series = pd.Series(my_dictionary)
my_series
Explanation: Vectorized Operations
not necessary to write loops for element-by-element operations
pandas' Series objects can be passed to MOST NumPy functions
documenta... |
2,753 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Perceptron Learning in Python
(C) 2017-2019 by Damir Cavar
Download
Step1: Our example data, weights $w$, bias $b$, and input $x$ are defined as
Step2: Our neural unit would compute $z$ as... | Python Code:
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
Explanation: Perceptron Learning in Python
(C) 2017-2019 by Damir Cavar
Download: This and various other Jupyter notebooks are available from my GitHub repo.
License: Creative Commons Attribution-ShareAlike 4.0 International License (CA BY-... |
2,754 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Detailed stats of HGVS in ClinVar
Looking only at records with no functional consequences and no complete chr_pos_ref_alt coordinates. Based on June consequence predictions and ClinVa... | Python Code:
import os
import re
import sys
import numpy as np
from eva_cttv_pipeline.clinvar_xml_utils import *
from eva_cttv_pipeline.clinvar_identifier_parsing import *
%matplotlib inline
import matplotlib.pyplot as plt
PROJECT_ROOT = '/home/april/projects/opentargets/complex-events'
# dump of all records with no fu... |
2,755 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quadratic Programming
1. Introduction
1.1 Libraries Used
For Quadratic Programming, the packages quadprog and cvxopt were installed
Step1: 1.2 Theory
1.2.1 Lagrange Multipliers
The Lagrangi... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import scipy
import cvxopt
import quadprog
from numpy.random import permutation
from sklearn import linear_model
from sympy import var, diff, exp, latex, factor, log, simplify
from IPython.display import display, Math, Latex
np.set_printoptions(precision=4... |
2,756 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mag Inversion
Step1
Step1: Step2
Step2: Step3 | Python Code:
cs = 25.
hxind = [(cs,5,-1.3), (cs, 31),(cs,5,1.3)]
hyind = [(cs,5,-1.3), (cs, 31),(cs,5,1.3)]
hzind = [(cs,5,-1.3), (cs, 30),(cs,5,1.3)]
mesh = Mesh.TensorMesh([hxind, hyind, hzind], 'CCC')
Explanation: Mag Inversion
Step1: Generating mesh
End of explanation
chibkg = 1e-5
chiblk = 0.1
chi = np.ones(mesh.n... |
2,757 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Updated NOAA Data
Looks like NOAA technically has back to 1946, but first actual read of any precipitation is on September 24, 1970
Step1: N-Year Metrics
Using rolling time series in pandas... | Python Code:
rain_df = rain_df['1970-09-01':]
rain_df.head()
# Resampling the dataframe into one hour increments, accessing max because accumulation listed more often than hourly (i.e.
# every 15 minutes) is the total precipitation since the hour began
# Description: http://www1.ncdc.noaa.gov/pub/data/cdo/documentatio... |
2,758 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Natural Neighbor Verification
Walks through the steps of Natural Neighbor interpolation to validate that the algorithmic
approach taken in MetPy is correct.
Find natural neighbors visual tes... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial import ConvexHull, Delaunay, delaunay_plot_2d, Voronoi, voronoi_plot_2d
from scipy.spatial.distance import euclidean
from metpy.gridding import polygons, triangles
from metpy.gridding.interpolation import nn_point
Explanation: Natural Ne... |
2,759 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sources and receivers
Defining the sources and receiver position is necessary for any seismic simulation or inversion problem. This notebook shows how to do so, and present the different fun... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
from SeisCL import SeisCL
seis = SeisCL()
Explanation: Sources and receivers
Defining the sources and receiver position is necessary for any seismic simulation or inversion problem. This notebook shows how to do so, and present the different functionalitie... |
2,760 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise 4
Step1: Part 1
Step2: Part 2
Step3: Unrolling the parameters into one vector
Step4: Part 3
Step5: The cost at the given parameters should be about 0.287629.
Step6: The cost a... | Python Code:
import numpy as np
import scipy.io
import scipy.optimize
import matplotlib.pyplot as plt
%matplotlib inline
# uncomment for console - useful for debugging
# %qtconsole
ex3data1 = scipy.io.loadmat("./ex4data1.mat")
X = ex3data1['X']
y = ex3data1['y'][:,0]
m, n = X.shape
m, n
input_layer_size = n # 20x20 I... |
2,761 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Science Tutorial 01 @ Data Science Society
那須野薫(Kaoru Nasuno)/ 東京大学(The University of Tokyo)
データサイエンスの基礎的なスキルを身につける為のチュートリアルです。
KaggleのコンペティションであるRECRUIT Challenge, Coupon Purchase Pred... | Python Code:
# TODO: You Must Change the setting bellow
MYSQL = {
'user': 'root',
'passwd': '',
'db': 'coupon_purchase',
'host': '127.0.0.1',
'port': 3306,
'local_infile': True,
'charset': 'utf8',
}
DATA_DIR = '/home/nasuno/recruit_kaggle_datasets' # ディレクトリの名前に日本語(マルチバイト文字)は使わないでください。
OUTP... |
2,762 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Enums
This notebook is an introduction to Python Enums as introduced in Python 3.4 and subsequently backported to other version of Python.
More details can be found in the library documentat... | Python Code:
from enum import Enum
class MyEnum(Enum):
first = 1
second = 2
third = 3
Explanation: Enums
This notebook is an introduction to Python Enums as introduced in Python 3.4 and subsequently backported to other version of Python.
More details can be found in the library documentation: https://docs.p... |
2,763 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I want to convert a 1-dimensional array into a 2-dimensional array by specifying the number of rows in the 2D array. Something that would work like this: | Problem:
import numpy as np
A = np.array([1,2,3,4,5,6])
nrow = 3
B = np.reshape(A, (nrow, -1)) |
2,764 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Topological insulators II/01
Step1: Some more handy simple Fock space operators are defined below. First the total fermion number operator
Step2: And the fermion particle number parity ope... | Python Code:
def fermion_Fock_matrices(NN=3):
'''
Returns list of 2^NN X 2^NN sparse matrices,
representing fermionic annihilation operators
acting on the Fock space of NN fermions.
'''
l=list(map(lambda x: list(map(int,list(binary_repr(x,NN)))),arange(0,2**NN)))
ll=-(-1)**cumsum(l,axis=1)
... |
2,765 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Set Up
We have again provided code to do the basic loading, review and model-building. Run the cell below to set everything up
Step1: The first few questions require examining the distribut... | Python Code:
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
import shap
# Environment Set-Up for feedback system.
from learntools.core import binder
binder.bind(globals())
from learntools.ml_explainability.ex5 import *
print... |
2,766 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Data
Step2: View Average Ages By City
Step3: View Max Age By City
Step4: View Count Of Criminals By City
Step5: View Total Age By City | Python Code:
# Ignore
%load_ext sql
%sql sqlite://
%config SqlMagic.feedback = False
Explanation: Title: Calculate Counts, Sums, Max, and Averages
Slug: sums_counts_max_averages
Summary: Calculate Counts, Sums, and Averages in SQL.
Date: 2017-01-16 12:00
Category: SQL
Tags: Basics
Authors: Chris Albon
Note: This... |
2,767 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I'm using tensorflow 2.10.0. | Problem:
import tensorflow as tf
import numpy as np
np.random.seed(10)
a = tf.constant(np.random.rand(50, 100, 1, 512))
def g(a):
return tf.squeeze(a)
result = g(a.__copy__()) |
2,768 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Detection of meteor scatter pings in GRAVES recording
This notebook shows an algorithm for the detection of meteor scatter pings in a recording of GRAVES done on 2018-08-11, during the Perse... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal
import scipy.stats
import matplotlib.patches
Explanation: Detection of meteor scatter pings in GRAVES recording
This notebook shows an algorithm for the detection of meteor scatter pings in a recording of GRAVES done ... |
2,769 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
It seems that the DF9NP GPSDO lost lock shortly after 2019-11-20T04
Step1: RMS phase difference
Step2: Recompute Allan deviations (takes several minutes) | Python Code:
data = load_file('gpsdo_phase_2019-11-17T21:55:29.989819.f32').sel(time = slice('2019-11-17T21:55:31', '2019-11-20T04:57:30'))
(data.coords['time'][-1] - data.coords['time'][0]).astype('float')*1e-9
residual_freq = np.polyfit((data.coords['time'] - data.coords['time'][0]).astype('float') * 1e-9, data['phas... |
2,770 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Autoencoder
This notebook demonstrates the invocation of the SystemML autoencoder script, and alternative ways of passing in/out data.
This notebook is supported with SystemML 0.14.0 and abo... | Python Code:
!pip show systemml
import pandas as pd
from systemml import MLContext, dml
ml = MLContext(sc)
print(ml.info())
sc.version
Explanation: Autoencoder
This notebook demonstrates the invocation of the SystemML autoencoder script, and alternative ways of passing in/out data.
This notebook is supported with Syste... |
2,771 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate ... | Python Code:
import numpy as np
import tensorflow as tf
with open('../sentiment-network/reviews.txt', 'r') as f:
reviews = f.read()
with open('../sentiment-network/labels.txt', 'r') as f:
labels = f.read()
reviews[:2000]
Explanation: Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent ... |
2,772 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
[MSE-01] モジュールをインポートして、乱数のシードを設定します。
Step1: [MSE-02] MNISTのデータセットを用意します。
Step2: [MSE-03] ソフトマックス関数による確率 p の計算式を用意します。
Step3: [MSE-04] 誤差関数 loss とトレーニングアルゴリズム train_step を用意します。
Step4: [M... | Python Code:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
np.random.seed(20160604)
Explanation: [MSE-01] モジュールをインポートして、乱数のシードを設定します。
End of explanation
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
Explanation: [MSE... |
2,773 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
HoloViews is designed to be both highly customizable, allowing you to control how your visualizations appear, but also to enforce a strong separation between your data (with any semantically... | Python Code:
import numpy as np
import holoviews as hv
%reload_ext holoviews.ipython
x,y = np.mgrid[-50:51, -50:51] * 0.1
image = hv.Image(np.sin(x**2+y**2), group="Function", label="Sine")
coords = [(0.1*i, np.sin(0.1*i)) for i in range(100)]
curve = hv.Curve(coords)
curves = {phase: hv.Curve([(0.1*i, np.sin(phase+0.... |
2,774 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
Glossary
1. Radio Science using Interferometric Arrays
Previous
Step1: Import section specific modules
Step3: 1.9 A brief introduction to interferometry and its history
1.9.1 The d... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import HTML
HTML('../style/course.css') #apply general CSS
Explanation: Outline
Glossary
1. Radio Science using Interferometric Arrays
Previous: 1.8 Astronomical radio sources
Next: 1.10 The Limits of Single Dish As... |
2,775 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Normalizing text
Step1: Normalizing columns
Step2: Answers in questions
Step3: Only 0.6% of the answers appear in the questions itself. Out of this 0.6%, a sample of the questions shows t... | Python Code:
import string
def norm_words(words):
words = words.lower().translate(None, string.punctuation)
return words
jeopardy["clean_question"] = jeopardy["Question"].apply(norm_words)
jeopardy["clean_answer"] = jeopardy["Answer"].apply(norm_words)
jeopardy.head()
Explanation: Normalizing text
End of explan... |
2,776 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
2,777 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Collaborative filtering on the MovieLense Dataset
Learning Objectives
Know how to build a BigQuery ML Matrix Factorization Model
Know how to use the model to make recommendations for a user
... | Python Code:
import os
PROJECT = "your-project-here" # REPLACE WITH YOUR PROJECT ID
# Do not change these
os.environ["PROJECT"] = PROJECT
%%bash
rm -r bqml_data
mkdir bqml_data
cd bqml_data
curl -O 'http://files.grouplens.org/datasets/movielens/ml-20m.zip'
unzip ml-20m.zip
yes | bq rm -r $PROJECT:movielens
bq --locatio... |
2,778 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Непараметрические криетрии
Критерий | Одновыборочный | Двухвыборочный | Двухвыборочный (связанные выборки)
------------- | -------------|
Знаков | $\times$ | | $\times$
Ранговый | $\... | Python Code:
import numpy as np
import pandas as pd
import itertools
from scipy import stats
from statsmodels.stats.descriptivestats import sign_test
from statsmodels.stats.weightstats import zconfint
from statsmodels.stats.weightstats import *
%pylab inline
Explanation: Непараметрические криетрии
Критерий | Одновыборо... |
2,779 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step4: Inline visualization of TensorFlow graph from https
Step5: Preprocessing the data
Step7: Function for providing batches
Step8: Definining the TensorFlow model with the core API
Ste... | Python Code:
from IPython.display import clear_output, Image, display, HTML
# Helper functions for TF Graph visualization
def strip_consts(graph_def, max_const_size=32):
Strip large constant values from graph_def.
strip_def = tf.GraphDef()
for n0 in graph_def.node:
n = strip_def.node.add()
... |
2,780 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#PRODUCT_ID" data-toc-modified-id="PRODUCT_ID-1"><span class="toc-item-num">1 </span>PRODUCT_ID</a></div><div class="lev1 ... | Python Code:
# setup
from pyrise import products as prod
obsid = prod.OBSERVATION_ID('PSP_003072_0985')
# test orbit number
assert obsid.orbit == '003072'
# test setting orbit property
obsid.orbit = 4080
assert obsid.orbit == '004080'
# test repr
assert obsid.__repr__() == 'PSP_004080_0985'
# test targetcode
assert ob... |
2,781 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Merge a bar's reviews into a single document
Step1: Now we must generate a dictionary which maps vocabulary into a number | Python Code:
from itertools import chain
from collections import OrderedDict
reviews_merged = OrderedDict()
# Flatten the reviews, so each review is just a single list of words.
n_reviews = -1
for bus_id in set(review.business_id.values[:n_reviews]):
# This horrible line first collapses each review of a correspondi... |
2,782 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework 8 Key
CHE 116
Step1: 2.2
The 99% confidence interval is $\mu > -10.1$
Step2: 2.3
The 85% confidence interval is $12.5 \pm 4.3$
Step3: 2.4
The 95% confidence interval is $12.5 \pm... | Python Code:
import scipy.stats as ss
data_21 = [65.58, -28.15, 21.17, -0.57, 6.04, -10.21, 36.46, 10.67, 77.98, 15.97]
se = np.std(data_21, ddof=1) / np.sqrt(len(data_21))
T = ss.t.ppf(0.9, df=len(data_21) - 1)
print(np.mean(data_21), T * se)
Explanation: Homework 8 Key
CHE 116: Numerical Methods and Statistics
2/21/2... |
2,783 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intermediate Pandas
ToC
Navigating multilevel index
Accessing rows and columns
Naming indices
Accessing rows and columns using cross section
Missing data
dropna
fillna
Data aggregation
group... | Python Code:
import pandas as pd
import numpy as np
# Index Levels
outside = ['G1','G1','G1','G2','G2','G2']
inside = [1,2,3,1,2,3]
hier_index = list(zip(outside,inside)) #create a list of tuples
hier_index
#create a multiindex
hier_index = pd.MultiIndex.from_tuples(hier_index)
hier_index
# Create a dataframe (6,2) wit... |
2,784 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fitting Models Exercise 1
Imports
Step1: Fitting a quadratic curve
For this problem we are going to work with the following model
Step2: First, generate a dataset using this model using th... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
Explanation: Fitting Models Exercise 1
Imports
End of explanation
a_true = 0.5
b_true = 2.0
c_true = -4.0
Explanation: Fitting a quadratic curve
For this problem we are going to work with the following model:... |
2,785 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Leren
Step1: 1) Reading in data
Step2: 2) Gradient function
Step3: 3) Parameter updating
Step4: 4) Cost function
Step5: 5) Optimization learning rate and iterations
Step6: Polynomial R... | Python Code:
from __future__ import division
import numpy as np
import pandas as pd
import csv
import matplotlib.pylab as plt
class linReg:
df = None
input_vars = None
output_vars = None
thetas = None
alpha = 0.0
# formats the self.df properly
def __init__(self, fileName, alpha):
sel... |
2,786 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Curved edges
It doesn't appear that toyplot has the functionality to do radial curvature of edges. I need to dive into the actual SVG code that it writes to check...
https
Step1: Primer
M
S... | Python Code:
import numpy as np
import toyplot
#import toytree
import toyplot.svg
from IPython.display import SVG
Explanation: Curved edges
It doesn't appear that toyplot has the functionality to do radial curvature of edges. I need to dive into the actual SVG code that it writes to check...
https://developer.mozilla.o... |
2,787 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Neural Network for Image Classification
Step1: 2 - Dataset
You will use the same "Cat vs non-Cat" dataset as in "Logistic Regression as a Neural Network" (Assignment 2). The model you ... | Python Code:
import time
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
from dnn_app_utils_v2 import *
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
p... |
2,788 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
活性化関数
ステップ関数
$y=\begin{cases}1 & ( x \gt 0 ) \-1 & ( x \leqq 0 )\end{cases}$
Step1: シグモイド関数
$y = \frac{1}{1 + exp(-x)}$
Step2: ReLU関数
$y=\begin{cases}x & ( x \gt 0 ) \ 0 & ( x \leqq 0 ) \e... | Python Code:
x = np.arange(-5.0, 5.0, 0.1)
y = np.array(x > 0, dtype=np.int)
plt.plot(x, y)
plt.show()
Explanation: 活性化関数
ステップ関数
$y=\begin{cases}1 & ( x \gt 0 ) \-1 & ( x \leqq 0 )\end{cases}$
End of explanation
x = np.arange(-5.0, 5.0, 0.1)
y = 1 / (1 + np.exp(-x))
plt.plot(x, y)
plt.show()
Explanation: シグモイド関数
$y = \... |
2,789 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Continuous Target Decoding with SPoC
Source Power Comodulation (SPoC)
Step1: Plot the contributions to the detected components (i.e., the forward model) | Python Code:
# Author: Alexandre Barachant <alexandre.barachant@gmail.com>
# Jean-Remi King <jeanremi.king@gmail.com>
#
# License: BSD (3-clause)
import matplotlib.pyplot as plt
import mne
from mne import Epochs
from mne.decoding import SPoC
from mne.datasets.fieldtrip_cmc import data_path
from sklearn.pipeline... |
2,790 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: After confirming the java environment, install tabula-py by using pip.
Step2: Before trying tabula-py, check your environment via tabula-py environment_info() functio... | Python Code:
!java -version
Explanation: <a href="https://colab.research.google.com/github/chezou/tabula-py/blob/master/examples/tabula_example.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
tabula-py example notebook
tabula-py is a tool for convert... |
2,791 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this example, we will create a typical CANDU bundle with rings of fuel pins. At present, OpenMC does not have a specialized lattice for this type of fuel arrangement, so we must resort to... | Python Code:
%matplotlib inline
from math import pi, sin, cos
import numpy as np
import openmc
Explanation: In this example, we will create a typical CANDU bundle with rings of fuel pins. At present, OpenMC does not have a specialized lattice for this type of fuel arrangement, so we must resort to manual creation of th... |
2,792 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Triplet Loss on Totally Looks Like dataset
This notebook is inspired from this Keras tutorial by Hazem Essam and Santiago L. Valdarrama.
The goal is to showcase the use of siamese networks a... | Python Code:
import os
import os.path as op
from urllib.request import urlretrieve
from pathlib import Path
URL = "https://github.com/m2dsupsdlclass/lectures-labs/releases/download/totallylookslike/dataset_totally.zip"
FILENAME = "dataset_totally.zip"
if not op.exists(FILENAME):
print('Downloading %s to %s...' % (U... |
2,793 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Binding Model
The binding model may be represented by the following graph
$$P+L \; \underset{K_{D}^{'}}{\rightleftharpoons} \; P \bullet L \; \underset{K_{D}^{''}}{\rightleftharpoons} \;... | Python Code:
#Kd-prime and Kd-doubleprime as expressions of Kd and alpha (cooperativity)
#as well as their concentration ratios
kd, alpha, p, l, pl, plp = symbols('K_{D} alpha [P] [L] [PL] [PLP]')
kd_p = Eq(kd / 2, p * l / pl)
kd_p
kd_pp = Eq(2 * kd / alpha, p * pl / plp)
kd_pp
Explanation: The Binding Model
The bindin... |
2,794 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TF-Agents Authors.
Step1: A Tutorial on Multi-Armed Bandits with Per-Arm Features
Get Started
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_bla... | 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... |
2,795 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Practical PyTorch
Step1: Here we will also define a constant to decide whether to use the GPU (with CUDA specifically) or the CPU. If you don't have a GPU, set this to False. Later when we ... | Python Code:
import unicodedata
import string
import re
import random
import time
import math
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
Explanation: Practical PyTorch: Translation with a Sequence to Sequence Network and Attention
In th... |
2,796 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BET Surface Area
The BET equation for determining the specific surface area from multilayer adsorption of nitrogen was first reported in 1938.
Brunauer, Stephen, Paul Hugh Emmett, and Edward... | Python Code:
%matplotlib inline
from micromeritics import bet, util, isotherm_examples as ex, plots
s = ex.carbon_black() # example isotherm of Carbon Black with N2.
min = 0.05 # 0.05 to 0.30 range for BET
max = 0.3
Q,P = util.restrict_isotherm(s.Qads, s.Prel, min, max)
plots.plotIsotherm(s.Qads, s.Pr... |
2,797 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2A.eco - API, API REST
Petite revue d'API REST.
Step1: Définition
Step2: Faire appel à l'API de Tastekid
La Banque Mondiale c'était assez soft
Step3: Pour demander à l'API quels sont le... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: 2A.eco - API, API REST
Petite revue d'API REST.
End of explanation
import requests
data_json = requests.get("http://api.worldbank.org/v2/countries?incomeLevel=LMC&format=json").json()
data_json
data_json[0]
# On voit qu'il y a nou... |
2,798 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to read BigQuery data from TensorFlow 2.0 efficiently
This notebook accompanies the article
"How to read BigQuery data from TensorFlow 2.0 efficiently"
The example problem is to find cr... | Python Code:
%%bash
# create output dataset
bq mk advdata
%%bigquery
CREATE OR REPLACE MODEL advdata.ulb_fraud_detection
TRANSFORM(
* EXCEPT(Amount),
SAFE.LOG(Amount) AS log_amount
)
OPTIONS(
INPUT_LABEL_COLS=['class'],
AUTO_CLASS_WEIGHTS = TRUE,
DATA_SPLIT_METHOD='seq',
DATA_SPLIT_COL='Time',
... |
2,799 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create relaxed geodynamic 1D profile
NOTE
Step1: Now a few imports
Step2: The following code block sets up some parameters for our problem,
including the PerpleX model we will use to deter... | Python Code:
interactive = True
if interactive:
%matplotlib ipympl
import ipywidgets as widgets
import mpl_interactions.ipyplot as iplt
Explanation: Create relaxed geodynamic 1D profile
NOTE: This notebook contains an interactive figure with sliders. it relies on python modules ipympl and mpl_interactions.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.