Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
13,500
Given the following text description, write Python code to implement the functionality described below step by step Description: MNIST classification with Vowpal Wabbit Neural Net Step1: Train I found some help with parameters here Step2: Predict -t is for test file -i specifies the model file created earlier...
Python Code: from __future__ import division import re import numpy as np from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt %matplotlib inline #%qtconsole Explanation: MNIST classification with Vowpal Wabbit Neural Net End of explanation !rm train.vw.cache !rm mnist_train_nn.model !vw -d data...
13,501
Given the following text description, write Python code to implement the functionality described below step by step Description: Keras Toy 2D binary classification Install Keras https Step1: Make the dataset Step2: Make the classifier Step3: Bonnus
Python Code: import tensorflow as tf tf.__version__ import keras keras.__version__ import h5py h5py.__version__ import pydot pydot.__version__ Explanation: Keras Toy 2D binary classification Install Keras https://keras.io/#installation Install dependencies Install TensorFlow backend: https://www.tensorflow.org/install/...
13,502
Given the following text description, write Python code to implement the functionality described below step by step Description: ipynb for a 2-D CNN for classifying ECGs Best results found so far used Step9: Import and process data Step10: Neural Network Step11: Test accuracy of model(s) 20% of training data held b...
Python Code: import tensorflow as tf #import tensorflow.contrib.learn.python.learn as learn import tflearn import scipy as sp import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from random import shuffle, randint from sklearn.utils import shuffle as mutualShuf import os import ...
13,503
Given the following text description, write Python code to implement the functionality described below step by step Description: Day 11 Step1: Functions for parsing the initial state Map the floors to integers Step2: Parse an item (microchip or generator) Step3: Parse all items on a floor Step4: Use these function...
Python Code: with open("input/day11.txt", "r") as f: inputLines = tuple(line.strip() for line in f) import itertools import re Explanation: Day 11: Radioisotope Thermoelectric Generators End of explanation floors = { "first" : 1, "second" : 2, "third" : 3, "fourth" : 4, } Explanation: Functions fo...
13,504
Given the following text description, write Python code to implement the functionality described below step by step Description: Tree-based Methods Tree-based methods can be used to solve regression and classification problems. Decision Trees A decision tree is a tree structure that partition data points into regions...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline df = pd.read_csv('data/titanic-train.csv') df.head() df['Survival State'] = df['Survived'].apply(lambda x: 'Survived' if x == 1 else 'Died') df['Survival State'].value_counts() Explanation: Tree-...
13,505
Given the following text description, write Python code to implement the functionality described below step by step Description: Language modeling Data The large movie view dataset contains a collection of 50,000 reviews from IMDB. The dataset contains an even number of positive and negative reviews. The authors consi...
Python Code: PATH='data/aclImdb/' TRN_PATH = 'train/all/' VAL_PATH = 'test/all/' TRN = f'{PATH}{TRN_PATH}' VAL = f'{PATH}{VAL_PATH}' %ls {PATH} Explanation: Language modeling Data The large movie view dataset contains a collection of 50,000 reviews from IMDB. The dataset contains an even number of positive and negative...
13,506
Given the following text description, write Python code to implement the functionality described below step by step Description: Overview The notebook shows how the lime_image tools can be applied to a smaller dataset like mnist. The dataset is very low resolution and allows quite a bit of rapid-iteration. Step2: Set...
Python Code: import numpy as np import matplotlib.pyplot as plt from skimage.color import gray2rgb, rgb2gray, label2rgb # since the code wants color images from sklearn.datasets import fetch_openml mnist = fetch_openml('mnist_784') # make each image color so lime_image works correctly X_vec = np.stack([gray2rgb(iimg) f...
13,507
Given the following text description, write Python code to implement the functionality described below step by step Description: We'll start with this image Step1: And here it is now that we've blurred it
Python Code: imgpath = 'images/original/image.bmp' blurredpath = 'images/image_blurred.bmp' img = Image.open(imgpath) blurred = img.copy().filter(ImageFilter.BLUR) blurred.save(blurredpath) Explanation: We'll start with this image: End of explanation [red_flipped, green_flipped, blue_flipped] = compare_images(imgpath, ...
13,508
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create Dataframe Step2: Create Functions To Process Data Step3: Create A Pipeline Of Those Functions
Python Code: import pandas as pd Explanation: Title: Create A Pipeline In Pandas Slug: pandas_create_pipeline Summary: Create a pipeline in pandas. Date: 2017-01-16 12:00 Category: Python Tags: Data Wrangling Authors: Chris Albon Pandas' pipeline feature allows you to string together Python functions in order to bui...
13,509
Given the following text description, write Python code to implement the functionality described below step by step Description: 2A.eco - Traitement automatique de la langue en Python - correction Correction d'exercices liés au traitement automatique du langage naturel. Step1: On télécharge les données textuelles néc...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 2A.eco - Traitement automatique de la langue en Python - correction Correction d'exercices liés au traitement automatique du langage naturel. End of explanation import nltk nltk.download('stopwords') Explanation: On télécharge les...
13,510
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', 'mpi-m', 'mpi-esm-1-2-lr', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: MPI-M Source ID: MPI-ESM-1-2-LR Topic: Aerosol Sub-Topics: Transpor...
13,511
Given the following text description, write Python code to implement the functionality described below step by step Description: SiPANN We can also leverage the sipann compact model library. SIPANN provides with a linear regression fit from mode solver simulations to compute the Sparameters. Straight Step1: Coupler r...
Python Code: import numpy as np import matplotlib.pyplot as plt import gdsfactory as gf import gdsfactory.simulation.sipann as gs def pltAttr(x, y, title=None, legend="upper right", save=None): if legend is not None: plt.legend(loc=legend) plt.xlabel(x) plt.ylabel(y) if title is not None: ...
13,512
Given the following text description, write Python code to implement the functionality described below step by step Description: 9. Audience Upload to GMP GMP and Google Ads Connector is used to upload audience data to GMP (e.g. Google Analytics, Campaign Manager) or Google Ads in an automatic and reliable way. Follow...
Python Code: # Add custom utils module to Python environment import os import sys sys.path.append(os.path.abspath(os.pardir)) from IPython import display from utils import helpers Explanation: 9. Audience Upload to GMP GMP and Google Ads Connector is used to upload audience data to GMP (e.g. Google Analytics, Campaign ...
13,513
Given the following text description, write Python code to implement the functionality described below step by step Description: SciPy 2016 Scikit-learn Tutorial Out-of-core Learning - Large Scale Text Classification for Sentiment Analysis Scalability Issues The sklearn.feature_extraction.text.CountVectorizer and skle...
Python Code: from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer(min_df=1) vectorizer.fit([ "The cat sat on the mat.", ]) vectorizer.vocabulary_ Explanation: SciPy 2016 Scikit-learn Tutorial Out-of-core Learning - Large Scale Text Classification for Sentiment Analysis Scalabilit...
13,514
Given the following text description, write Python code to implement the functionality described below step by step Description: Continuous Training with AutoML Vertex Pipelines with Batch Predictions Learning Objectives Step1: BigQuery Data If you have not gone through the KFP Walkthrough lab, you will need to run t...
Python Code: import os from google.cloud import aiplatform REGION = "us-central1" PROJECT = !(gcloud config get-value project) PROJECT = PROJECT[0] os.environ["PROJECT"] = PROJECT # Set `PATH` to include the directory containing KFP CLI PATH = %env PATH %env PATH=/home/jupyter/.local/bin:{PATH} Explanation: Continuous ...
13,515
Given the following text description, write Python code to implement the functionality described below step by step Description: Weight Initialization In this lesson, you'll learn how to find good initial weights for a neural network. Having good initial weights can place the neural network close to the optimal soluti...
Python Code: %matplotlib inline import tensorflow as tf import helper from tensorflow.examples.tutorials.mnist import input_data print('Getting MNIST Dataset...') mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) print('Data Extracted.') Explanation: Weight Initialization In this lesson, you'll learn how t...
13,516
Given the following text description, write Python code to implement the functionality described below step by step Description: Python example using Spark SQL over Cloudant as a source This sample notebook is written in Python and expects the Python 2.7.5 runtime. Make sure the kernel is started and you are connect t...
Python Code: # Import Python stuff import pprint from collections import Counter # Import PySpark stuff from pyspark.sql import * from pyspark.sql.functions import udf, asc, desc from pyspark import SparkContext, SparkConf from pyspark.sql.types import IntegerType Explanation: Python example using S...
13,517
Given the following text description, write Python code to implement the functionality described below step by step Description: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9. This kind of neural network is used in a ...
Python Code: # Import Numpy, TensorFlow, TFLearn, and MNIST data import numpy as np import tensorflow as tf import tflearn import tflearn.datasets.mnist as mnist Explanation: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-...
13,518
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) Explanation: Language Translation In this project, you’re going ...
13,519
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Is it possible to delete or insert a step in a sklearn.pipeline.Pipeline object?
Problem: import numpy as np import pandas as pd from sklearn.pipeline import Pipeline from sklearn.svm import SVC from sklearn.decomposition import PCA from sklearn.preprocessing import PolynomialFeatures estimators = [('reduce_poly', PolynomialFeatures()), ('dim_svm', PCA()), ('sVm_233', SVC())] clf = Pipeline(estimat...
13,520
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Theano For a Theano tutorial please see Step1: Now you can invoke f and pass the input values, i.e. f(1,1), f(10,-3) and the result for this operation is returned. Step2: P...
Python Code: import theano import theano.tensor as T x = T.dscalar('x') #First input variable to the compute graph y = T.dscalar('y') #Second input variable to the compute graph z = 3*x + x*y + 3*y #Our formula we like to compute #Compile for the output z, given the inputs x and y f = theano.function(inputs=[x,y], outp...
13,521
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', 'cas', 'sandbox-2', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: CAS Source ID: SANDBOX-2 Topic: Ocean Sub-Topics: Timestepping Framework, Adve...
13,522
Given the following text description, write Python code to implement the functionality described below step by step Description: Heads-up The following code models an inverted pendulum, and uses a GP model to determine the safe region of attraction (ROA). The following is inteded to illustrate the algorithm, not to be...
Python Code: n = 2 m = 1 # 'Wrong' model parameters mass = 0.1 friction = 0. length = 0.5 gravity = 9.81 inertia = mass * length ** 2 # True model parameters true_mass = 0.15 true_friction = 0.05 true_length = length true_inertia = true_mass * true_length ** 2 # Input saturation x_max = np.deg2rad(30) u_max = gravity *...
13,523
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify ...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mpi-m', 'sandbox-3', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: MPI-M Source ID: SANDBOX-3 Topic: Seaice Sub-Topics: Dynamics, Thermodynam...
13,524
Given the following text description, write Python code to implement the functionality described below step by step Description: More SQL Let's grab a fairly large dataset, load it into a database, and work with it. Getting your data Capital Bikeshare trip data is a fun source of transactional data. We can work with ...
Python Code: !wget https://www.capitalbikeshare.com/assets/files/trip-history-data/2013-Q1-Trips-History-Data.zip Explanation: More SQL Let's grab a fairly large dataset, load it into a database, and work with it. Getting your data Capital Bikeshare trip data is a fun source of transactional data. We can work with one...
13,525
Given the following text description, write Python code to implement the functionality described below step by step Description: Preprocessing functional near-infrared spectroscopy (fNIRS) data This tutorial covers how to convert functional near-infrared spectroscopy (fNIRS) data from raw measurements to relative oxyh...
Python Code: import os import numpy as np import matplotlib.pyplot as plt from itertools import compress import mne fnirs_data_folder = mne.datasets.fnirs_motor.data_path() fnirs_cw_amplitude_dir = os.path.join(fnirs_data_folder, 'Participant-1') raw_intensity = mne.io.read_raw_nirx(fnirs_cw_amplitude_dir, verbose=True...
13,526
Given the following text description, write Python code to implement the functionality described below step by step Description: Automated Clustering of Similar Amendments The Italian Senate is clogged by computer-generated amendments. This notebook aims to cluster similar amendments in an automated fashion, so that t...
Python Code: import os import re from itertools import combinations import xml.etree.ElementTree as ET from matplotlib import pyplot as plt from scipy.cluster.hierarchy import dendrogram, linkage %matplotlib inline DATA_FOLDER = 'data/cirinna' NAMESPACE = {'an': 'http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD03'}...
13,527
Given the following text description, write Python code to implement the functionality described below step by step Description: A recursive neural network that decides how many times to run itself Produces variable-length outputs for static-length inputs. Step1: The neural network accepts an input vector of length 2...
Python Code: import numpy as np X = np.array([[0,0],[0,1],[1,0],[1,1]]) y = np.array([[0],[0,0],[0,0,0],[0,0,0,0]]) def sigmoid(x): return np.matrix(1.0 / (1.0 + np.exp(-x))) def relu(x): alpha = 0.01 return np.maximum(x, (alpha * x)) #initialize random weights numIn, numHid, numOut = 2, 3, 2 theta1 = np.ar...
13,528
Given the following text description, write Python code to implement the functionality described below step by step Description: Understanding recurrent neural networks This notebook contains the code samples found in Chapter 6, Section 2 of Deep Learning with Python. Note that the original text features far more cont...
Python Code: from keras.layers import SimpleRNN Explanation: Understanding recurrent neural networks This notebook contains the code samples found in Chapter 6, Section 2 of Deep Learning with Python. Note that the original text features far more content, in particular further explanations and figures: in this notebook...
13,529
Given the following text description, write Python code to implement the functionality described below step by step Description: Text Classification using TensorFlow and Google Cloud - Part 1 This bigquery-public-data Step1: Importing libraries Step2: 1. Source Query Step3: 2. Raw metadata Step4: 3. Preprocessing ...
Python Code: import os class Params: pass # Set to run on GCP Params.GCP_PROJECT_ID = 'ksalama-gcp-playground' Params.REGION = 'europe-west1' Params.BUCKET = 'ksalama-gcs-cloudml' Params.PLATFORM = 'local' # local | GCP Params.DATA_DIR = 'data/news' if Params.PLATFORM == 'local' else 'gs://{}/data/news'.format(Par...
13,530
Given the following text description, write Python code to implement the functionality described below step by step Description: Unterricht zur Kammerprüfung Step1: Sommer_2014 Step2: Frage 1 Erstellen Sie eine SQL-Abfrage, die alle Artikel auflistet, deren Artikelbezeichnungen die Zeichenketten "Schmerzmittel" oder...
Python Code: %load_ext sql Explanation: Unterricht zur Kammerprüfung End of explanation %sql mysql://steinam:steinam@localhost/sommer_2014 Explanation: Sommer_2014 End of explanation %%sql select * from artikel where Art_Bezeichnung like '%Schmerzmittel%' or Art_Bezeichnung like '%schmerzmittel%'; Explanation...
13,531
Given the following text description, write Python code to implement the functionality described below step by step Description: Turning transaction data into dimensional data Let's grab a fairly large dataset, load it into a database, and create a simple dimensional model with one fact table and one dimension from it...
Python Code: !wget https://www.capitalbikeshare.com/assets/files/trip-history-data/2013-Q1-Trips-History-Data.zip !wget https://www.capitalbikeshare.com/assets/files/trip-history-data/2013-Q2-Trips-History-Data.zip !wget https://www.capitalbikeshare.com/assets/files/trip-history-data/2013-Q3-Trips-History-Data.zip !wge...
13,532
Given the following text description, write Python code to implement the functionality described below step by step Description: Self-Driving Car Engineer Nanodegree Deep Learning Project Step1: Step 1 Step2: 3. Include an exploratory visualization of the dataset Visualize the German Traffic Signs Dataset using the ...
Python Code: # Load pickled data import pickle from keras.datasets import cifar10 from sklearn.model_selection import train_test_split (X_train_temp, y_train_temp), (X_test, y_test) = cifar10.load_data() # y_train.shape is 2d, (50000, 1). While Keras is smart enough to handle this # it's a good idea to flatten the arra...
13,533
Given the following text description, write Python code to implement the functionality described. Description: Find sum of digits in factorial of a number Function to multiply x with large number stored in vector v . Result is stored in v . ; Calculate res + prev carry ; updation at ith position ; Returns sum of digits...
Python Code: def multiply(v , x ) : carry = 0 size = len(v ) for i in range(size ) : res = carry + v[i ] * x v[i ] = res % 10 carry = res // 10  while(carry != 0 ) : v . append(carry % 10 ) carry //= 10   def findSumOfDigits(n ) : for i in range(1 , n + 1 ) : multiply(v , i )  sum = 0...
13,534
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to LAPM LAPM is a python package for the analysis of linear autonomous pool (compartmental) models. It can be used to obtain a large set of different system-level diagnostics of...
Python Code: from sympy import * from LAPM import * from LAPM.linear_autonomous_pool_model import LinearAutonomousPoolModel Explanation: Introduction to LAPM LAPM is a python package for the analysis of linear autonomous pool (compartmental) models. It can be used to obtain a large set of different system-level diagnos...
13,535
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Convolutional Networks So far we have worked with deep fully-connected networks, using them to explore different optimization strategies and network architectures. Fully-connected net...
Python Code: # As usual, a bit of setup from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.cnn import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient_array, eval_numerical_gradient from cs231n.layers...
13,536
Given the following text description, write Python code to implement the functionality described below step by step Description: Overview of artifact detection This tutorial covers the basics of artifact detection, and introduces the artifact detection tools available in MNE-Python. We begin as always by importing the...
Python Code: import os import numpy as np import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file) raw.crop(0, 60).load_data() # j...
13,537
Given the following text description, write Python code to implement the functionality described below step by step Description: An object-oriented, containerized model of music notation Abjad extends the Python programming language with an object-oriented, containerized model of common practice music notation. Let's ...
Python Code: note = abjad.Note("d''2.") abjad.show(note) Explanation: An object-oriented, containerized model of music notation Abjad extends the Python programming language with an object-oriented, containerized model of common practice music notation. Let's explore the notes, rests and chords that make up the simples...
13,538
Given the following text description, write Python code to implement the functionality described. Description: Compress a Binary Tree from top to bottom with overlapping condition Structure of a node of th tree ; Function to compress all the nodes on the same vertical line ; Stores node by compressing all nodes on the ...
Python Code: class TreeNode : def __init__(self , val = ' ' , left = None , right = None ) : self . val = val self . left = left self . right = right   def evalComp(arr ) : ans = 0 getBit = 1 for i in range(32 ) : S = 0 NS = 0 for j in arr : if getBit & j : S += 1  else : NS += 1...
13,539
Given the following text description, write Python code to implement the functionality described below step by step Description: Business Feasibility Overview The purpose of this notebook is to analyze the feasibility of a business based on its intrinsic probabilities of loss/gain and return on investment in the cases...
Python Code: # Numpy import numpy as np # Scipy from scipy import stats from scipy import linspace # Plotly from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import plotly.graph_objs as go init_notebook_mode(connected=True) # Offline plotting Explanation: Business Feasibility Overview The pu...
13,540
Given the following text description, write Python code to implement the functionality described below step by step Description: "Spatial Clustering" - the Galaxy Correlation Function The degree to which objects positions are correlated with each other - "clustered" - is of great interest in astronomy. We expect gala...
Python Code: %load_ext autoreload %autoreload 2 from __future__ import print_function import numpy as np import SDSS import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import copy # We want to select galaxies, and then are only interested in their positions on the sky. data = pd.read_csv("downloads/...
13,541
Given the following text description, write Python code to implement the functionality described below step by step Description: The rise of Newsletter Spam Step1: Connect to the Gmail API To get our emails, we will use the Gmail API. To to this we first need to enable the Gmail api and download a credential file. In...
Python Code: import httplib2 import os import base64 import numpy as np import pandas as pd import datetime import logging import time import matplotlib.pyplot as plt import seaborn as sns from typing import Union, Any, List, Optional, cast from googleapiclient.discovery import build from google_auth_oauthlib.flow impo...
13,542
Given the following text description, write Python code to implement the functionality described below step by step Description: ISWC 2017 RSP Demo Ensure you have the latest version of rsplib Step1: A simple Experiment Using CITYBENCH Streams Step2: Deploy The Experiment, i.e. register streams, queries and observer...
Python Code: !pip install rsplib --upgrade from rsplib.processing import execute, deploy from rsplib.processing.consumer.query import * from rsplib.experiments import Experiment, ExperimentExecution, Report Explanation: ISWC 2017 RSP Demo Ensure you have the latest version of rsplib End of explanation #create the exper...
13,543
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify ...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'fio-ronm', 'sandbox-2', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: FIO-RONM Source ID: SANDBOX-2 Topic: Seaice Sub-Topics: Dynamics, Therm...
13,544
Given the following text description, write Python code to implement the functionality described below step by step Description: Using a Pre-trained PyTorch Model for Inference In this demo, we will use a pre-trained model to perform inference on a single image. There are 3 components to this demo Step1: Model Step2...
Python Code: import torch import torchvision import torchvision.transforms as transforms import timm from einops import rearrange from PIL import Image Explanation: Using a Pre-trained PyTorch Model for Inference In this demo, we will use a pre-trained model to perform inference on a single image. There are 3 compon...
13,545
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to OpenFermion A codealong of openfermion_tutorial.ipynb Wayne H Nixalo – 2018/6/27 <div class="alert alert-info"> Note that all the examples below must be run sequentially with...
Python Code: from openfermion.ops import FermionOperator my_term = FermionOperator(((3,1), (1,0))) print(my_term) my_term = FermionOperator('3^ 1') print(my_term) Explanation: Introduction to OpenFermion A codealong of openfermion_tutorial.ipynb Wayne H Nixalo – 2018/6/27 <div class="alert alert-info"> Note that all th...
13,546
Given the following text description, write Python code to implement the functionality described below step by step Description: 第二章 探索数据 加载CSV 通常NumPy, pandas和matplotlib是用来进行数据分析的常用包 Step1: 创建一个变量url,指向一个csv文件。然后通过read_csv()函数来加载它。 Step2: 变量df包含了一个DataFrame对象,一种二维表的pandas数据结构。 接下来就调用head(n)方法来显示前n列的数据吧。notebook会将其显...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline Explanation: 第二章 探索数据 加载CSV 通常NumPy, pandas和matplotlib是用来进行数据分析的常用包 End of explanation url = 'http://aima.cs.berkeley.edu/data/iris.csv' df = pd.read_csv(url,delimiter=',') Explanation: 创建一个变量url,指向一个csv文件。然后通过read_cs...
13,547
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex SDK Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Once you've installed the additional packages, you need to restart the no...
Python Code: import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG Explanation: Vertex SDK: Custom training image classification model for online prediction with explain...
13,548
Given the following text description, write Python code to implement the functionality described below step by step Description: Plot Trajectories with Pictures take dimension (e.g. red) that I've trained the nn features to classify and plot sequences in that dimension. use sequences that have images Step1: Plot Tra...
Python Code: # our lib from lib.resnet50 import ResNet50 from lib.imagenet_utils import preprocess_input, decode_predictions #keras from keras.preprocessing import image from keras.models import Model import glob def preprocess_img(img_path): img = image.load_img(img_path, target_size=(224, 224)) x = image.img...
13,549
Given the following text description, write Python code to implement the functionality described below step by step Description: Shooting victims by block Which Chicago block has the most shooting victims so far this year? Fetch the data from NewsroomDB NewsroomDB is the Tribune's proprietary database for tracking dat...
Python Code: import os import requests def get_table_url(table_name, base_url=os.environ['NEWSROOMDB_URL']): return '{}table/json/{}'.format(os.environ['NEWSROOMDB_URL'], table_name) def get_table_data(table_name): url = get_table_url(table_name) try: r = requests.get(url) return r.json...
13,550
Given the following text description, write Python code to implement the functionality described. Description: Return True if all numbers in the list l are below threshold t. This is how the function will work: below_threshold([1, 2, 4, 10], 100) True This is how the function will work: below_threshold(...
Python Code: def below_threshold(l: list, t: int): for e in l: if e >= t: return False return True
13,551
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 18 Wednesday, November 8th, 2017 Databases with SQlite SQLite Exercises Today you will work with the candidates and contributors datasets to create a database in Python using SQLite....
Python Code: import sqlite3 Explanation: Lecture 18 Wednesday, November 8th, 2017 Databases with SQlite SQLite Exercises Today you will work with the candidates and contributors datasets to create a database in Python using SQLite. The exercises will consist of a sequence of steps to help illustrate basic commands. <a ...
13,552
Given the following text description, write Python code to implement the functionality described below step by step Description: Review from the previous lecture In yesterday's Lecture 2, you learned how to use the numpy module, how to make your own functions, and how to import and export data. Below is a quick review...
Python Code: import numpy as np Explanation: Review from the previous lecture In yesterday's Lecture 2, you learned how to use the numpy module, how to make your own functions, and how to import and export data. Below is a quick review before we move on to Lecture 3. Remember, to use the numpy module, first it must be ...
13,553
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Several pieces of the puzzle have come together lately to really demonstrate the power of the scientific python software packages to handle complex dynamic and controls problems...
Python Code: from IPython.display import SVG SVG(filename='n-pendulum-with-cart.svg') Explanation: Introduction Several pieces of the puzzle have come together lately to really demonstrate the power of the scientific python software packages to handle complex dynamic and controls problems (i.e. IPython notebooks, matpl...
13,554
Given the following text description, write Python code to implement the functionality described below step by step Description: Linear Programming with OR-Tools In this notebook, we do some basic LP solving with Google's OR-Tools. Problems used will be examples in Hamdy Taha's Operations Research Step1: Reddy Mikks ...
Python Code: from ortools.linear_solver import pywraplp Explanation: Linear Programming with OR-Tools In this notebook, we do some basic LP solving with Google's OR-Tools. Problems used will be examples in Hamdy Taha's Operations Research: An Introduction, 9th Edition, which I have in paperback. End of explanation redd...
13,555
Given the following text description, write Python code to implement the functionality described below step by step Description: Training and Serving with TFX and Vertex Pipelines Learning objectives Prepare example data. Create a pipeline. Run the pipeline on Vertex Pipelines. Test with a prediction request. Introduc...
Python Code: # Use the latest version of pip. !pip install --upgrade pip !pip install --upgrade "tfx[kfp]<2" Explanation: Training and Serving with TFX and Vertex Pipelines Learning objectives Prepare example data. Create a pipeline. Run the pipeline on Vertex Pipelines. Test with a prediction request. Introduction In ...
13,556
Given the following text description, write Python code to implement the functionality described below step by step Description: <p style="text-align Step2: 1. Implementar o algoritmo K-means Nesta etapa você irá implementar as funções que compõe o algoritmo do KMeans uma a uma. É importante entender e ler a document...
Python Code: # import libraries # linear algebra import numpy as np # data processing import pandas as pd # data visualization from matplotlib import pyplot as plt # load the data with pandas dataset = pd.read_csv('dataset.csv', header=None) dataset = np.array(dataset) plt.scatter(dataset[:,0], dataset[:,1], s=10) p...
13,557
Given the following text description, write Python code to implement the functionality described below step by step Description: Algorithms Exercise 1 Imports Step3: Word counting Write a function tokenize that takes a string of English text returns a list of words. It should also remove stop words, which are common ...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np Explanation: Algorithms Exercise 1 Imports End of explanation def tokenize(s, stop_words=None, punctuation='`~!@#$%^&*()_-+={[}]|\:;"<,>.?/}\t'): Split a string into a list of words, removing punctuation and stop words. all_...
13,558
Given the following text description, write Python code to implement the functionality described below step by step Description: # Defensive programming (1) How much time do you spend writing software? How much time do you spend debugging that software? It turns out that it is very easy to spend lots of time fi...
Python Code: def cell_volume(X, Y, Z): # Return the volume of a unit cell # described by lattice vectors X, Y and Z # The volume is given by the determinant of # the matrix formed by sticking the three # vectors together. i.e. # # | X[0] Y[0] Z[0] | # V = | X[1] Y[1] Z[1] | # ...
13,559
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...
13,560
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 4 Step1: Polynomial regression, revisited We build on the material from Week 3, where we wrote the function to produce an SFrame with columns containing the powers of a give...
Python Code: import graphlab Explanation: Regression Week 4: Ridge Regression (interpretation) In this notebook, we will run ridge regression multiple times with different L2 penalties to see which one produces the best fit. We will revisit the example of polynomial regression as a means to see the effect of L2 regular...
13,561
Given the following text description, write Python code to implement the functionality described below step by step Description: Try not to peek at the solutions when you go through the exercises. ;-) First let's make sure this notebook works well in both Python 2 and Python 3 Step1: Techniques for Training Deep Nets...
Python Code: from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf tf.__version__ from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("tmp/data/") Explanation: Try not to peek at the solutions when you go through the exercises...
13,562
Given the following text description, write Python code to implement the functionality described below step by step Description: Elemento Beam Fundamento teórico El elemento Beam (viga) es un elemento finito bidimensional donde las coordenadas locales y globales coinciden. Está caracterizado por una función de forma l...
Python Code: %matplotlib inline import numpy as np from nusa import * import itertools import matplotlib.pyplot as plt def pairwise(iterable): #~ "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = itertools.tee(iterable) next(b, None) return zip(a, b) # Input data E = 210e9 # Pa I = 1e-5 L = 1 P = 10e3 nelm...
13,563
Given the following text description, write Python code to implement the functionality described below step by step Description: Hints to know Step1: Example code block print("Hello man" Example maths $$ y = \frac{a}{b+c} $$ $$ \int f(x) dx $$ $$ \int f(x)\,dx $$ Detailed info for LaTex in jupyter Timing code Step2: ...
Python Code: print("Hello man") Explanation: Hints to know End of explanation def fibo(n): if n == 0: return 0 elif n == 1: return 1 return fibo(n-1) + fibo(n-2) %timeit fibo(20) Explanation: Example code block print("Hello man" Example maths $$ y = \frac{a}{b+c} $$ $$ \int f(x) dx $$ $$ \in...
13,564
Given the following text description, write Python code to implement the functionality described below step by step Description: Demonstrate using the simulator for a surface simulation, deterministic integration. Run time Step1: Perform the simulation Step2: Plot pretty pictures of what we just did
Python Code: from tvb.datatypes.cortex import Cortex from tvb.datatypes.local_connectivity import LocalConnectivity from tvb.simulator.lab import * Explanation: Demonstrate using the simulator for a surface simulation, deterministic integration. Run time: approximately 35 s (geodist step of local Connect) + ~5 min (wor...
13,565
Given the following text description, write Python code to implement the functionality described below step by step Description: Remote texting demo Start a Mosquitto container first. For example Step1: Start client Step2: Prepare messages Step3: Send out messages and get asynchonous results Step4: Stop the demo
Python Code: import os import sys import time sys.path.append(os.path.abspath(os.path.join(os.path.pardir, '..\\codes', 'client'))) sys.path.append(os.path.abspath(os.path.join(os.path.pardir, '..\\codes', 'node'))) sys.path.append(os.path.abspath(os.path.join(os.path.pardir, '..\\codes', 'shared'))) sys.path.append(...
13,566
Given the following text description, write Python code to implement the functionality described below step by step Description: Units and Quantities Objectives Use units Create functions that accept quantities as arguments Create new units Basics How do we define a Quantity and which parts does it have? Step1: Quant...
Python Code: from astropy import units as u # Define a quantity length # print it # Type of quantity # Type of unit # Quantity # value # unit # information Explanation: Units and Quantities Objectives Use units Create functions that accept quantities as arguments Create new units Basics How do we define a Quantity and ...
13,567
Given the following text description, write Python code to implement the functionality described below step by step Description: Turn magnitudes into colors Step1: Filter out bad data Step2: Create classification labels Step3: Load the IDs of the narrowband population Step4: Setup locations of images Step5: Copy ...
Python Code: combined["g_minus_r"] = combined.gcmodel_mag - combined.rcmodel_mag combined["r_minus_i"] = combined.rcmodel_mag - combined.icmodel_mag combined["i_minus_z"] = combined.icmodel_mag - combined.zcmodel_mag combined["z_minus_y"] = combined.zcmodel_mag - combined.ycmodel_mag Explanation: Turn magnitudes into c...
13,568
Given the following text description, write Python code to implement the functionality described below step by step Description: STA 208 Step1: Load the following medical dataset with 750 patients. The response variable is survival dates (Y), the predictors are 104 measurements measured at a specific time (numerical ...
Python Code: import numpy as np import pandas as pd # dataset path data_dir = "." Explanation: STA 208: Homework 2 This is based on the material in Chapters 3, 4.4 of 'Elements of Statistical Learning' (ESL), in addition to lectures 4-6. Chunzhe Zhang came up with the dataset and the analysis in the second section. In...
13,569
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="http Step1: The first step in creating your own class is to use the class keyword, then the name of the class as shown in Figure 4. In this course the class parent will always be o...
Python Code: import matplotlib.pyplot as plt %matplotlib inline Explanation: <a href="http://cocl.us/topNotebooksPython101Coursera"><img src = "https://ibm.box.com/shared/static/yfe6h4az47ktg2mm9h05wby2n7e8kei3.png" width = 750, align = "center"></a> <a href="https://www.bigdatauniversity.com"><img src = "https://ibm...
13,570
Given the following text description, write Python code to implement the functionality described below step by step Description: Parsing nemeth.json in python to integrate in pybrl nemeth.json is a file which includes the Nemeth code in order to translate LaTeX files. I found it in the latex2nemeth project by Antonis ...
Python Code: # Import the dependencies import six # Python 2 and 3 compatibility import json # Load/Save JSON import pybrl as brl # pybrl # Load the JSON file jdata = {} with open("nemeth.json", 'r') as f: jdata = json.load(f) jdata.keys() Explanation: Parsing nemeth.json in python to inte...
13,571
Given the following text description, write Python code to implement the functionality described below step by step Description: Finding Lane Lines on the Road In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of indiv...
Python Code: #importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline #reading in an image image = mpimg.imread('test_images/solidWhiteRight.jpg') #printing out some stats and plotting print('This image is:', type(image), 'with dim...
13,572
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step3: Naive forecasting <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step4: Trend and Seasonality Ste...
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...
13,573
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Python as a Calculator Let's try some simple python commands Numbers The interpreter acts as a simple calculator Step1: With Python, use ** operator to calculate powers. Step2: Use e...
Python Code: 4 2 + 2 50 - 5*6 (50-5)*6 8/5 8//5 # Floor division discards the fractional part 8%5 # The % operator return the remainder of the division Explanation: Using Python as a Calculator Let's try some simple python commands Numbers The interpreter acts as a simple calculator: you can type an expression at it ...
13,574
Given the following text description, write Python code to implement the functionality described below step by step Description: Correlação Cruzada - biblioteca Scipy signal.correlate2d Passos para simulação de template matching que tem como objetivo encontrar a localização do olho direito da modelo (Lena) da imagem ...
Python Code: import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg from scipy import signal img = mpimg.imread('../figures/lena_greyscale.png') arr = np.asarray(img) template = np.copy(arr[240:290, 240:290]) #plt.figure(figsize=(15,10)) plt.subplot(1,2,1) plt.title('Template - olhos de Len...
13,575
Given the following text description, write Python code to implement the functionality described below step by step Description: I would want to get rid of all rows missing any of the data before running the sampler. Step1: Do Geweke Test to see if trace has converged. Burn-in looks to be around 2000. Step2: Make pr...
Python Code: train = train[train['longitude'] > 1] train = train[train['latitude'] < 0] train = train[train['construction_year'] != 0] train = train[train['gps_height'] != 0] features = ['longitude','latitude'] trainLoc = train[features] #hasLocIdx = train['longitude']>1 #trainLoc = trainLoc[hasLocIdx] #remove rows wit...
13,576
Given the following text description, write Python code to implement the functionality described below step by step Description: XGBoost Training on AI Platform This notebook uses the Census Income Data Set to demonstrate how to train a model on Ai Platform. How to bring your model to AI Platform Getting your model re...
Python Code: %env PROJECT_ID <YOUR_PROJECT_ID> %env BUCKET_ID <YOUR_BUCKET_ID> %env REGION <REGION> %env TRAINER_PACKAGE_PATH ./census_training %env MAIN_TRAINER_MODULE census_training.train %env JOB_DIR <gs://YOUR_BUCKET_ID/xgb_job_dir> %env RUNTIME_VERSION 1.9 %env PYTHON_VERSION 3.5 ! mkdir census_training Explanati...
13,577
Given the following text description, write Python code to implement the functionality described below step by step Description: Ch 5. Interactive Data Analysis This notebook introduces carrying out interactive data analysis of data in BigQuery using a Jupyter Notebook managed by Vertex AI Workbench. This cell, for ex...
Python Code: a = 3 b = a + 5 print("a={} b={}".format(a,b)) Explanation: Ch 5. Interactive Data Analysis This notebook introduces carrying out interactive data analysis of data in BigQuery using a Jupyter Notebook managed by Vertex AI Workbench. This cell, for example, is a mark-down cell. Which is why you are seeing ...
13,578
Given the following text description, write Python code to implement the functionality described. Description: Cumulative product of digits of all numbers in the given range Function to get product of digits ; Function to find the product of digits of all natural numbers in range L to R ; Iterate between L to R ; Drive...
Python Code: def getProduct(n ) : product = 1 while(n != 0 ) : product = product *(n % 10 ) n = int(n / 10 )  return product  def productinRange(l , r ) : if(r - l > 9 ) : return 0  else : p = 1 for i in range(l , r + 1 ) : p = p * getProduct(i )  return p   l = 11 r = 15 pri...
13,579
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"); Step1: tf.data Step2: Basic mechanics <a id="basic-mechanics"/> To create an input pi...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # 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...
13,580
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Probability Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: Approximate inference for STS models with non-Gaussian observations...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # 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...
13,581
Given the following text description, write Python code to implement the functionality described below step by step Description: Painting OM10 Lens Systems with Synthetic Colors Jenny Kim, Michael Baumer, Phil Marshall The OM10 mock lensed quasar catalog qso_mock.fits contains estimates of the lens galaxy $i$-band mag...
Python Code: import matplotlib.pyplot as plt import seaborn as sns import os, matplotlib, numpy as np import om10, corner from om10 import plotting from __future__ import division, print_function from astropy.table import Table from astropy.io import ascii import pandas as pd sns.set() %load_ext autoreload %autoreload ...
13,582
Given the following text description, write Python code to implement the functionality described below step by step Description: Read a forward operator and display sensitivity maps Forward solutions can be read using read_forward_solution in Python. Step1: Show gain matrix a.k.a. leadfield matrix with sensitivity ma...
Python Code: # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import mne from mne.datasets import sample import matplotlib.pyplot as plt print(__doc__) data_path = sample.data_path() fname = data_path + '/MEG/sample/sa...
13,583
Given the following text description, write Python code to implement the functionality described below step by step Description: Word2Vec Tutorial In case you missed the buzz, word2vec is a widely featured as a member of the “new wave” of machine learning algorithms based on neural networks, commonly referred to as "d...
Python Code: # import modules & set up logging import gensim, logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) sentences = [['first', 'sentence'], ['second', 'sentence']] # train word2vec on the two sentences model = gensim.models.Word2Vec(sentences, min_count=1) Expla...
13,584
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Custom layers <table class="tfo-notebook-buttons" align="left"><td> <a target="_blank" href="https Step2: Layers Step3: The full list of pre...
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...
13,585
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Laminar Pipe Flow</h1> In this first tutorial, you will simulate a laminar pipe flow using the cad file <FONT FACE="courier" style="color Step1: The wall shear stress is defined
Python Code: D = 2.5e-2 # m nu = 15.e-6 #m^2/s rho = 1.2 #kg/m^3 mu = nu/rho R = D/2 Re = 500. Ub = Re * nu / D print("Bulk velocity= %2.2f m/s" %Ub) import numpy as np n = 30 r = np.linspace(0,R,n) U = 2 * Ub * (1 - np.power(r,2)/R**2) import matplotlib.pyplot as plt plt.plot(r,U,linewidth = 2) plt.xlabel(r"$r$ (m)",...
13,586
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial 01 Step1: This scenario, as well as all other scenarios in Flow, is parametrized by the following arguments Step2: 2.2 VehicleParams The VehicleParams class stores state informati...
Python Code: from flow.scenarios.loop import LoopScenario Explanation: Tutorial 01: Running Sumo Simulations This tutorial walks through the process of running non-RL traffic simulations in Flow. Simulations of this form act as non-autonomous baselines and depict the behavior of human dynamics on a network. Similar sim...
13,587
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting the SPY's Future Closing Price with a Multi-Model Forecast Creating many machine learning models to predict future price movements from Redis. How? Uses pricing metrics (hlocv) St...
Python Code: from __future__ import print_function import sys, os, requests, json, datetime # Load the environment and login the user from src.common.load_redten_ipython_env import user_token, user_login, csv_file, run_job, core, api_urls, ppj, rt_url, rt_user, rt_pass, rt_email, lg, good, boom, anmt, mark, ppj, uni_ke...
13,588
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: 迁移学习和微调 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: 数据预处理 数据下载 在本教程中,您将使用包含数千个猫和狗图像的数据集。下载并解...
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...
13,589
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Landice 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', 'noaa-gfdl', 'gfdl-esm2m', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: NOAA-GFDL Source ID: GFDL-ESM2M Topic: Landice Sub-Topics: Glaciers...
13,590
Given the following text description, write Python code to implement the functionality described below step by step Description: A simple Deep Neural Network using Keras In this notebook, we are going to explore a deep neural network to classify MNIST dataset. We have picked Keras, which is high level wrapper over The...
Python Code: from __future__ import print_function import keras # For MNIST dataset from keras.datasets import mnist # Keras model module from keras.models import Sequential # Keras core layers from keras.layers import Dense, Dropout, Flatten # Keras CNN Layers from keras.layers import Conv2D, MaxPooling2D from keras i...
13,591
Given the following text description, write Python code to implement the functionality described. Description: Find 2 ^ ( 2 ^ A ) % B Function to return 2 ^ ( 2 ^ A ) % B ; Base case , 2 ^ ( 2 ^ 1 ) % B = 4 % B ; Driver code ; Print 2 ^ ( 2 ^ A ) % B
Python Code: def F(A , B ) : if(A == 1 ) : return(4 % B ) ;  else : temp = F(A - 1 , B ) ; return(temp * temp ) % B ;   A = 25 ; B = 50 ; print(F(A , B ) ) ;
13,592
Given the following text description, write Python code to implement the functionality described below step by step Description: Load a neuroimaging dataset Step1: Advanced visualization with nilearn Step2: Processing data with nilearn Step3: Check nilearn website http
Python Code: import nibabel as nib fp = '/home/grg/upf/Data/RM/rch2.nii' im = nib.load(fp) print im.header.keys() print im.header['pixdim'] %matplotlib inline im.orthoview() from matplotlib import pyplot as plt import numpy as np d_t1 = np.array(im.dataobj) d2 = d_t1[35,:,:] plt.imshow(d2) fp2 = '/home/grg/upf/Data/RM/...
13,593
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TF-Agents Authors. Step1: SAC minitaur with the Actor-Learner API <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Setu...
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...
13,594
Given the following text description, write Python code to implement the functionality described below step by step Description: Constrained Local Models - Basics The aim of this notebook is to showcase how one can build and fit CLMs to images using menpofit. Note that this notebook assumes that the user has previousl...
Python Code: %matplotlib inline from pathlib import Path path_to_lfpw = Path('/vol/atlas/databases/lfpw') import menpo.io as mio training_images = [] # load landmarked images for i in mio.import_images(path_to_lfpw / 'trainset', verbose=True): # crop image i = i.crop_to_landmarks_proportion(0.1) # convert i...
13,595
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework #4 These problem sets focus on list comprehensions, string operations and regular expressions. Problem set #1 Step1: In the following cell, complete the code with an expression tha...
Python Code: numbers_str = '496,258,332,550,506,699,7,985,171,581,436,804,736,528,65,855,68,279,721,120' Explanation: Homework #4 These problem sets focus on list comprehensions, string operations and regular expressions. Problem set #1: List slices and list comprehensions Let's start with some data. The following cell...
13,596
Given the following text description, write Python code to implement the functionality described below step by step Description: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyri...
Python Code: import random import string import mxnet as mx from mxnet import gluon, np import numpy as onp Explanation: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright owner...
13,597
Given the following text description, write Python code to implement the functionality described below step by step Description: The Shunting Yard Algorithm (Operator Precedence Parsing) The function $\texttt{toInt}(s)$ tries to convert the string $s$ to an integer. If this works out, the integer is returned. Otherw...
Python Code: def toInt(s): try: return int(s) except ValueError: return s toInt('123') toInt('**') Explanation: The Shunting Yard Algorithm (Operator Precedence Parsing) The function $\texttt{toInt}(s)$ tries to convert the string $s$ to an integer. If this works out, the integer is returned...
13,598
Given the following text description, write Python code to implement the functionality described below step by step Description: Evaluation of Poincare Embeddings This notebook demonstrates how well Poincare embeddings perform on the tasks detailed in the original paper about the embeddings. The following two external...
Python Code: %cd ../.. # Some libraries need to be installed that are not part of Gensim ! pip install click>=6.7 nltk>=3.2.5 prettytable>=0.7.2 pygtrie>=2.2 import csv from collections import OrderedDict from IPython.display import display, HTML import logging import os import pickle import random import re import cli...
13,599
Given the following text description, write Python code to implement the functionality described below step by step Description: Source of the materials Step1: Graphics including GenomeDiagram The Bio.Graphics module depends on the third party Python library ReportLab. Although focused on producing PDF files, ReportL...
Python Code: #Lets load notebook's Image from IPython.core.display import Image from reportlab.lib import colors from reportlab.lib.units import cm from Bio.Graphics import GenomeDiagram from Bio import SeqIO Explanation: Source of the materials: Biopython cookbook (adapted) End of explanation record = SeqIO.read("dat...