Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
1,700
Given the following text description, write Python code to implement the functionality described below step by step Description: Lesson One This lesson will go over digital data input and introduction to programming in Python. Sensors If someone were to ask you what color an apple is, you would look at the apple and t...
Python Code: print 40 + 2 print 7*6 print 67-25 print 798/19 Explanation: Lesson One This lesson will go over digital data input and introduction to programming in Python. Sensors If someone were to ask you what color an apple is, you would look at the apple and tell them what color you saw. If they then asked you whic...
1,701
Given the following text description, write Python code to implement the functionality described below step by step Description: 2. Categorical Predictors The syntax for handling categorical predictors is different between standard regression models/two-stage-models (i.e. Step1: Dummy-coded/Treatment contrasts +++++...
Python Code: # import basic libraries and sample data import os import pandas as pd from pymer4.utils import get_resource_path from pymer4.models import Lm # IV3 is a categorical predictors with 3 levels in the sample data df = pd.read_csv(os.path.join(get_resource_path(), "sample_data.csv")) Explanation: 2. Categorica...
1,702
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Import the necessary packages to read in the data, plot, and create a linear regression model Step1: 2. Read in the hanford.csv file Step2: County Step3: 3. Calculate the basic descrip...
Python Code: import pandas as pd import pandas as pd import matplotlib.pyplot as plt # package for doing plotting (necessary for adding the line) import statsmodels.formula.api as smf # package we'll be using for linear regression %matplotlib inline Explanation: 1. Import the necessary packages to read in the data, plo...
1,703
Given the following text description, write Python code to implement the functionality described below step by step Description: Editing BEM surfaces in Blender Sometimes when creating a BEM model the surfaces need manual correction because of a series of problems that can arise (e.g. intersection between surfaces). H...
Python Code: # Authors: Marijn van Vliet <w.m.vanvliet@gmail.com> # Ezequiel Mikulan <e.mikulan@gmail.com> # Manorama Kadwani <manorama.kadwani@gmail.com> # # License: BSD-3-Clause import os import os.path as op import shutil import mne data_path = mne.datasets.sample.data_path() subjects_dir = op.joi...
1,704
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: OpenCV OpenCV is an open-source computer vision library. It comes packaged with many powerful computer vision tools, including image and video processing utilities. Th...
Python Code: # 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 # distribute...
1,705
Given the following text description, write Python code to implement the functionality described below step by step Description: This model was developed by Permamodel workgroup. Basic theory is Kudryavtsev's method. Reference Step1: Spatially visualize active layer thickness Step2: Spatially visualize mean annual g...
Python Code: import os,sys sys.path.append('../../permamodel/') from permamodel.components import bmi_Ku_component from permamodel import examples_directory import numpy as np %matplotlib inline import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap, addcyclic import matplotlib as mpl print examples_d...
1,706
Given the following text description, write Python code to implement the functionality described below step by step Description: Run a Web Server in a Notebook In this notebook, we show how to run a Tornado or Flask web server within a notebook, and access it from the public Internet. It sounds hacky, but the techniqu...
Python Code: import matplotlib.pyplot as plt import pandas as pd import numpy import io pd.options.display.mpl_style = 'default' def plot_random_numbers(n=50): ''' Plot random numbers as a line graph. ''' fig, ax = plt.subplots() # generate some random numbers arr = numpy.random.randn(n) ax....
1,707
Given the following text description, write Python code to implement the functionality described below step by step Description: Randomized LASSO This selection algorithm allows the researcher to form a model after observing the subgradient of this optimization problem $$ \text{minimize}_{\beta} \frac{1}{2} \|y-X\bet...
Python Code: import numpy as np from selectinf.randomized.api import lasso from selectinf.tests.instance import gaussian_instance np.random.seed(0) # for reproducibility X, y = gaussian_instance(n=100, p=20, s=5, signal=3, ...
1,708
Given the following text description, write Python code to implement the functionality described below step by step Description: update changes to pypi ```bash update pypi rm -r dist # remove old source files python setup.py sdist # make source distribution python setup.py bdist_wheel # make bui...
Python Code: %ls dist Explanation: update changes to pypi ```bash update pypi rm -r dist # remove old source files python setup.py sdist # make source distribution python setup.py bdist_wheel # make build distribution with .whl file twine upload dist/ # pip install twine ``` End of explanat...
1,709
Given the following text description, write Python code to implement the functionality described below step by step Description: Class 18 Step1: Evaluation Now we want to examine the statistical properties of the simulated model
Python Code: # 1. Input model parameters and print parameters = pd.Series() parameters['rho'] = .75 parameters['sigma'] = 0.006 parameters['alpha'] = 0.35 parameters['delta'] = 0.025 parameters['beta'] = 0.99 print(parameters) # 2. Compute the steady state of the model directly A = 1 K = (parameters.alpha*A/(parameters...
1,710
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial on Causal Inference and its Connections to Machine Learning (Using DoWhy+EconML) This tutorial presents a walk-through on using DoWhy+EconML libraries for causal inference. Along th...
Python Code: # Required libraries import dowhy from dowhy import CausalModel import dowhy.datasets # Avoiding unnecessary log messges and warnings import logging logging.getLogger("dowhy").setLevel(logging.WARNING) import warnings from sklearn.exceptions import DataConversionWarning warnings.filterwarnings(action='igno...
1,711
Given the following text description, write Python code to implement the functionality described below step by step Description: Derivatives fundamentals This notebook will introduce you to the fundamentals of computing the derivative of the solution map to optimization problems. The derivative can be used for sensitv...
Python Code: import cvxpy as cp x = cp.Variable(pos=True) y = cp.Variable(pos=True) z = cp.Variable(pos=True) a = cp.Parameter(pos=True) b = cp.Parameter(pos=True) c = cp.Parameter() objective_fn = 1/(x*y*z) objective = cp.Minimize(objective_fn) constraints = [a*(x*y + x*z + y*z) <= b, x >= y**c] problem = cp.Problem(o...
1,712
Given the following text description, write Python code to implement the functionality described below step by step Description: Please find jax implementation of this notebook here Step1: Model We use a slightly modified version of the LeNet CNN. Step2: Copying parameters across devices Step4: All-reduce will copy...
Python Code: import numpy as np import matplotlib.pyplot as plt import math from IPython import display try: import torch except ModuleNotFoundError: %pip install -qq torch import torch try: import torchvision except ModuleNotFoundError: %pip install -qq torchvision import torchvision from torch...
1,713
Given the following text description, write Python code to implement the functionality described below step by step Description: Baseline prediction for homework type The baseline prediction method we use for predicting which homework the notebook came from uses the popular plagiarism detector JPlag. We feed each note...
Python Code: # First step is to load a balanced dataset of homeworks import sys home_directory = '/dfs/scratch2/fcipollone' sys.path.append(home_directory) import numpy as np from nbminer.notebook_miner import NotebookMiner hw_filenames = np.load('../homework_names_jplag_combined_per_student.npy') min_val = min([len(te...
1,714
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Factor Risk Exposure By Evgenia "Jenny" Nitishinskaya, Delaney Granizo-Mackenzie, and Maxwell Margenot. Part of the Quantopian Lecture Series Step2: How did each factor do over 2014?...
Python Code: import numpy as np import statsmodels.api as sm import scipy.stats as stats from statsmodels import regression import matplotlib.pyplot as plt import pandas as pd import numpy as np from quantopian.pipeline import Pipeline from quantopian.pipeline.data import morningstar from quantopian.pipeline.data.built...
1,715
Given the following text description, write Python code to implement the functionality described below step by step Description: Experiment Run Hebbian pruning with non-binary activations. Motivation Attempt pruning given intuition offered up in "Memory Aware Synapses" paper Step1: Dense Model Step2: Static Sparse S...
Python Code: from IPython.display import Markdown, display %load_ext autoreload %autoreload 2 import sys import itertools sys.path.append("../../") from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import glob import tabulate import pprint import clic...
1,716
Given the following text description, write Python code to implement the functionality described below step by step Description: Using nbtlib The Named Binary Tag (NBT) file format is a simple structured binary format that is mainly used by the game Minecraft (see the official specification for more details). This sho...
Python Code: import nbtlib nbt_file = nbtlib.load('nbt_files/bigtest.nbt') nbt_file['stringTest'] Explanation: Using nbtlib The Named Binary Tag (NBT) file format is a simple structured binary format that is mainly used by the game Minecraft (see the official specification for more details). This short documentation wi...
1,717
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="http Step1: Risk Factor Models The first step is to define a model for the risk-neutral discounting. Step2: We then define a market environment containing the major parameter spe...
Python Code: import dx import datetime as dt import pandas as pd import seaborn as sns; sns.set() Explanation: <img src="http://hilpisch.com/tpq_logo.png" alt="The Python Quants" width="45%" align="right" border="4"> Quickstart This brief first part illustrates---without much explanation---the usage of the DX Analytics...
1,718
Given the following text description, write Python code to implement the functionality described below step by step Description: Streaming Sourmash This notebook demonstrates how to use goetia to perform a streaming analysis of sourmash minhash signatures. Goetia includes the sourmash C++ header and exposes it with cp...
Python Code: # First, import the necessary libraries from goetia import libgoetia from goetia.alphabets import DNAN_SIMPLE from goetia.signatures import SourmashSignature from sourmash import load_one_signature, MinHash import screed from ficus import FigureManager import seaborn as sns import numpy as np Explanation: ...
1,719
Given the following text description, write Python code to implement the functionality described below step by step Description: Bandicoot bandicoot is an open-source python toolbox to analyze mobile phone metadata. For more information, see Step1: Input files <img src="mini-mockups-01.png" width="80%" style="border ...
Python Code: %pylab inline import seaborn as sns Explanation: Bandicoot bandicoot is an open-source python toolbox to analyze mobile phone metadata. For more information, see: http://bandicoot.mit.edu/ <hr> End of explanation !head -n 5 data/ego.csv !head -n 5 data/antennas.csv Explanation: Input files <img src="mini-m...
1,720
Given the following text description, write Python code to implement the functionality described below step by step Description: Attention Based Classification Tutorial Recommended time Step1: Load & Explore Data Let's begin by downloading the data from Figshare and cleaning and splitting it for use in training. Step...
Python Code: %load_ext autoreload %autoreload 2 from __future__ import absolute_import from __future__ import division from __future__ import print_function import pandas as pd import tensorflow as tf import numpy as np import time import os from sklearn import metrics from visualize_attention import attentionDisplay f...
1,721
Given the following text description, write Python code to implement the functionality described below step by step Description: Artificial Intelligence & Machine Learning Ujian Akhir Semester Mekanisme Anda hanya diwajibkan untuk mengumpulkan file ini saja ke uploader yang disediakan di https Step1: Soal 1.2.a (2 po...
Python Code: import networkx as nx # Kode Anda di sini Explanation: Artificial Intelligence & Machine Learning Ujian Akhir Semester Mekanisme Anda hanya diwajibkan untuk mengumpulkan file ini saja ke uploader yang disediakan di https://elearning.uai.ac.id/. Ganti nama file ini saat pengumpulan menjadi uas_NIM.ipynb. Ke...
1,722
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">Regression with Categorical Variables</h1> Step2: The BirthSmokers Data Researchers interested in answering the above research question collected the following data (birt...
Python Code: %pylab inline pylab.style.use('ggplot') import numpy as np import pandas as pd Explanation: <h1 align="center">Regression with Categorical Variables</h1> End of explanation smoking_txt = Wgt Gest Smoke 2940 38 yes 3130 38 no 2420 36 yes 2450 34 no 2760 39 yes 2440 35 yes 3226 40 no 3301 42 yes 2729 37 no 3...
1,723
Given the following text description, write Python code to implement the functionality described below step by step Description: Flux sampling Basic usage The easiest way to get started with flux sampling is using the sample function in the flux_analysis submodule. sample takes at least two arguments Step1: By defaul...
Python Code: from cobra.test import create_test_model from cobra.flux_analysis import sample model = create_test_model("textbook") s = sample(model, 100) s.head() Explanation: Flux sampling Basic usage The easiest way to get started with flux sampling is using the sample function in the flux_analysis submodule. sample ...
1,724
Given the following text description, write Python code to implement the functionality described below step by step Description: Opening and previewing This uses the tiny excel spreadsheet example1.xls. It is small enough to preview inline in this notebook. But for bigger spreadsheet tables you will want to open the...
Python Code: # Load in the functions from databaker.framework import * # Load the spreadsheet tabs = loadxlstabs("example1.xls") # Select the first table tab = tabs[0] print("The unordered bag of cells for this table looks like:") print(tab) Explanation: Opening and previewing This uses the tiny excel spreadsheet examp...
1,725
Given the following text description, write Python code to implement the functionality described below step by step Description: Python for Bioinformatics This Jupyter notebook is intented to be used alongside the book Python for Bioinformatics Chapter 5 Step1: Once the previous command are executed, you can open the...
Python Code: !curl https://raw.githubusercontent.com/Serulab/Py4Bio/master/samples/samples.tar.bz2 -o samples.tar.bz2 !mkdir samples !tar xvfj samples.tar.bz2 -C samples Explanation: Python for Bioinformatics This Jupyter notebook is intented to be used alongside the book Python for Bioinformatics Chapter 5: Handling F...
1,726
Given the following text description, write Python code to implement the functionality described below step by step Description: Немного безумия смотрим, работают ли attention models и другие модели Step2: Вспомогательные функции Step3: Графики Step4: Просто поезд + inclusive Step5: Для сравнения фильтрация выборк...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy import root_numpy # import pandas - no pandas today from astropy.table import Table from sklearn.metrics import roc_auc_score from scipy.special import logit from decisiontrain import DecisionTrainClassifier from collections import Order...
1,727
Given the following text description, write Python code to implement the functionality described below step by step Description: SFR package example Demonstrates functionality of Flopy SFR module using the example documented by Prudic and others (2004) Step1: copy over the example files to the working directory Step2...
Python Code: import sys import platform import os import numpy as np import glob import shutil import matplotlib as mpl import matplotlib.pyplot as plt import flopy import flopy.utils.binaryfile as bf #Set name of MODFLOW exe # assumes executable is in users path statement exe_name = 'mf2005' if platform.system() == '...
1,728
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting Started Tensors are similar to numpy's ndarrays, with the addition being that Tensors can also be used on a GPU to accelerate computing. Step1: Numpy Bridge The torch Tensor and num...
Python Code: x = torch.Tensor(5, 3); x x = torch.rand(5, 3); x x.size() y = torch.rand(5, 3) x + y torch.add(x, y) result = torch.Tensor(5, 3) torch.add(x, y, out=result) result1 = torch.Tensor(5, 3) result1 = x + y result1 # anything ending in '_' is an in-place operation y.add_(x) # adds x to y in-place # standard nu...
1,729
Given the following text description, write Python code to implement the functionality described below step by step Description: Last updated Step1: 1. Loading data More details, see http Step2: From a local text file Let's first load some temperature data which covers all lattitudes. Since read_table is supposed to...
Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt from pandas import set_option set_option("display.max_rows", 16) LARGE_FIGSIZE = (12, 8) # Change this cell to the demo location on YOUR machine %cd 'D:\\Git\\Pandas_Tutorial\\demos\\climate_timeseries' %ls Explanatio...
1,730
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Classification & How To "Frame Problems" for a Neural Network by Andrew Trask Twitter Step1: Note Step2: Lesson Step3: Project 1 Step4: We'll create three Counter objects, one ...
Python Code: def pretty_print_review_and_label(i): print(labels[i] + "\t:\t" + reviews[i][:80] + "...") g = open('reviews.txt','r') # What we know! reviews = list(map(lambda x:x[:-1],g.readlines())) g.close() g = open('labels.txt','r') # What we WANT to know! labels = list(map(lambda x:x[:-1].upper(),g.readlines())...
1,731
Given the following text description, write Python code to implement the functionality described. Description: Count minimum factor jumps required to reach the end of an Array vector to store factors of each integer ; dp array ; Precomputing all factors of integers from 1 to 100000 ; Function to count the minimum jumps...
Python Code: factors =[[ ] for i in range(100005 ) ] ; dp =[0 for i in range(100005 ) ] ; def precompute() : for i in range(1 , 100001 ) : for j in range(i , 100001 , i ) : factors[j ] . append(i ) ;    def solve(arr , k , n ) : if(k == n - 1 ) : return 0 ;  if(k >= n ) : return 1000000000...
1,732
Given the following text description, write Python code to implement the functionality described below step by step Description: Ch5 Categorizing and Tagging Words 本章的目標是回答這些問題 Step1: 上面的範例中,CC是對等連接詞、RB是副詞、IN是介系詞、NN是名詞、JJ則是形容詞。如果想知道詳細的tag定義,可以用nltk.help.upenn_tagset('RB')來查詢。 Tagged Corpora 在NLTK的習慣上,tagged token會表示成...
Python Code: import nltk text = nltk.word_tokenize("And now for something completely different") nltk.pos_tag(text) Explanation: Ch5 Categorizing and Tagging Words 本章的目標是回答這些問題: 什麼是lexical categories? 它們如何應用在NLP中? 要儲存單字和分類的資料結構是什麼? 如何自動為每個單字分類? 本章會提到一些基本的NLP方法,例如sequence labeling、n-gram models、backoff、evaluation。 辨識單字的...
1,733
Given the following text description, write Python code to implement the functionality described below step by step Description: Automate the ML process using pipelines There are standard workflows in a machine learning project that can be automated. In Python scikit-learn, Pipelines help to clearly define and automat...
Python Code: %matplotlib inline import matplotlib.pyplot as plt # Create a pipeline that standardizes the data then creates a model #Load libraries for data processing import pandas as pd #data processing, CSV file I/O (e.g. pd.read_csv) import numpy as np from scipy.stats import norm from sklearn.model_selection impor...
1,734
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="#Chapter-1" data-toc-modified-id="Chapter-1-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Chapter 1</a></div><div class="lev2 toc...
Python Code: from graphviz import Digraph dot = Digraph('Ex 1.4') dot.edge('Coin 1', 'Ball 1') dot.edge('Coin 2', 'Ball 2') dot.edge('Ball 1', 'Sample 1=red') dot.edge('Ball 2', 'Sample 1=red') dot.edge('Ball 1', 'Sample 2=red') dot.edge('Ball 2', 'Sample 2=red') dot.edge('Ball 1', 'Sample 3=red') dot.edge('Ball 2', 'S...
1,735
Given the following text description, write Python code to implement the functionality described below step by step Description: The business ID field has already been filtered for only restaurants We want to filter the users collection for the following Step1: Create a new dictionary with the following structure and...
Python Code: #Find a list of users with at least 20 reviews user_list = [] for user in users.find(): if user['review_count'] >= 20: user_list.append(user['_id']) else: pass Explanation: The business ID field has already been filtered for only restaurants We want to filter the users collection fo...
1,736
Given the following text description, write Python code to implement the functionality described below step by step Description: Think Bayes Step1: Improving Reading Ability From DASL(http Step2: And use groupby to compute the means for the two groups. Step4: The Normal class provides a Likelihood function that com...
Python Code: from __future__ import print_function, division % matplotlib inline import warnings warnings.filterwarnings('ignore') import math import numpy as np from thinkbayes2 import Pmf, Cdf, Suite, Joint, EvalBinomialPmf import thinkplot Explanation: Think Bayes: Chapter 9 This notebook presents code and exercises...
1,737
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: OT for image color adaptation This example presents a way of transferring colors between two images with Optimal Transport as introduced in [6] [6] Ferradans, S., Papadakis, N., Peyre...
Python Code: # Authors: Remi Flamary <remi.flamary@unice.fr> # Stanislas Chambon <stan.chambon@gmail.com> # # License: MIT License import numpy as np from scipy import ndimage import matplotlib.pylab as pl import ot r = np.random.RandomState(42) def im2mat(I): Converts an image to matrix (one pixel per lin...
1,738
Given the following text description, write Python code to implement the functionality described below step by step Description: Fourier analysis & resonances A great benefit of being able to call rebound from within python is the ability to directly apply sophisticated analysis tools from scipy and other python libra...
Python Code: import rebound import numpy as np sim = rebound.Simulation() sim.units = ('AU', 'yr', 'Msun') sim.add("Sun") sim.add("Jupiter") sim.add("Saturn") Explanation: Fourier analysis & resonances A great benefit of being able to call rebound from within python is the ability to directly apply sophisticated analys...
1,739
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: 使用近似最近邻和文本嵌入向量构建语义搜索 <table class="tfo-notebook-buttons" align="left"> <t...
Python Code: # Copyright 2018 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 # # Unless re...
1,740
Given the following text description, write Python code to implement the functionality described below step by step Description: <!-- The ipynb was auto-generated from markdown using notedown. Instead of modifying the ipynb file modify the markdown source. --> <h1 class="tocheading">Spark</h1> <div id="toc"></div> <...
Python Code: from pyspark import SparkContext sc = SparkContext() Explanation: <!-- The ipynb was auto-generated from markdown using notedown. Instead of modifying the ipynb file modify the markdown source. --> <h1 class="tocheading">Spark</h1> <div id="toc"></div> <img src="images/spark-logo.png"> Apache Spark Spark...
1,741
Given the following text description, write Python code to implement the functionality described below step by step Description: Performing a full distance comparison using PSA In this example, PSA is used to compute the mutual pairwise distances between a set of trajectories. In this notebook, we show how to perform ...
Python Code: %matplotlib inline %load_ext autoreload %autoreload 2 # Suppress FutureWarning about element-wise comparison to None # Occurs when calling PSA plotting functions import warnings warnings.filterwarnings('ignore') Explanation: Performing a full distance comparison using PSA In this example, PSA is used to co...
1,742
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute source power estimate by projecting the covariance with MNE We can apply the MNE inverse operator to a covariance matrix to obtain an estimate of source power. This is computationall...
Python Code: # Author: Denis A. Engemann <denis-alexander.engemann@inria.fr> # Luke Bloy <luke.bloy@gmail.com> # # License: BSD-3-Clause import os.path as op import numpy as np import mne from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse_cov data_path = sample.dat...
1,743
Given the following text description, write Python code to implement the functionality described below step by step Description: Multiple Traveling Salesman and the Problem of routing vehicles Imagine we have instead of one salesman traveling to all the sites, that instead the workload is shared among many salesman. T...
Python Code: from pulp import * import numpy as np import matplotlib.pyplot as plt %matplotlib inline import seaborn as sn Explanation: Multiple Traveling Salesman and the Problem of routing vehicles Imagine we have instead of one salesman traveling to all the sites, that instead the workload is shared among many sales...
1,744
Given the following text description, write Python code to implement the functionality described below step by step Description: Naive Bayes Male or Female Multivariate author Step1: Since we are simply using two Multivariate Gaussian Distributions, our Naive Bayes model is very simple to initialize. Step2: Of cours...
Python Code: from pomegranate import * import numpy as np Explanation: Naive Bayes Male or Female Multivariate author: Nicholas Farn [<a href="sendto:nicholasfarn@gmail.com">nicholasfarn@gmail.com</a>] This example shows how to create a Multivariate Guassian Naive Bayes Classifier using pomegranate. In this example we ...
1,745
Given the following text description, write Python code to implement the functionality described below step by step Description: Graded = 10/11 Homework #4 These problem sets focus on list comprehensions, string operations and regular expressions. Problem set #1 Step1: In the following cell, complete the code with an...
Python Code: numbers_str = '496,258,332,550,506,699,7,985,171,581,436,804,736,528,65,855,68,279,721,120' Explanation: Graded = 10/11 Homework #4 These problem sets focus on list comprehensions, string operations and regular expressions. Problem set #1: List slices and list comprehensions Let's start with some data. The...
1,746
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Generate Features And Target Data Step2: Create Logistic Regression Step3: Cross-Validate Model Using Precision
Python Code: # Load libraries from sklearn.model_selection import cross_val_score from sklearn.linear_model import LogisticRegression from sklearn.datasets import make_classification Explanation: Title: Precision Slug: precision Summary: How to evaluate a Python machine learning using precision. Date: 2017-09-15 12:0...
1,747
Given the following text description, write Python code to implement the functionality described below step by step Description: For high dpi displays. Step1: 0. General note This example compares pressure calculated from pytheos and original publication for the gold scale by Dorogokupets 2007. 1. Global setup Step2:...
Python Code: %config InlineBackend.figure_format = 'retina' Explanation: For high dpi displays. End of explanation import matplotlib.pyplot as plt import numpy as np from uncertainties import unumpy as unp import pytheos as eos Explanation: 0. General note This example compares pressure calculated from pytheos and orig...
1,748
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Testing averaging methods From this post The equation is Step2: $$\frac{\partial\phi}{\partial t}+\nabla . \left(-D\left(\phi_{0}\right)\nabla \phi\right)+\nabla.\left(-\nabla \phi_{...
Python Code: from fipy import Grid2D, CellVariable, FaceVariable import numpy as np def upwindValues(mesh, field, velocity): Calculate the upwind face values for a field variable Note that the mesh.faceNormals point from `id1` to `id2` so if velocity is in the same direction as the `faceNormal`s then we tak...
1,749
Given the following text description, write Python code to implement the functionality described below step by step Description: Trees and Forests NOTE Step1: Decision Tree Classification Step2: Random Forests Step3: Selecting the Optimal Estimator via Cross-Validation Step4: Fit the forest manually
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt Explanation: Trees and Forests NOTE: This module code was partly taken from Andreas Muellers Adavanced scikit-learn O'Reilly Course It is just used to explore the scikit-learn random forest object in a systematic manner I've added more c...
1,750
Given the following text description, write Python code to implement the functionality described below step by step Description: Intro to Cython Why Cython Outline Step1: Now, let's time this Step2: Not too bad, but this can add up. Let's see if Cython can do better Step3: That's a little bit faster, which is nice ...
Python Code: def f(x): y = x**4 - 3*x return y def integrate_f(a, b, n): dx = (b - a) / n dx2 = dx / 2 s = f(a) * dx2 for i in range(1, n): s += f(a + i * dx) * dx s += f(b) * dx2 return s Explanation: Intro to Cython Why Cython Outline: Speed up Python code Interact with Nu...
1,751
Given the following text description, write Python code to implement the functionality described below step by step Description: PyLadies and local Python User Groups Last updated Step1: Part 1 Step2: The Meetup API limits requests, however their documentation isn't exactly helpful. Using their headers, I saw that ...
Python Code: from __future__ import print_function from collections import defaultdict import json import os import time import requests Explanation: PyLadies and local Python User Groups Last updated: August 4, 2015 I am not a statistician by trade; far from it. I did take a few stats & econometrics courses in colleg...
1,752
Given the following text description, write Python code to implement the functionality described below step by step Description: GPyTorch Regression Tutorial Introduction In this notebook, we demonstrate many of the design features of GPyTorch using the simplest example, training an RBF kernel Gaussian process on a si...
Python Code: import math import torch import gpytorch from matplotlib import pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 Explanation: GPyTorch Regression Tutorial Introduction In this notebook, we demonstrate many of the design features of GPyTorch using the simplest example, training an RBF ker...
1,753
Given the following text description, write Python code to implement the functionality described below step by step Description: Linear algebra Step1: Matrix and vector products Q1. Predict the results of the following code. Step2: Q2. Predict the results of the following code. Step3: Q3. Predict the results of the...
Python Code: import numpy as np np.__version__ Explanation: Linear algebra End of explanation x = [1,2] y = [[4, 1], [2, 2]] print np.dot(x, y) print np.dot(y, x) print np.matmul(x, y) print np.inner(x, y) print np.inner(y, x) Explanation: Matrix and vector products Q1. Predict the results of the following code. End of...
1,754
Given the following text description, write Python code to implement the functionality described below step by step Description: Inverse Kinematics Problem In this example, we are going to use the pyswarms library to solve a 6-DOF (Degrees of Freedom) Inverse Kinematics (IK) problem by treating it as an optimization p...
Python Code: # Import modules import numpy as np # Import PySwarms import pyswarms as ps # Some more magic so that the notebook will reload external python modules; # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython %load_ext autoreload %autoreload 2 Explanation: Inverse Kinematics Proble...
1,755
Given the following text description, write Python code to implement the functionality described below step by step Description: Text classification with a RNN Tutorial in Tensorflow 2.0 Step1: Set up input pipeline The IMDB large movie review dataset is a binary classification dataset—all the reviews have either a p...
Python Code: import tensorflow as tf import tensorflow_datasets as tfds import matplotlib.pyplot as plt import time Explanation: Text classification with a RNN Tutorial in Tensorflow 2.0 End of explanation dataset, info = tfds.load("imdb_reviews/subwords8k", with_info=True, as_supervised=True) train_dataset, test_datas...
1,756
Given the following text description, write Python code to implement the functionality described below step by step Description: Introducción a Python para Ciencias Biólogicas Curso de Biofísica - Universidad de Antioquia Daniel Mejía Raigosa (email Step1: Probemos creando una variable que inicialice a una palabra Es...
Python Code: print("Hola mundo!") print("1+1=",2) print("Hola, otra vez","1+1=",2) print("Hola, otra vez.","Sabias que 1+1 =",2,"?") numero=3 print(numero) numero=3.1415 print(numero) Explanation: Introducción a Python para Ciencias Biólogicas Curso de Biofísica - Universidad de Antioquia Daniel Mejía Raigosa (email: d...
1,757
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Outlier Detection with bqplot In this notebook, we create a class DNA that leverages the new bqplot canvas based HeatMap along with the ipywidgets Range Slider to help us detect and c...
Python Code: from bqplot import ( DateScale, ColorScale, HeatMap, Figure, LinearScale, OrdinalScale, Axis, ) from scipy.stats import percentileofscore from scipy.interpolate import interp1d import bqplot.pyplot as plt from traitlets import List, Float, observe from ipywidgets import IntRange...
1,758
Given the following text description, write Python code to implement the functionality described below step by step Description: Accessing and Plotting Meshes Setup Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don...
Python Code: !pip install -I "phoebe>=2.1,<2.2" Explanation: Accessing and Plotting Meshes Setup Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End of explanation %matplot...
1,759
Given the following text description, write Python code to implement the functionality described below step by step Description: <H1>Multivariate regression</H1> Step1: Let's evaluate how much the membrane potential depends on Input resistance and membrane time constant and the sag ratio. We will create the followin...
Python Code: %pylab inline import pandas as pd mypath = 'Cell_types.xlsx' xls = pd.read_excel(mypath) xls.head() xls.InputR xls['Vrest'].mean() xls['Vrest'].unique() # get NumPy array Explanation: <H1>Multivariate regression</H1> End of explanation x = xls[['InputR', 'SagRatio','mbTau']] y = xls[['Vrest']] # import sta...
1,760
Given the following text description, write Python code to implement the functionality described below step by step Description: Cross Validation Step1: cross_val_score uses the KFold or StratifiedKFold strategies by default Step2: Cross Validation Iterator K-Fold - KFold divides all the samples in k groups of ...
Python Code: # import from sklearn.datasets import load_iris from sklearn.cross_validation import cross_val_score, KFold, train_test_split, cross_val_predict, LeaveOneOut, LeavePOut from sklearn.cross_validation import ShuffleSplit, StratifiedKFold, StratifiedShuffleSplit from sklearn.metrics import accuracy_score from...
1,761
Given the following text description, write Python code to implement the functionality described below step by step Description: <small><i>This notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small> Density Estimation Step1: Introducing Gaussian Mixture Models We previously sa...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy import stats plt.style.use('seaborn') Explanation: <small><i>This notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small> Density Estimation: Gaussian Mixture Models Here we'll explore G...
1,762
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', 'nims-kma', 'sandbox-2', 'atmoschem') Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: NIMS-KMA Source ID: SANDBOX-2 Topic: Atmoschem Sub-Topics: Transp...
1,763
Given the following text description, write Python code to implement the functionality described below step by step Description: A Simple Autoencoder We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed represen...
Python Code: %matplotlib inline import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', validation_size=0) Explanation: A Simple Autoencoder We'll start off by building a simple autoencoder to c...
1,764
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Part 5 Step1: There are actually two different approaches you can take to using TensorFlow or PyTorch models with DeepChem. It depends on whether you want to use TensorFlow/PyTorc...
Python Code: !curl -Lo conda_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py import conda_installer conda_installer.install() !/root/miniconda/bin/conda info -e !pip install --pre deepchem Explanation: Tutorial Part 5: Creating Models with TensorFlow and PyTorch In the t...
1,765
Given the following text description, write Python code to implement the functionality described below step by step Description: You are currently looking at version 1.0 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook ...
Python Code: %matplotlib notebook import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.datasets import load_digits dataset = load_digits() X, y = dataset.data, dataset.target for class_name, class_count in zip(data...
1,766
Given the following text description, write Python code to implement the functionality described below step by step Description: The intensity is $\theta * X$ where $X$ is a row vector. Step1: We consider different shapes for the intensity
Python Code: theta = np.array([2]) Explanation: The intensity is $\theta * X$ where $X$ is a row vector. End of explanation X = 0.1*np.random.normal(size = (d,N)) X = np.reshape(np.ones(N,),(1,N)) X = np.reshape(np.sin(np.arange(N)),(1,N)) dt = 0.1 # discretization step l = np.exp(np.dot(X.T,theta)) u = np.random.unifo...
1,767
Given the following text description, write Python code to implement the functionality described below step by step Description: Plot the histogram of the number of trajectories over queries. Step1: Plot the histogram of the length of trajectory given a start point. Step2: Compute the ratio of multi-label when query...
Python Code: plt.figure(figsize=[15, 5]) ax = plt.subplot() ax.set_xlabel('#Trajectories') ax.set_ylabel('#Queries') ax.set_title('Histogram of #Trajectories') queries = sorted(dat_obj.TRAJID_GROUP_DICT.keys()) X = [len(dat_obj.TRAJID_GROUP_DICT[q]) for q in queries] pd.Series(X).hist(ax=ax, bins=20) Explanation: Plot ...
1,768
Given the following text description, write Python code to implement the functionality described below step by step Description: Big Data Applications and Analytics - Term Project Sean M. Shiverick Fall 2017 Classification of Prescription Opioid Misuse Step1: Part 1. Load Project dataset Delete first two columns and ...
Python Code: import sklearn import mglearn import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline Explanation: Big Data Applications and Analytics - Term Project Sean M. Shiverick Fall 2017 Classification of Prescription Opioid Misuse: PRL Logistic Regression Classifier, Decision Tree...
1,769
Given the following text description, write Python code to implement the functionality described below step by step Description: LAB 2b Step1: Import necessary libraries. Step2: Lab Task #1 Step3: The source dataset Our dataset is hosted in BigQuery. The CDC's Natality data has details on US births from 1969 to 200...
Python Code: %%bash sudo pip freeze | grep google-cloud-bigquery==1.6.1 || \ sudo pip install google-cloud-bigquery==1.6.1 Explanation: LAB 2b: Prepare babyweight dataset. Learning Objectives Setup up the environment Preprocess natality dataset Augment natality dataset Create the train and eval tables in BigQuery Expo...
1,770
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-...
1,771
Given the following text description, write Python code to implement the functionality described below step by step Description: Correlation Matrix By calling df.corr() on a full pandas DataFrame will return a square matrix containing all pairs of correlations. By plotting them as a heatmap, you can visualize many cor...
Python Code: df = x_plus_noise(randomness=0) sns.heatmap(df.corr(), vmin=0, vmax=1) df.corr() Explanation: Correlation Matrix By calling df.corr() on a full pandas DataFrame will return a square matrix containing all pairs of correlations. By plotting them as a heatmap, you can visualize many correlations more efficien...
1,772
Given the following text description, write Python code to implement the functionality described below step by step Description: Gravitational Redshift (rv_grav) Setup Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab). ...
Python Code: #!pip install -I "phoebe>=2.3,<2.4" Explanation: Gravitational Redshift (rv_grav) Setup Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab). End of explanation import phoebe from phoebe import u # units import...
1,773
Given the following text description, write Python code to implement the functionality described below step by step Description: Algorithms Exercise 3 Imports Step2: Character counting and entropy Write a function char_probs that takes a string and computes the probabilities of each character in the string Step4: Th...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact Explanation: Algorithms Exercise 3 Imports End of explanation def char_probs(s): Find the probabilities of the unique characters in the string s. Parameters ---------- s...
1,774
Given the following text description, write Python code to implement the functionality described below step by step Description: The notebook interface The IPython -- being rebranded as Jupyter -- notebook interface is becoming a standard for a number of languages other than Python Step1: For instance, you can benchm...
Python Code: %quickref Explanation: The notebook interface The IPython -- being rebranded as Jupyter -- notebook interface is becoming a standard for a number of languages other than Python: Julia, Scala, R, Haskell, bash are all getting their kernels in IPython. Since Python allows you to call MATLAB anyway, you can a...
1,775
Given the following text description, write Python code to implement the functionality described below step by step Description: Peak finder Can one break a peak into several gaussian peaks usding pymc? Step1: Simulate data Step2: Now we know that the answer two overlayed gaussians. So model it that way and see what...
Python Code: # http://onlinelibrary.wiley.com/doi/10.1002/2016JA022652/epdf import datetime import pymc from pprint import pprint import numpy as np import matplotlib.pyplot as plt import spacepy.plot as spp print(datetime.datetime.now().isoformat()) Explanation: Peak finder Can one break a peak into several gaussian p...
1,776
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading an event file Read events from a file. For a more detailed guide on how to read events using MNE-Python, see tut_epoching_and_averaging. Step1: Reading events Below we'll read in an...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Chris Holdgraf <choldgraf@berkeley.edu> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne.datasets import sample print(__doc__) data_path = sample.data_path() fname = data_path + '/MEG/sample/sa...
1,777
Given the following text description, write Python code to implement the functionality described below step by step Description: Visual Comparison Between Different Classification Methods in Shogun Notebook by Youssef Emad El-Din (Github ID Step1: <a id = "section1">Data Generation and Visualization</a> Transformatio...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') from shogun import * import shogun as sg #Needed lists for the final plot classifiers_linear = []*10 classifiers_non_linear = []*10 classifiers_names = []*10 fadings...
1,778
Given the following text description, write Python code to implement the functionality described below step by step Description: Finding similar documents with Word2Vec and WMD Word Mover's Distance is a promising new tool in machine learning that allows us to submit a query and return the most relevant documents. For...
Python Code: from time import time start_nb = time() # Initialize logging. import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s') sentence_obama = 'Obama speaks to the media in Illinois' sentence_president = 'The president greets the press in Chicago' sentence_obama = sentence_obama.lowe...
1,779
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Soundscape Analysis by Shift-Invariant Latent Components</h1> <h2>Michael Casey - Bregman Labs, Dartmouth College</h2> A toolkit for matrix factorization of soundscape spectrograms into ...
Python Code: from pylab import * # numpy, matplotlib, plt from bregman.suite import * # Bregman audio feature extraction library from soundscapeecology import * # 2D time-frequency shift-invariant convolutive matrix factorization %matplotlib inline rcParams['figure.figsize'] = (15.0, 9.0) Explanation: <h1>Soundscape An...
1,780
Given the following text description, write Python code to implement the functionality described below step by step Description: Drag from Tides This adds a constant time lag model (Hut 1981) to tides raised on either the primary and/or the orbiting bodies. As an example, we'll add the tides raised on a post-main sequ...
Python Code: import rebound import reboundx import numpy as np %matplotlib inline import matplotlib.pyplot as plt def getsim(): sim = rebound.Simulation() sim.units = ('yr', 'AU', 'Msun') sim.add(m=0.86) # post-MS Sun sim.add(m=3.e-6, a=1., e=0.03) # Earth sim.move_to_com() rebx = reboun...
1,781
Given the following text description, write Python code to implement the functionality described below step by step Description: Storage Commands Google Cloud Datalab provides a set of commands for working with data stored in Google Cloud Storage. They can help you work with data files containing data that is not stor...
Python Code: %%gcs --help Explanation: Storage Commands Google Cloud Datalab provides a set of commands for working with data stored in Google Cloud Storage. They can help you work with data files containing data that is not stored in BigQuery or manage data imported into or exported from BigQuery. This notebook introd...
1,782
Given the following text description, write Python code to implement the functionality described below step by step Description: Continuous renal replacement therapy (CRRT) This notebook overviews the process of defining CRRT Step2: Step 1 Step4: The above gives us some hints to expand our initial search Step6: Man...
Python Code: # Import libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import psycopg2 from IPython.display import display, HTML # used to print out pretty pandas dataframes import matplotlib.dates as dates import matplotlib.lines as mlines %matplotlib inline plt.style.use('ggplot') # s...
1,783
Given the following text description, write Python code to implement the functionality described below step by step Description: Quick introduction to GRASS GIS Temporal Framework The GRASS GIS Temporal Framework implements temporal GIS functionality at user level and provides additionally an API to implement new spat...
Python Code: import grass.temporal as tgis import grass.script as gscript Explanation: Quick introduction to GRASS GIS Temporal Framework The GRASS GIS Temporal Framework implements temporal GIS functionality at user level and provides additionally an API to implement new spatio-temporal processing modules. The tempora...
1,784
Given the following text description, write Python code to implement the functionality described below step by step Description: DAT210x - Programming with Python for DS Module5- Lab4 Step1: You can experiment with these parameters Step2: Some Convenience Functions Step3: Load up the dataset. It may or may not have...
Python Code: import math import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib from sklearn import preprocessing from sklearn.decomposition import PCA # You might need to import more modules here.. # .. your code here .. matplotlib.style.use('ggplot') # Look Pretty c = ['red', 'green'...
1,785
Given the following text description, write Python code to implement the functionality described below step by step Description: Magic functions You can enable magic functions by loading pandas_td.ipython Step1: It can be loaded automatically by the following configuration in "~/.ipython/profile_default/ipython_confi...
Python Code: %load_ext pandas_td.ipython Explanation: Magic functions You can enable magic functions by loading pandas_td.ipython: End of explanation c = get_config() c.InteractiveShellApp.extensions = [ 'pandas_td.ipython', ] Explanation: It can be loaded automatically by the following configuration in "~/.ipython...
1,786
Given the following text description, write Python code to implement the functionality described below step by step Description: Repaso (Módulo 1) Recordar que el tema principal del módulo 1 son las ecuaciones diferenciales. Entonces, al finalizar este módulo, las competencias principales que deben tener ustedes es - ...
Python Code: # Numeral 1 # Importar librerías necesarias import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Definimos funcion mu def mu(x, r): return r*(1-x) # Definimos conjunto de valores en x x = np.linspace(0, 1.2, 50) # Valor del parametro solicitado r = 1 # Conjunto de valores en y y = mu...
1,787
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1 toc-item"><a href="#Rotations" data-toc-modified-id="Rotations-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Rotations</a></div><div class="lev1 toc...
Python Code: import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import xgboost as xgb from sklearn.metrics import roc_curve, auc from sklearn.metrics import precision_recall_curve df = pd.read_csv("iris.csv") Explanation: Table of Contents <p><div class="lev1 toc-item"><a href=...
1,788
Given the following text description, write Python code to implement the functionality described below step by step Description: User Defined Functions User defined functions make for neater and more efficient programming. We have already made use of several library functions in the math, scipy and numpy libraries. St...
Python Code: import numpy as np import scipy.constants as constants print('Pi = ', constants.pi) h = float(input("Enter the height of the tower (in metres): ")) t = float(input("Enter the time interval (in seconds): ")) s = constants.g*t**2/2 print("The height of the ball is",h-s,"meters") Explanation: User Defined Fun...
1,789
Given the following text description, write Python code to implement the functionality described below step by step Description: In this short tutorial, we will build and expand on the previous tutorials by computing the dynamic connectivity, using Time-Varying Functional Connectivity Graphs. In the near future, the s...
Python Code: import numpy as np import tqdm raw_eeg_eyes_open = np.load("data/eeg_eyes_opened.npy") raw_eeg_eyes_closed = np.load("data/eeg_eyes_closed.npy") num_trials, num_channels, num_samples = np.shape(raw_eeg_eyes_open) read_trials = 10 eeg_eyes_open = raw_eeg_eyes_open[0:read_trials, ...] eeg_eyes_closed = raw_e...
1,790
Given the following text description, write Python code to implement the functionality described below step by step Description: 随机变量及其分布 Random Variable and its Distribution 包括以下内容: 1. 随机变量 Random Variable 2. 伯努利分布 Bernoulli Distribution 3. 二项分布 Binomial Distribution 4. 泊松分布 Poisson Distribution 5...
Python Code: import math import numpy as np import pandas as pd from pandas import Series, DataFrame # 引入绘图包 import matplotlib.pyplot as plt import seaborn as sns sns.set_style('whitegrid') %matplotlib inline Explanation: 随机变量及其分布 Random Variable and its Distribution 包括以下内容: 1. 随机变量 Random Variable 2. 伯努利分布 Ber...
1,791
Given the following text description, write Python code to implement the functionality described below step by step Description: use spearman correlation between OTUs and 5 VitD variables (with BH FDR corrected p-val <= 0.05 as threshold) use lasso regression on all OTUs vs. 5 VitD variables (need Cross-validation to ...
Python Code: import warnings warnings.filterwarnings("ignore") import pandas as pd import numpy as np from scipy.stats import spearmanr, pearsonr from statsmodels.sandbox.stats.multicomp import multipletests from sklearn.model_selection import train_test_split from sklearn.linear_model import LassoLarsCV from sklearn.p...
1,792
Given the following text description, write Python code to implement the functionality described below step by step Description: Chap 3 線形回帰 (ML) 問題設定 $N$ 個の観測値 ${\bf x}_n$, $(n=1, ..., N)$ とそれに対応する目標値 ${\bf t_n}$ のデータから ${\bf x}$ と ${\bf t}$ の関係をモデル化する。 線形回帰では、$M$ 個の重み係数 $w_j$, $(j=1, ..., M)$ と基底関数 ${\phi_j({\bf x})...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np Explanation: Chap 3 線形回帰 (ML) 問題設定 $N$ 個の観測値 ${\bf x}_n$, $(n=1, ..., N)$ とそれに対応する目標値 ${\bf t_n}$ のデータから ${\bf x}$ と ${\bf t}$ の関係をモデル化する。 線形回帰では、$M$ 個の重み係数 $w_j$, $(j=1, ..., M)$ と基底関数 ${\phi_j({\bf x})}$ の線形和 $$ y({\bf x}, {\bf w}) = \...
1,793
Given the following text description, write Python code to implement the functionality described below step by step Description: 가설검정 Step1: 오늘의 주요 예제 Step2: sp.factorial() 함수를 이용하여 조합의 경우의 수인 $\binom{n}{r}$을 계산하는 함수를 정의한다. Step3: 이제 이항분포 확률를 구하는 함수는 다음과 같다. n, r, p 세 개의 인자를 사용하며 p는 한 번 실행할 때 특정 사건이 발생할 확률이다. Step4...
Python Code: import numpy as np from __future__ import print_function, division Explanation: 가설검정 End of explanation import sympy as sp sp.factorial(5) Explanation: 오늘의 주요 예제: 동전던지기 동전을 30번 던져서 앞면(Head)이 24번 나왔을 때, 정상적인 동전이라 할 수 있을까? 영가설(H0): 정상적인 동전이라면 30번 중에 보통은 15번은 앞면(Head), 15번은 뒷면(Tail)이 나온다. 따라서 정상적인 동전이 아니다. 대...
1,794
Given the following text description, write Python code to implement the functionality described below step by step Description: Computation The labels associated with DataArray and Dataset objects enables some powerful shortcuts for computation, notably including aggregation and broadcasting by dimension names. Basic...
Python Code: %matplotlib inline import numpy as np import xarray as xr arr = xr.DataArray(np.random.randn(2, 3), [('x', ['a', 'b']), ('y', [10, 20, 30])]) arr - 3 abs(arr) Explanation: Computation The labels associated with DataArray and Dataset objects enables some powerful shortcuts for computation, notably including...
1,795
Given the following text description, write Python code to implement the functionality described below step by step Description: Classification Class MLPClassifier implements a multi-layer perceptron (MLP) algorithm that trains using Backpropagation. MLP trains on two arrays Step1: MLP can fit a non-linear model to t...
Python Code: ## Input X = [[0., 0.], [1., 1.]] ## Labels y = [0, 1] ## Create Model clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1) ## Fit clf.fit(X, y) ## Make Predictions clf.predict([[2., 2.], [-1., -2.]]) Explanation: Classification Class MLPClassifier ...
1,796
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have a dataframe, e.g:
Problem: import pandas as pd df = pd.DataFrame({'Date': ['20.07.2018', '20.07.2018', '21.07.2018', '21.07.2018'], 'B': [10, 1, 0, 1], 'C': [8, 0, 1, 0]}) def g(df): df1 = df.groupby('Date').agg(lambda x: (x%2==0).sum()) df2 = df.groupby('Date').agg(lambda x: (x%2==1).sum())...
1,797
Given the following text description, write Python code to implement the functionality described below step by step Description: MultiGraph Create 3 views Step1: Code the user can supply to view the streaming data Given the streams with the 3 different moving averages, create 3 separate views to obtain the data. Step...
Python Code: from streamsx.topology.topology import Topology from streamsx.topology import context from some_module import jsonRandomWalk, movingAverage #from streamsx import rest import json # Define operators rw = jsonRandomWalk() ma_150 = movingAverage(150) ma_50 = movingAverage(50) # Define topology & submit top = ...
1,798
Given the following text description, write Python code to implement the functionality described below step by step Description: 正規表現 20. JSONデータの読み込み Wikipedia記事のJSONファイルを読み込み, 「イギリス」に関する記事本文を表示せよ. 問題21-29では, ここで抽出した記事本文に対して実行せよ. Step1: 21. カテゴリ名を含む行を抽出 記事中でカテゴリ名を宣言している行を抽出せよ.
Python Code: import pandas as pd import json def get_article(title): for line in open('jawiki-country.json', 'r'): data = json.loads(line) if data['title'] == title: return data['text'].split('\n') England = get_article('イギリス') print(type(England), England) Explanation: 正規表現 20....
1,799
Given the following text description, write Python code to implement the functionality described below step by step Description: Class Coding Lab Step1: Part 1 Step2: Testing Out your API The documentation for the API can be found here Step3: Next we setup the headers and the rest is like calling any other API... S...
Python Code: # Run this to make sure you have the pre-requisites! !pip install -q requests # start by importing the modules we will need import requests import json Explanation: Class Coding Lab: Web Services and APIs Overview The web has long evolved from user-consumption to device consumption. In the early days of t...