Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
8,200
Given the following text description, write Python code to implement the functionality described below step by step Description: matplotlib의 여러가지 플롯 matplotlib는 기본적인 라인 프롯 이외에도 다양한 챠트/플롯 유형을 지원한다. 바 차트 x, y 데이터 중 하나가 카테고리 값인 경우에는 bar 명령과 barh 명령으로 바 차트(bar chart) 시각화를 할 수 있다. 가로 방향으로 바 차트를 그리려면 barh 명령을 사용한다. 자세한 내용은 ...
Python Code: y = [2, 3, 1] x = np.arange(len(y)) xlabel = ['A', 'B', 'C'] plt.bar(x, y, align='center') #보통은 이 명령어를 쳐야 가운데를 기준으로 x가 정렬, 설정 없으면 left가 디폴트 plt.xticks(x, xlabel); Explanation: matplotlib의 여러가지 플롯 matplotlib는 기본적인 라인 프롯 이외에도 다양한 챠트/플롯 유형을 지원한다. 바 차트 x, y 데이터 중 하나가 카테고리 값인 경우에는 bar 명령과 barh 명령으로 바 차트(bar ch...
8,201
Given the following text description, write Python code to implement the functionality described below step by step Description: Solution from Johannes Rieke and Alex Moore¶ Step1: Exercise 1 1. Step2: 2. Step3: For a = 0.5, the curve is flatter; for a = 2, the curve is steeper. 3. Picking $\mu$ = 0.1 Step4: 4. St...
Python Code: from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: Solution from Johannes Rieke and Alex Moore¶ End of explanation mu = 0.2 sigma = 0.5 dt = 0.01 time = np.arange(0, 10, dt) for i in range(5): x = np.zeros_like(time) fo...
8,202
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercises Step1: Exercise 1 a. Series Given an array of data, please create a pandas Series s with a datetime index starting 2016-01-01. The index should be daily frequency and should be th...
Python Code: # Useful Functions import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Exercises: Introduction to pandas By Christopher van Hoecke, Maxwell Margenot Lecture Link : https://www.quantopian.com/lectures/introduction-to-pandas IMPORTANT NOTE: This lecture corresponds to the Intr...
8,203
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify ...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'test-institute-1', 'sandbox-1', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: TEST-INSTITUTE-1 Source ID: SANDBOX-1 Topic: Seaice Sub-Topics:...
8,204
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">TensorFlow Neural Network Lab</h1> <img src="image/notmnist.png"> In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl...
Python Code: import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfile import ZipFile p...
8,205
Given the following text description, write Python code to implement the functionality described below step by step Description: LDA on simon's example The LDA is a well-known probabilistic model to handle mixtures of topics in an unsupervised way. It has been applied to a large number of problems (Blei, 2012). The ...
Python Code: from IPython.display import Image Image(filename='lda_plate.png') Explanation: LDA on simon's example The LDA is a well-known probabilistic model to handle mixtures of topics in an unsupervised way. It has been applied to a large number of problems (Blei, 2012). The original paper has over 10000 citation...
8,206
Given the following text description, write Python code to implement the functionality described below step by step Description: Gas Streaming in Disks Step2: Initialize the data First we need to define a function that tells us the speed of the gas at a given distance from the center of the star or galaxy. We conside...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import math Explanation: Gas Streaming in Disks: circular orbit approach The gas streaming around a young star, or in a galactic disk is dominated by gravity. So we can simply compute the orbits of a point mass around a star, or in the m...
8,207
Given the following text description, write Python code to implement the functionality described below step by step Description: Relaunched Hedge Funds This program is a replication of Stata Script Version 0.2 Step1: Prepare Data Step2: Analysis Merge managers with the start/end dates Step3: Find First End Date for...
Python Code: import pandas as pd from datetime import timedelta # ****************** Program Settings ****************** Folder = "" # Location of program scripts Data = "temp/" # Location to which temporary files are generated DataSource = "data/" # Location of the original data files (ASCII) Gap_Days = 60...
8,208
Given the following text description, write Python code to implement the functionality described below step by step Description: String operations Step1: Q1. Concatenate x1 and x2. Step2: Q2. Repeat x three time element-wise. Step3: Q3-1. Capitalize the first letter of x element-wise.<br/> Q3-2. Lowercase x element...
Python Code: from __future__ import print_function import numpy as np author = "kyubyong. https://github.com/Kyubyong/numpy_exercises" np.__version__ Explanation: String operations End of explanation x1 = np.array(['Hello', 'Say'], dtype=np.str) x2 = np.array([' world', ' something'], dtype=np.str) Explanation: Q1. Con...
8,209
Given the following text description, write Python code to implement the functionality described below step by step Description: metachars . any char \w any alphanumeric (a-z, A-Z, 0-9, _) \s any whitespace char (" _, \t, \n) \S any nonwhitespace \d any digit (0-9) . searches for an actual period Step1: define your o...
Python Code: #subject lines that have dates, e.g. 12/01/99 [line for line in subjects if re.search("\d\d/\d\d/\d\d", line)] Explanation: metachars . any char \w any alphanumeric (a-z, A-Z, 0-9, _) \s any whitespace char (" _, \t, \n) \S any nonwhitespace \d any digit (0-9) . searches for an actual period End of explana...
8,210
Given the following text description, write Python code to implement the functionality described below step by step Description: Multi-objective memetic approach In this third tutorial we consider an example with two dimensional input data and we approach its solution using a multi-objective approach where, aside the ...
Python Code: # Some necessary imports. import dcgpy import pygmo as pg # Sympy is nice to have for basic symbolic manipulation. from sympy import init_printing from sympy.parsing.sympy_parser import * init_printing() # Fundamental for plotting. from matplotlib import pyplot as plt %matplotlib inline Explanation: Multi-...
8,211
Given the following text description, write Python code to implement the functionality described below step by step Description: From http Step1: Array operations are very similar to that of the Python list. For example, the following code snippet creates a Python list and then converts it to a NumPy array Step2: In...
Python Code: import numpy as np Explanation: From http://www.codemag.com/article/1611081 <h1>NumPy Array Basics</h1> In NumPy, an array is of type ndarray (n-dimensional array). A NumPy array is an array of homogeneous values (all of the same type), and all items occupy a contiguous block of memory. To use NumPy, you f...
8,212
Given the following text description, write Python code to implement the functionality described below step by step Description: <div class="alert alert-block alert-info" style="margin-top Step1: <a id="ref0"></a> <h2> Logistic Function </h2> Step2: Create a tensor ranging from -100 to 100 Step3: Create a sigmoid o...
Python Code: import torch.nn as nn import torch import matplotlib.pyplot as plt Explanation: <div class="alert alert-block alert-info" style="margin-top: 20px"> <a href="http://cocl.us/pytorch_link_top"><img src = "http://cocl.us/Pytorch_top" width = 950, align = "center"></a> <img src = "https://ibm.box.com/shared/s...
8,213
Given the following text description, write Python code to implement the functionality described below step by step Description: FullAdder - Combinational Circuits This notebook walks through the implementation of a basic combinational circuit, a full adder. This example introduces many of the features of Magma includ...
Python Code: import magma as m import mantle Explanation: FullAdder - Combinational Circuits This notebook walks through the implementation of a basic combinational circuit, a full adder. This example introduces many of the features of Magma including circuits, wiring, operators, and the type system. Start by importing...
8,214
Given the following text description, write Python code to implement the functionality described below step by step Description: Convolutional Autoencoder Sticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. Again, loading modules and the data. Step1: Network Archit...
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) img = mnist.train.images[2] plt.imshow(img.reshape((28, 28)), cmap='Greys_r') Explanati...
8,215
Given the following text description, write Python code to implement the functionality described below step by step Description: Add2 Circuit Now let's build a 2-bit adder using full_adder. We'll use a simple ripple carry adder design by connecting the carry out of one full adder to the carry in of the next full adde...
Python Code: import ast_tools from ast_tools.transformers.loop_unroller import unroll_for_loops from ast_tools.passes import begin_rewrite, end_rewrite, loop_unroll @m.circuit.combinational def full_adder(A: m.Bit, B: m.Bit, C: m.Bit) -> (m.Bit, m.Bit): return A ^ B ^ C, A & B | B & C | C & A # sum, carry @m.circu...
8,216
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Fully-Connected Neural Nets In the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since t...
Python Code: # As usual, a bit of setup from __future__ import print_function import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array fro...
8,217
Given the following text description, write Python code to implement the functionality described below step by step Description: Why the proper Z function fails to show convergence We will here investigate why the function called "properZ" fails to give convergence. Initialize Step1: The function called "proper Z" (a...
Python Code: %matplotlib notebook from IPython.display import display from sympy import init_printing from sympy import S, Eq, Limit from sympy import sin, cos, tanh, pi from sympy import symbols from boutdata.mms import x, z init_printing() Explanation: Why the proper Z function fails to show convergence We will here ...
8,218
Given the following text description, write Python code to implement the functionality described below step by step Description: Removing Duplicates from a Sequence while Maintaining Order Problem You want to eliminate the duplicate values in a sequence, but preserve the order of the remaining items. Solution If the v...
Python Code: def dedupe(items): seen = set() for item in items: if item not in seen: yield item seen.add(item) a = [1, 5, 2, 1, 9, 1, 5, 10] list(dedupe(a)) Explanation: Removing Duplicates from a Sequence while Maintaining Order Problem You want to eliminate the duplicate valu...
8,219
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploring data Names of group members // Put your names here! Goals of this assignment The purpose of this assignment is to explore data using visualization and statistics. Section 1 The f...
Python Code: # put your code here, and add additional cells as necessary. Explanation: Exploring data Names of group members // Put your names here! Goals of this assignment The purpose of this assignment is to explore data using visualization and statistics. Section 1 The file datafile_1.csv contains a three-dimensi...
8,220
Given the following text description, write Python code to implement the functionality described below step by step Description: Cheatsheet for Decision Tree Classification Algorithm Start at the root node as parent node Split the parent node at the feature a to minimize the sum of the child node impurities (maximize ...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline def entropy(p): return - p*np.log2(p) - (1 - p)*np.log2((1 - p)) x = np.arange(0.0, 1.0, 0.01) ent = [entropy(p) if p != 0 else None for p in x] plt.plot(x, ent) plt.ylim([0,1.1]) plt.xlabel('p(i=1)') plt.axhline(y=1.0, linewidth=1, ...
8,221
Given the following text description, write Python code to implement the functionality described below step by step Description: Learning to tokenize in Vision Transformers Authors Step1: Hyperparameters Please feel free to change the hyperparameters and check your results. The best way to develop intuition about the...
Python Code: import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import tensorflow_addons as tfa from datetime import datetime import matplotlib.pyplot as plt import numpy as np import math Explanation: Learning to tokenize in Vision Transformers Authors: Aritra Roy Gosthipaty, Saya...
8,222
Given the following text description, write Python code to implement the functionality described below step by step Description: In the last chapter, our tests failed. This time we'll go about fixing them. Our First Django App, and Our First Unit Test Django encourages you to structure your code into apps Step1: Unit...
Python Code: #%cd ../examples/superlists/ # Make a new app called lists #!python3 manage.py startapp lists !tree . Explanation: In the last chapter, our tests failed. This time we'll go about fixing them. Our First Django App, and Our First Unit Test Django encourages you to structure your code into apps: the theory is...
8,223
Given the following text description, write Python code to implement the functionality described below step by step Description: Sveučilište u Zagrebu<br> Fakultet elektrotehnike i računarstva Strojno učenje <a href="http Step1: Sadržaj Step2: Linearno zavisne varijable imaju $\rho$ blizu $1$ ili $-1$. Međutim, neli...
Python Code: import scipy as sp import scipy.stats as stats import matplotlib.pyplot as plt from numpy.random import normal %pylab inline Explanation: Sveučilište u Zagrebu<br> Fakultet elektrotehnike i računarstva Strojno učenje <a href="http://www.fer.unizg.hr/predmet/su">http://www.fer.unizg.hr/predmet/su</a> Ak. go...
8,224
Given the following text description, write Python code to implement the functionality described below step by step Description: Apply logistic regression to categorize whether a county had high mortality rate due to contamination 1. Import the necessary packages to read in the data, plot, and create a logistic regres...
Python Code: import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import numpy as np from sklearn.linear_model import LogisticRegression Explanation: Apply logistic regression to categorize whether a county had high mortality rate due to contamination 1. Import the necessary packages to read in the da...
8,225
Given the following text description, write Python code to implement the functionality described below step by step Description: 선형 회귀 분석의 기초 결정론적 모형은 그냥 함수를 찾는 것. 간단한 함수부터 시작을 한다. 간단한 함수는 선형식을 의미하는 듯 선형 회귀 분석은 부호, 크기, 관계 등을 알려주기 때문에 불안전하다는 단점에도 불구하고 잘 쓰이고 있다. 비선형회귀분석의 문제점으로는 overfitting 현상이 발생한다는 점. 그리고 방법도 너무 많다는 점 ...
Python Code: from sklearn.datasets import make_regression bias = 100 X0, y, coef = make_regression(n_samples=100, n_features=1, bias=bias, noise=10, coef=True, random_state=1) X = np.hstack([np.ones_like(X0), X0]) X[:5] Explanation: 선형 회귀 분석의 기초 결정론적 모형은 그냥 함수를 찾는 것. 간단한 함수부터 시작을 한다. 간단한 함수는 선형식을 의미하는 듯 선형 회귀 분석은 부호, 크...
8,226
Given the following text description, write Python code to implement the functionality described below step by step Description: STEM Introduction This notebook demonstrates how to do a basic STEM simulation using PyQSTEM with ASE. Step1: We create an orthorhombic unit cell of MoS2. The unit cell is repeated 3x3 time...
Python Code: from __future__ import print_function %matplotlib inline import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib as mpl from ase.io import read from pyqstem.util import atoms_plot from pyqstem import PyQSTEM from ase.build import mx2 mpl....
8,227
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Regression Step2: The Auto MPG dataset The dataset is available from the UCI Machine Learning Repository. Get the data First download the data...
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...
8,228
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 s=[] i=0 def find_peaks(a): Find the indices of the local maxima in a sequence. # YOUR CODE HERE if a[0]>a[1]: #if the first number is b...
8,229
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Toplevel MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specif...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nerc', 'sandbox-1', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: NERC Source ID: SANDBOX-1 Sub-Topics: Radiative Forcings. Properties: ...
8,230
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'noaa-gfdl', 'gfdl-cm4', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: NOAA-GFDL Source ID: GFDL-CM4 Topic: Ocean Sub-Topics: Timestepping Frame...
8,231
Given the following text description, write Python code to implement the functionality described below step by step Description: A Decision Tree of Observable Operators Part 1 Step1: ..that was returned from a function called at subscribe-time Step2: ..that was returned from an Action, Callable, Runnable, or somethi...
Python Code: reset_start_time(O.just) stream = O.just({'answer': rand()}) disposable = subs(stream) sleep(0.5) disposable = subs(stream) # same answer # all stream ops work, its a real stream: disposable = subs(stream.map(lambda x: x.get('answer', 0) * 2)) Explanation: A Decision Tree of Observable Operators Part 1: NE...
8,232
Given the following text description, write Python code to implement the functionality described below step by step Description: Autoregressive Moving Average (ARMA) Step1: Generate some data from an ARMA process Step2: The conventions of the arma_generate function require that we specify a 1 for the zero-lag of the...
Python Code: %matplotlib inline from __future__ import print_function import numpy as np import statsmodels.api as sm import pandas as pd from statsmodels.tsa.arima_process import arma_generate_sample np.random.seed(12345) Explanation: Autoregressive Moving Average (ARMA): Artificial data End of explanation arparams = ...
8,233
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic Relative Permeability Example in 2D This example using invasion percolation to invade air (non-wetting) into a water-filled (wetting) 2D network. Being in 2D helps with visualization ...
Python Code: import warnings import scipy as sp import numpy as np import openpnm as op import matplotlib.pyplot as plt np.set_printoptions(precision=4) np.random.seed(10) %matplotlib inline ws = op.Workspace() ws.settings["loglevel"] = 40 Explanation: Basic Relative Permeability Example in 2D This example using invasi...
8,234
Given the following text description, write Python code to implement the functionality described below step by step Description: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 5</font> Download Step1: Objetos Em Python, tudo é objeto!
Python Code: # Versão da Linguagem Python from platform import python_version print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version()) Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 5</font> Download: http://github.com/dsacademybr End of explanation # Cri...
8,235
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading the data Step1: Build clustering model Here we build a kmeans model , and select the "optimal" of clusters. Here we see that the optimal number of clusters is 2. Step2: Build the o...
Python Code: #contributions = pd.read_json(path_or_buf='../data/EGALITE4.brut.json', orient="columns") def loadContributions(file, withsexe=False): contributions = pd.read_json(path_or_buf=file, orient="columns") rows = []; rindex = []; for i in range(0, contributions.shape[0]): row = {}; ...
8,236
Given the following text description, write Python code to implement the functionality described below step by step Description: What is Pandas? One of the best options for working with tabular data in Python is to use the Python Data Analysis Library (a.k.a. Pandas). The Pandas library provides data structures, produ...
Python Code: #Import the package import pandas as pd Explanation: What is Pandas? One of the best options for working with tabular data in Python is to use the Python Data Analysis Library (a.k.a. Pandas). The Pandas library provides data structures, produces high quality plots with matplotlib and integrates nicely wit...
8,237
Given the following text description, write Python code to implement the functionality described below step by step Description: Option chains Step1: Suppose we want to find the options on the SPX, with the following conditions Step2: To avoid issues with market data permissions, we'll use delayed data Step3: Then ...
Python Code: from ib_insync import * util.startLoop() ib = IB() ib.connect('127.0.0.1', 7497, clientId=12) Explanation: Option chains End of explanation spx = Index('SPX', 'CBOE') ib.qualifyContracts(spx) Explanation: Suppose we want to find the options on the SPX, with the following conditions: Use the next three mont...
8,238
Given the following text description, write Python code to implement the functionality described below step by step Description: HIV Methylation Age Advancement Step1: Looking at Predicted Time of Onset The idea of age acceleration, only really makes sense in this context as a person should age normally until the ons...
Python Code: import NotebookImport from IPython.display import clear_output from HIV_Age_Advancement import * from Setup.DX_Imports import * import statsmodels.api as sm import seaborn as sns sns.set_context("paper", font_scale=1.7, rc={"lines.linewidth": 2.5}) sns.set_style("white") Explanation: HIV Methylation Age Ad...
8,239
Given the following text description, write Python code to implement the functionality described below step by step Description: What is a Jupyter Notebook? From the Jupyter website (http Step1: Text can be entered into cells by designating it for markdown, allowing simple formatting. It is also possible to enter Lat...
Python Code: # code goes into these boxes ("cells") # cells are executed consecutively, with the output printed immediately beneath the cell print("Welcome to SMARTFest 2018!") Explanation: What is a Jupyter Notebook? From the Jupyter website (http://jupyter.org): The Jupyter Notebook is an open-source web application ...
8,240
Given the following text description, write Python code to implement the functionality described below step by step Description: Illustrates numpy vs einsum In deep learning, we perform a lot of tensor operations. einsum simplifies and unifies the APIs for these operations. einsum can be found in numerical computation...
Python Code: import numpy as np from numpy import einsum w = np.arange(6).reshape(2,3).astype(np.float32) x = np.ones((3,1), dtype=np.float32) print("w:\n", w) print("x:\n", x) y = np.matmul(w, x) print("y:\n", y) y = einsum('ij,jk->ik', torch.from_numpy(w), torch.from_numpy(x)) print("y:\n", y) Explanation: Illustrate...
8,241
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) Explanation: Language Translation In this project, you’re going ...
8,242
Given the following text description, write Python code to implement the functionality described below step by step Description: Neural Network <img style="float Step1: Initialize Weights Let's start looking at some initial weights. All Zeros or Ones If you follow the principle of Occam's razor, you might think setti...
Python Code: # Save the shapes of weights for each layer layer_1_weight_shape = (mnist.train.images.shape[1], 256) layer_2_weight_shape = (256, 128) layer_3_weight_shape = (128, mnist.train.labels.shape[1]) Explanation: Neural Network <img style="float: left" src="images/neural_network.png"/> For the neural network, we...
8,243
Given the following text description, write Python code to implement the functionality described below step by step Description: iching is a packge developed by Cheng-Jun Wang. It employs the method of Shicao prediction to reproce the prediction of I Ching--the Book of Exchanges. The I Ching ([î tɕíŋ]; Chinese Step1...
Python Code: from iching import iching from datetime import date today = date.today() today = str(today).replace('-', '') birthtoday = int('19850526' + today) iching.ichingDate(birthtoday) fixPred, changePred = iching.getPredict() print iching.ichingName(fixPred, changePred ), iching.ichingText(fixPred, iching) ich...
8,244
Given the following text description, write Python code to implement the functionality described below step by step Description: 2.0 - Evaluate RnR Performance Simple example which will Step1: Set RnR Cluster ID Refer to the sample notebook 1.0 - Create RnR Cluster & Train Ranker for help setting up a cluster. Step2:...
Python Code: import sys from os import path, getcwd import json from tempfile import mkdtemp import glob sys.path.extend([path.abspath(path.join(getcwd(), path.pardir))]) from rnr_debug_helpers.utils.rnr_wrappers import RetrieveAndRankProxy, \ RankerProxy from rnr_debug_helpers.utils.io_helpers import load_config, ...
8,245
Given the following text description, write Python code to implement the functionality described below step by step Description: This shows how to have some data and update priors form posterious as we get more data NOTE this requires Pymc3 3.1 Updating priors In this notebook, I will show how it is possible to update...
Python Code: # pymc3.distributions.DensityDist? import matplotlib.pyplot as plt import matplotlib as mpl from pymc3 import Model, Normal, Slice from pymc3 import sample from pymc3 import traceplot from pymc3.distributions import Interpolated from theano import as_op import theano.tensor as tt import numpy as np from sc...
8,246
Given the following text description, write Python code to implement the functionality described below step by step Description: Logistic Regression with a Neural Network mindset Welcome to your first (required) programming assignment! You will build a logistic regression classifier to recognize cats. This assignment...
Python Code: import numpy as np import matplotlib.pyplot as plt import h5py import scipy from PIL import Image from scipy import ndimage from lr_utils import load_dataset %matplotlib inline Explanation: Logistic Regression with a Neural Network mindset Welcome to your first (required) programming assignment! You will b...
8,247
Given the following text description, write Python code to implement the functionality described below step by step Description: MD Top 15 violations by total revenue (revenue and total) Step1: Areas to explore Failure to secure dc tags --- huge revenue maker Residential Parking beyond permit period Park at Expired M...
Python Code: dc_df = df[(df.rp_plate_state.isin(['MD']))] dc_fines = dc_df.groupby(['violation_code']).fine.sum().reset_index('violation_code') fine_codes_15 = dc_fines.sort_values(by='fine', ascending=False)[:15] top_codes = dc_df[dc_df.violation_code.isin(fine_codes_15.violation_code)] top_violation_by_state = top_co...
8,248
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Analysis Evaluation Author Step1: Process AQS for evaluation Download annual zip file(s) Unzip Use sed, grep, or awk to get spatial/temporal subset Reshape data Missing data should b...
Python Code: # Prepare my slides %pylab inline %cd working Explanation: Python Analysis Evaluation Author: Barron H. Henderson End of explanation !pncaqsraw4pnceval.py --help Explanation: Process AQS for evaluation Download annual zip file(s) Unzip Use sed, grep, or awk to get spatial/temporal subset Reshape data Missi...
8,249
Given the following text description, write Python code to implement the functionality described below step by step Description: Catalog Step1: Setup OpenCGA Variables Once we have defined a variable with the client configuration and credentials, we can access to all the methods defined for the client. These methods ...
Python Code: ## Step 1. Import pyopencga dependecies from pyopencga.opencga_config import ClientConfiguration # import configuration module from pyopencga.opencga_client import OpencgaClient # import client module from pprint import pprint from IPython.display import JSON import matplotlib.pyplot as plt import seaborn ...
8,250
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmos MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'inpe', 'sandbox-1', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: INPE Source ID: SANDBOX-1 Topic: Atmos Sub-Topics: Dynamical Core, Radiation,...
8,251
Given the following text description, write Python code to implement the functionality described below step by step Description: Video Codec Unit (VCU) Demo Example Step1: Run the Demo Step2: Insert input file path and host IP Step3: Output Format Step4: Advanced options
Python Code: from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value...
8,252
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Running TFLite models <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Create a basic model ...
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...
8,253
Given the following text description, write Python code to implement the functionality described below step by step Description: Blind Source Separation with the Shogun Machine Learning Toolbox By Kevin Hughes This notebook illustrates <a href="http Step1: Next we're going to need a way to play the audio files we're ...
Python Code: import numpy as np import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') from scipy.io import wavfile from scipy.signal import resample def load_wav(filename,samplerate=44100): # load file rate, data = wavfile.read(filename) # convert stereo to mono if len(data.shape)...
8,254
Given the following text description, write Python code to implement the functionality described below step by step Description: <small><i>This notebook was prepared by mrb00l34n. Source and license info is on GitHub.</i></small> Challenge Notebook Problem Step1: Unit Test The following unit test is expected to fail ...
Python Code: def change_ways(n, coins): # TODO: Implement me return n Explanation: <small><i>This notebook was prepared by mrb00l34n. Source and license info is on GitHub.</i></small> Challenge Notebook Problem: Counting Ways of Making Change Explanation Test Cases Algorithm Code Unit Test Solution Notebook Exp...
8,255
Given the following text description, write Python code to implement the functionality described below step by step Description: Tarea 1 Step1: Ejercicio1 Escribe los metodos repr y str para la clase Array de forma que se imprima legiblemente como en numpy arrays. Step2: Ejercicio2 Escribe el metodo setitem para que...
Python Code: class Array: "Una clase minima para algebra lineal" def __init__(self, list_of_rows): "Constructor y validador" # obtener dimensiones self.data = list_of_rows nrow = len(list_of_rows) # ___caso vector: redimensionar correctamente if not...
8,256
Given the following text description, write Python code to implement the functionality described below step by step Description: Building your Deep Neural Network Step2: 2 - Outline of the Assignment To build your neural network, you will be implementing several "helper functions". These helper functions will be used...
Python Code: import numpy as np import h5py import matplotlib.pyplot as plt from testCases import * from dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams...
8,257
Given the following text description, write Python code to implement the functionality described below step by step Description: The Forward Euler method for first order differential equations $$$$ The Euler method (also called forward Euler method) is a first-order numerical procedure for solving ordinary differentia...
Python Code: import math Explanation: The Forward Euler method for first order differential equations $$$$ The Euler method (also called forward Euler method) is a first-order numerical procedure for solving ordinary differential equations (ODEs) with a given initial value. End of explanation def forward_euler(f, x0, y...
8,258
Given the following text description, write Python code to implement the functionality described below step by step Description: These are the URLs for the JSON data powering the ESRI/ArcGIS maps. Step1: We need a way to easily extract the actual data points from the JSON. The data will actually contain multiple laye...
Python Code: few_crashes_url = 'http://www.arcgis.com/sharing/rest/content/items/5a8841f92e4a42999c73e9a07aca0c23/data?f=json&token=lddNjwpwjOibZcyrhJiogNmyjIZmzh-pulx7jPD9c559e05tWo6Qr8eTcP7Deqw_CIDPwZasbNOCSBHfthynf-8WRMmguxHbIFptbZQvnpRupJHSY8Abrz__xUteBS93MitgvoU6AqSN5eDVKRYiUg..' removed_url = 'http://www.arcgis.c...
8,259
Given the following text description, write Python code to implement the functionality described below step by step Description: Tables to Networks, Networks to Tables Networks can be represented in a tabular form in two ways Step1: At this point, we have our stations and trips data loaded into memory. How we constr...
Python Code: import zipfile # This block of code checks to make sure that a particular directory is present. if "divvy_2013" not in os.listdir('datasets/'): print('Unzipping the divvy_2013.zip file in the datasets folder.') with zipfile.ZipFile("datasets/divvy_2013.zip","r") as zip_ref: zip_ref.extracta...
8,260
Given the following text description, write Python code to implement the functionality described below step by step Description: Performance optimization overview The purpose of this tutorial is twofold Illustrate the performance optimizations applied to the code generated by an Operator. Describe the options Devito p...
Python Code: from examples.performance import unidiff_output, print_kernel Explanation: Performance optimization overview The purpose of this tutorial is twofold Illustrate the performance optimizations applied to the code generated by an Operator. Describe the options Devito provides to users to steer the optimization...
8,261
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook is meant to test the functions written in python to analyze AFiNES simulation output. It's going to be messy, but so it goes... Step1: First a test of the readData function th...
Python Code: import os import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl %matplotlib notebook import pandas as pd import h5py import afinesanalysis.afinesanalysis as aa Explanation: This notebook is meant to test the functions written in python to analyze AFiNES simulation output. It's going t...
8,262
Given the following text description, write Python code to implement the functionality described below step by step Description: ```python R = 40. H = 60 x_w = 0. y_w = 60. f = lambda x,y Step1: Monte-Carlo integration Step2: Cartessian Gausss-Legendre quadrature Step3: integrating before in y Step5: Radial Gauss-...
Python Code: R = 40. H = 60 x_w = 30. y_w = 90. Rw = 20 seed = 1 def f(x,y): np.random.seed(seed) return - 3.*np.exp( -((x-x_w)**2. + (y-y_w)**2.)/(Rw**2.) ) + \ - 3.*np.exp( -((x-30)**2. + (y-40)**2.)/(20**2.) ) + \ - 1.5*np.exp( -((x-np.random.uniform(-60,60))**2. + (y-np.random.uniform(...
8,263
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: SVM Hyperparameter Tuning - Using GridSearchCV to Tune a SVC Model
Python Code:: from sklearn.svm import SVC from sklearn.metrics import classification_report from sklearn.model_selection import GridSearchCV # declare parameter ranges to try params = {'C':[1, 2, 3], 'kernel':['linear', 'poly', 'rbf']} # initialise estimator svm_classifier = SVC(class_weight='balanced') # ini...
8,264
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">Theanets</h1> <h4 align="center">Korepanova Natalia</h4> <h5 align="center">Moscow, 2015</h5> The theanets is a deep learning and neural network toolkit. Written in Python...
Python Code: import theanets # 1. create a model -- here, a regression model. net = theanets.Regressor([10, 100, 2]) # optional: set up additional losses. net.add_loss('mae', weight=0.1) # 2. train the model. net.train( training_data, validation_data, algo='rmsprop', hidden_l1=0.01, # apply a regulariz...
8,265
Given the following text description, write Python code to implement the functionality described below step by step Description: Fetch the data from NewsroomDB NewsroomDB is the Tribune's proprietary database for tracking data that needs to be manually entered and validated rather than something that can be ingested f...
Python Code: import os import requests # A big object to hold all our data between steps data = {} def get_table_url(table_name, base_url=os.environ['NEWSROOMDB_URL']): return '{}table/json/{}'.format(os.environ['NEWSROOMDB_URL'], table_name) def get_table_data(table_name): url = get_table_url(table_name) ...
8,266
Given the following text description, write Python code to implement the functionality described below step by step Description: INDIA, G-20 AND THE WORLD - Statistical Year Book India 2016 Navigation Path Step1: Data Cleanup Step2: Experiments Step3: Ideas Show top 5 countries Show only comparable countries Step4...
Python Code: %%sh # ls -l ~/Downloads/G20*csv # mv ~/Downloads/G20*csv G20.csv Explanation: INDIA, G-20 AND THE WORLD - Statistical Year Book India 2016 Navigation Path: Home > Statistical Year Book India 2016 > INDIA, G-20 AND THE WORLD The G20 (or G-20 or Group of Twenty) is an international forum for the governmen...
8,267
Given the following text description, write Python code to implement the functionality described below step by step Description: Retrain a CNN, part 2.2, using bottleneck features https Step1: This script goes along the blog post "Building powerful image classification models using very little data" from blog.keras.i...
Python Code: import warnings warnings.filterwarnings('ignore') %matplotlib inline %pylab inline import matplotlib.pylab as plt import numpy as np from distutils.version import StrictVersion import sklearn print(sklearn.__version__) assert StrictVersion(sklearn.__version__ ) >= StrictVersion('0.18.1') import tensorflow ...
8,268
Given the following text description, write Python code to implement the functionality described below step by step Description: Bins Mark This Mark is essentially the same as the Hist Mark from a user point of view, but is actually a Bars instance that bins sample data. The difference with Hist is that the binning is...
Python Code: # Create a sample of Gaussian draws np.random.seed(0) x_data = np.random.randn(1000) Explanation: Bins Mark This Mark is essentially the same as the Hist Mark from a user point of view, but is actually a Bars instance that bins sample data. The difference with Hist is that the binning is done in the backen...
8,269
Given the following text description, write Python code to implement the functionality described below step by step Description: The Alien Blaster problem This notebook presents solutions to exercises in Think Bayes. Copyright 2016 Allen B. Downey MIT License Step1: Part One In preparation for an alien invasion, the ...
Python Code: from __future__ import print_function, division % matplotlib inline import warnings warnings.filterwarnings('ignore') import numpy as np from thinkbayes2 import Hist, Pmf, Cdf, Suite, Beta import thinkplot Explanation: The Alien Blaster problem This notebook presents solutions to exercises in Think Bayes. ...
8,270
Given the following text description, write Python code to implement the functionality described below step by step Description: Variational Autoencoder Tutorial in TensorFlow David Zoltowski The tutorial is organized in the following manner Step1: When defining the model we will define many sets of weight and bias p...
Python Code: import numpy as np import tensorflow as tf # import MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) Explanation: Variational Autoencoder Tutorial in TensorFlow David Zoltowski The tutorial is organized in the following man...
8,271
Given the following text description, write Python code to implement the functionality described below step by step Description: <div style="width Step1: Try reading extracted data with Xarray Step2: Try plotting the LambertConformal data with Cartopy
Python Code: import matplotlib.pyplot as plt import numpy as np %matplotlib inline # Resolve the latest HRRR dataset from siphon.catalog import get_latest_access_url hrrr_catalog = "http://thredds.ucar.edu/thredds/catalog/grib/NCEP/HRRR/CONUS_2p5km/catalog.xml" latest_hrrr_ncss = get_latest_access_url(hrrr_catalog, "Ne...
8,272
Given the following text description, write Python code to implement the functionality described below step by step Description: Variable Names Before moving on, let's say a few things about variable names. If you want to name some object in Python you have to abide by a few 'concrete' rules Step1: In addition to the...
Python Code: print = 10.20 # Rule 1: "print" is a reserved word in Python and therefore we cannot use it. 0sales = 10.20 # Rule 2: cannot start a name with a number. this has spaces = 10.20 # Rule 2: space character is punctation. thisnamehasa+init = 10.20 # Rule 3: Fails because "+" is a s...
8,273
Given the following text description, write Python code to implement the functionality described below step by step Description: Лабораторные работы DES DES - блочный алгоритм для симметричного шифрования. - Работает на блоках данных по 64 бита - Размер ключа - 64 бита (56 бит + 8 проверочных (parity bits)) ...
Python Code: import bitarray import itertools from collections import deque class DES(object): _initial_permutation = [ 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, ...
8,274
Given the following text description, write Python code to implement the functionality described below step by step Description: SVHN Preprocessing This notebook implements SVHN pre-processing. The key steps are Step1: The following code reads the images and crops according to the steps above. Then it encodes the lab...
Python Code: import scipy.ndimage as img import scipy.misc as misc import h5py import numpy as np import matplotlib.pyplot as plt import random as rnd import os import sklearn.preprocessing as skproc from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import scale import DigitStructFile import cP...
8,275
Given the following text description, write Python code to implement the functionality described below step by step Description: Multi-task recommenders Learning Objectives 1. Training a model which focuses on ratings. 2. Training a model which focuses on retrieval. 3. Training a joint model that assigns positiv...
Python Code: # Installing the necessary libraries. !pip install -q tensorflow-recommenders !pip install -q --upgrade tensorflow-datasets Explanation: Multi-task recommenders Learning Objectives 1. Training a model which focuses on ratings. 2. Training a model which focuses on retrieval. 3. Training a joint model ...
8,276
Given the following text description, write Python code to implement the functionality described below step by step Description: Red bipartita de usuarios y palabras Autor Step2: Número de nodos y enlaces Código para leer el archivo de texto con la red y a partir del mismo obtener un arreglo con los enlaces y sus res...
Python Code: # Librerías necesarias para correr el proyecto import networkx as nx from networkx.algorithms import bipartite import matplotlib.pyplot as plt import seaborn as sns import numpy as np import operator import community from scipy.stats import powerlaw %matplotlib inline sns.set() Explanation: Red bipartita d...
8,277
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmos MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'bcc', 'bcc-esm1', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: BCC Source ID: BCC-ESM1 Topic: Atmos Sub-Topics: Dynamical Core, Radiation, Tur...
8,278
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute site visits This notebook computes the number of visits at each sample site from an excel file exported from an online database (arcgis online) of site visits. Required pacakges <a h...
Python Code: excel_filepath = "" csv_output_filepath = "" Explanation: Compute site visits This notebook computes the number of visits at each sample site from an excel file exported from an online database (arcgis online) of site visits. Required pacakges <a href="https://github.com/pydata/pandas">pandas</a> Variable ...
8,279
Given the following text description, write Python code to implement the functionality described below step by step Description: MNIST in Keras with Tensorboard This sample trains an "MNIST" handwritten digit recognition model on a GPU or TPU backend using a Keras model. Data are handled using the tf.data.Datset API....
Python Code: BATCH_SIZE = 64 LEARNING_RATE = 0.002 # GCS bucket for training logs and for saving the trained model # You can leave this empty for local saving, unless you are using a TPU. # TPUs do not have access to your local instance and can only write to GCS. BUCKET="" # a valid bucket name must start with gs:// tr...
8,280
Given the following text description, write Python code to implement the functionality described below step by step Description: 01 - Raw Scraping What we do here is the scraping of the Swiss Parliament website from the hierarchy described in the metadata we were given. We were able to create a typical URL from which ...
Python Code: from bs4 import BeautifulSoup import urllib.request import pandas as pd import html5lib from lxml import * import numpy as np import xmljson from xmljson import badgerfish as bf from json import * import xml.etree.ElementTree as ET from io import StringIO import webbrowser import requests import os as os...
8,281
Given the following text description, write Python code to implement the functionality described below step by step Description: Save this file as studentid1_studentid2_lab#.ipynb (Your student-id is the number shown on your student card.) E.g. if you work with 3 people, the notebook should be named Step1: Lab 3 Step...
Python Code: NAME = "Michelle Appel" NAME2 = "Verna Dankers" NAME3 = "Yves van Montfort" EMAIL = "michelle.appel@student.uva.nl" EMAIL2 = "verna.dankers@student.uva.nl" EMAIL3 = "yves.vanmontfort@student.uva.nl" Explanation: Save this file as studentid1_studentid2_lab#.ipynb (Your student-id is the number shown on your...
8,282
Given the following text description, write Python code to implement the functionality described below step by step Description: In this Notebook Gaussian Naive Bayes is used on wisconsin cancer dataset to classify if it is Malignant or Benign In the following pandas is used for showing our dataset. We are going to do...
Python Code: import pandas as pd df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data', header=None) Explanation: In this Notebook Gaussian Naive Bayes is used on wisconsin cancer dataset to classify if it is Malignant or Benign In the following pandas is used fo...
8,283
Given the following text description, write Python code to implement the functionality described below step by step Description: <div class="alert alert-block alert-info" style="margin-top Step1: <a id="ref0"></a> <h2 align=center>Get Some Data </h2> Create polynomial dataset objects Step2: Create a dataset object S...
Python Code: import torch import matplotlib.pyplot as plt import torch.nn as nn import numpy as np Explanation: <div class="alert alert-block alert-info" style="margin-top: 20px"> <a href="http://cocl.us/pytorch_link_top"><img src = "http://cocl.us/Pytorch_top" width = 950, align = "center"></a> <img src = "https://ib...
8,284
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have the following dataframe:
Problem: import pandas as pd df = pd.DataFrame({'key1': ['a', 'a', 'b', 'b', 'a', 'c'], 'key2': ['one', 'two', 'one', 'two', 'one', 'two']}) def g(df): return df.groupby('key1')['key2'].apply(lambda x: (x=='one').sum()).reset_index(name='count') result = g(df.copy())
8,285
Given the following text description, write Python code to implement the functionality described below step by step Description: Let's read the data Step1: Let's check what's inside these files... Step2: Only proper rows with posts Step3: Let's parse this mess... Step4: Better Step5: Let's compute tag counts! Ste...
Python Code: ! gsutil ls gs://pyspark-workshop/so-posts lines = sc.textFile("gs://pyspark-workshop/so-posts/*") # or a smaller piece of them lines = sc.textFile("gs://pyspark-workshop/so-posts/Posts.xml-*a") Explanation: Let's read the data End of explanation lines.take(5) Explanation: Let's check what's inside these f...
8,286
Given the following text description, write Python code to implement the functionality described below step by step Description: Task In this assignment, you will implement simple algorithmic trading policies and modify a very simple backtester. In the following, you will find a Backtester1 function that gets as an in...
Python Code: import pandas as pd import pandas.io.data as web import numpy as np import datetime msft = pd.read_csv("msft.csv", index_col=0, parse_dates=True) aapl = pd.read_csv("aapl.csv", index_col=0, parse_dates=True) msft['2012-01'] Explanation: Task In this assignment, you will implement simple algorithmic trading...
8,287
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Land MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify do...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'miroc', 'nicam16-7s', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: MIROC Source ID: NICAM16-7S Topic: Land Sub-Topics: Soil, Snow, Vegetation, E...
8,288
Given the following text description, write Python code to implement the functionality described below step by step Description: Authorization Following the Nest authorization documentation. Setup Get the values of Client ID and Client secret from the clients page and set them in the environment before running this IP...
Python Code: import os DEN_CLIENT_ID = os.environ["DEN_CLIENT_ID"] DEN_CLIENT_SECRET = os.environ["DEN_CLIENT_SECRET"] Explanation: Authorization Following the Nest authorization documentation. Setup Get the values of Client ID and Client secret from the clients page and set them in the environment before running this ...
8,289
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling and Simulation in Python Chapter 10 Example Step1: Pendulum This notebook solves the Spider-Man problem from spiderman.ipynb, demonstrating a different development process for phys...
Python Code: # If you want the figures to appear in the notebook, # and you want to interact with them, use # %matplotlib notebook # If you want the figures to appear in the notebook, # and you don't want to interact with them, use # %matplotlib inline # If you want the figures to appear in separate windows, use # %m...
8,290
Given the following text description, write Python code to implement the functionality described below step by step Description: author Step1: QC-filtered samples Step2: Per-study endemism Objective Step3: Per-sample endemism Step4: Abundance vs. prevalence Step5: Subset 2k
Python Code: import pandas as pd import numpy as np import locale import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline locale.setlocale(locale.LC_ALL, 'en_US') def list_otu_studies(df, index): return(set([x.split('.')[0] for x in df.loc[index]['list_samples'].split(',')])) locale.format("%d", 12...
8,291
Given the following text description, write Python code to implement the functionality described below step by step Description: Project (Option 2) - PageRank Authors Step3: Simulation time! We now want to empirically test what we solved above by modeling a random user hopping along those webpages. We will start the...
Python Code: import numpy as np from __future__ import division P = np.matrix([[0, 1/5, 1/5, 1/5, 1/5, 0, 0, 1/5], [1/2, 0, 0, 0, 1/2, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 1/3, 1/3, 1/3, 0, 0, 0, 0], [1/4,0,1/4,0,0,0...
8,292
Given the following text description, write Python code to implement the functionality described below step by step Description: Example to demonstrate optimized backdoor variable search for Causal Identification This notebook compares the performance between causal identification using vanilla backdoor search and the...
Python Code: import time import random from networkx.linalg.graphmatrix import adjacency_matrix import numpy as np import pandas as pd import networkx as nx import dowhy from dowhy import CausalModel from dowhy.utils import graph_operations import dowhy.datasets Explanation: Example to demonstrate optimized backdoor va...
8,293
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualising statistical significance thresholds on EEG data MNE-Python provides a range of tools for statistical hypothesis testing and the visualisation of the results. Here, we show a few ...
Python Code: import numpy as np import matplotlib.pyplot as plt from scipy.stats import ttest_ind import mne from mne.channels import find_ch_connectivity, make_1020_channel_selections from mne.stats import spatio_temporal_cluster_test np.random.seed(0) # Load the data path = mne.datasets.kiloword.data_path() + '/kword...
8,294
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="images/logo.jpg" style="display Step1: <p style="text-align Step2: <p style="text-align Step3: <p style="text-align Step4: <p style="text-align Step5: <p style="text-align Ste...
Python Code: prime_ministers = ['David Ben-Gurion', 'Moshe Sharett', 'David Ben-Gurion', 'Levi Eshkol', 'Yigal Alon', 'Golda Meir'] Explanation: <img src="images/logo.jpg" style="display: block; margin-left: auto; margin-right: auto;" alt="לוגו של מיזם לימוד הפייתון. נחש מצויר בצבעי צהוב וכחול, הנע בין האותיות של שם הק...
8,295
Given the following text description, write Python code to implement the functionality described below step by step Description: 11. タブをスペースに置換 タブ1文字につきスペース1文字に置換せよ.確認にはsedコマンド,trコマンド,もしくはexpandコマンドを用いよ. Step1: 12. 1列目をcol1.txtに,2列目をcol2.txtに保存 各行の1列目だけを抜き出したものをcol1.txtに, 2列目だけを抜き出したものをcol2.txtとしてファイルに保存せよ. 確認にはcutコマ...
Python Code: hightemp = "".join(map(str, [i.replace('\t', ' ') for i in open('hightemp.txt', 'r')])) print(hightemp) Explanation: 11. タブをスペースに置換 タブ1文字につきスペース1文字に置換せよ.確認にはsedコマンド,trコマンド,もしくはexpandコマンドを用いよ. End of explanation col1 = open('col1.txt', 'w') col2 = open('col2.txt', 'w') hightemp = [i.replace('\t', ' ').split...
8,296
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: OT for image color adaptation with mapping estimation OT for domain adaptation with image color adaptation [6] with mapping estimation [8]. [6] Ferradans, S., Papadakis, N., Peyre, G....
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 and image to matrix (one pixel per li...
8,297
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting Started Bambi requires a working Python interpreter (3.7+). We recommend installing Python and key numerical libraries using the Anaconda Distribution, which has one-click installers...
Python Code: import arviz as az import bambi as bmb import numpy as np import pandas as pd az.style.use("arviz-darkgrid") Explanation: Getting Started Bambi requires a working Python interpreter (3.7+). We recommend installing Python and key numerical libraries using the Anaconda Distribution, which has one-click insta...
8,298
Given the following text description, write Python code to implement the functionality described below step by step Description: Hello Feature Class example Step1: Getting the test case Test cases can be downloaded to temporary files. This is handled by the radiomics.getTestCase() function, which checks if the reques...
Python Code: from __future__ import print_function import os import collections import SimpleITK as sitk import numpy import six import radiomics from radiomics import firstorder, glcm, imageoperations, shape, glrlm, glszm Explanation: Hello Feature Class example: using the feature classes to calculate features This ex...
8,299
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: perform Image segmentation using encoder-decoder architecture
Python Code:: import tensorflow as tf model = tf.keras.Model() model.add(tf.keras.layers.Input((width, height, channels))) model.add(tf.keras.layers.Lambda(lambda x: x / 255)) model.add(tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')) model.add(tf.keras.layers.Dropo...