Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
3,700
Given the following text description, write Python code to implement the functionality described below step by step Description: OT for domain adaptation on empirical distributions This example introduces a domain adaptation in a 2D setting. It explicits the problem of domain adaptation and introduces some optimal tra...
Python Code: # Authors: Remi Flamary <remi.flamary@unice.fr> # Stanislas Chambon <stan.chambon@gmail.com> # # License: MIT License import matplotlib.pylab as pl import ot import ot.plot Explanation: OT for domain adaptation on empirical distributions This example introduces a domain adaptation in a 2D setting....
3,701
Given the following text description, write Python code to implement the functionality described below step by step Description: Exact solution used in MES runs We would like to MES the operation \begin{eqnarray} \frac{\int_0^{2\pi} f \rho d\theta}{\int_0^{2\pi} \rho d\theta} = \frac{\int_0^{2\pi} f d\theta}{\int_0^{2...
Python Code: %matplotlib notebook from sympy import init_printing from sympy import S from sympy import sin, cos, tanh, exp, pi, sqrt from sympy import integrate import numpy as np from boutdata.mms import x, y, z, t import os, sys # If we add to sys.path, then it must be an absolute path common_dir = os.path.abspath('...
3,702
Given the following text description, write Python code to implement the functionality described below step by step Description: Triplet Loss for Implicit Feedback Neural Recommender Systems The goal of this notebook is first to demonstrate how it is possible to build a bi-linear recommender system only using positive...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd import os.path as op from zipfile import ZipFile try: from urllib.request import urlretrieve except ImportError: # Python 2 compat from urllib import urlretrieve ML_100K_URL = "http://files.grouplens.org/data...
3,703
Given the following text description, write Python code to implement the functionality described below step by step Description: Using the frame context in the TIMIT MLP model This notebook is an extension of the MLP_TIMIT demo which takes a context of many frames at input to model the same output. So if we have a pho...
Python Code: import os os.environ['CUDA_VISIBLE_DEVICES']='1' import numpy as np from keras.models import Sequential from keras.layers.core import Dense, Activation, Reshape from keras.optimizers import Adam, SGD from IPython.display import clear_output from tqdm import * Explanation: Using the frame context in the TIM...
3,704
Given the following text description, write Python code to implement the functionality described below step by step Description: Whitening evoked data with a noise covariance Evoked data are loaded and then whitened using a given noise covariance matrix. It's an excellent quality check to see if baseline signals match...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis A. Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import mne from mne import io from mne.datasets import sample from mne.cov import compute_covariance print(__doc__) Explanation: Whitening evoked data ...
3,705
Given the following text description, write Python code to implement the functionality described below step by step Description: 파이썬 기본 자료형 2부 수정 사항 문자열 메소드 사용 예제 Step1: 실제로 확인하면 웹사이트의 내용 전체가 하나의 문자열로 저장되어 있다. 주의 Step2: 소스코드에서 줄바꾸기, 띄어쓰기, 인용부호 등 특수 기호를 적절하게 해석하여 출력하고자 하면 print 명령어를 사용한다. Step3: 문자열 자료형 Step4: 유니코드...
Python Code: import urllib.request page = urllib.request.urlopen("http://beans-r-us.appspot.com/prices.html") text = page.read().decode("utf8") Explanation: 파이썬 기본 자료형 2부 수정 사항 문자열 메소드 사용 예제: 보다 실용적인 예제였으면 함. 요약 문자열 자료형 다루기 문자열 메소드 활용 응용: 웹 상에 있는 데이터를 가져와서 정보 활용하기 준비 사항 문자열의 정의화 기초적인 활용법에 대한 자세한 설명은 여기를 참조한다. ...
3,706
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: フェデレーテッドラーニングリサーチの TFF Step2: TFF が動作していることを確認します。 Step4: 入力データを準備する このセクションでは、TFF に含まれる EMNIST データセットを読み込んで事前処理します。EMNIST データセットの詳細は、画像分類のフェ...
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...
3,707
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Plot dynamics functions Step2: Sample data from the ARHMM Step3: Below, we visualize each component of of the observation variable as a time series. The colors corre...
Python Code: !pip install git+git://github.com/lindermanlab/ssm-jax-refactor.git import ssm import copy import jax.numpy as np import jax.random as jr from tensorflow_probability.substrates import jax as tfp from ssm.distributions.linreg import GaussianLinearRegression from ssm.arhmm import GaussianARHMM from ssm.util...
3,708
Given the following text description, write Python code to implement the functionality described below step by step Description: Pipelining estimators In this section we study how different estimators maybe be chained. A simple example Step1: Previously, we applied the feature extraction manually, like so Step2: The...
Python Code: import os with open(os.path.join("datasets", "smsspam", "SMSSpamCollection")) as f: lines = [line.strip().split("\t") for line in f.readlines()] text = [x[1] for x in lines] y = [x[0] == "ham" for x in lines] from sklearn.cross_validation import train_test_split text_train, text_test, y_train, y_test =...
3,709
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial 2 Step1: These variables do not change anything in the simulation engine, but are just standard Python variables. They are used to increase the readability and flexibility of the s...
Python Code: from espressomd import System, electrostatics import espressomd import numpy import matplotlib.pyplot as plt plt.ion() # Print enabled features required_features = ["EXTERNAL_FORCES", "MASS", "ELECTROSTATICS", "LENNARD_JONES"] espressomd.assert_features(required_features) print(espressomd.features()) # Sys...
3,710
Given the following text description, write Python code to implement the functionality described below step by step Description: Combine all blast hits into a single dataframe Step1: Extract the best hits for each cluster from each DB (q_cov > 80 and e_value < 1e-3 )
Python Code: all_blast_hits = blast_hits[0] for search_hits in blast_hits[1:]: all_blast_hits = all_blast_hits.append(search_hits) all_blast_hits.head() all_blast_hits.db.unique() Explanation: Combine all blast hits into a single dataframe End of explanation #all_blast_hits[all_blast_hits.e_value < 0.001].groupby([...
3,711
Given the following text description, write Python code to implement the functionality described below step by step Description: Downloading genome data from NCBI with Biopython and Entrez Introduction In this worksheet, you will use Biopython to download pathogen genome data from NCBI programmatically with Python. I...
Python Code: # This line imports the Bio.Entrez module, and makes it available # as 'Entrez'. from Bio import Entrez # The line below imports the Bio.SeqIO module, which allows reading # and writing of common bioinformatics sequence formats. from Bio import SeqIO # Create a new directory (if needed) for output/download...
3,712
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: 케라스와 텐서플로 허브를 사용한 영화 리뷰 텍스트 분류하기 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: IMDB 데이터셋 ...
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...
3,713
Given the following text description, write Python code to implement the functionality described below step by step Description: Orthogonality in Potapov modes The modes of a system will not always be orthogonal because some of the signal leaks out of the system. Let's use the Potapov analysis for a specific example t...
Python Code: import Potapov_Code.Roots as Roots import Potapov_Code.Potapov as Potapov import Potapov_Code.Time_Delay_Network as Time_Delay_Network import Potapov_Code.Time_Sims as Time_Sims import Potapov_Code.functions as functions import Potapov_Code.tests as tests import numpy as np import numpy.linalg as la impor...
3,714
Given the following text description, write Python code to implement the functionality described below step by step Description: Finite-Length Capacity of the Binary-Input AWGN (BI-AWGN) Channel This code is provided as supplementary material of the lecture Channel Coding 2 - Advanced Methods. This code illustrates * ...
Python Code: import numpy as np import scipy.integrate as integrate from scipy.stats import norm import matplotlib.pyplot as plt Explanation: Finite-Length Capacity of the Binary-Input AWGN (BI-AWGN) Channel This code is provided as supplementary material of the lecture Channel Coding 2 - Advanced Methods. This code il...
3,715
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t...
3,716
Given the following text description, write Python code to implement the functionality described below step by step Description: ========================================= Reading/Writing a noise covariance matrix ========================================= Plot a noise covariance matrix. Step1: Show covariance
Python Code: # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) from os import path as op import mne from mne.datasets import sample print(__doc__) data_path = sample.data_path() fname_cov = op.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif') fname_evo = op.join(data_path, '...
3,717
Given the following text description, write Python code to implement the functionality described below step by step Description: Using dstoolbox visualization Table of contents Nodes and edges of a pipeline Visualizing a pipeline Step1: Nodes and edges of a pipeline Every sklearn Pipeline and FeatureUnion can be seen...
Python Code: from pprint import pprint from IPython.display import Image from sklearn.pipeline import Pipeline from sklearn.pipeline import FeatureUnion from sklearn.preprocessing import FunctionTransformer from sklearn.preprocessing import StandardScaler from dstoolbox.utils import get_nodes_edges from dstoolbox.visua...
3,718
Given the following text description, write Python code to implement the functionality described below step by step Description: Using a CFSv2 forecast CFSv2 is a seasonal forecast system, used for analysing past climate and also making seasonal, up to 9-month, forecasts. Here we give a brief example on how to use Pl...
Python Code: %matplotlib notebook import numpy as np import pandas as pd import matplotlib.pyplot as plt import calendar import datetime import matplotlib.dates as mdates from API_client.python.datahub import datahub_main from API_client.python.lib.dataset import dataset from API_client.python.lib.variables import vari...
3,719
Given the following text description, write Python code to implement the functionality described below step by step Description: Variational Inference Step1: Model specification A neural network is quite simple. The basic unit is a perceptron which is nothing more than logistic regression. We use many of these in par...
Python Code: %matplotlib inline import theano theano.config.floatX = 'float64' import pymc3 as pm import theano.tensor as T import sklearn import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style('white') from sklearn import datasets from sklearn.preprocessing import scale from sklearn.cro...
3,720
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License") Step1: Build the libcoral C++ examples This Colab provides a convenient way to build the libcoral C+...
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...
3,721
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.algo - Optimisation sous contrainte (correction) Un peu plus de détails dans cet article Step1: On rappelle le problème d'optimisation à résoudre Step2: Exercice 2 Step3: La code pr...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 1A.algo - Optimisation sous contrainte (correction) Un peu plus de détails dans cet article : Damped Arrow-Hurwicz algorithm for sphere packing. End of explanation from cvxopt import solvers, matrix import random def fonction(x=No...
3,722
Given the following text description, write Python code to implement the functionality described below step by step Description: Decomposition framework of the PySAL segregation module This is a notebook that explains a step-by-step procedure to perform decomposition on comparative segregation measures. First, let's i...
Python Code: import pandas as pd import pickle import numpy as np import matplotlib.pyplot as plt from pysal.explore import segregation from pysal.explore.segregation.decomposition import DecomposeSegregation Explanation: Decomposition framework of the PySAL segregation module This is a notebook that explains a step-by...
3,723
Given the following text description, write Python code to implement the functionality described below step by step Description: Batch Normalization – Practice Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll create a convolutional neural network with 20 convolutional l...
Python Code: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False) Explanation: Batch Normalization – Practice Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll crea...
3,724
Given the following text description, write Python code to implement the functionality described below step by step Description: The porepy grid structure In this tutorial we investigate the PorePy grid structure, and explain how to access information stored in the grid. Basic grid construction The simplest grids are...
Python Code: import numpy as np import porepy as pp nx = np.array([3, 2]) g = pp.CartGrid(nx) Explanation: The porepy grid structure In this tutorial we investigate the PorePy grid structure, and explain how to access information stored in the grid. Basic grid construction The simplest grids are Cartesian. PorePy can ...
3,725
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise 1 Learn how to use tensorflow basic concepts and variables First start to learn about the graph structure, tensorflow is built upon the nodes Step1: Next, we are going to show how ...
Python Code: # basic imported headers import tensorflow as tf Second, learn how to fetch the data from the result input1 = tf.constant(3.0) input2 = tf.constant(2.0) input3 = tf.constant(5.0) intermd = tf.add(input1, input2) mult = tf.multiply(input3, intermd) with tf.Session() as sess: result = sess.run([mult,...
3,726
Given the following text description, write Python code to implement the functionality described below step by step Description: Computing source space SNR This example shows how to compute and plot source space SNR as in Step1: EEG Next we do the same for EEG and plot the result on the cortex
Python Code: # Author: Padma Sundaram <tottochan@gmail.com> # Kaisu Lankinen <klankinen@mgh.harvard.edu> # # License: BSD (3-clause) import mne from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse import numpy as np import matplotlib.pyplot as plt print(__doc__) data...
3,727
Given the following text description, write Python code to implement the functionality described below step by step Description: Converting a Deterministic <span style="font-variant Step1: The function regexp_sum takes a set $S = { r_1, \cdots, r_n }$ of regular expressions as its argument. It returns the regular ex...
Python Code: def arb(S): for x in S: return x Explanation: Converting a Deterministic <span style="font-variant:small-caps;">Fsm</span> into a Regular Expression Given a set S, the function arb(S) returns an arbitrary member from S. End of explanation def regexp_sum(S): n = len(S) if n == 0: ...
3,728
Given the following text description, write Python code to implement the functionality described below step by step Description: On this notebook the best models and input parameters will be searched for. The problem at hand is predicting the price of any stock symbol 56 days ahead, assuming one model for all the symb...
Python Code: # Basic imports import os import pandas as pd import matplotlib.pyplot as plt import numpy as np import datetime as dt import scipy.optimize as spo import sys from time import time from sklearn.metrics import r2_score, median_absolute_error %matplotlib inline %pylab inline pylab.rcParams['figure.figsize'] ...
3,729
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="../../images/qiskit-heading.gif" alt="Note Step1: Single Qubit Quantum states A single qubit quantum state can be written as $$|\psi\rangle = \alpha|0\rangle + \beta |1\rangle$$ w...
Python Code: # Useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, register, get_backend from qiskit.tools.visualization import circuit_...
3,730
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction In this notebook I study the stokeslet, foundamental solution of stokes equation $$ \nabla \mathbf p +\mu \nabla^2 \mathbf u=\mathbf f$$ The stokeslet gives the flow field $\mat...
Python Code: import numpy as np import pylab as pl import seaborn as sns sns.set_style("white") %matplotlib inline x,X,y,Y=-5,5,-5,5 #our space dx,dy=.5,.5 #discretisation mX,mY=np.meshgrid(np.arange(x,X,dx),np.arange(y,Y,dy)) pl.scatter(mX,mY,s=1,lw=1,c='r') Explanation: Introduction In this notebook I study the...
3,731
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Checks Schema checks Step1: A bit of basic pandas Let's first start by reading in the CSV file as a pandas.DataFrame(). Step2: To get the columns of a DataFrame object df, call df.col...
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline %config InlineBackend.figure_format = 'retina' Explanation: Data Checks Schema checks: Making sure that only the columns that are expected are provided. Datum checks: Looking for missing values Ensuring that expected value ranges are correct Statistical...
3,732
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction You are getting to the point where you can own an analysis from beginning to end. So you'll do more data exploration in this exercise than you've done before. Before you get st...
Python Code: # Set up feedback system from learntools.core import binder binder.bind(globals()) from learntools.sql.ex5 import * print("Setup Complete") Explanation: Introduction You are getting to the point where you can own an analysis from beginning to end. So you'll do more data exploration in this exercise than yo...
3,733
Given the following text description, write Python code to implement the functionality described below step by step Description: Matplotlib Basics Step1: Functional method Step2: Object oriented method Step3: Matplotlib Basics continued...2 Step4: Figure Size and DPI Step5: Saving figures Step6: Matplotlib Basic...
Python Code: import matplotlib.pyplot as plt import numpy as np %matplotlib inline x = np.linspace(0,5,11) y = x ** 2 x y Explanation: Matplotlib Basics End of explanation plt.plot(x, y) plt.xlabel('X Label') plt.ylabel('Y Label') plt.title('Title') plt.show() # Multiplot on same canvas plt.subplot(1,2,1) # rows, col...
3,734
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have data of sample 1 and sample 2 (`a` and `b`) – size is different for sample 1 and sample 2. I want to do a weighted (take n into account) two-tailed t-test.
Problem: import numpy as np import scipy.stats a = np.random.randn(40) b = 4*np.random.randn(50) _, p_value = scipy.stats.ttest_ind(a, b, equal_var = False)
3,735
Given the following text description, write Python code to implement the functionality described below step by step Description: \title{Combinational-Circuit Building Blocks aka medium scale integrated circuit (MSI) in myHDL} \author{Steven K Armour} \maketitle Table of Contents <p><div class="lev1 toc-item"><a href="...
Python Code: import numpy as np import pandas as pd from sympy import * init_printing() from myhdl import * from myhdlpeek import * import random from sympy_myhdl_tools import * pass Explanation: \title{Combinational-Circuit Building Blocks aka medium scale integrated circuit (MSI) in myHDL} \author{Steven K Armour} \m...
3,736
Given the following text description, write Python code to implement the functionality described below step by step Description: Geomath - Conhecendo os Recursos Explorando Pontos Pontos são a unidade basica da Geometria Analítica, eles são os objetos que podem definir se algo existe ou não existe e muitos outros fato...
Python Code: from geomath.point import Point A = Point(0,0) B = Point(4,4) A.distance(B) A.midpoint(B) B.quadrant() Explanation: Geomath - Conhecendo os Recursos Explorando Pontos Pontos são a unidade basica da Geometria Analítica, eles são os objetos que podem definir se algo existe ou não existe e muitos outros fator...
3,737
Given the following text description, write Python code to implement the functionality described below step by step Description: This images and the equacions are from Step1: For now I´m using only the forces b and d, the force b are the force applied in the point b, and the force d are the force applied on the point...
Python Code: %matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt import math #Ipython Libraries # Remember to remove when you pass to Spyder. from IPython.display import Image Image(filename='axis.png') a1 = 1 a2 = 1 b1 = 1 b2 = 1 c1 = 1 c2 = 1 d1 = 1 d2 = 1 theta = math.radians(56.6...
3,738
Given the following text description, write Python code to implement the functionality described below step by step Description: A significant portion of the time you spend on the problem sets in CogSci131 will be spent debugging. In this notebook we discuss simple strategies to minimize hair loss and maximize coding ...
Python Code: # for inline plotting in the notebook %matplotlib inline import numpy as np import matplotlib.pyplot as plt def plot_log(): figure, axis = plt.subplots(2, 1) x = np.linspace(1, 2, 10) axis.plot(x, np.log(x)) plt.show() plot_log() # Call the function, generate plot Explanation: A significa...
3,739
Given the following text description, write Python code to implement the functionality described below step by step Description: Batch Normalization – Practice Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll create a convolutional neural network with 20 convolutional l...
Python Code: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False) Explanation: Batch Normalization – Practice Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll crea...
3,740
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Numerical Integration Step3: Below is, mathematically, $f_{-h} Step4: Then, we can use sympy to calculate, symbolically, $f_{h} Step5: Success! Trapezoid rule was rederived (stop...
Python Code: from itertools import combinations import sympy from sympy import Function, integrate, Product, Sum, Symbol, symbols from sympy.abc import a,b,h,i,k,m,n,x from sympy import Rational as Rat def lagrange_basis_polys(N,x,xpts=None): lagrange_basis_polynomials(N,x,xpts) returns the Lagrange basis ...
3,741
Given the following text description, write Python code to implement the functionality described below step by step Description: Manual publication DB insertion from raw text using syntax features Publications and conferences of Dr. AVRAM Sanda, Profesor Universitar http Step1: 47 pubs obtained DB Storage (TODO) Time...
Python Code: class HelperMethods: @staticmethod def IsDate(text): # print("text") # print(text) for c in text.lstrip(): if c not in "1234567890 ": return False return True import pandas import requests page = requests.get('http://www.cs.ubbcluj.ro/~san...
3,742
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 11 Input File Interlude Wednesday, October 11th 2017 Input Files and Parsing We usually want to read data into our software Step1: Looping Over Child Elements Step2: Accessing Chil...
Python Code: import xml.etree.ElementTree as ET tree = ET.parse('shelterdogs.xml') dogshelter = tree.getroot() print(dogshelter) print(dogshelter.tag) print(dogshelter.attrib) Explanation: Lecture 11 Input File Interlude Wednesday, October 11th 2017 Input Files and Parsing We usually want to read data into our software...
3,743
Given the following text description, write Python code to implement the functionality described below step by step Description: We can then canonicalize the MPS Step1: And we can compute the inner product as Step2: This relies on them sharing the same physical indices, site_ind_id, which the conjugated copy p.H na...
Python Code: p.left_canonize() p.show() Explanation: We can then canonicalize the MPS: End of explanation p.H @ p Explanation: And we can compute the inner product as: End of explanation (p.H & p).graph(color=[f'I{i}' for i in range(30)], initial_layout='random') p2 = (p + p) / 2 p2.show() Explanation: This relies on t...
3,744
Given the following text description, write Python code to implement the functionality described below step by step Description: Sigma to Pressure Interpolation By using metpy.calc.log_interp, data with sigma as the vertical coordinate can be interpolated to isobaric coordinates. Step1: Data The data for this example...
Python Code: import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt from netCDF4 import Dataset, num2date from metpy.cbook import get_test_data from metpy.interpolate import log_interpolate_1d from metpy.plots import add_metpy_logo, add_timestamp from metpy.units import units Expl...
3,745
Given the following text description, write Python code to implement the functionality described below step by step Description: Algorithms Exercise 2 Imports Step2: Peak finding Write a function find_peaks that finds and returns the indices of the local maxima in a sequence. Your function should Step3: Here is a st...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import seaborn as sns import numpy as np Explanation: Algorithms Exercise 2 Imports End of explanation def find_peaks(a): Find the indices of the local maxima in a sequence. b = np.array(a) c = b.max() return b[c] p1 = find_peaks([2,0,...
3,746
Given the following text description, write Python code to implement the functionality described below step by step Description: Logistic Neurons Step1: Activation of a logistic neuron Step2: Step 2 Step3: Step 3 Step4: Exercise
Python Code: import numpy as np from utils import make_classification, draw_decision_boundary, sigmoid from sklearn.metrics import accuracy_score from theano import tensor as T from theano import function, shared import matplotlib.pyplot as plt plt.style.use('ggplot') plt.rc('figure', figsize=(8, 6)) %matplotlib inline...
3,747
Given the following text description, write Python code to implement the functionality described below step by step Description: Opgave 1 Maak een lege lijst aan en noem deze lijst getallen_a. Vul deze lijst via een for loop met de getallen 2, 4, 6 , 8 en 10 Check of de lijst er zo uitziet als verwacht, hoeveel el...
Python Code: # 1.1 getallen_a = [] # 1.2 for i in range(2, 11, 2): getallen_a.append(i) # 1.3 print("Lijst getallen_a:", getallen_a) print("Lengte of aantal elementen:", len(getallen_a)) print("Getal op plek 0:", getallen_a[0]) print("Getal op plek 3:", getallen_a[3]) print("Getal op plek -1:", getallen_a[-1]) # 1....
3,748
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Q1 Step3: Let's solve ${\bf Hx} ={\bf b}$. Create a linear system by picking an ${\bf x}$ and generating a ${\bf b}$ by multiplying by the matrix ${\bf H}$. Then use the scipy.lina...
Python Code: def hilbert(n): return a Hilbert matrix, H_ij = (i + j - 1)^{-1} H = np.zeros((n,n), dtype=np.float64) for i in range(1, n+1): for j in range(1, n+1): H[i-1,j-1] = 1.0/(i + j - 1.0) return H Explanation: Q1: integrating a sampled vs. analytic function Numerical integra...
3,749
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Sentiment Classification on Large Movie Reviews Sentiment Analysis is understood as a classic natural language processing problem. In this example, a large moview review dataset was c...
Python Code: from bigdl.dataset import base import numpy as np def download_imdb(dest_dir): Download pre-processed IMDB movie review data :argument dest_dir: destination directory to store the data :return The absolute path of the stored data file_name = "imdb.npz" file_abs_path...
3,750
Given the following text description, write Python code to implement the functionality described below step by step Description: textblob Step1: Vamos a crear nuestro primer ejemplo de textblob a través del objeto TextBlob. Piensa en estos textblobs como una especie de cadenas de texto de Python, analaizadas y enriqu...
Python Code: from textblob import TextBlob Explanation: textblob: otro módulo para tareas de PLN (NLTK + pattern) textblob es una librería de procesamiento del texto para Python que permite realizar tareas de Procesamiento del Lenguaje Natural como análisis morfológico, extracción de entidades, análisis de opinión, tra...
3,751
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Plots Step1: Duncan's Prestige Dataset Load the Data We can use a utility function to load any R dataset available from the great <a href="https Step2: Influence plots Influence...
Python Code: %matplotlib inline from statsmodels.compat import lzip import numpy as np import matplotlib.pyplot as plt import statsmodels.api as sm from statsmodels.formula.api import ols plt.rc("figure", figsize=(16,8)) plt.rc("font", size=14) Explanation: Regression Plots End of explanation prestige = sm.datasets.get...
3,752
Given the following text description, write Python code to implement the functionality described below step by step Description: 如何使用和开发微信聊天机器人的系列教程 A workshop to develop & use an intelligent and interactive chat-bot in WeChat WeChat is a popular social media app, which has more than 800 million monthly active users. ...
Python Code: # from __future__ import unicode_literals, division # import time, datetime, requests import itchat from itchat.content import * Explanation: 如何使用和开发微信聊天机器人的系列教程 A workshop to develop & use an intelligent and interactive chat-bot in WeChat WeChat is a popular social media app, which has more than 800 milli...
3,753
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 26 Modeling and Simulation in Python Copyright 2021 Allen Downey License Step1: Case studies! Bungee jumping Suppose you want to set the world record for the highest "bungee dunk", ...
Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/...
3,754
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook is part of the clifford documentation Step1: Convert a complex number to a spinor Step2: Convert a spinor to a complex number Step3: Make sure we get what we started with wh...
Python Code: import clifford as cf layout, blades = cf.Cl(2) # instantiate a 2D- GA locals().update(blades) # put all blades into local namespace def c2s(z): '''convert a complex number to a spinor''' return z.real + z.imag*e12 def s2c(S): '''convert a spinor to a complex number''' S0 = float(S(0)) ...
3,755
Given the following text description, write Python code to implement the functionality described below step by step Description: EventVestor Step1: Let's go over the columns Step2: <a id='pipeline'></a> Pipeline Overview Accessing the data in your algorithms & research The only method for accessing partner data with...
Python Code: # import the dataset from quantopian.interactive.data.eventvestor import mergers_and_acquisitions_free as dataset # or if you want to import the free dataset, use: #from quantopian.data.eventvestor import buyback_auth_free # import data operations from odo import odo # import other libraries we will use im...
3,756
Given the following text description, write Python code to implement the functionality described. Description: How to swap two bits in a given integer ? This function swaps bit at positions p1 and p2 in an integer n ; Move p1 'th to rightmost side ; Move p2 'th to rightmost side ; XOR the two bits ; Put the xor bit bac...
Python Code: def swapBits(n , p1 , p2 ) : bit1 =(n >> p1 ) & 1 bit2 =(n >> p2 ) & 1 x =(bit1 ^ bit2 ) x =(x << p1 ) |(x << p2 ) result = n ^ x return result  if __name__== ' __main __' : res = swapBits(28 , 0 , 3 ) print("Result ▁ = ▁ ", res ) 
3,757
Given the following text description, write Python code to implement the functionality described below step by step Description: Understanding Hyperbole using RSA "My new kettle cost a million dollars." Hyperbole -- using an exagerated utterance to convey strong opinions -- is a common non-literal use of language. Yet...
Python Code: #first some imports import torch torch.set_default_dtype(torch.float64) # double precision for numerical stability import collections import argparse import matplotlib.pyplot as plt import pyro import pyro.distributions as dist import pyro.poutine as poutine from search_inference import HashingMarginal, m...
3,758
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Get the Data Read in the advertising.csv file and set it to a data frame called ad_data. Step2: Check the head of ad_data Step3: Use info and describe() on ad_data St...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> Logistic Regression Project In this project we will be working with a fake advertising data set, indi...
3,759
Given the following text description, write Python code to implement the functionality described below step by step Description: Spark version of wordcount examples Prepare the pyspark environment. Step1: Make sure your HDFS is still on and the input files (the three books) are still in the input folder. Create the i...
Python Code: import findspark import os findspark.init('/home/ubuntu/shortcourse/spark-1.5.1-bin-hadoop2.6') from pyspark import SparkContext, SparkConf conf = SparkConf().setAppName("test").setMaster("local[2]") sc = SparkContext(conf=conf) Explanation: Spark version of wordcount examples Prepare the pyspark environme...
3,760
Given the following text description, write Python code to implement the functionality described below step by step Description: Reproducing the black hole discovery in Thompson et al. 2019 In this science demo tutorial, we will reproduce the results in Thompson et al. 2019, who found and followed-up a candidate stell...
Python Code: from astropy.io import ascii from astropy.time import Time import astropy.units as u import matplotlib.pyplot as plt %matplotlib inline import numpy as np import pymc3 as pm import pymc3_ext as pmx import exoplanet.units as xu import exoplanet as xo import corner import arviz as az import thejoker as tj fr...
3,761
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 1 Step1: コメント 1. 行頭に#をつける Step3: 2. 文字列としてコメントを書く. ソースコードの中に文字列を埋め込むことができる. 表示しない文字列を書いても,正常に実行することができる. Step4: 1-2. 変数 代入と参照 代入:具体的な値を変数に入れること. 参照:変数に代入した値を利用すること Step5: 数値に対する演...
Python Code: print("Hello") Explanation: Chapter 1: Pythonの基本編 Pythonの概要 対話モード スクリプトの実行 コメントの書き方 変数 代入と参照 数値に対する演算 関数 標準入力 ファイルの読み書き 練習問題 1-1. Pythonの概要 対話モード コマンドライン上で`python`というコマンドを入力することで起動する.対話モードでは,プログラムを入力し,`Enter`キーを押してすぐに実行することができる.また,対話モードを終了するためには,`exit()`と入力し実行するか`Ctrl+D`を押す. スクリプトの実行 ファイル名`filename.py`のように...
3,762
Given the following text description, write Python code to implement the functionality described below step by step Description: Digits This notebook one-vs-all logistic regression and neural networks to recognize hand-written digits. 1 - Overview of the data set The dataset contains 5000 training examples of handwri...
Python Code: from scipy.io import loadmat dataset = loadmat('../datasets/mnist-data.mat') # comes as dictionary dataset.keys() Explanation: Digits This notebook one-vs-all logistic regression and neural networks to recognize hand-written digits. 1 - Overview of the data set The dataset contains 5000 training examples ...
3,763
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t...
3,764
Given the following text description, write Python code to implement the functionality described below step by step Description: Required Step1: Install Jekyll by Ruxi Feb 8, 2016 What is Jekyll? Its a static templating library enables blogging on github pages It follows this directory structure Step2: Instructions ...
Python Code: import os.path, gitpath #pip install git+'https://github.com/ruxi/python-gitpath.git' os.chdir(gitpath.root()) # changes path to .git root #os.getcwd() #check current work directory Explanation: Required: End of explanation from IPython.display import IFrame url = 'http://jekyllrb.com/docs/structure/' IFra...
3,765
Given the following text description, write Python code to implement the functionality described below step by step Description: MaxPooling3D [pooling.MaxPooling3D.0] input 4x4x4x2, pool_size=(2, 2, 2), strides=None, padding='valid', data_format='channels_last' Step1: [pooling.MaxPooling3D.1] input 4x4x4x2, pool_size...
Python Code: data_in_shape = (4, 4, 4, 2) L = MaxPooling3D(pool_size=(2, 2, 2), strides=None, padding='valid', data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(290) ...
3,766
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Convolutional Neural Networks Convolutional Neural Networks (CNNs) are deep neural networks with the addition of two very special types of layers Step2: Now let's cre...
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...
3,767
Given the following text description, write Python code to implement the functionality described below step by step Description: Hugging Face Accelerate Demo Note Step1: Import the required modules. Step2: wandb initialization. See wandb_demo notebook for more details. Step3: Build the model Use a ResNet18 from tor...
Python Code: !pip install accelerate Explanation: Hugging Face Accelerate Demo Note: Before running this demo, please make sure that you have wandb.ai free account. Let us install accelerate. End of explanation import torch import torchvision import wandb import datetime from torch.optim import SGD from torch.optim.lr...
3,768
Given the following text description, write Python code to implement the functionality described below step by step Description: Filtering and resampling data This tutorial covers filtering and resampling, and gives examples of how filtering can be used for artifact repair. We begin as always by importing the necessar...
Python Code: import os import numpy as np import matplotlib.pyplot as plt import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file) ...
3,769
Given the following text description, write Python code to implement the functionality described below step by step Description: Padding We're almost ready to train our model. There's just one hitch though Step1: Let's inspect the shapes of our padded questions. Step2: Great, each of our questions is now of length m...
Python Code: maxlen = 100 max_training_instances=10000 # It takes a long time to train on all 400,000 samples on CPU (5 hours/epoch) --- let's cut it down to # max_training_instances size. The dataset itself is a bit unbalanced, around 67% non-duplicate # / 33% duplicate. We can use this opportunity to make it more b...
3,770
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Windrose with MesoWest Data Introduction Who are we? http Step1: #### Customize matplotlib It's so much easier to modify matplotlib defaults like this rather than inline with the p...
Python Code: %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np from datetime import datetime import json from urllib.request import urlopen # Confirm that `pm25rose.py` is in your directory from pm25rose import WindroseAxes import mesowest Explanat...
3,771
Given the following text description, write Python code to implement the functionality described below step by step Description: Bivariate A bivariate analysis differs from a univariate, or distribution analysis, in that it is the analysis of two separate sets of data. These two sets of data are compared to one anothe...
Python Code: import numpy as np import scipy.stats as st from sci_analysis import analyze %matplotlib inline # Create x-sequence and y-sequence from random variables. np.random.seed(987654321) x_sequence = st.norm.rvs(2, size=2000) y_sequence = np.array([x + st.norm.rvs(0, 0.5, size=1) for x in x_sequence]) Explanation...
3,772
Given the following text description, write Python code to implement the functionality described below step by step Description: Trabajo en clase 02 Step1: Primer Punto Leemos primero los datos de los tiempos medidos en el laboratorio guardados en el archivo 'data.csv' Step2: # Análisis Para el caso en el que se usa...
Python Code: # Librerías import matplotlib from scipy import misc from scipy import stats from scipy import special import pylab as plt import numpy as np %matplotlib inline font = {'weight' : 'bold', 'size' : 16} matplotlib.rc('font', **font) from IPython.display import display from IPython.display import HT...
3,773
Given the following text description, write Python code to implement the functionality described below step by step Description: Let's create a polygon that can be transformed (i.e. rotated and scaled) and dragged. You can drag the polygon around, or use the handler to rotate it and to scale it. Note that the transfor...
Python Code: pg = Polygon(locations=polygon_coords, transform=True, draggable=True) m += pg Explanation: Let's create a polygon that can be transformed (i.e. rotated and scaled) and dragged. You can drag the polygon around, or use the handler to rotate it and to scale it. Note that the transformations are synced across...
3,774
Given the following text description, write Python code to implement the functionality described below step by step Description: reduce() Many times students have difficulty understanding reduce() so pay careful attention to this lecture. The function reduce(function, sequence) continually applies the function to the ...
Python Code: lst =[47,11,42,13] reduce(lambda x,y: x+y,lst) Explanation: reduce() Many times students have difficulty understanding reduce() so pay careful attention to this lecture. The function reduce(function, sequence) continually applies the function to the sequence. It then returns a single value. If seq = [ s1,...
3,775
Given the following text description, write Python code to implement the functionality described below step by step Description: Chained Visualizations with Yellowbrick Pipelines In Yellowbrick, VisualPipelines are modeled on Scikit-Learn Pipelines, which allow us to chain estimators together in a sane way and use the...
Python Code: %matplotlib inline import os import sys # Modify the path sys.path.append("/Users/rebeccabilbro/Desktop/waves/stuff/yellowbrick") import requests import numpy as np import pandas as pd import yellowbrick as yb import matplotlib.pyplot as plt Explanation: Chained Visualizations with Yellowbrick Pipeline...
3,776
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Wifi_Scan Data Step1: <br/> 2. Housing Project Data https Step2: - "OpenStreetMap" - "Mapbox Bright" (Limited levels of zoom for free tiles) - "Mapbox Control Room" (Limited levels of z...
Python Code: # Read File df = pd.read_csv("/home/dj/Desktop/motoG4_062212.csv") # convert Unix timestamp into readable timestamp df['time2'] = map(lambda x: dt.datetime.fromtimestamp(x), df.time.astype(float)/1000) df['month'] = map(lambda x: x.month, df['time2']) df['day'] = map(lambda x: x.day, df['time2']) df['hour'...
3,777
Given the following text description, write Python code to implement the functionality described below step by step Description: An Exploration of Nueral Net Capabilities Step1: Abstract A nueral network is a computational analogy to the methods by which humans think. Their design builds upon the idea of a neuron eit...
Python Code: import numpy as np import matplotlib from matplotlib import pyplot as plt matplotlib.style.use('ggplot') import IPython as ipynb %matplotlib inline Explanation: An Exploration of Nueral Net Capabilities End of explanation z = np.linspace(-10, 10, 100) f=plt.figure(figsize=(15, 5)) plt.subplot(1, 2,1) plt.p...
3,778
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Learn to calculate with seq2seq model In this assignment, you will learn how to use neural networks to solve sequence-to-sequence prediction tasks. Seq2Seq models are very popular the...
Python Code: import random def generate_equations(allowed_operators, dataset_size, min_value, max_value): Generates pairs of equations and solutions to them. Each equation has a form of two integers with an operator in between. Each solution is an integer with the result of the operaion. ...
3,779
Given the following text description, write Python code to implement the functionality described below step by step Description: Arrow Vaex supports Arrow. We will demonstrate vaex+arrow by giving a quick look at a large dataset that does not fit into memory. The NYC taxi dataset for the year 2015 contains about 150 m...
Python Code: !ls -alh /Users/maartenbreddels/datasets/nytaxi/nyc_taxi2015.arrow import vaex Explanation: Arrow Vaex supports Arrow. We will demonstrate vaex+arrow by giving a quick look at a large dataset that does not fit into memory. The NYC taxi dataset for the year 2015 contains about 150 million rows containing in...
3,780
Given the following text description, write Python code to implement the functionality described below step by step Description: Introducción al aprendizaje automático con scikit-learn En los últimos tiempos habrás oído hablar de machine learning, deep learning, reinforcement learning, muchas más cosas que contienen l...
Python Code: # X_train, X_test, Y_train, Y_test = # preserve X_train.shape, Y_train.shape # preserve X_test.shape, Y_test.shape Explanation: Introducción al aprendizaje automático con scikit-learn En los últimos tiempos habrás oído hablar de machine learning, deep learning, reinforcement learning, muchas más cosas que ...
3,781
Given the following text description, write Python code to implement the functionality described below step by step Description: Compare the read depth and number of strains This data is the average read depth of each metagenome. The table in read_depth.strains.tsv has the SRA ID, the average read depth across the amp...
Python Code: #instantiate our environment import os import sys %matplotlib inline import pandas as pd import statsmodels.api as sm # read the data into a pandas dataframe df = pd.read_csv("read_depth.strains.tsv", header=0, delimiter="\t") print("Shape: {}".format(df.shape)) df.head() Explanation: Compare the read dept...
3,782
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create one column as a function of two columns Step2: Create two columns as a function of one column
Python Code: # Import modules import pandas as pd # Example dataframe raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'], 'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st...
3,783
Given the following text description, write Python code to implement the functionality described below step by step Description: Today Step1: Q. What should this yield? Step2: Q. And this? Step3: Q. So, what will this print out? Step4: I'm smelling a violation of the DRY principle! How can we improve? Another func...
Python Code: x = 6.28 # set the variable x equal to tau, the real circular constant # Note this is the only correct way to check equality on floats. # Subtract the expected value and compare to your allowed error: eps = 1e-10 # my deviation I allow until I call them 'equal' if((x - 6.28) < eps): # if x is equal ...
3,784
Given the following text description, write Python code to implement the functionality described below step by step Description: <p><font size="6"><b>Python the essentials Step1: Python is a calculator Step2: also logical operators Step3: Variable assignment Step4: More information on print format Step5: <div cla...
Python Code: print("Hello INBO_course!") # python 3(!) Explanation: <p><font size="6"><b>Python the essentials: A minimal introduction</b></font></p> Introduction to GIS scripting May, 2017 © 2017, Stijn Van Hoey (&#115;&#116;&#105;&#106;&#110;&#118;&#97;&#110;&#104;&#111;&#101;&#121;&#64;&#103;&#109;&#97;&#105;&#108;&...
3,785
Given the following text description, write Python code to implement the functionality described below step by step Description: Custom generators Step1: Independent field generators At its most basic, a custom generator provides simply a convenient way of grouping other generators together in a single namespace. Ste...
Python Code: import tohu from tohu.v6.primitive_generators import * from tohu.v6.derived_generators import * from tohu.v6.generator_dispatch import * from tohu.v6.custom_generator import * from tohu.v6.utils import print_generated_sequence, make_dummy_tuples #tohu.v6.logging.logger.setLevel('DEBUG') from pandas.util.te...
3,786
Given the following text description, write Python code to implement the functionality described below step by step Description: long-short-portfolio On the first trading day of every month, rebalance portfolio to given percentages. One of the positions is a short position. Step1: Define Portfolios Note Step2: Some...
Python Code: import datetime import matplotlib.pyplot as plt import pandas as pd import pinkfish as pf # Format price data. pd.options.display.float_format = '{:0.2f}'.format %matplotlib inline # Set size of inline plots. '''note: rcParams can't be in same cell as import matplotlib or %matplotlib inline %matp...
3,787
Given the following text description, write Python code to implement the functionality described below step by step Description: Whitening evoked data with a noise covariance Evoked data are loaded and then whitened using a given noise covariance matrix. It's an excellent quality check to see if baseline signals match...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis A. Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import mne from mne import io from mne.datasets import sample from mne.cov import compute_covariance print(__doc__) Explanation: Whitening evoked data ...
3,788
Given the following text description, write Python code to implement the functionality described below step by step Description: From raw data to dSPM on SPM Faces dataset Runs a full pipeline using MNE-Python Step1: Load and filter data, set up epochs Step2: Visualize fields on MEG helmet Step3: Look at the whiten...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD-3-Clause import matplotlib.pyplot as plt import mne from mne.datasets import spm_face from mne.preprocessing import ICA, create_eog_epochs from mne import io, combine_evoked fro...
3,789
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 2 Step1: Example 1 Step2: Example 2 Step3: Example 3 Step4: Example 4 Step5: Example 5 Step6: Example 6
Python Code: # Import relevant modules %matplotlib inline %load_ext autoreload %autoreload 2 import numpy as np import healpy as hp from NPTFit import create_mask as cm # Module for creating masks Explanation: Example 2: Creating Masks In this example we show how to create masks using create_mask.py. Often it is conven...
3,790
Given the following text description, write Python code to implement the functionality described below step by step Description: Bienvenid@s a otra reunión de Pyladies!! En esta sesión aprenderemos a crear nuestras propias funciones en python.Pero primero que son funciones? Una función en python es un bloque de código...
Python Code: animales = ['perro', 'gato', 'perico'] len(animales) animales[1] x = 4 type(int('43')) Explanation: Bienvenid@s a otra reunión de Pyladies!! En esta sesión aprenderemos a crear nuestras propias funciones en python.Pero primero que son funciones? Una función en python es un bloque de código organizado y reu...
3,791
Given the following text description, write Python code to implement the functionality described below step by step Description: Keras Hello World Install Keras https Step1: TODO
Python Code: import tensorflow as tf tf.__version__ import keras keras.__version__ import h5py h5py.__version__ import pydot pydot.__version__ from keras.models import Sequential model = Sequential() from keras.layers import Dense model.add(Dense(units=6, activation='relu', input_dim=4)) model.add(Dense(units=3, activa...
3,792
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: List assignment Step2: Break up a string into variables Step3: Breaking up a number into separate variables Step4: Assign the first letter of 'spam' into varible a, assign a...
Python Code: variableName = 'This is a string.' Explanation: Title: Breaking Up String Variables Slug: breaking_up_string_variables Summary: Breaking Up String Variables Date: 2016-05-01 12:00 Category: Python Tags: Basics Authors: Chris Albon Basic name assignment End of explanation One, Two, Three = [1, 2, 3] Expla...
3,793
Given the following text description, write Python code to implement the functionality described below step by step Description: Toric Code Ground State <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step1: Toric code Hamiltonian The toric code Hamiltonian \begin{equation}...
Python Code: try: import recirq except ImportError: !pip install --quiet git+https://github.com/quantumlib/ReCirq import recirq try: import qsimcirq except ImportError: !pip install qsimcirq --quiet import qsimcirq import cirq import matplotlib.pyplot as plt import recirq.toric_code.toric_code_p...
3,794
Given the following text description, write Python code to implement the functionality described below step by step Description: Poisson $$f\left(\left.y\right|x_{i}\right)=\frac{\exp\left(-\mu\left(x_{i}\right)\right)\mu\left(x_{i}\right)^{y}}{y!}$$ $$\mu\left(X_{i}\right)=\exp\left(X_{i}\theta\right)$$ Step1: Gener...
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: Poisson $$f\left(\left.y\right|x_{i}\right)=\frac{\exp\left(-\mu\left(x_{i}\right)\right)\mu\left(x_{i}\right)^{y}}{y!}$$ $$\mu...
3,795
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Check for missing values Step2: Take a quick look at the ham and spam label column Step3: <font color=green>We see that 4825 out of 5572 messages, or 86.6%, are ham.<...
Python Code: import numpy as np import pandas as pd df = pd.read_csv('../TextFiles/smsspamcollection.tsv', sep='\t') df.head() len(df) Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> Scikit-learn Primer Scikit-learn (http://scikit-learn.org/) is an open-source machine learn...
3,796
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: 医療画像処理向けに DICOM ファイルをデコードする <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: 必要なパッケージをインストールし、...
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...
3,797
Given the following text description, write Python code to implement the functionality described below step by step Description: Whitening evoked data with a noise covariance Evoked data are loaded and then whitened using a given noise covariance matrix. It's an excellent quality check to see if baseline signals match...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis A. Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import mne from mne import io from mne.datasets import sample from mne.cov import compute_covariance print(__doc__) Explanation: Whitening evoked data ...
3,798
Given the following text description, write Python code to implement the functionality described below step by step Description: Example of using the Google API Client to access BigQuery Note that this is <b>not</b> the recommended approach. You should use the BigQuery client library because that is idiomatic Python. ...
Python Code: PROJECT='cloud-training-demos' # CHANGE THIS from googleapiclient.discovery import build service = build('bigquery', 'v2') Explanation: Example of using the Google API Client to access BigQuery Note that this is <b>not</b> the recommended approach. You should use the BigQuery client library because that i...
3,799
Given the following text description, write Python code to implement the functionality described below step by step Description: Análisis de los datos obtenidos Uso de ipython para el análsis y muestra de los datos obtenidos durante la producción.Se implementa un regulador experto. Los datos analizados son del día 12 ...
Python Code: #Importamos las librerías utilizadas import numpy as np import pandas as pd import seaborn as sns #Mostramos las versiones usadas de cada librerías print ("Numpy v{}".format(np.__version__)) print ("Pandas v{}".format(pd.__version__)) print ("Seaborn v{}".format(sns.__version__)) #Abrimos el fichero csv co...