Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
600
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Intro to Autoencoders <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Load the dataset To s...
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...
601
Given the following text description, write Python code to implement the functionality described below step by step Description: The Lasso Modified from the github repo Step1: Hitters dataset Let's load the dataset from the previous lab.
Python Code: # %load ../standard_import.txt import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import scale from sklearn.model_selection import LeaveOneOut from sklearn.linear_model import LinearRegression, lars_path, Lasso, LassoCV %matplotlib inline n=100 p=1000 X = np....
602
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Keras 中的权重聚类示例 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: 在不使用聚类的情况下为 MNIST 训练 tf.keras 模型 ...
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...
603
Given the following text description, write Python code to implement the functionality described below step by step Description: Groupby operations Some imports Step1: Recap Step2: Using the filtering and reductions operations we have seen in the previous notebooks, we could do something like Step3: Pandas does not...
Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt try: import seaborn except ImportError: pass pd.options.display.max_rows = 10 Explanation: Groupby operations Some imports: End of explanation df = pd.DataFrame({'key':['A','B','C','A','B','C','A','B','C'], ...
604
Given the following text description, write Python code to implement the functionality described below step by step Description: <div style="width Step1: 3. Download settings 3.1 Choose download location The original data can either be downloaded from the original data sources as specified below or from the opsd-Serv...
Python Code: # Import all functions from external file from download_and_process_DE_functions import * # Jupyter functions %matplotlib inline Explanation: <div style="width:100%; background-color: #D9EDF7; border: 1px solid #CFCFCF; text-align: left; padding: 10px;"> <b>Conventional Power Plants: Power Plants in ...
605
Given the following text description, write Python code to implement the functionality described below step by step Description: USDA Food Data - Preliminary Analysis USDA Food Data is obtained from a consolidated dataset published by the Open Food Facts organization (https Step1: Preliminary look at the USDA data St...
Python Code: # load pre-requisite imports import pandas as pd import numpy as np import matplotlib.pyplot as plt import re from gensim import corpora, models, similarities # load world food data into a pandas dataframe world_food_facts =pd.read_csv("../w209finalproject_data/data/en.openfoodfacts.org.products.tsv", sep=...
606
Given the following text description, write Python code to implement the functionality described below step by step Description: Tinkering with Keras The goal of this notebook is to store useful insights made through my learning process of Keras. Since I will be closely working with a colleague who uses Theano, the id...
Python Code: %reset -f import keras.backend as K x = K.variable(42.) # Solution 1: sess = K.get_session() print sess.run(x) # Solution 2 (seamless): print K.eval(x) Explanation: Tinkering with Keras The goal of this notebook is to store useful insights made through my learning process of Keras. Since I will be closely ...
607
Given the following text description, write Python code to implement the functionality described below step by step Description: We're going to start by grabbing the geometry for the Austin community area. Step1: Now let's get the shootings data. Step2: Now let's iterate through the shootings, generate shapely point...
Python Code: import requests from shapely.geometry import shape, Point r = requests.get('https://data.cityofchicago.org/api/geospatial/cauq-8yn6?method=export&format=GeoJSON') for feature in r.json()['features']: if feature['properties']['community'] == 'AUSTIN': austin = feature poly = shape(austin['geomet...
608
Given the following text description, write Python code to implement the functionality described below step by step Description: Bagging元估计器 Bagging是Bootstrap Aggregating的简称,意思就是再取样(Bootstrap)然后在每个样本上训练出来的模型进行集成. 通常如果目标是分类,则集成的方式是投票;如果目标是回归,则集成方式是取平均. 在集成算法中,bagging方法会在原始训练集的随机子集上构建一类黑盒估计器的多个实例,然后把这些估计器的预测结果结合起来形成最终的预...
Python Code: import requests import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder,StandardScaler from sklearn.neural_network import MLPClassifier from sklearn.metrics import classification_report from sklearn.ensemble import BaggingClassifier Explanatio...
609
Given the following text description, write Python code to implement the functionality described below step by step Description: Uncovering Configuration and Behavior Drift When debugging network issues, it is important to understand how the network is different today compared to yesterday or to the desired golden sta...
Python Code: # Use recursive diff, followed by some pretty printing hacks !diff -ur networks/drift/reference networks/drift/snapshot | sed -e 's;diff.*snapshot/\(configs.*cfg\);^-----------\1---------;g' | tr '^' '\n' | grep -v networks/drift Explanation: Uncovering Configuration and Behavior Drift When debugging netwo...
610
Given the following text description, write Python code to implement the functionality described below step by step Description: Pymagicc Usage Examples Step1: Scenarios The four RCP scenarios are already preloaded in Pymagicc. They are loaded as MAGICCData objects with metadata attributes. metadata contains metadata...
Python Code: # NBVAL_IGNORE_OUTPUT from pprint import pprint import pymagicc from pymagicc import MAGICC6 from pymagicc.io import MAGICCData from pymagicc.scenarios import rcp26, rcp45, rcps %matplotlib inline from matplotlib import pyplot as plt plt.style.use("ggplot") plt.rcParams["figure.figsize"] = 16, 9 Explanatio...
611
Given the following text description, write Python code to implement the functionality described below step by step Description: Interpolating Parameters If parameters are changing significantly on dynamical timescales (e.g. mass transfer at pericenter on very eccentric orbits) you need a specialized numerical scheme ...
Python Code: import numpy as np data = np.loadtxt('m.txt') # return (N, 2) array mtimes = data[:, 0] # return only 1st col masses = data[:, 1] # return only 2nd col data = np.loadtxt('r.txt') rtimes = data[:, 0] Rsuns = data[:, 1] # data in Rsun units # convert Rsun to AU radii = np.zeros(Rsuns.si...
612
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="http Step1: Create the grid We are going to build a uniform rectilinear grid with a node spacing of 10 km in the y-direction and 20 km in the x-direction on which we will solve the...
Python Code: %matplotlib inline import numpy as np Explanation: <a href="http://landlab.github.io"><img style="float: left" src="../../landlab_header.png"></a> Using the Landlab flexure component <hr> <small>For more Landlab tutorials, click here: <a href="https://landlab.readthedocs.io/en/latest/user_guide/tutorials.h...
613
Given the following text description, write Python code to implement the functionality described below step by step Description: Examples and Exercises from Think Stats, 2nd Edition http Step1: Time series analysis Load the data from "Price of Weed". Step3: The following function takes a DataFrame of transactions an...
Python Code: from __future__ import print_function, division %matplotlib inline import warnings warnings.filterwarnings('ignore', category=FutureWarning) import numpy as np import pandas as pd import random import thinkstats2 import thinkplot Explanation: Examples and Exercises from Think Stats, 2nd Edition http://thin...
614
Given the following text description, write Python code to implement the functionality described below step by step Description: Subselect / Unterabfragen) Zur Durchführung einer Abfrage werden Informationen benötigt, die erst durch eine eigene Abfrage geholt werden müssen. Sie können stehen als Vertreter für einen We...
Python Code: %load_ext sql %sql mysql://steinam:steinam@localhost/versicherung_complete Explanation: Subselect / Unterabfragen) Zur Durchführung einer Abfrage werden Informationen benötigt, die erst durch eine eigene Abfrage geholt werden müssen. Sie können stehen als Vertreter für einen Wert als Vertreter für eine Lis...
615
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to TensorFlow, fitting point by point In this notebook, we introduce TensorFlow by fitting a line of the form y=m*x+b point by point. This is a derivation of Jared Ostmeyer's Na...
Python Code: import numpy as np np.random.seed(42) import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import tensorflow as tf tf.set_random_seed(42) Explanation: Introduction to TensorFlow, fitting point by point In this notebook, we introduce TensorFlow by fitting a line of the form y=m*x+b point b...
616
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', 'awi', 'sandbox-3', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: AWI Source ID: SANDBOX-3 Topic: Atmos Sub-Topics: Dynamical Core, Radiation, T...
617
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="../Pierian-Data-Logo.PNG"> <br> <strong><center>Copyright 2019. Created by Jose Marcial Portilla.</center></strong> RNN for Text Generation Generating Text (encoded variables) We s...
Python Code: import torch from torch import nn import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: <img src="../Pierian-Data-Logo.PNG"> <br> <strong><center>Copyright 2019. Created by Jose Marcial Portilla.</center></strong> RNN for Text Generation Generati...
618
Given the following text description, write Python code to implement the functionality described below step by step Description: Manipulating the Pandas DataFrame The iPython notebook for this demo can be found in Step1: First I'm going to pull out a small subset to work with Step2: I happen to like the way that's o...
Python Code: import os import pyNastran pkg_path = pyNastran.__path__[0] from pyNastran.op2.op2 import read_op2 import pandas as pd pd.set_option('precision', 2) op2_filename = os.path.join(pkg_path, '..', 'models', 'iSat', 'iSat_launch_100Hz.op2') from pyNastran.op2.op2 import read_op2 isat = read_op2(op2_filename, bu...
619
Given the following text description, write Python code to implement the functionality described below step by step Description: <br /> <br /> Gilles Pirio @ Ripple Research & Data Team August 20, 2015 Visualizing order books on Ripple Ripple is a distributed ledger that is not limited to one currency. The Ripple prot...
Python Code: import matplotlib.pyplot as plt %matplotlib inline from pyripple.feed import syncfeed feed = syncfeed.SyncFeed() Explanation: <br /> <br /> Gilles Pirio @ Ripple Research & Data Team August 20, 2015 Visualizing order books on Ripple Ripple is a distributed ledger that is not limited to one currency. The Ri...
620
Given the following text description, write Python code to implement the functionality described below step by step Description: Importar GraphLab Step1: Cargar el dataset Step2: Los datos contienen articulos de wikipedia sobre diferentes personas. Step3: Buscaremos al expresidente Barack Obama Step4: Contar las p...
Python Code: import graphlab Explanation: Importar GraphLab End of explanation people = graphlab.SFrame('people_wiki.gl/') Explanation: Cargar el dataset End of explanation people.head() len(people) Explanation: Los datos contienen articulos de wikipedia sobre diferentes personas. End of explanation obama = people[peop...
621
Given the following text description, write Python code to implement the functionality described below step by step Description: Poster popularity by state This notebook loads data of poster viewership at the SfN 2016 annual meeting, organized by the states that were affiliated with each poster. We find that the poste...
Python Code: %config InlineBackend.figure_format = 'retina' %matplotlib inline import numpy as np import scipy as sp import matplotlib.pyplot as plt import seaborn as sns sns.set_style('white') import pandas as pd # Load data df = pd.DataFrame.from_csv('./posterviewers_by_state.csv') key_N = 'Number of people' Explanat...
622
Given the following text description, write Python code to implement the functionality described below step by step Description: EAS Testing - Recents Fling on Android The goal of this experiment is to collect frame statistics while swiping up and down tabs of recently opened applications on a Nexus N5X running Androi...
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 os from time import sleep # Support to access the remote target import devlib ...
623
Given the following text description, write Python code to implement the functionality described below step by step Description: Problem Set 2 Exercise 5 Part 2.5.d.iv Step1: First we need to load the training and testing data sets and shape the data to run the analysis. Step2: Then we compute the boosting data usin...
Python Code: import numpy as np import matplotlib.pyplot as plt import load_data as ld import random_booster as rb import stump_booster as sb import errors_over_time as eot Explanation: Problem Set 2 Exercise 5 Part 2.5.d.iv End of explanation training_data, testing_data = ld.load_dataset('boosting-train.csv', 'boostin...
624
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Step1: Import raw data The user needs to specify the directories containing the data of interest. Each sample type should have a key which corresponds to the directory path. Ad...
Python Code: import deltascope as ds import deltascope.alignment as ut import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import normalize from scipy.optimize import minimize import os import tqdm import json import time Explanation: Introduction: Landmarks End of explanat...
625
Given the following text description, write Python code to implement the functionality described below step by step Description: Use the astropy interface to get the location of Jupiter as the time that you want to use. Step1: Conclusion
Python Code: dt = 0. # Using JPL Horizons web interface at 2017-05-19T01:34:40 horizon_ephem = SkyCoord(*[193.1535, -4.01689]*u.deg) for orbit in orbits: tstart = orbit[0] tend = orbit[1] print() # print('Orbit duration: ', tstart.isoformat(), tend.isoformat()) on_time = (tend - tstart).total_seconds...
626
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', 'test-institute-2', 'sandbox-1', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: TEST-INSTITUTE-2 Source ID: SANDBOX-1 Topic: Ocean Sub-Topics: Ti...
627
Given the following text description, write Python code to implement the functionality described below step by step Description: Twitter data Copyright and Licensing You are free to use or adapt this notebook for any purpose you'd like. However, please respect the Simplified BSD License that governs its use. Twitter A...
Python Code: import pickle import os if not os.path.exists('secret_twitter_credentials.pkl'): Twitter={} Twitter['Consumer Key'] = '' Twitter['Consumer Secret'] = '' Twitter['Access Token'] = '' Twitter['Access Token Secret'] = '' with open('secret_twitter_credentials.pkl','wb') as f: pi...
628
Given the following text description, write Python code to implement the functionality described below step by step Description: Mapping Names to Sequence Elements Problem You have code that accesses list or tuple elements by position, but this makes the code somewhat difficult to read at times. You’d also like to be ...
Python Code: from collections import namedtuple Subscriber = namedtuple('Subscriber', ['addr', 'joined']) sub = Subscriber('jonesy@example.com', '2012-10-19') sub print(sub.addr) print(sub.joined) Explanation: Mapping Names to Sequence Elements Problem You have code that accesses list or tuple elements by position, but...
629
Given the following text description, write Python code to implement the functionality described below step by step Description: Autoregressive Moving Average (ARMA) Step1: Sunpots Data Step2: Does our model obey the theory? Step3: This indicates a lack of fit. In-sample dynamic prediction. How good does our model ...
Python Code: %matplotlib inline from __future__ import print_function import numpy as np from scipy import stats import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm from statsmodels.graphics.api import qqplot Explanation: Autoregressive Moving Average (ARMA): Sunspots data This notebook rep...
630
Given the following text description, write Python code to implement the functionality described below step by step Description: MetPy Declarative Syntax Tutorial The declarative syntax that is a part of the MetPy packaged is designed to aid in simple data exploration and analysis needs by simplifying the plotting con...
Python Code: from datetime import datetime, timedelta import xarray as xr import metpy.calc as mpcalc from metpy.cbook import get_test_data from metpy.io import metar from metpy.plots.declarative import (BarbPlot, ContourPlot, FilledContourPlot, MapPanel, PanelContainer, PlotObs) fr...
631
Given the following text description, write Python code to implement the functionality described below step by step Description: Centralities In this section, I'm going to learn how Centrality works and try to interpret the data based on small real dataset. I'm using Facebook DataSet from SNAP https Step1: Now let's ...
Python Code: %matplotlib inline import networkx as nx import matplotlib.pyplot as plt import operator import timeit g_fb = nx.read_edgelist('facebook_combined.txt', create_using = nx.Graph(), nodetype = int) print nx.info(g_fb) print nx.is_directed(g_fb) Explanation: Centralities In this section, I'm going to learn how...
632
Given the following text description, write Python code to implement the functionality described below step by step Description: Python's iterators and generators TODO * https Step1: Iterator TODO... Step2: Generator Goal Step3: Generator iterator https Step4: Generator expression https Step5: Strange test
Python Code: # import python packages here... Explanation: Python's iterators and generators TODO * https://stackoverflow.com/questions/2776829/difference-between-pythons-generators-and-iterators * https://docs.python.org/3/glossary.html#term-generator * https://docs.python.org/3/glossary.html#term-generator-iterator *...
633
Given the following text description, write Python code to implement the functionality described below step by step Description: NumPy Step1: 1. Создание векторов Самый простой способ создать вектор в NumPy — задать его явно с помощью numpy.array(list, dtype=None, ...). Параметр list задает итерируемый объект, из кот...
Python Code: import numpy as np Explanation: NumPy: векторы и операции над ними В этом ноутбуке нам понадобятся библиотека NumPy. Для удобства импортируем ее под более коротким именем: End of explanation a = np.array([1, 2, 3, 4]) print 'Вектор:\n', a b = np.array([1, 2, 3, 4, 5], dtype=float) print 'Вещественный векто...
634
Given the following text description, write Python code to implement the functionality described below step by step Description: Загрузим файл о именах,поле и числе детей с сайта https Step1: Посчитаем количество родившихся в зависимости от пола Step2: Теперь создадим первую сводную таблицу Step3: Построим график...
Python Code: import pandas as pd import matplotlib.pyplot as plt names1880 = pd.read_csv('/Users/kirill/Downloads/names/yob1880.txt', names= ['name', 'sex', 'births']) names1880 Explanation: Загрузим файл о именах,поле и числе детей с сайта https://www.ssa.gov/oact/babynames/limits.html Собер...
635
Given the following text description, write Python code to implement the functionality described below step by step Description: Use decision optimization to determine Cloud balancing. This tutorial includes everything you need to set up decision optimization engines, build mathematical programming models, and a solve...
Python Code: import sys try: import docplex.mp except: raise Exception('Please install docplex. See https://pypi.org/project/docplex/') Explanation: Use decision optimization to determine Cloud balancing. This tutorial includes everything you need to set up decision optimization engines, build mathematical prog...
636
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: MNIST Test WNixalo 2018/5/19-20;25-26 Making sure I have a working baseline for the MNIST dataset. PyTorch version Step2: 1. Data 1.1 PyTorch method Step4: 1.1.1 Aside Step5: 1.3 F...
Python Code: %matplotlib inline %reload_ext autoreload %autoreload 2 import torch import torchvision import torch.nn as nn import torch.nn.functional as F import numpy as np from pathlib import Path import os import struct # for IDX conversion import gzip # for IDX conversion from urllib.request import urlretriev...
637
Given the following text description, write Python code to implement the functionality described below step by step Description: Препроцессинг фич Step1: Обучение моделей Step2: Submission
Python Code: # train_raw = pd.read_csv("data/train.csv") train_raw = pd.read_csv("data/train_without_noise.csv") macro = pd.read_csv("data/macro.csv") train_raw.head() def preprocess_anomaly(df): df["full_sq"] = map(lambda x: x if x > 10 else float("NaN"), df["full_sq"]) df["life_sq"] = map(lambda x: x if x > 5...
638
Given the following text description, write Python code to implement the functionality described below step by step Description: Neural Nets for Digit Classification by Khaled Nasr as a part of a <a href="https Step1: Creating the network To create a neural network in shogun, we'll first create an instance of NeuralN...
Python Code: %pylab inline %matplotlib inline import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') from scipy.io import loadmat from shogun import features, MulticlassLabels, Math # load the dataset dataset = loadmat(os.path.join(SHOGUN_DATA_DIR, 'multiclass/usps.mat')) Xall = dataset['data'] # the u...
639
Given the following text description, write Python code to implement the functionality described below step by step Description: Generic fit for approximating with a polynomial Step1: Define a quality-of-fit measure, $\chi^2$ Step2: We want to minimized $\chi^2$. Take derivative wrt the coefficients ($a_k$) and set ...
Python Code: f = Symbol('f') # Function to approximate f_approx = Symbol('fbar') # Approximating function w = Symbol('w') # weighting function chi2 = Symbol('chi^2') f, f_approx, w, chi2 M = Symbol('M', integer=True) k = Symbol('k', integer=True,positive=True) a = IndexedBase('a',(M,)) # coefficient h = IndexedBase...
640
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab Step1: Some helper functions Step2: Plotting the data Step3: 2. Build a Linear Regression Model Create a regression model and assign the weights to the array bmi_life_model. Fit the m...
Python Code: import numpy as np import pandas as pd # TODO: Load the data in Pandas bmi_life_data = None # Print the data bmi_life_data Explanation: Lab: Predicting Life Expectancy from BMI in Countries using Linear Regression In this lab, you'll be working with data on the average life expectancy at birth and the aver...
641
Given the following text description, write Python code to implement the functionality described below step by step Description: Software Engineering for Data Scientists Sophisticated Data Manipulation DATA 515 A 1. Python's Data Science Ecosystem With this simple Python computation experience under our belt, we can n...
Python Code: import numpy as np Explanation: Software Engineering for Data Scientists Sophisticated Data Manipulation DATA 515 A 1. Python's Data Science Ecosystem With this simple Python computation experience under our belt, we can now move to doing some more interesting analysis. Python's Data Science Ecosystem In a...
642
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mohc', 'sandbox-1', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: MOHC Source ID: SANDBOX-1 Topic: Ocnbgchem Sub-Topics: Tracers. Prop...
643
Given the following text description, write Python code to implement the functionality described below step by step Description: Accessing Databases via Web APIs Step1: 1. Constructing API GET Request In the first place, we know that every call will require us to provide Step2: You often want to send some sort of da...
Python Code: # Import required libraries import requests import json from __future__ import division import math import csv import matplotlib.pyplot as plt Explanation: Accessing Databases via Web APIs End of explanation # set key key="be8992a420bfd16cf65e8757f77a5403:8:44644296" # set base url base_url="http://api.nyt...
644
Given the following text description, write Python code to implement the functionality described below step by step Description: Grove Temperature Sensor 1.2 This example shows how to use the Grove Temperature Sensor v1.2. You will also see how to plot a graph using matplotlib. The Grove Temperature sensor produces an...
Python Code: from pynq.overlays.base import BaseOverlay base = BaseOverlay("base.bit") Explanation: Grove Temperature Sensor 1.2 This example shows how to use the Grove Temperature Sensor v1.2. You will also see how to plot a graph using matplotlib. The Grove Temperature sensor produces an analog signal, and requires a...
645
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: repeat(1,10000)重复一次,每次10000遍 Step2: 这个就没有重复多少次,就一次,一次10000遍 注意这里timeit.timeit的函数声明,第三个参数是timer,为了避过该参数,到了number这里,显式的声明该参数
Python Code: setup_sum='sum=0' run_sum= for i in range(1,1000): if i % 3 ==0: sum = sum + i print(timeit.Timer(run_sum, setup="sum=0").repeat(1,10000)) Explanation: repeat(1,10000)重复一次,每次10000遍 End of explanation t=timeit.timeit(run_sum,setup_sum,number=10000) print("Time for built-in sum(): {}".format(t)) ...
646
Given the following text description, write Python code to implement the functionality described below step by step Description: Contexts The Vcsn platform relies on a central concept Step1: If instead of a simple accepter that returns "yes" or "no", you want to compute an integer, work in $\mathbb{Z}$ Step2: To use...
Python Code: import vcsn vcsn.context('lal<char(abc)>, b') Explanation: Contexts The Vcsn platform relies on a central concept: "contexts". They denote typing information about automata, rational expressions, etc. This information is alike a function type: an input type (the label), and an output type (the weight). C...
647
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: plot line chats between two arrays k and l
Python Code:: import matplotlib.pyplot as plt plt.plot(k,l)
648
Given the following text description, write Python code to implement the functionality described below step by step Description: Properties of Rectangular Waveguide Introduction This example demonstrates how to use scikit-rf to calculate some properties of rectangular waveguide. For more information regarding the theo...
Python Code: %matplotlib inline import skrf as rf rf.stylely() # imports from scipy.constants import mil,c from skrf.media import RectangularWaveguide, Freespace from skrf.frequency import Frequency import matplotlib as mpl # plot formating mpl.rcParams['lines.linewidth'] = 2 # create frequency objects for standard b...
649
Given the following text description, write Python code to implement the functionality described below step by step Description: Module 2 Step1: As the tide moves through the Strait, it creates a change in the elevation of the water surface. Below we'll cycle through a tidal cycle and look at how the tide moves throu...
Python Code: import tydal.module2_utils as tide import tydal.quiz2 stationmap = tide.add_station_maps() stationmap Explanation: Module 2: Tides in the Puget Sound Learning Objectives I. Tidal Movement II. Tidal Cycle and Connection to Sea Surface Elevation Let's take a closer look at the movement of tides through the ...
650
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have a table of measured values for a quantity that depends on two parameters. So say I have a function fuelConsumption(speed, temperature), for which data on a mesh are known.
Problem: import numpy as np import scipy.interpolate s = np.linspace(-1, 1, 50) t = np.linspace(-2, 0, 50) x, y = np.ogrid[-1:1:10j,-2:0:10j] z = (x + y)*np.exp(-6.0 * (x * x + y * y)) spl = scipy.interpolate.RectBivariateSpline(x, y, z) result = spl(s, t, grid=False)
651
Given the following text description, write Python code to implement the functionality described below step by step Description: Data were munged here. Step1: <h5>First Step2: <h3>When did River Grove open, when did the last owners take over, and how many companies have owned the facility?</h3> Step3: <h3>How many ...
Python Code: import pandas as pd import numpy as np from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) df = pd.read_csv('../../data/processed/complaints-3-29-scrape.csv') owners = pd.read_csv('../../data/raw/APD_HistOwner.csv') Explanation: Data were mun...
652
Given the following text description, write Python code to implement the functionality described below step by step Description: A Network Tour of Data Science Pierre Vandergheynst, Full Professor, and Michaël Defferrard, PhD student, EPFL LTS2. Exercise 5 Step1: 1 Graph Goal Step2: Step 2 Step3: Step 3 Step4: Ste...
Python Code: import numpy as np import scipy.spatial import matplotlib.pyplot as plt %matplotlib inline Explanation: A Network Tour of Data Science Pierre Vandergheynst, Full Professor, and Michaël Defferrard, PhD student, EPFL LTS2. Exercise 5: Graph Signals and Fourier Transform The goal of this exercise is to experi...
653
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1><span style="color Step1: Species tree model Step2: Coalescent simulations The SNPs output is saved to an HDF5 database file. Step3: [optional] Build an IMAP dictionary A dictionary m...
Python Code: # conda install ipyrad -c conda-forge -c bioconda # conda install ipcoal -c conda-forge import ipyrad.analysis as ipa import ipcoal import toyplot import toytree Explanation: <h1><span style="color:gray">ipyrad-analysis toolkit:</span> distance</h1> Genetic distance matrices are used in many contexts to st...
654
Given the following text description, write Python code to implement the functionality described below step by step Description: Remote Sensing Systems (RSS, http Step2: Weight functions Step3: Netcdf data Step4: We need to calculate the element area (on a unit sphere) as follows Step5: Let's create averaging weig...
Python Code: #!wget http://www.remss.com/data/msu/data/netcdf/uat4_tb_v03r03_avrg_chTLT_197812_201308.nc3.nc #!mv uat4_tb_v03r03_avrg_chTLT_197812_201308.nc3.nc data/ #!wget http://www.remss.com/data/msu/data/netcdf/uat4_tb_v03r03_anom_chTLT_197812_201308.nc3.nc #!mv uat4_tb_v03r03_anom_chTLT_197812_201308.nc3.nc data/...
655
Given the following text description, write Python code to implement the functionality described below step by step Description: Recuperando Tweets Para utilizar qualquer API do Twitter temos que importar os módulos e definir as chaves e tokens de acesso. Step1: Com as chaves e tokens de acesso, iremos criar a autent...
Python Code: import tweepy consumer_key = '' consumer_secret = '' access_token = '' access_token_secret = '' Explanation: Recuperando Tweets Para utilizar qualquer API do Twitter temos que importar os módulos e definir as chaves e tokens de acesso. End of explanation autorizar = tweepy.OAuthHandler(consumer_key, consum...
656
Given the following text description, write Python code to implement the functionality described below step by step Description: User comparison tests Table of Contents Preparation User data vectors User lists Sessions' checkpoints Assembly Time Preparation <a id=preparation /> Step1: Data vectors of users <a id=user...
Python Code: %run "../Functions/1. Google form analysis.ipynb" %run "../Functions/4. User comparison.ipynb" Explanation: User comparison tests Table of Contents Preparation User data vectors User lists Sessions' checkpoints Assembly Time Preparation <a id=preparation /> End of explanation #getAllResponders() setAnswerT...
657
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Exploration of a publicly available dataset. <img align="right" src="http Step1: Two columns that are a mistaken copy of each other?... We also suspect that the 'inactive' column and t...
Python Code: # This exercise is mostly for us to understand what kind of data we have and then # run some simple stats on the fields/values in the data. Pandas will be great for that import pandas as pd pd.__version__ # Set default figure sizes pylab.rcParams['figure.figsize'] = (14.0, 5.0) # This data url can be a web...
658
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', 'miroc', 'miroc-es2l', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: MIROC Source ID: MIROC-ES2L Topic: Atmos Sub-Topics: Dynamical Core, Radiat...
659
Given the following text description, write Python code to implement the functionality described below step by step Description: Model Evaluation, Scoring Metrics, and Dealing with Imbalanced Classes In the previous notebook, we already went into some detail on how to evaluate a model and how to pick the best model. S...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np np.set_printoptions(precision=2) from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from sklearn.svm import LinearSVC digits = load_digits() X, y = digits.data, digits.target X_train, X_test, y_...
660
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="#Summary" data-toc-modified-id="Summary-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Summary</a></div><div class="lev1 toc-item"...
Python Code: %run ../../code/version_check.py Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#Summary" data-toc-modified-id="Summary-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Summary</a></div><div class="lev1 toc-item"><a href="#Version-Control" data-toc-modified-id="Version-Control-2"><s...
661
Given the following text description, write Python code to implement the functionality described below step by step Description: Note Step1: How old are the programmers that answered this survey? Step2: What industries are these individuals working in? Step3: What text editor do these individuals prefer? Step4: Wh...
Python Code: # workon dataanalysis - my virtual environment import pandas as pd import matplotlib.pyplot as plt %matplotlib inline # df = pd.read_table('34933-0001-Data.tsv') odf = pd.read_csv('accreditation_2016_03.csv') odf.head() odf.columns odf['Campus_City'].value_counts().head(10) top_cities = odf['Campus_City']....
662
Given the following text description, write Python code to implement the functionality described below step by step Description: NOTAS CALCULAR EN BASE AL MODELO DE CURVAS LAS DERIVADAS Y DONDE HACE EL PICO EN EDAD DOWNLOAD DATA Step1: NEW VARIABLES FOR MODEL Graficos exploratorios Step2: PLOTS FOR LnINCOME ~ EDUC A...
Python Code: #get data getEPHdbf('t310') data1 = pd.read_csv('data/cleanDatat310.csv') data2 = categorize.categorize(data1) data3 = schoolYears.schoolYears(data2) data = make_dummy.make_dummy(data3) dataModel = functionsForModels.prepareDataForModel(data) dataModel.head() Explanation: NOTAS CALCULAR EN BASE AL MODELO D...
663
Given the following text description, write Python code to implement the functionality described below step by step Description: Tensor Transformations Step1: NOTE on notation * _x, _y, _z, ... Step2: Q2. Let X be a tensor [[1, 2], [3, 4]] of int32. Convert the data type of X to float64. Step3: Q3. Let X be a tenso...
Python Code: from __future__ import print_function import tensorflow as tf import numpy as np from datetime import date date.today() author = "kyubyong. https://github.com/Kyubyong/tensorflow-exercises" tf.__version__ np.__version__ sess = tf.InteractiveSession() Explanation: Tensor Transformations End of explanation _...
664
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Assignment 2 - Building CNNs ASSIGNMENT DEADLINE Step4: Convolution Step5: FOR SUBMISSION Step7: Aside Step8: Convolution Step9: ReLU layer Step10: FOR SUBMISSION Step11: Max p...
Python Code: # A bit of setup from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from code_base.classifiers.cnn import * from code_base.data_utils import get_CIFAR2_data from code_base.gradient_check import eval_numerical_gradient_array, eval_numerical_gradient from code_base.layer...
665
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 5 Imports Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell. Step2: Interact with SVG display SVG is a simple way of drawing vec...
Python Code: # YOUR CODE HERE import matplotlib as plt import numpy as np import IPython as ipy from IPython.display import SVG from IPython.html.widgets import interactive, fixed from IPython.html import widgets from IPython.display import display Explanation: Interact Exercise 5 Imports Put the standard imports for M...
666
Given the following text description, write Python code to implement the functionality described below step by step Description: Programmatic Access to Genome Nexus This notebook gives some examples in Python for programmatic access to http Step1: Connect with cBioPortal API cBioPortal also uses Swagger for their API...
Python Code: from bravado.client import SwaggerClient client = SwaggerClient.from_url('https://www.genomenexus.org/v2/api-docs', config={"validate_requests":False,"validate_responses":False}) print(client) dir(client) for a in dir(client): client.__setattr__(a[:-len('-controller')], ...
667
Given the following text description, write Python code to implement the functionality described below step by step Description: Santandar Customer Satisfaction Step 1 Step1: Exercise 1 Find column types for train and test. Exercise 2 Find unique column types for train and test Exercise 3 Find number of rows and col...
Python Code: import numpy as np import pandas as pd #Read train, test and sample submission datasets train = pd.read_csv("../data/train.csv") test = pd.read_csv("../data/test.csv") samplesub = pd.read_csv("../data/sample_submission.csv") Explanation: Santandar Customer Satisfaction Step 1: Frame From frontline support ...
668
Given the following text description, write Python code to implement the functionality described below step by step Description: 9 - Advanced topics - 1 axis torque tube Shading for 1 day (Research Documentation) Recreating JPV 2019 / PVSC 2018 Fig. 13 Calculating and plotting shading from torque tube on 1-axis tracki...
Python Code: import os from pathlib import Path testfolder = str(Path().resolve().parent.parent / 'bifacial_radiance' / 'TEMP' / 'Tutorial_09') if not os.path.exists(testfolder): os.makedirs(testfolder) print ("Your simulation will be stored in %s" % testfolder) # VARIABLES of the simulation: lat = 35.1 # ABQ lon ...
669
Given the following text description, write Python code to implement the functionality described below step by step Description: Collocational Analysis "You shall know a word by the company it keeps!" These are the oft-quoted words of the linguist J.R. Firth in describing the meaning and spirit of collocational analys...
Python Code: # This is where the modules are imported import csv import sys import codecs import nltk import nltk.collocations import collections import statistics from nltk.metrics.spearman import * from nltk.collocations import * from nltk.stem import WordNetLemmatizer from os import listdir from os.path import split...
670
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: How do I apply sort to a pandas groupby operation? The command below returns an error saying that 'bool' object is not callable
Problem: import pandas as pd df = pd.DataFrame({'cokey':[11168155,11168155,11168155,11168156,11168156], 'A':[18,0,56,96,0], 'B':[56,18,96,152,96]}) def g(df): return df.groupby('cokey').apply(pd.DataFrame.sort_values, 'A') result = g(df.copy())
671
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementing the Gradient Descent Algorithm In this lab, we'll implement the basic functions of the Gradient Descent algorithm to find the boundary in a small dataset. First, we'll start wit...
Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd #Some helper functions for plotting and drawing lines def plot_points(X, y): admitted = X[np.argwhere(y==1)] rejected = X[np.argwhere(y==0)] plt.scatter([s[0][0] for s in rejected], [s[0][1] for s in rejected], s = 25, color...
672
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2017 Google LLC. Step1: # Creación y manipulación de tensores Objetivos de aprendizaje Step2: ## Suma de vectores Puedes realizar muchas operaciones matemáticas en los tensores (...
Python Code: # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribute...
673
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This tutorial introduces the basic features for simulating titratable systems via the constant pH method. The constant pH method is one of the methods implemented for simulating...
Python Code: import matplotlib.pyplot as plt import numpy as np import scipy.constants # physical constants import espressomd import pint # module for working with units and dimensions from espressomd import electrostatics, polymer, reaction_ensemble from espressomd.interactions import HarmonicBond ureg = pint.UnitRe...
674
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Pipeline In this notebook, we show how to run the flowers classification workflow as a pipeline Set up Step1: Build the container Step2: Convert JPEG files to TF Records S...
Python Code: %pip install --upgrade --user kfp # CHANGE AS needed REGION = 'us-central1' # Change as needed to a region where you have quota KFPHOST = 'https://40e09ee3a33a422-dot-us-central1.pipelines.googleusercontent.com' # Note name of launched Kubeflow Pipelines cluster PROJECT = !gcloud config get-value project...
675
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Machine Learning to Predict Breast Cancer Matt Massie, UC Berkeley Computer Sciences Machine learning (ML) is data driven. Machine learning algorithms are constructed to learn from and...
Python Code: import numpy as np import pandas as pd def load_data(filename): import csv with open(filename, 'rb') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') df = pd.DataFrame([[-1 if el == '?' else int(el) for el in r] for r in csvreader]) df.columns=["patient_id", "radiu...
676
Given the following text description, write Python code to implement the functionality described below step by step Description: Stiffness matrix for a perfectly square bilinear element. Summary This notebook describes the computational steps required in the computation of the displacement based finite element stiffne...
Python Code: %matplotlib notebook from __future__ import division import numpy as np import sympy as sym import matplotlib.pyplot as plt from IPython.display import Image Explanation: Stiffness matrix for a perfectly square bilinear element. Summary This notebook describes the computational steps required in the comput...
677
Given the following text description, write Python code to implement the functionality described below step by step Description: AutoGraph Step1: Fibonacci numbers https Step2: Generated code Step3: Fizz Buzz https Step4: Generated code Step5: Conway's Game of Life https Step6: Game of Life for AutoGraph Note St...
Python Code: !pip install -U -q tf-nightly-2.0-preview import tensorflow as tf tf = tf.compat.v2 tf.enable_v2_behavior() Explanation: AutoGraph: examples of simple algorithms This notebook shows how you can use AutoGraph to compile simple algorithms and run them in TensorFlow. It requires the nightly build of TensorFlo...
678
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: scikit-image advanced panorama tutorial Enhanced from the original demo as featured in the scikit-image paper. Multiple overlapping images of the same scene, combined into a single im...
Python Code: import numpy as np import matplotlib.pyplot as plt def compare(*images, **kwargs): Utility function to display images side by side. Parameters ---------- image0, image1, image2, ... : ndarrray Images to display. labels : list Labels for the different images. ...
679
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Step1: In this profile, diffusivity drops to 0 at $y=0.5$ and at $y=0$ and $y=1$. In the absence of advection, particles starting out in one half of the domain should remain confin...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import xarray as xr from datetime import timedelta from parcels import ParcelsRandom from parcels import (FieldSet, Field, ParticleSet, JITParticle, AdvectionRK4, ErrorCode, DiffusionUniformKh, AdvectionDiffusionM1, ...
680
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TensorFlow Authors. Step1: Human Pose Classification with MoveNet and TensorFlow Lite This notebook teaches you how to train a pose classification model using MoveNet and...
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...
681
Given the following text description, write Python code to implement the functionality described below step by step Description: Wing modelling example In this example, we demonstrate, how to build up a wing surface by starting with a list of curves. These curves are then interpolated using a B-spline suface interpola...
Python Code: import tigl3.curve_factories import tigl3.surface_factories from OCC.gp import gp_Pnt from OCC.Display.SimpleGui import init_display import numpy as np Explanation: Wing modelling example In this example, we demonstrate, how to build up a wing surface by starting with a list of curves. These curves are the...
682
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Step1: Import raw data The user needs to specify the directories containing the data of interest. Each sample type should have a key which corresponds to the directory path. Ad...
Python Code: import deltascope as ds import deltascope.alignment as ut import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import normalize from scipy.optimize import minimize import os import tqdm import json import time Explanation: Introduction: Landmarks End of explanat...
683
Given the following text description, write Python code to implement the functionality described below step by step Description: Assignment - part 2 Now that we have a better understanding of how to set up a basic neural network in Tensorflow, let's see if we can convert our dataset to a classificiation problem, and t...
Python Code: %matplotlib inline import math import random import seaborn as sns import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_boston '''Since this is a classification problem, we will need to represent our targets as one-hot encoding vectors (see previous lab). To do this we wil...
684
Given the following text description, write Python code to implement the functionality described below step by step Description: The first step in any data analysis is acquiring and munging the data Our starting data set can be found here Step1: Problems Step2: Problems Step3: Problems Step4: If we want to look at...
Python Code: running_id = 0 output = [[0]] with open("E:/output.txt") as file_open: for row in file_open.read().split("\n"): cols = row.split(",") if cols[0] == output[-1][0]: output[-1].append(cols[1]) output[-1].append(True) else: output.append(cols) ...
685
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ncc', 'sandbox-2', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: NCC Source ID: SANDBOX-2 Topic: Ocnbgchem Sub-Topics: Tracers. Proper...
686
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"). Convolutional VAE Step1: Import TensorFlow and enable Eager execution Step2: Load the...
Python Code: # to generate gifs !pip install imageio Explanation: Copyright 2018 The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"). Convolutional VAE: An example with tf.keras and eager <table class="tfo-notebook-buttons" align="left"><td> <a target="_blank" href="https://colab.res...
687
Given the following text description, write Python code to implement the functionality described below step by step Description: Name Step1: Part One Step2: plot xkcd style Step3: Part Two Step4: Calculating the letter frequency for male names. Step5: Calculating the letter frequency for female names. Step6: Ca...
Python Code: #import required libraries import pandas as pd import numpy as np #for counter operations from collections import Counter #for plotting graphs import matplotlib.pyplot as plt # Make the graphs a bit prettier, and bigger pd.set_option('display.mpl_style', 'default') pd.set_option('display.width', 5000) pd.s...
688
Given the following text description, write Python code to implement the functionality described below step by step Description: Figure 4 csv data generation Figure data consolidation for Figure 4, which shows patterns entropy for taxa and across the phylogeny Figure 4a Step1: Figure 4b Step2: Figure 4c Step3: Figu...
Python Code: # read in exported table for genus fig4a_genus = pd.read_csv('../../../data/07-entropy-and-covariation/genus-level-distribution.csv', header=0) # read in exported table for otu fig4a_otu = pd.read_csv('../../../data/07-entropy-and-covariation/otu-level-distribution-400.csv', header=0) Explanation: Figure 4...
689
Given the following text description, write Python code to implement the functionality described below step by step Description: Graded = 9/10 Homework 11 Step1: 4. "Date first observed" is a pretty weird column, but it seems like it has a date hiding inside. Using a function with .apply, transform the string (e.g. "...
Python Code: import pandas as pd dates=['Issue Date', 'Vehicle Expiration Date'] #Importing dates as datetime col_types={'Plate ID': 'str','Date First Observed':'str'} #Importing Plate ID and the Date First Observed as a string, because it has to be made into a time by a function. df=pd.read_csv("small-violations.csv"...
690
Given the following text description, write Python code to implement the functionality described below step by step Description: INTRODUCTION TO COMPUTING WITH TENSOR FLOW Tensor flow can be visualised as computations in a graph with nodes that has definite operations. In simple terms, tensor flow carries out computat...
Python Code: #```python # Objective of the program is to do a simple multiplication on an input tensor of # constant values # To use tensor flow; import it import tensorflow as tf # tf.constant creates constant values. The below command creates a tensor;shape (2,2) # with constant values. Be sure that each element ar...
691
Given the following text description, write Python code to implement the functionality described below step by step Description: Logistic Regression Resources Step1: The logistic regression equation has a very simiar representation like linear regression. The difference is that the output value being modelled is bina...
Python Code: import numpy as np import matplotlib.pyplot as plt import seaborn %matplotlib inline x = np.linspace(-6, 6, num = 1000) plt.figure(figsize = (12,8)) plt.plot(x, 1 / (1 + np.exp(-x))); # Sigmoid Function plt.title("Sigmoid Function"); Explanation: Logistic Regression Resources: Logistic Regression Tutorial ...
692
Given the following text description, write Python code to implement the functionality described below step by step Description: Generating human faces with Adversarial Networks (5 points) <img src="https Step1: Generative adversarial nets 101 <img src="https Step2: Discriminator Discriminator is your usual convolut...
Python Code: from torchvision import utils import matplotlib.pyplot as plt %matplotlib inline import numpy as np import torch, torch.nn as nn import torch.nn.functional as F from itertools import count from IPython import display import warnings import time plt.rcParams.update({'axes.titlesize': 'small'}) from sklearn....
693
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: Retraining an Image Classifier <table class="tfo-notebook-buttons" align="l...
Python Code: # Copyright 2021 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
694
Given the following text description, write Python code to implement the functionality described below step by step Description: 2A.ml - Machine Learning et données cryptées - correction Comment faire du machine learning avec des données cryptées ? Ce notebook propose d'en montrer un principe exposés CryptoNets Step1:...
Python Code: %matplotlib inline from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 2A.ml - Machine Learning et données cryptées - correction Comment faire du machine learning avec des données cryptées ? Ce notebook propose d'en montrer un principe exposés CryptoNets: Applying Neural Networks t...
695
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Step1: Note Step2: Definition of the layers So let us define the layers for the convolutional net. In general, layers are assembled in a list. Each element of the list is a tuple ...
Python Code: import os import matplotlib.pyplot as plt %pylab inline import numpy as np from lasagne.layers import DenseLayer from lasagne.layers import InputLayer from lasagne.layers import DropoutLayer from lasagne.layers import Conv2DLayer from lasagne.layers import MaxPool2DLayer from lasagne.nonlinearities import ...
696
Given the following text description, write Python code to implement the functionality described below step by step Description: Mastr Mastr es la nueva herramienta de valoración y agregación diseñada encima de PALM, que permite describir carteras y escenarios de riesgo de manera separada a la implementación de los pr...
Python Code: from mastr.idn.sandbox import Sandbox sandbox = Sandbox() Explanation: Mastr Mastr es la nueva herramienta de valoración y agregación diseñada encima de PALM, que permite describir carteras y escenarios de riesgo de manera separada a la implementación de los pricers y los objetos. PALM se utiliza para pode...
697
Given the following text description, write Python code to implement the functionality described below step by step Description: Matplotlib Exercise 1 Imports Step1: Line plot of sunspot data Download the .txt data for the "Yearly mean total sunspot number [1700 - now]" from the SILSO website. Upload the file to the ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np Explanation: Matplotlib Exercise 1 Imports End of explanation import os assert os.path.isfile('yearssn.dat') Explanation: Line plot of sunspot data Download the .txt data for the "Yearly mean total sunspot number [1700 - now]" from the S...
698
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate ...
Python Code: import numpy as np import tensorflow as tf with open('reviews.txt', 'r') as f: reviews = f.read() with open('labels.txt', 'r') as f: labels = f.read() reviews[:2000] Explanation: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent neural network that performs sentiment ana...
699
Given the following text description, write Python code to implement the functionality described below step by step Description: Titanic 沉没 这是一个分类任务,特征包含离散特征和连续特征,数据如下:Kaggle地址。目标是根据数据特征预测一个人是否能在泰坦尼克的沉没事故中存活下来。接下来解释下数据的格式: survival 目标列,是否存活,1代表存活 (0 = No; 1 = Yes) pclass 乘坐的舱位级别 (1 = 1st; 2 = 2nd; 3 ...
Python Code: # -*- coding: UTF-8 -*- %matplotlib inline import pandas as pd import string import numpy as np import matplotlib.pyplot as plt from sklearn import preprocessing train = pd.read_csv('train.csv') test = pd.read_csv('test.csv') def substrings_in_string(big_string, substrings): for substring in substrings...