Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
6,000
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 2 Lógica proposicional "Poder-se-á definir a Lógica como a ciência das regras que legitimam a utilização da palavra portanto." B. Ruyer in Logique. Proposição No caso das instruções...
Python Code: # # Tabela da Negação # for p in [True,False]: print('not',p,"=", not p) Explanation: Chapter 2 Lógica proposicional "Poder-se-á definir a Lógica como a ciência das regras que legitimam a utilização da palavra portanto." B. Ruyer in Logique. Proposição No caso das instruções if e while, a execução dum...
6,001
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Part 9 Step1: Hyperparameter Optimization Let's start by loading the HIV dataset. It classifies over 40,000 molecules based on whether they inhibit HIV replication. Step2: Now le...
Python Code: !curl -Lo conda_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py import conda_installer conda_installer.install() !/root/miniconda/bin/conda info -e !pip install --pre deepchem import deepchem deepchem.__version__ Explanation: Tutorial Part 9: Advanced Model ...
6,002
Given the following text description, write Python code to implement the functionality described below step by step Description: MNIST end to end on Kubeflow on GKE This example guides you through Step1: Install the required libraries Run the next cell to import the libraries required to train this model. Step2: Wai...
Python Code: import logging import os import uuid from importlib import reload from oauth2client.client import GoogleCredentials credentials = GoogleCredentials.get_application_default() Explanation: MNIST end to end on Kubeflow on GKE This example guides you through: Taking an example TensorFlow model and modifying it...
6,003
Given the following text description, write Python code to implement the functionality described below step by step Description: Compare the Different Corpora Corpora Step1: Compare the fraction of emotional sentences per text For the different corpora. An emotional sentence is a sentence for which at least one HEEM ...
Python Code: # Render our plots inline %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np import os pd.set_option('display.mpl_style', 'default') # Make the graphs a bit prettier plt.rcParams['figure.figsize'] = (16, 6) # adjust to your local directories embem_data_dir = '/home/j...
6,004
Given the following text description, write Python code to implement the functionality described below step by step Description: Feedback k domácím projektům Jde tento kód napsat jednodušeji, aby ale dělal úplně totéž? Step1: Ano, lze Step2: A co tento? Step3: Ten taky Step4: Nejmenší číslo Upovídané řešení z dom...
Python Code: for radek in range(4): radek += 1 for value in range(radek): print('X', end=' ') print('') Explanation: Feedback k domácím projektům Jde tento kód napsat jednodušeji, aby ale dělal úplně totéž? End of explanation for radek in range(1, 5): print('X ' * radek) Explanation: Ano, lze :-) End of exp...
6,005
Given the following text description, write Python code to implement the functionality described below step by step Description: ← Back to Index Sheet Music Representations Music can be represented in many different ways. The printed, visual form of a musical work is called a score or sheet music. For example, he...
Python Code: ipd.SVG("https://upload.wikimedia.org/wikipedia/commons/2/27/MozartExcerptK331.svg") ipd.YouTubeVideo('dP9KWQ8hAYk') Explanation: ← Back to Index Sheet Music Representations Music can be represented in many different ways. The printed, visual form of a musical work is called a score or sheet music. Fo...
6,006
Given the following text description, write Python code to implement the functionality described below step by step Description: SuchLinkedTrees In the last article, we saw how to use SuchTree to probe the topology of very large trees. In this article, we're going to look at the other component of the package, SuchLin...
Python Code: %pylab inline %config InlineBackend.figure_format='retina' from SuchTree import SuchTree, SuchLinkedTrees import seaborn import pandas from scipy.cluster.hierarchy import ClusterWarning from scipy.stats import pearsonr warnings.simplefilter( 'ignore', UserWarning ) Explanation: SuchLinkedTrees In the last ...
6,007
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 class="title">Text Classification and Clustering</h1> <ul> <li>Research Seminar Information Retrieval <li>Humboldt-University Berlin <li>2015-07-01 <li>Stefan Baerisch <ul/> # Gliederung...
Python Code: # Baseline Classifier : Weist jedem Wert die häufigste Klasse zu. from collections import Counter model = Counter() def fit(value, cls): model.update([cls]) def predict(value): return model.most_common(1)[0][0] #Drei Aufrufe von train, fit("Banana","fruit") fit("Apple","fruit") fit("Bean","Vegetab...
6,008
Given the following text description, write Python code to implement the functionality described below step by step Description: Data preprocessing Here will download and subset NCEP reanalysis data, and read in files created from the DesInventar database. Then create a map showing the regions where disaster records a...
Python Code: #--- Libraries import pandas as pd # statistics packages import numpy as np # linear algebra packages import matplotlib.pyplot as plt # plotting routines import seaborn as sns # more plot...
6,009
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 3, Table 3 This notebook explains how I used the Harvard General Inquirer to streamline interpretation of a predictive model. I'm italicizing the word "streamline" because I want to ...
Python Code: # some standard modules import csv, os, sys from collections import Counter import numpy as np from scipy.stats import pearsonr # now a module that I wrote myself, located # a few directories up, in the software # library for this repository sys.path.append('../../lib') import FileCabinet as filecab Explan...
6,010
Given the following text description, write Python code to implement the functionality described below step by step Description: Experience Based on wordnet as ground truth, we tried to learn a classifier to detect antonymics relations between words (small != big / good != bad) To do so we will explore the carthesian ...
Python Code: summaryDf = pd.DataFrame([extractSummaryLine(l) for l in open('../../data/learnedModel/anto/summary.txt').readlines()], columns=['bidirectional', 'strict', 'clf', 'feature', 'post', 'precision', 'recall', 'f1']) summaryDf.sort_values('f1', ascending=False)[:10] Explanation: Experien...
6,011
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <a href='#motivation'>Motivation</a> <a href='#constructor'>Constructing a dataset</a> <a href='#attributes'>Attributes</a> <a href='#access'>Accessing samples</a> <a href=...
Python Code: import sys, os import numpy as np import matplotlib %matplotlib %matplotlib inline import matplotlib.pyplot as plt n = 10 # number of samples p = 3 # number of features X = np.random.random([n, p]) # random data for illustration y = [1]*5 + [2]*5 # random labels ... np.set_printoptions(precisio...
6,012
Given the following text description, write Python code to implement the functionality described below step by step Description: ATM 623 Step1: Contents The observed seasonal cycle from NCEP Reanalysis data Analytical toy model of the seasonal cycle Exploring the amplitude of the seasonal cycle with an EBM The season...
Python Code: # Ensure compatibility with Python 2 and 3 from __future__ import print_function, division Explanation: ATM 623: Climate Modeling Brian E. J. Rose, University at Albany Lecture 19: Modeling the seasonal cycle of surface temperature Warning: content out of date and not maintained You really should be looki...
6,013
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework #1 This notebook contains the first homework for this class, and is due on Friday, October 23rd, 2016 at 11 Step2: Section 3
Python Code: # write any code you need here! # Create additional cells if you need them by using the # 'Insert' menu at the top of the browser window. Explanation: Homework #1 This notebook contains the first homework for this class, and is due on Friday, October 23rd, 2016 at 11:59 p.m.. Please make sure to get st...
6,014
Given the following text description, write Python code to implement the functionality described below step by step Description: Statements Assessment Test Lets test your knowledge! Use for, split(), and if to create a Statement that will print out words that start with 's' Step1: Use range() to print all the even nu...
Python Code: st = 'Print only the words that start with s in this sentence' #Code here st = 'Print only the words that start with s in this sentence' for word in st.split(): if word[0] == 's': print(word ) Explanation: Statements Assessment Test Lets test your knowledge! Use for, split(), and if to create a...
6,015
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploration Exploration of prepocessed DF Step1: Input Privacy restriction Step2: Exploration Step3: Preparation for Modeling Missing Values Step4: DFs for Modeling Step5: Dummie Encodi...
Python Code: import numpy as np import pandas as pd import math import matplotlib.pyplot as plt %matplotlib inline Explanation: Exploration Exploration of prepocessed DF End of explanation file_path = "../data/events_df.pkl" df = pd.read_pickle(file_path) print(df.shape) print(df.dtypes) df.head() Explanation: Input Pr...
6,016
Given the following text description, write Python code to implement the functionality described below step by step Description: Markov chains for finding CpG islands Step5: As training data, we use some already-called CpG islands. These were called in a prior study that used a kind of Hidden Markov Model. Relevant...
Python Code: from __future__ import print_function import random import re import gzip from itertools import islice from operator import itemgetter import numpy as np from future.standard_library import install_aliases install_aliases() from urllib.request import urlopen, urlcleanup, urlretrieve Explanation: Markov cha...
6,017
Given the following text description, write Python code to implement the functionality described below step by step Description: Hour of Code 2015 For Mr. Clifford's Class (5C) Perry Grossman December 2015 Introduction From the Hour of Code to the Power of Co How to use programming skills for data analysis, or "data s...
Python Code: # you can also access this directly: from PIL import Image im = Image.open("DataScienceProcess.jpg") im #path=\'DataScienceProcess.jpg' #image=Image.open(path) Explanation: Hour of Code 2015 For Mr. Clifford's Class (5C) Perry Grossman December 2015 Introduction From the Hour of Code to the Power of Co How...
6,018
Given the following text description, write Python code to implement the functionality described below step by step Description: Facies classification using Convolutional Neural Networks Team StoDIG - Statoil Deep-learning Interest Group David Wade, John Thurmond & Eskil Kulseth Dahl In this python notebook we propos...
Python Code: %%sh pip install pandas pip install scikit-learn pip install keras pip install sklearn from __future__ import print_function import time import numpy as np %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import matplotlib.colors as colors from mpl_toolkits.axes_grid1 import make_axes...
6,019
Given the following text description, write Python code to implement the functionality described. Description: Count number of ways to reach a given score in a game Returns number of ways to reach score n . ; table [ i ] will store count of solutions for value i . Initialize all table values as 0. ; Base case ( If give...
Python Code: def count(n ) : table =[0 for i in range(n + 1 ) ] table[0 ] = 1 for i in range(3 , n + 1 ) : table[i ] += table[i - 3 ]  for i in range(5 , n + 1 ) : table[i ] += table[i - 5 ]  for i in range(10 , n + 1 ) : table[i ] += table[i - 10 ]  return table[n ]  n = 20 print(' Count ...
6,020
Given the following text description, write Python code to implement the functionality described below step by step Description: Description This is a test of SimulatedAnnealing. Basics Step4: Set Parameters State in MetropolisSampler is np.array([float]). The smaller the re_scaling be, the faster it anneals. Step5: ...
Python Code: import sys sys.path.append('../sample/') from simulated_annealing import Temperature, SimulatedAnnealing from random import uniform, gauss import numpy as np import matplotlib.pyplot as plt Explanation: Description This is a test of SimulatedAnnealing. Basics End of explanation def temperature_of_time(t, r...
6,021
Given the following text description, write Python code to implement the functionality described below step by step Description: Nucleosynthetic yields These are key to every chemical evolution model. Chempy supports three nucleosynthetic channels at the moment Step1: Hyper Nova (HN) is only provided for Nomoto 2013 ...
Python Code: %pylab inline from Chempy.parameter import ModelParameters from Chempy.yields import SN2_feedback, AGB_feedback, SN1a_feedback, Hypernova_feedback from Chempy.infall import PRIMORDIAL_INFALL, INFALL # This loads the default parameters, you can check and change them in paramter.py a = ModelParameters() # I...
6,022
Given the following text description, write Python code to implement the functionality described below step by step Description: EAS Testing - Antutu benchmark on Android The goal of this experiment is to run benchmarks on a Hikey running Android with an EAS kernel and collect results. The analysis phase will consist ...
Python Code: import logging reload(logging) log_fmt = '%(asctime)-9s %(levelname)-8s: %(message)s' logging.basicConfig(format=log_fmt) # Change to info once the notebook runs ok logging.getLogger().setLevel(logging.INFO) %pylab inline import copy import os from time import sleep from subprocess import Popen import pand...
6,023
Given the following text description, write Python code to implement the functionality described below step by step Description: Quick Setup Step1: Download Data - MNIST The MNIST dataset contains labeled images of handwritten digits, where each example is a 28x28 pixel image of grayscale values in the range [0,255] ...
Python Code: # Create a SystemML MLContext object from systemml import MLContext, dml ml = MLContext(sc) Explanation: Quick Setup End of explanation %%sh mkdir -p data/mnist/ cd data/mnist/ curl -O https://pjreddie.com/media/files/mnist_train.csv curl -O https://pjreddie.com/media/files/mnist_test.csv Explanation: Down...
6,024
Given the following text description, write Python code to implement the functionality described below step by step Description: Week 5 - Crafting the public interface. Learning Objectives Explain what a public interface is Discuss the advantages of defining a public interface Compare different public interfaces Desig...
Python Code: class Item(object): def __init__(self, name, description, location): self.name = name self.description = description self.location = location def update_location(self, new_location): pass class Equipment(Item): pass class Consumable(It...
6,025
Given the following text description, write Python code to implement the functionality described below step by step Description: Now that we know how to read the data, we will add some processing to generate a gridded field.<br /> In the first part, we will use the loop on the files to store all the data, then in the ...
Python Code: year = 2015 month = 7 %matplotlib inline import glob import os import netCDF4 import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from matplotlib import colors Explanation: Now that we know how to read the data, we will add some processing to generate a gridded fiel...
6,026
Given the following text description, write Python code to implement the functionality described below step by step Description: 파이썬 기본 자료형 1부 파이썬 언어에서 사용되는 값들의 기본 자료형을 살펴본다. 변수에 할당될 수 있는 가장 단순한 자료형에는 네 종류가 있다 Step1: 변수를 선언하고 값을 바로 확인할 수 있다. Step2: 파이썬을 계산기처럼 활용할 수도 있다. Step3: 주의 Step4: 나머지를 계산하는 연산자는 % 이다. Step5...
Python Code: print("Hello World") Explanation: 파이썬 기본 자료형 1부 파이썬 언어에서 사용되는 값들의 기본 자료형을 살펴본다. 변수에 할당될 수 있는 가장 단순한 자료형에는 네 종류가 있다: 정수 자료형(int): ..., -3, -2, -1, 0, 1, 2, 3, 등등 1 + 2, -2 * 3, 등등 부동소수점 자료형(float): 1.2, 0.333333, -1.2, -3.7680, 등등 2.0 \ 3.5, 3.555 + 3.4 * 7.9, 등등 불리언 자료형(bool): True, False를 포함하여 두 값으로 계...
6,027
Given the following text description, write Python code to implement the functionality described below step by step Description: Importing Necessary Modules To discover something new is to explore where it has never been explored. Added Conv Visuals Also (Working) Step1: Loading The Dataset Step2: Normalising The D...
Python Code: import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib.pyplot as plt #for plotting from collections import Counter from sklearn.metrics import confusion_matrix import itertools import seaborn as sns from subprocess import check_output pr...
6,028
Given the following text description, write Python code to implement the functionality described below step by step Description: TabNet Step1: Authenticate your GCP account If you are using AI Platform Notebooks, your environment is already authenticated. Skip this step. If you are using Colab, run the cell below and...
Python Code: PROJECT_ID = "[<your-project-id>]" Explanation: TabNet: Attentive Interpretable Tabular Learning <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/ml-on-gcp/blob/master/tutorials/explanations/ai-explanations-tabnet-algorithm.ipynb"> <img src="https:...
6,029
Given the following text description, write Python code to implement the functionality described below step by step Description: Artifact correction with Maxwell filter This tutorial shows how to clean MEG data with Maxwell filtering. Maxwell filtering in MNE can be used to suppress sources of external intereference a...
Python Code: import mne from mne.preprocessing import maxwell_filter data_path = mne.datasets.sample.data_path() Explanation: Artifact correction with Maxwell filter This tutorial shows how to clean MEG data with Maxwell filtering. Maxwell filtering in MNE can be used to suppress sources of external intereference and c...
6,030
Given the following text description, write Python code to implement the functionality described below step by step Description: Ordinary Differential Equations Exercise 1 Imports Step2: Euler's method Euler's method is the simplest numerical approach for solving a first order ODE numerically. Given the differential ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy.integrate import odeint from IPython.html.widgets import interact, fixed Explanation: Ordinary Differential Equations Exercise 1 Imports End of explanation def solve_euler(derivs, y0, x): Solve a 1d O...
6,031
Given the following text description, write Python code to implement the functionality described below step by step Description: Over-dispersed Age-Period-Cohort Models We replicate the data example in Harnau and Nielsen (2017) in Section 6. The work on this vignette was supported by the European Research Council, gra...
Python Code: import apc # Turn off a FutureWarnings import warnings warnings.simplefilter('ignore', FutureWarning) Explanation: Over-dispersed Age-Period-Cohort Models We replicate the data example in Harnau and Nielsen (2017) in Section 6. The work on this vignette was supported by the European Research Council, grant...
6,032
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Derivation of the inversion stencil using a non-symmetric forward-backward scheme Derivation of a non-symmetric stencil of $$b = \nabla\cdot(A\nabla_\perp f)+Bf$$ using a forward ste...
Python Code: from IPython.display import display from sympy import init_printing from sympy import symbols, expand, together, as_finite_diff, collect from sympy import Function, Eq, Subs from collections import deque init_printing() def finiteDifferenceOfOneTerm(factors, wrt, stencil): Finds the finite differe...
6,033
Given the following text description, write Python code to implement the functionality described below step by step Description: Mining performance hotspots with JProfiler, jQAssistant, Neo4j and Pandas TL;DR I show how I determine the parts of an application that trigger unnecessary SQL statements by using graph anal...
Python Code: with open (r'input/spring-petclinic/JDBC_Probe_Hot_Spots_jmeter_test.xml') as log: [print(line[:97] + "...") for line in log.readlines()[:10]] Explanation: Mining performance hotspots with JProfiler, jQAssistant, Neo4j and Pandas TL;DR I show how I determine the parts of an application that trigger unn...
6,034
Given the following text description, write Python code to implement the functionality described below step by step Description: constitutive Step1: L_iso Provides the elastic stiffness tensor for an isotropic material. The two first arguments are a couple of elastic properties. The third argument specifies which co...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from simmit import smartplus as sim import os Explanation: constitutive : The Constitutive Library End of explanation E = 70000.0 nu = 0.3 L = sim.L_iso(E,nu,"Enu") print np.array_str(L, precision=4, suppress_small=True) d = sim.check_sy...
6,035
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting Breast Cancer Proliferation Scores with Apache Spark and Apache SystemML Preprocessing Setup Step1: Execute Preprocessing & Save Step2: Sample Data TODO
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline import os import shutil import matplotlib.pyplot as plt import numpy as np from breastcancer.preprocessing import preprocess, save, train_val_split # Ship a fresh copy of the `breastcancer` package to the Spark workers. # Note: The zip must include the ...
6,036
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting sensor layouts of EEG systems This example illustrates how to load all the EEG system montages shipped in MNE-python, and display it on the fsaverage template subject. Step1: Check...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Joan Massich <mailsik@gmail.com> # # License: BSD Style. import os.path as op import mne from mne.channels.montage import get_builtin_montages from mne.datasets import fetch_fsaverage from mne.viz import set_3d_title, set_3d_view Explan...
6,037
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Core Test Step2: Mesh Test Step3: FunctionSpace Test Step4: Exporter Test
Python Code: !echo "deb https://dl.bintray.com/feelpp/ubuntu bionic latest" | tee -a /etc/apt/sources.list !wget -qO - https://bintray.com/user/downloadSubjectPublicKey?username=bintray | apt-key add - !apt update !apt install feelpp-quickstart feelpp-data !apt install python3-mpi4py python3-feelpp ssh Explanation: <a...
6,038
Given the following text description, write Python code to implement the functionality described below step by step Description: Peer in THRG Generated Graphs Dev Space System Step1: Network Dynamics Let's examine the network dynamics Step2: THRG Using time1.py we learn or derive the production rules from the given ...
Python Code: # imports import networkx as nx %matplotlib inline import matplotlib.pyplot as plt params = {'legend.fontsize':'small', 'figure.figsize': (7,7), 'axes.labelsize': 'small', 'axes.titlesize': 'small', 'xtick.labelsize':'small', 'ytick.labelsize':'small'} plt....
6,039
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1 toc-item"><a href="#Honors-Physics-PHYS1010" data-toc-modified-id="Honors-Physics-PHYS1010-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Honors Phys...
Python Code: from PIL import Image, ImageDraw import math, colorsys, numpy from matplotlib import colors from IPython.display import Image as ipythonImage Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#Honors-Physics-PHYS1010" data-toc-modified-id="Honors-Physics-PHYS1010-1"><span class="toc-ite...
6,040
Given the following text description, write Python code to implement the functionality described below step by step Description: Uncertainty in Deep Learning A common criticism of deep learning models is that they tend to act as black boxes. A model produces outputs, but doesn't given enough context to interpret them...
Python Code: !pip install --pre deepchem import deepchem deepchem.__version__ Explanation: Uncertainty in Deep Learning A common criticism of deep learning models is that they tend to act as black boxes. A model produces outputs, but doesn't given enough context to interpret them properly. How reliable are the model'...
6,041
Given the following text description, write Python code to implement the functionality described below step by step Description: Cargue de datos s SciDB 1) Verificar Prerequisitos Python SciDB-Py requires Python 2.6-2.7 or 3.3 Step1: NumPy tested with version 1.9 (1.13.1) Step2: Requests tested with version 2.7 (2.1...
Python Code: import sys sys.version_info Explanation: Cargue de datos s SciDB 1) Verificar Prerequisitos Python SciDB-Py requires Python 2.6-2.7 or 3.3 End of explanation import numpy as np np.__version__ Explanation: NumPy tested with version 1.9 (1.13.1) End of explanation import requests requests.__version__ Explana...
6,042
Given the following text description, write Python code to implement the functionality described below step by step Description: A1 Step1: Step 1 Step2: Run the above function to call the API and assign the responses to variables Step3: Export the API raw data files. This section has been commented out in order to ...
Python Code: import json import matplotlib.pyplot as plt import numpy as np import pandas as pd import requests from datetime import datetime %matplotlib inline Explanation: A1: Data curation Dane Jordan Import necessary libraries that will be used End of explanation # since we will be performing api calls at least fiv...
6,043
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', 'uhh', 'sandbox-2', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: UHH Source ID: SANDBOX-2 Topic: Atmos Sub-Topics: Dynamical Core, Radiation, T...
6,044
Given the following text description, write Python code to implement the functionality described below step by step Description: Use tensorboard to visualize tensorflow graph, plot quantitative metrics about the execution of your graph, and show addinal data like images that pass through it. Step1: Tensorboard operat...
Python Code: import tensorboard as tb import tensorflow as tf Explanation: Use tensorboard to visualize tensorflow graph, plot quantitative metrics about the execution of your graph, and show addinal data like images that pass through it. End of explanation def variable_summaries (var): with tf.name_scope ('summari...
6,045
Given the following text description, write Python code to implement the functionality described. Description: Swap the elements between any two given quadrants of a Matrix Python3 program for the above approach ; Function to iterate over the X quadrant and swap its element with Y quadrant ; Iterate over X quadrant ; S...
Python Code: N , M = 6 , 6 def swap(mat , startx_X , starty_X , startx_Y , starty_Y ) : row , col = 0 , 0 i = startx_X while(bool(True ) ) : col = 0 j = startx_X while(bool(True ) ) : temp = mat[i ][j ] mat[i ][j ] = mat[startx_Y + row ][starty_Y + col ] mat[startx_Y + row ][starty_Y + col ] = te...
6,046
Given the following text description, write Python code to implement the functionality described below step by step Description: 19 - Introduction to Deep Learning - MLP by Alejandro Correa Bahnsen and Jesus Solano version 1.4, May 2019 Part of the class Practical Machine Learning This notebook is licensed under a Cre...
Python Code: # Import the required packages import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt import scipy # Package imports import numpy as np import matplotlib.pyplot as plt import sklearn import sklearn.datasets import sklearn.linear_model Explanation: 19 - Introduction to Deep...
6,047
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 5 Examples and Exercises from Think Stats, 2nd Edition http Step1: Exponential distribution Here's what the exponential CDF looks like with a range of parameters. Step2: Here's the...
Python Code: from os.path import basename, exists def download(url): filename = basename(url) if not exists(filename): from urllib.request import urlretrieve local, _ = urlretrieve(url, filename) print("Downloaded " + local) download("https://github.com/AllenDowney/ThinkStats2/raw/master...
6,048
Given the following text description, write Python code to implement the functionality described below step by step Description: Step3: General intro Step4: Defining the structure of the network For the neural network to train on your data, you need the following <a href="https Step5: Training Step6: Test
Python Code: %matplotlib inline import os from urllib import urlretrieve import math import tensorflow as tf import matplotlib.pyplot as plt 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 f...
6,049
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to the Python Plotting Tutorial for Com597I! This is intended as a self-guided exercise to help you explore python plotting. Please follow the document, follow the links and read the...
Python Code: # This section imports some important libraries that we'll need. # the most important is the second line. After you run this, "plt" will be # the plotting library in python. import numpy import matplotlib.pyplot as plt %pylab inline Explanation: Welcome to the Python Plotting Tutorial for Com597I! This is ...
6,050
Given the following text description, write Python code to implement the functionality described below step by step Description: Load some data Step1: Load pairs of covers and non-covers ```Python def get_pairs(clique_dict) Step2: Cut chroma features to fixed-length arrays ```Python def patchwork(chroma, n_patches=7...
Python Code: # ratio = (5, 15, 80) ratio = (1, 9, 90) clique_dict, cliques_by_uri = SHS_data.read_cliques() train_cliques, test_cliques, val_cliques = util.split_train_test_validation(clique_dict, ratio=ratio) Explanation: Load some data End of explanation pairs, non_pairs = paired_data.get_pairs(train_cliques) assert ...
6,051
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This is a basic tutorial on using Jupyter to use the scipy modules. Example of plotting sine and cosine functions in the same plot Install matplotlib through conda via Step1: T...
Python Code: import math import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 3 * math.pi, 50) y = np.sin(x) plt.plot(x, y) plt.show() Explanation: Introduction This is a basic tutorial on using Jupyter to use the scipy modules. Example of plotting sine and cosine functions ...
6,052
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nims-kma', 'sandbox-3', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: NIMS-KMA Source ID: SANDBOX-3 Topic: Aerosol Sub-Topics: Transport, E...
6,053
Given the following text description, write Python code to implement the functionality described below step by step Description: This example is kindly contributed by FreddyBaudine for reproducing pygae/galgebra#26 and pygae/galgebra#30 with modifications by utensil. Please note before Python code, there's an invisibl...
Python Code: from __future__ import print_function import sys from galgebra.printer import Format, xpdf Format() from sympy import symbols, sin, pi, latex, Array, permutedims from galgebra.ga import Ga from IPython.display import Math Explanation: This example is kindly contributed by FreddyBaudine for reproducing pyg...
6,054
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: tf.function과 함께 XLA 사용하기 <table class="tfo-notebook-buttons" align="left"> <td> <img src="https Step2: 그런 다음, 몇 가지 필요한 상수를 정의하고 MNIST 데이터세트를...
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...
6,055
Given the following text description, write Python code to implement the functionality described below step by step Description: Is the Grass Wet? This is an example used by Pearl in his book 'Causality'. I've used the conditional probability tables from here Step1: We begin with some variables, each with 2 states .....
Python Code: from causalinfo import * # You only need this if you want to draw pretty pictures of the Networksa from nxpd import draw, nxpdParams nxpdParams['show'] = 'ipynb' Explanation: Is the Grass Wet? This is an example used by Pearl in his book 'Causality'. I've used the conditional probability tables from here: ...
6,056
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Word Cookie Solver This program will find all of the words that can be made from a specified set of letters. Setup First, let's write some code to check if a single word can be made f...
Python Code: def word_works(letters, word, allow_repeats=False): Return True if word can be spelled using only letters. letters is a single string. allow_repeats allows each letter to be used many times. letters_remaining = letters.lower() # because dictionary words will be lowercase for letter ...
6,057
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Feature Engineering </h1> In this notebook, you will learn how to incorporate feature engineering into your pipeline. <ul> <li> Working with feature columns </li> <li> Adding feature cr...
Python Code: !pip install --user apache-beam[gcp]==2.16.0 !pip install --user httplib2==0.12.0 Explanation: <h1> Feature Engineering </h1> In this notebook, you will learn how to incorporate feature engineering into your pipeline. <ul> <li> Working with feature columns </li> <li> Adding feature crosses in TensorFlow ...
6,058
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with ...
Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical Explanation: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a n...
6,059
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Modeling in Practice Assignment Step1: Let's check that the quantitative variable are effectively centered. Step2: The means are both very close to 0; confirming the centering. ...
Python Code: # Magic command to insert the graph directly in the notebook %matplotlib inline # Load a useful Python libraries for handling data import pandas as pd import numpy as np import statsmodels.formula.api as smf import seaborn as sns import matplotlib.pyplot as plt from IPython.display import Markdown, display...
6,060
Given the following text description, write Python code to implement the functionality described below step by step Description: $\newcommand{\xv}{\mathbf{x}} \newcommand{\Xv}{\mathbf{X}} \newcommand{\piv}{\mathbf{\pi}} \newcommand{\yv}{\mathbf{y}} \newcommand{\Yv}{\mathbf{Y}} \newcommand{\zv}{\mathbf{z}} \newcommand{...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: $\newcommand{\xv}{\mathbf{x}} \newcommand{\Xv}{\mathbf{X}} \newcommand{\piv}{\mathbf{\pi}} \newcommand{\yv}{\mathbf{y}} \newcommand{\Yv}{\mathbf{Y}} \newcommand{\zv}{\mathbf{z}} \newcommand{\av}{\mathbf{a}} \newcommand{\Wv}{...
6,061
Given the following text description, write Python code to implement the functionality described below step by step Description: 全体の流れ 分析の前準備 BigQueryから収集したデータの抽出 データを扱いやすく整形 統計情報を確認 データの可視化 データの特徴 外気温は比較的一定 CPU温度はよく変化する 分析の実施 CPU温度が外気温を越えて熱くならないようにコントロールしたい。そのためにどうデータを扱うかのサンプルを確認する。ここで作ったモデルを実際にプロダクション環境に組み込めることを想定して...
Python Code: %%bq query -n requests SELECT datetime, cpu_temperature, temperature FROM `soracom_handson.raspi_env` order by datetime asc import google.datalab.bigquery as bq import pandas as pd df_from_bq = requests.execute(output_options=bq.QueryOutput.dataframe()).result() # データの確認 df_from_bq # 文字列型でデータが取得されているので変換 ...
6,062
Given the following text description, write Python code to implement the functionality described below step by step Description: Распределение товаров по категориям Инициализация Step1: Загружаю данные о продуктах Описание полей Step2: Загружаем все возможные наименования продуктов У разных поставщиков один и тот-же...
Python Code: import os import sys from django.utils import timezone sys.path.append('/home/ubuntu/anodos.ru/anodos/') os.environ['DJANGO_SETTINGS_MODULE'] = 'anodos.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() %matplotlib inline import numpy as np import pandas as pd ...
6,063
Given the following text description, write Python code to implement the functionality described below step by step Description: Winpython Default checker Step1: Compilers Step2: Cython (a compiler for writing C extensions for the Python language) WinPython 3.5 and 3.6 users may not have mingwpy available, and so ne...
Python Code: import warnings #warnings.filterwarnings("ignore", category=DeprecationWarning) #warnings.filterwarnings("ignore", category=UserWarning) #warnings.filterwarnings("ignore", category=FutureWarning) # warnings.filterwarnings("ignore") # would silence all warnings %matplotlib inline # use %matplotlib widget f...
6,064
Given the following text description, write Python code to implement the functionality described below step by step Description: Test a Perceptual Phenomenon - Stroop data Katie Truong Step1: Introduction In a Stroop experiment, participants are shown two lists of word of color names, printed in different ink colors,...
Python Code: import pandas as pd import numpy as np import scipy.stats as st import matplotlib.pyplot as plt import seaborn as sns import math Explanation: Test a Perceptual Phenomenon - Stroop data Katie Truong End of explanation stroopdata = pd.read_csv("stroopdata.csv") stroopdata Explanation: Introduction In a Stro...
6,065
Given the following text description, write Python code to implement the functionality described below step by step Description: Learning to Play Pong {tip} For a production-grade implementation of distributed reinforcement learning, use [Ray RLlib](https Step1: Hyperparameters Here we'll define a couple of the hyper...
Python Code: import numpy as np import os import ray import time import gym Explanation: Learning to Play Pong {tip} For a production-grade implementation of distributed reinforcement learning, use [Ray RLlib](https://docs.ray.io/en/master/rllib/index.html). In this example, we'll train a very simple neural network to ...
6,066
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Implementing a Neural Network In this exercise we will develop a neural network with fully-connected layers to perform classification, and test it out on the CIFAR-10 dataset. Step2: ...
Python Code: # A bit of setup import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.neural_net import TwoLayerNet %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for aut...
6,067
Given the following text description, write Python code to implement the functionality described below step by step Description: load image as ndarray http Step1: let's do k-mean my version will take more than 10 mins... ok. I know why I shouldn't implement my own ML library. In the future I will only implement ML al...
Python Code: from skimage import io # cast to float, you need to do this otherwise the color would be weird after clustring pic = io.imread('data/bird_small.png') / 255. io.imshow(pic) pic.shape # serialize data data = pic.reshape(128*128, 3) Explanation: load image as ndarray http://scikit-image.org/ End of explanatio...
6,068
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading BCH/BATCH Files BCH/BATCH files are created by FEMAG during a calculation. They hold most of the results. Their values are grouped into different sections such as Step1: Show the ca...
Python Code: import femagtools.bch bch = femagtools.bch.read('TEST_002.BCH') Explanation: Reading BCH/BATCH Files BCH/BATCH files are created by FEMAG during a calculation. They hold most of the results. Their values are grouped into different sections such as: Flux, Torque, Machine, dqPar etc. The actual number of sec...
6,069
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: two different ways to implement categorical cross entropy in TensorFlow
Python Code:: import tensorflow as tf from tensorflow.keras.losses import CategoricalCrossentropy y_true = [[0, 1, 0], [1, 0, 0]] y_pred = [[0.15, 0.75, 0.1], [0.75, 0.15, 0.1]] cross_entropy_loss = CategoricalCrossentropy() print(cross_entropy_loss(y_true, y_pred).numpy()) import tensorflow as tf from tensorflow.keras...
6,070
Given the following text description, write Python code to implement the functionality described below step by step Description: Google form analysis tests Purpose Step1: Sorted total answers to questions <a id=sortedtotalanswers /> Step2: Cross-samples t-tests <a id=crossttests /> Purpose Step3: Conclusion
Python Code: %run "../Functions/2. Google form analysis.ipynb" Explanation: Google form analysis tests Purpose: determine in what extent the current data can accurately describe correlations, underlying factors on the score. Especially concerning the answerTemporalities[0] groups: are there underlying groups explaining...
6,071
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', 'miroc', 'miroc-es2l', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: MIROC Source ID: MIROC-ES2L Topic: Ocean Sub-Topics: Timestepping Framework...
6,072
Given the following text description, write Python code to implement the functionality described below step by step Description: Extracting the IRIS XGB Models and Analysis from Redis Labs Cloud This notebook demonstrates how to extract the machine learning Models + Analysis from the Redis Labs Cloud (https Step1: 2)...
Python Code: # Setup the Sci-pype environment import sys, os # Only Redis Labs is needed for this notebook: os.environ["ENV_DEPLOYMENT_TYPE"] = "RedisLabs" # Load the Sci-pype PyCore as a named-object called "core" and environment variables from src.common.load_ipython_env import * Explanation: Extracting the IRIS XGB ...
6,073
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cnrm-cerfacs', 'cnrm-esm2-1', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: CNRM-CERFACS Source ID: CNRM-ESM2-1 Topic: Aerosol Sub-Topics: ...
6,074
Given the following text description, write Python code to implement the functionality described below step by step Description: Filter out video games which have no title Filter out video games which have less than 5 ratings Filter out users which have less than 5 ratings Merge ratings and videogames dataframe on pro...
Python Code: correlated_items = ratings_pivot.corr()["B002I0JZOC"].sort_values(ascending=False).head(5) correlated_items.index Explanation: Filter out video games which have no title Filter out video games which have less than 5 ratings Filter out users which have less than 5 ratings Merge ratings and videogames datafr...
6,075
Given the following text description, write Python code to implement the functionality described below step by step Description: NERC region maps NERC shapefiles are from Tamayao, M.-A. M., Michalek, J. J., Hendrickson, C. & Azevedo, I. M. L. Regional Variability and Uncertainty of Electric Vehicle Life Cycle CO2 Emis...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import numpy as np import geopandas as gpd import os from os.path import join import pandas as pd import sys sns.set(style='white') cwd = os.getcwd() data_path = join(cwd, '..', 'Data storage') figure_path = join(cwd,'..', 'Figures') ...
6,076
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br> Allen Downey Step1: Exercise 5.1 In the BRFSS (see Section 5.4), the distribution of heights is roughly normal with parameters µ...
Python Code: from __future__ import print_function, division import thinkstats2 import thinkplot from brfss import * import populations as p import random import pandas as pd import test_models %matplotlib inline Explanation: Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br> Allen Downey End of explanation i...
6,077
Given the following text description, write Python code to implement the functionality described below step by step Description: Time Series Stationary Measures I'm going to try different metrics to measure whether a time series is stationary, because there are different types of stationary, different metrics measure ...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt from pandas.plotting import autocorrelation_plot from statsmodels.tsa.stattools import kpss from statsmodels.tsa.stattools import adfuller # This is the original time series def parser(x): return pd.datetime.strptime('190'+x, '%Y-%m...
6,078
Given the following text description, write Python code to implement the functionality described below step by step Description: Web service Since Parselmouth is a normal Python library, it can also easily be used within the context of a web server. There are several Python frameworks that allow to quickly set up a we...
Python Code: %%writefile server.py from flask import Flask, request, jsonify import tempfile app = Flask(__name__) @app.route('/pitch_track', methods=['POST']) def pitch_track(): import parselmouth # Save the file that was sent, and read it into a parselmouth.Sound with tempfile.NamedTemporaryFile() as tmp:...
6,079
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian optimization with context variables In this notebook we are going to see how to use Emukit to solve optimization problems in which certain variables are fixed during the optimizatio...
Python Code: from emukit.test_functions import branin_function from emukit.core import ParameterSpace, ContinuousParameter, DiscreteParameter from emukit.core.initial_designs import RandomDesign from GPy.models import GPRegression from emukit.model_wrappers import GPyModelWrapper from emukit.bayesian_optimization.acqui...
6,080
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Step1: As always, let's do imports and initialize a logger and a new Bundle. See Building a System for more details. Step2: Accessing Settings Settings are found with their own c...
Python Code: !pip install -I "phoebe>=2.2,<2.3" Explanation: Advanced: Settings The Bundle also contains a few Parameters that provide settings for that Bundle. Note that these are not system-wide and only apply to the current Bundle. They are however maintained when saving and loading a Bundle. Setup Let's first mak...
6,081
Given the following text description, write Python code to implement the functionality described below step by step Description: IST256 Lesson 13 Visualizations Zybook Ch10 Links Participation Step1: A. y[ ['b'] == 'x' ] B. y[ y['b'] == 'x' ] C. y['b'] == 'x' D. y[ y['b'] == y['x'] ] Vote Now Step2: A. y[ 'a','c' ...
Python Code: import pandas as pd x = [ { 'a' :2, 'b' : 'x', 'c' : 10}, { 'a' :4, 'b' : 'y', 'c' : 3}, { 'a' :1, 'b' : 'x', 'c' : 6} ] y = pd.DataFrame(x) Explanation: IST256 Lesson 13 Visualizations Zybook Ch10 Links Participation: https://poll.ist256.com Zoom Chat! Agenda Last Lecture... but we ain't gone...
6,082
Given the following text description, write Python code to implement the functionality described below step by step Description: Fitting Models Exercise 2 Imports Step1: Fitting a decaying oscillation For this problem you are given a raw dataset in the file decay_osc.npz. This file contains three arrays Step2: Now, ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.optimize as opt Explanation: Fitting Models Exercise 2 Imports End of explanation # YOUR CODE HERE #raise NotImplementedError() with np.load('decay_osc.npz') as data: tdata = data['tdata'] ydata = data['ydata'] d...
6,083
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id='top'></a> Kolmogorov-Smirnov test In this notebook we will illustrate the use of the Kolmogorov-Smirnov test (K-S test) using functions from the SciPy stats module. In particular, we ...
Python Code: import sys import math import numpy as np import scipy as sp import matplotlib as mpl import pandas as pd Explanation: <a id='top'></a> Kolmogorov-Smirnov test In this notebook we will illustrate the use of the Kolmogorov-Smirnov test (K-S test) using functions from the SciPy stats module. In particular, w...
6,084
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have set up a GridSearchCV and have a set of parameters, with I will find the best combination of parameters. My GridSearch consists of 12 candidate models total.
Problem: import numpy as np import pandas as pd from sklearn.model_selection import GridSearchCV GridSearch_fitted = load_data() assert type(GridSearch_fitted) == sklearn.model_selection._search.GridSearchCV full_results = pd.DataFrame(GridSearch_fitted.cv_results_)
6,085
Given the following text description, write Python code to implement the functionality described below step by step Description: LeNet Lab Solution Source Step1: The MNIST data that TensorFlow pre-loads comes as 28x28x1 images. However, the LeNet architecture only accepts 32x32xC images, where C is the number of colo...
Python Code: from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", reshape=False) X_train, y_train = mnist.train.images, mnist.train.labels X_validation, y_validation = mnist.validation.images, mnist.validation.labels X_test, y_test = mnist.tes...
6,086
Given the following text description, write Python code to implement the functionality described below step by step Description: Showing Csound k-Values in Matplotlib Animation The goal of this notebook is to show how Csound control signals can be seen in real-time in the Python Matplotlib using the Animation module. ...
Python Code: %matplotlib qt5 Explanation: Showing Csound k-Values in Matplotlib Animation The goal of this notebook is to show how Csound control signals can be seen in real-time in the Python Matplotlib using the Animation module. This can be quite instructive for teaching Csound. Written by Joachim Heintz, August 201...
6,087
Given the following text description, write Python code to implement the functionality described below step by step Description: Trend analysis with bootstrap resampling Python / Numpy implementation of the trend analysis presented in Gardiner et al., 2008 The following model is used to fit the annual trend (drift) + ...
Python Code: import pprint import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline Explanation: Trend analysis with bootstrap resampling Python / Numpy implementation of the trend analysis presented in Gardiner et al., 2008 The following model is used to fit the annual trend (drift) ...
6,088
Given the following text description, write Python code to implement the functionality described below step by step Description: Lightning data analysis (from WWLN or Blitzortung) Development notebook This iPython notebook extracts lighning data from raw WWLN data files or Blitzortung network. Code by Step1: Notes It...
Python Code: # Load required packages import numpy as np import datetime as dt from datetime import timedelta import pandas as pd from tqdm import tqdm import os import pkg_resources as pkg import geopandas as gpd from shapely.geometry import Point from bokeh.plotting import Figure, show, output_notebook, vplot from bo...
6,089
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: This is a direct copy of the Earth to Venus mission plan. I'm doing this to make sure I get the functions correct, before proceeding further on the Earth to Mars. Below is the capt...
Python Code: class PlanetaryObject(): A simple class used to store pertinant information about the plantary object def __init__(self, date, L, e, SMA, i, peri, asc, r, v, anom, fp, mu): self.date = date # Event Date self.L = L # Longitude self.e = e # Eccentri...
6,090
Given the following text description, write Python code to implement the functionality described below step by step Description: ApJdataFrames 013 Step1: Table 1 - Spitzer IRAC/MIPS IC348 catalog Step2: Table 2 - SED Derived $\alpha_{IRAC}$ and $A_V$ But really... spectral types Step3: Table 3 - Convenient passband...
Python Code: %pylab inline import seaborn as sns import warnings warnings.filterwarnings("ignore") import pandas as pd from astropy.io import ascii from astropy.table import Table, join Explanation: ApJdataFrames 013: Lada2006 Title: Spitzer Observations of IC 348: The Disk Population at 2-3 Million Years Authors: Char...
6,091
Given the following text description, write Python code to implement the functionality described below step by step Description: "The Jupyter Notebook is a web application that allows you to create and share documents that contain live code, equations, visualizations and explanatory text. Uses include Step1: Pandas i...
Python Code: # this would be a comment # cells like this are like an advanced calculator # for example: 2+2 Explanation: "The Jupyter Notebook is a web application that allows you to create and share documents that contain live code, equations, visualizations and explanatory text. Uses include: data cleaning and transf...
6,092
Given the following text description, write Python code to implement the functionality described below step by step Description: gensim doc2vec & IMDB sentiment dataset TODO Step1: The data is small enough to be read into memory. Step2: Set-up Doc2Vec Training & Evaluation Models Approximating experiment of Le & Mik...
Python Code: import locale import glob import os.path import requests import tarfile import sys import codecs dirname = 'aclImdb' filename = 'aclImdb_v1.tar.gz' locale.setlocale(locale.LC_ALL, 'C') if sys.version > '3': control_chars = [chr(0x85)] else: control_chars = [unichr(0x85)] # Convert text to lower-cas...
6,093
Given the following text description, write Python code to implement the functionality described below step by step Description: Document retrieval from wikipedia data Fire up GraphLab Create Step1: Load some text data - from wikipedia, pages on people Step2: Data contains Step3: Explore the dataset and checkout th...
Python Code: import graphlab Explanation: Document retrieval from wikipedia data Fire up GraphLab Create End of explanation people = graphlab.SFrame('people_wiki.gl/') Explanation: Load some text data - from wikipedia, pages on people End of explanation people.head() len(people) Explanation: Data contains: link to wik...
6,094
Given the following text description, write Python code to implement the functionality described below step by step Description: Colaboratory Before you start When you open a new Colab from Github (like this one), you cannot save changes. So it's usually best to store the Colab in you personal drive "File &gt; Save a ...
Python Code: # YOUR ACTION REQUIRED: # Execute this cell first using <CTRL-ENTER> and then using <SHIFT-ENTER>. # Note the difference in which cell is selected after execution. print('Hello world!') Explanation: Colaboratory Before you start When you open a new Colab from Github (like this one), you cannot save changes...
6,095
Given the following text description, write Python code to implement the functionality described below step by step Description: Better ML Engineering with ML Metadata Learning Objectives Download the dataset Create an InteractiveContext Construct the TFX Pipeline Query the MLMD Database Introduction Assume a scenario...
Python Code: !pip install --upgrade pip Explanation: Better ML Engineering with ML Metadata Learning Objectives Download the dataset Create an InteractiveContext Construct the TFX Pipeline Query the MLMD Database Introduction Assume a scenario where you set up a production ML pipeline to classify penguins. The pipeline...
6,096
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', 'nerc', 'hadgem3-gc31-hh', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: NERC Source ID: HADGEM3-GC31-HH Topic: Ocean Sub-Topics: Timestepping F...
6,097
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I’m trying to solve a simple ODE to visualise the temporal response, which works well for constant input conditions using the new solve_ivp integration API in SciPy. For example:
Problem: import scipy.integrate import numpy as np N0 = 1 time_span = [0, 10] def dN1_dt(t, N1): input = 1-np.cos(t) if 0<t<2*np.pi else 0 return -100*N1 + input sol = scipy.integrate.solve_ivp(fun=dN1_dt, t_span=time_span, y0=[N0,])
6,098
Given the following text description, write Python code to implement the functionality described below step by step Description: Example of DOV search methods for interpretations (formele stratigrafie) Use cases explained below Get 'formele stratigrafie' in a bounding box Get 'formele stratigrafie' with specific prope...
Python Code: %matplotlib inline import inspect, sys # check pydov path import pydov Explanation: Example of DOV search methods for interpretations (formele stratigrafie) Use cases explained below Get 'formele stratigrafie' in a bounding box Get 'formele stratigrafie' with specific properties Get 'formele stratigrafie' ...
6,099
Given the following text description, write Python code to implement the functionality described below step by step Description: Display Exercise 1 Imports Put any needed imports needed to display rich output the following cell Step1: Basic rich display Find a Physics related image on the internet and display it in t...
Python Code: from IPython.display import Image from IPython.display import HTML from IPython.display import IFrame assert True # leave this to grade the import statements Explanation: Display Exercise 1 Imports Put any needed imports needed to display rich output the following cell: End of explanation Image(url = 'http...