Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
3,200
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> Earth's Energy Budget </center> <img src = 'https Step1: Clear sky downward solar flux is considered to be equivalent to solar radiation after clouds Step2: compare CIMIS (measure...
Python Code: from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value...
3,201
Given the following text description, write Python code to implement the functionality described below step by step Description: Webscraping with Beautiful Soup In this lesson we'll learn about various techniques to scrape data from websites. This lesson will include Step1: 1. Using BeautifulSoup 1.1 Make a GET reque...
Python Code: import requests # to make GET request from bs4 import BeautifulSoup # to parse the HTML response import time # to pause between calls import csv # to write data to csv import pandas # to see CSV Explanation: Webscraping with Beautiful Soup In this lesson we'll learn about various techniques to scrape ...
3,202
Given the following text description, write Python code to implement the functionality described below step by step Description: Importing and Exporting Data Data can be imported into Google BigQuery from a CSV file stored within Google Cloud Storage, or it can be streamed directly into BigQuery from Python code. Simi...
Python Code: from google.datalab import Context import google.datalab.bigquery as bq import google.datalab.storage as storage import pandas as pd try: from StringIO import StringIO except ImportError: from io import BytesIO as StringIO Explanation: Importing and Exporting Data Data can be imported into Google BigQu...
3,203
Given the following text description, write Python code to implement the functionality described below step by step Description: Step6: Processing Multisentence Documents Step8: Define markup_sentence We are putting the functionality we went through in the previous two notebooks (BasicSentenceMarkup and BasicSentence...
Python Code: import pyConTextNLP.pyConTextGraph as pyConText import pyConTextNLP.itemData as itemData from textblob import TextBlob import networkx as nx import pyConTextNLP.display.html as html from IPython.display import display, HTML reports = [ IMPRESSION: Evaluation limited by lack of IV contrast; however, no ...
3,204
Given the following text description, write Python code to implement the functionality described below step by step Description: Examining the 100-year storm From past analysis, we've seen that there have been 3 100-year storms in the last 46 years. This notebook takes a look at these 3 storms. Step1: Storm 1 -> Aug...
Python Code: from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np from datetime import datetime, timedelta import pandas as pd import matplotlib.pyplot as plt import operator import seaborn as sns %matplotlib inline n_year_storms = pd.read_csv('data/n_year_storms_ohare_n...
3,205
Given the following text description, write Python code to implement the functionality described below step by step Description: Cirq to Tensor Networks Here we demonstrate turning circuits into tensor network representations of the circuit's unitary, final state vector, final density matrix, and final noisy density m...
Python Code: import cirq import numpy as np import pandas as pd from cirq.contrib.svg import SVGCircuit import cirq.contrib.quimb as ccq import quimb import quimb.tensor as qtn Explanation: Cirq to Tensor Networks Here we demonstrate turning circuits into tensor network representations of the circuit's unitary, final s...
3,206
Given the following text description, write Python code to implement the functionality described below step by step Description: Stacks Stacks are one of the basic, linear datastructures that have the characteristical 2 end points (here Step1: Note that the addition and removal of a single item is a O(1) algorithm St...
Python Code: class Stack(object): def __init__(self): self.stack = [] def add(self, item): self.stack.append(item) def pop(self): self.stack.pop() def peek(self): return self.stack[-1] def size(self): return len(self.stack) Explanation: Sta...
3,207
Given the following text description, write Python code to implement the functionality described below step by step Description: An Introduction to Multi-fidelity Modeling in Emukit Overview A common issue encountered when applying machine learning to environmental sciences and engineering problems is the difficulty o...
Python Code: # General imports import numpy as np import matplotlib.pyplot as plt from matplotlib import colors as mcolors colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS) %matplotlib inline np.random.seed(20) Explanation: An Introduction to Multi-fidelity Modeling in Emukit Overview A common issue encountered...
3,208
Given the following text description, write Python code to implement the functionality described below step by step Description: Resumen de estructuras de datos de Python Tuplas, Listas, Sets, Diccionarios, Listas de comprehension, Funciones, Clases Vamos a ver ejemplos de estrucutras de datos en Python Tuplas Son el ...
Python Code: x = (1,2,3,0,2,1) x x = (0, 'Hola', (1,2)) x[1] Explanation: Resumen de estructuras de datos de Python Tuplas, Listas, Sets, Diccionarios, Listas de comprehension, Funciones, Clases Vamos a ver ejemplos de estrucutras de datos en Python Tuplas Son el tipo mas simple de estr. puede almacenar en una misma va...
3,209
Given the following text description, write Python code to implement the functionality described below step by step Description: Convolutional Autoencoder Sticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. Again, loading modules and the data. Step1: Network Archit...
Python Code: %matplotlib inline import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', validation_size=0) img = mnist.train.images[2] plt.imshow(img.reshape((28, 28)), cmap='Greys_r') Explanati...
3,210
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); Step1: Simple Activation Atlas This notebook uses Lucid to reproduce the results in Activation At...
Python Code: # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribute...
3,211
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook, we will work through a Bayes Net analysis using the GES algorithm with the TETRAD software (http Step1: Load the data generated using the DCM forward model. In this model,...
Python Code: import os,sys import numpy %matplotlib inline import matplotlib.pyplot as plt sys.path.insert(0,'../') from utils.mkdesign import create_design_singlecondition from nipy.modalities.fmri.hemodynamic_models import spm_hrf,compute_regressor from utils.make_data import make_continuous_data from utils.graph_uti...
3,212
Given the following text description, write Python code to implement the functionality described below step by step Description: Data block API foundations Step1: Jump_to lesson 11 video Step2: Image ItemList Previously we were reading in to RAM the whole MNIST dataset at once, loading it as a pickle file. We can't ...
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline #export from exp.nb_07a import * Explanation: Data block API foundations End of explanation datasets.URLs.IMAGENETTE_160 Explanation: Jump_to lesson 11 video End of explanation path = datasets.untar_data(datasets.URLs.IMAGENETTE_160) path Explanation: I...
3,213
Given the following text description, write Python code to implement the functionality described below step by step Description: PCA Analysis Step1: Feature Selection Step2: Logistic Regression Step3: Naive Bayes Step4: KNN Step5: Random Forest Step6: Decision Tree Step7: SVC Step8: Gradient Boosting Step9: C...
Python Code: # Build up the correlation mtrix Z = X1 correlation_matrix = Z.corr() #Eigenvectores & Eigenvalues eig_vals, eig_vecs = np.linalg.eig(correlation_matrix) sklearn_pca = PCA(n_components=len(Z.columns)) Y_sklearn = sklearn_pca.fit_transform(correlation_matrix) #From the Scree plot. plt.plot(eig_vals) plt.sho...
3,214
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 01 Import Step1: Interact basics Write a print_sum function that prints the sum of its arguments a and b. Step2: Use the interact function to interact with the print_sum ...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display Explanation: Interact Exercise 01 Import End of explanation def print_sum(a, b): print(a + b) Explanation: Interact basics Write a...
3,215
Given the following text description, write Python code to implement the functionality described below step by step Description: PyBroMo 5. Two-state dynamics - Dynamic smFRET simulation <small><i> This notebook is part of <a href="http Step1: Timestamps, detectors and particles for the two states Step2: Simulation ...
Python Code: from pathlib import Path from textwrap import dedent, indent import numpy as np import tables from scipy.stats import expon import phconvert as phc print('phconvert version:', phc.__version__) SIM_PATH = 'data/' filelist = list(Path(SIM_PATH).glob('smFRET_*_600s.hdf5')) [f.name for f in filelist] filename_...
3,216
Given the following text description, write Python code to implement the functionality described below step by step Description: <img align="left" src="imgs/logo.jpg" width="50px" style="margin-right Step1: We repeat our definition of the Spouse Candidate subclass, and load the test set Step2: I. Training a SparseLo...
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline import os import numpy as np # Connect to the database backend and initalize a Snorkel session from lib.init import * Explanation: <img align="left" src="imgs/logo.jpg" width="50px" style="margin-right:10px"> Snorkel Workshop: Extracting Spouse Relation...
3,217
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Optimizing Real World Problems In this workshop we will code up a model called POM3 and optimize it using the GA we developed in the first workshop. POM3 is a software estimation mode...
Python Code: %matplotlib inline # All the imports from __future__ import print_function, division from math import * import random import sys import matplotlib.pyplot as plt # TODO 1: Enter your unity ID here __author__ = "latimko" class O: Basic Class which - Helps dynamic updates - Pretty Pr...
3,218
Given the following text description, write Python code to implement the functionality described below step by step Description: PRINCIPLE COMPONENT ANALYSIS Authors Ndèye Gagnessiry Ndiaye and Christin Seifert License This work is licensed under the Creative Commons Attribution 3.0 Unported License https Step1: Th...
Python Code: import pandas as pd import numpy as np import pylab as plt import matplotlib.pyplot as plt from sklearn.decomposition import PCA Explanation: PRINCIPLE COMPONENT ANALYSIS Authors Ndèye Gagnessiry Ndiaye and Christin Seifert License This work is licensed under the Creative Commons Attribution 3.0 Unported...
3,219
Given the following text description, write Python code to implement the functionality described below step by step Description: Optimizing Python Code Step1: Pairwise Distance Estimation Step2: The timiing for the results in Jake's post (2013) and the results from this post (2017) are summarized below. Step3: The ...
Python Code: import numpy as np import numba import cython %load_ext cython import pandas as pd numba.__version__, cython.__version__, np.__version__ Explanation: Optimizing Python Code: Numba vs Cython Goutham Balaraman I came across an old post by jakevdp on Numba vs Cython. I thought I will revisit this topic becau...
3,220
Given the following text description, write Python code to implement the functionality described below step by step Description: Rotate Array Step1: Simple Solution The simplest solution splits the array at the point to rotate, and constructs a new array using the two parts. Step2: This solution has both time and sp...
Python Code: import sys; sys.path.append('../..') from puzzles import leet_puzzle leet_puzzle('rotate-array') n, k = 7, 4 example_array = list(range(n)) example_array Explanation: Rotate Array End of explanation def rotate_simple(input_array, order): order %= len(input_array) return input_array[order:] + input_...
3,221
Given the following text description, write Python code to implement the functionality described below step by step Description: AveragePooling2D [pooling.AveragePooling2D.0] input 6x6x3, pool_size=(2, 2), strides=None, padding='valid', data_format='channels_last' Step1: [pooling.AveragePooling2D.1] input 6x6x3, pool...
Python Code: data_in_shape = (6, 6, 3) L = AveragePooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(270) da...
3,222
Given the following text description, write Python code to implement the functionality described below step by step Description: Step4: Demo - Storing information in EEX Step8: Storing force field information So far, only the topology and coordinates of the system are specified, and we are not able to calculate an en...
Python Code: import eex import os import pandas as pd import numpy as np # Create empty data layer dl = eex.datalayer.DataLayer("butane", backend="Memory") dl.summary() First, we add atoms to the system. Atoms have associated metadata. The possible atom metadata is listed here. dl.list_valid_atom_properties() TOPOLOGY:...
3,223
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise 06 Data preparation and model evaluation exercise with Titanic data We'll be working with a dataset from Kaggle's Titanic competition Step1: Exercise 6.1 Impute the missing values ...
Python Code: import pandas as pd url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/titanic.csv' titanic = pd.read_csv(url, index_col='PassengerId') titanic.head() Explanation: Exercise 06 Data preparation and model evaluation exercise with Titanic data We'll be working with a dataset from Kaggle's T...
3,224
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: <i class="fa fa-diamond"></i> Primero pimpea tu libreta! Step2: Un poco de estadística Step3: Hacemos dos listas, la primera contendrá las edades de los chavos de clubes de ciencia ...
Python Code: from IPython.core.display import HTML import os def css_styling(): Load default custom.css file from ipython profile base = os.getcwd() styles = "<style>\n%s\n</style>" % (open(os.path.join(base,'files/custom.css'),'r').read()) return HTML(styles) css_styling() Explanation: <i class="fa fa-...
3,225
Given the following text description, write Python code to implement the functionality described below step by step Description: Spherical Harmonic Normalizations and Parseval's theorem The variance of a single spherical harmonic We will here demonstrate the relatioship between a function expressed in spherical harmon...
Python Code: %matplotlib inline from __future__ import print_function # only necessary if using Python 2.x import matplotlib.pyplot as plt import numpy as np from pyshtools.shclasses import SHCoeffs, SHGrid, SHWindow lmax = 100 coeffs = SHCoeffs.from_zeros(lmax) coeffs.set_coeffs(values=[1], ls=[5], ms=[2]) Explanation...
3,226
Given the following text description, write Python code to implement the functionality described below step by step Description: Test application Autor Step1: Test data from the application loaded into a simple data container. One row contains the data of a click. If not changed the first file from files is loaded. |...
Python Code: files = ['clicks_2020-01-24 09:48:51_touchpad_14"_monitor.csv', 'clicks_2020-01-24 09:44:46_mouse_24"_monitor.csv', 'clicks_2020-01-23 16:00:32_mouse_24"_monitor.csv'] Explanation: Test application Autor: Nils Verheyen\ Matriculation number: 3043171 Mouse and touchpad input were tested on...
3,227
Given the following text description, write Python code to implement the functionality described below step by step Description: Preparations Import libraries Step1: Load data Step2: Filtering There are two goals Step3: Save the hard-earned JDs and skills after all these filters Step4: Sample job postings Step5: ...
Python Code: import my_util as my_util; from my_util import * Explanation: Preparations Import libraries: End of explanation HOME_DIR = 'd:/larc_projects/job_analytics/' DATA_DIR = HOME_DIR + 'data/clean/' # job descriptions (JDs) init_posts = pd.read_csv(DATA_DIR + 'jd_df.csv') skill_df = pd.read_csv(DATA_DIR + 'skill...
3,228
Given the following text description, write Python code to implement the functionality described below step by step Description: Feladatok Minden feladatot külön notebookba oldj meg! A megoldásnotebook neve tartalmazza a feladat számát! A megoldasok kerüljenek a MEGOLDASOK mappába!<br> Csak azok a feladatok kerülnek...
Python Code: a=[12586269025, 20365011074, 32951280099, 53316291173, 86267571272, 139583862445, 225851433717,365435296162, 591286729879, 956722026041, 1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723, 17167680177565, 27777890035288, 44945570212853, 72723460248141, 117669030460994] b=[832040...
3,229
Given the following text description, write Python code to implement the functionality described below step by step Description: Main Workflow Step1: Load old colab notebook names Step2: Parse script names from colab notebooks Step3: Process the code Ways to import modules in python * import foo * import foo as bar...
Python Code: from time import time init = time() import re import os import sys import json import yaml from functools import reduce from collections import ChainMap import subprocess import pandas as pd from glob import glob import nbformat import jax Explanation: Main Workflow End of explanation old_nb_files = glob("...
3,230
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This notebook contains all of the code from the corresponding post on the One Codex Blog. These snippets are exactly what are in the blog post, and let you perfectly reproduce t...
Python Code: from onecodex import Api ocx = Api() project = ocx.Projects.get("d53ad03b010542e3") # get DIABIMMUNE project by ID samples = ocx.Samples.where(project=project.id, public=True, limit=50) samples.metadata[[ "gender", "host_age", "geo_loc_name", "totalige", "eggs", "vegetables", "...
3,231
Given the following text description, write Python code to implement the functionality described below step by step Description: Gaussian processes (GP) are a cornerstone of modern machine learning. They are often used for non-parametric regression and classification, and are extended from the theory behind Gaussian d...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt rng = np.random.RandomState(1999) n_samples = 1000 X = rng.rand(n_samples) y = np.sin(20 * X) + .05 * rng.randn(X.shape[0]) X_t = np.linspace(0, 1, 100) y_t = np.sin(20 * X_t) plt.scatter(X, y, color='steelblue', label='measured y') plt....
3,232
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualize source leakage among labels using a circular graph This example computes all-to-all pairwise leakage among 68 regions in source space based on MNE inverse solutions and a FreeSurfe...
Python Code: # Authors: Olaf Hauk <olaf.hauk@mrc-cbu.cam.ac.uk> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # Nicolas P. Rougier (graph code borrowed from his matplotlib gallery) # # License: BSD (3-clause) import numpy as np import matplot...
3,233
Given the following text description, write Python code to implement the functionality described below step by step Description: VIX as a measure of Market Uncertainty by Brandon Wang (bw1115) Data Bootcamp Final Project (NYU Stern Spring 2017) Abstract The VIX index, calculated and published by the Chicago Board Opti...
Python Code: # Setup import sys # system module import pandas as pd # data package import matplotlib.pyplot as plt # graphics module import datetime as dt # date and time module import seaborn as sns # seaborn graphics module imp...
3,234
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Science Summer School - Split '17 5. Generating images of digits with Generative Adversarial Networks Step1: Goals Step2: What are we going to do with the data? We have $70000$ images...
Python Code: %matplotlib inline %load_ext autoreload %autoreload 2 import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import os, util Explanation: Data Science Summer School - Split '17 5. Generating images of digits with Generative Adversarial Networks End of explanation data_folder = 'data'; d...
3,235
Given the following text description, write Python code to implement the functionality described below step by step Description: IST256 Lesson 04 Iterations Zybook Ch 4 P4E Ch5 Links Participation Step1: A. 4 B. 5 C. 6 D. 7 Vote Now Step2: The sequence of code that repeats is known as the Body. The Boolean express...
Python Code: i,j,k = 1, 20, 1 while (i<j): n = k*(j-i) print(n) i = i + 1 j = j - 1 k = k * 5 Explanation: IST256 Lesson 04 Iterations Zybook Ch 4 P4E Ch5 Links Participation: https://poll.ist256.com In-Class Questions: Zoom Chat! Agenda Exam 1 this week Go over HW 03 Iterations Make our code execut...
3,236
Given the following text description, write Python code to implement the functionality described below step by step Description: Hitting and Cold Weather in Baseball A project by Nathan Ding (njd304@stern.nyu.edu) on the effects of temperature on major league batters Spring 2016 Semester Introduction The Natural Gas L...
Python Code: import pandas as pd import matplotlib.pyplot as plt import statsmodels.formula.api as smf %matplotlib inline Explanation: Hitting and Cold Weather in Baseball A project by Nathan Ding (njd304@stern.nyu.edu) on the effects of temperature on major league batters Spring 2016 Semester Introduction The Natural ...
3,237
Given the following text description, write Python code to implement the functionality described below step by step Description: Variational Autoencoders Introduction The variational autoencoder (VAE) is arguably the simplest setup that realizes deep probabilistic modeling. Note that we're being careful in our choice ...
Python Code: import os import numpy as np import torch from pyro.contrib.examples.util import MNIST import torch.nn as nn import torchvision.transforms as transforms import pyro import pyro.distributions as dist import pyro.contrib.examples.util # patches torchvision from pyro.infer import SVI, Trace_ELBO from pyro.op...
3,238
Given the following text description, write Python code to implement the functionality described below step by step Description: Outline Glossary 1. Radio Science using Interferometric Arrays Previous Step1: Import section specific modules
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS Explanation: Outline Glossary 1. Radio Science using Interferometric Arrays Previous: 1.0 Introduction Next: 1.2 Electromagnetic radiation and astronomica...
3,239
Given the following text description, write Python code to implement the functionality described below step by step Description: CSE 6040, Fall 2015 [12] Step1: Exercise. Write a snippet of code to verify that the vertex IDs are dense in some interval $[1, n]$. That is, there is a minimum value of $1$, some maximum v...
Python Code: import sqlite3 as db import pandas as pd def get_table_names (conn): assert type (conn) == db.Connection # Only works for sqlite3 DBs query = "SELECT name FROM sqlite_master WHERE type='table'" return pd.read_sql_query (query, conn) def print_schemas (conn, table_names=None, limit=0): asser...
3,240
Given the following text description, write Python code to implement the functionality described below step by step Description: <hr> Script Development - <code>addPosTags.py</code> Development notebook for script to add tokens and categories to review data. <hr> Setup Step1: <hr> Development Add tri-grams Step2: Ad...
Python Code: import pyspark as ps from sentimentAnalysis import dataProcessing as dp # create spark session spark = ps.sql.SparkSession(sc) # get dataframes # specify s3 as sourc with s3a:// #df = spark.read.json("s3a://amazon-review-data/user_dedup.json.gz") #df_meta = spark.read.json("s3a://amazon-review-data/metadat...
3,241
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); Step1: Guided ES Demo This is a fully self-contained notebook that reproduces the toy example in F...
Python Code: # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribute...
3,242
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook-11 Step1: Layout of a Function As we briefly mentioned in another notebook, any 'word' followed by a set of parenthesis is a function. The 'word' is the function's name, and anythi...
Python Code: myList = [1,"two", False, 9.99] len(myList) # A function print(myList) # A different function! Explanation: Notebook-11: Introduction to Functions Lesson Content Function Anatomy 101 Function definiton & call Arguments Return statement Function calling! Assign a function to a variable Function as a paramet...
3,243
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This Notebook will help you to identify anomalies in your historical timeseries data (IoT data) in simple steps. Also, derive the threshold value for your historical data. This ...
Python Code: from pyspark.sql import SQLContext # adding the PySpark module to SparkContext sc.addPyFile("https://raw.githubusercontent.com/seahboonsiew/pyspark-csv/master/pyspark_csv.py") import pyspark_csv as pycsv # you may need to modify this line if the filename or path is different. sqlContext = SQLContext(sc) da...
3,244
Given the following text description, write Python code to implement the functionality described below step by step Description: Convolutional Neural Networks Step1: Run the next cell to load the "SIGNS" dataset you are going to use. Step2: As a reminder, the SIGNS dataset is a collection of 6 signs representing num...
Python Code: import math import numpy as np import h5py import matplotlib.pyplot as plt import scipy from PIL import Image from scipy import ndimage import tensorflow as tf from tensorflow.python.framework import ops from cnn_utils import * %matplotlib inline np.random.seed(1) Explanation: Convolutional Neural Networks...
3,245
Given the following text description, write Python code to implement the functionality described below step by step Description: Network from Nielsen's Chapter 1 http Step1: Set up Network Step2: Train Network Step3: Exercise
Python Code: import mnist_loader training_data, validation_data, test_data = mnist_loader.load_data_wrapper() Explanation: Network from Nielsen's Chapter 1 http://neuralnetworksanddeeplearning.com/chap1.html#implementing_our_network_to_classify_digits Load MNIST Data End of explanation import network # 784 (28 x 28 pix...
3,246
Given the following text description, write Python code to implement the functionality described below step by step Description: Sebastian Raschka, 2016 https Step1: Bonus Material - Softmax Regression Softmax Regression (synonyms Step2: First, we want to encode the class labels into a format that we can more easily...
Python Code: %load_ext watermark %watermark -a 'Sebastian Raschka' -u -d -v -p matplotlib,numpy,scipy # to install watermark just uncomment the following line: #%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py %matplotlib inline Explanation: Sebastian Raschka, 2016 https://github.com/r...
3,247
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> Saving and Loading Trained Models Refer back to this notebook as...
Python Code: torch.save(model.state_dict(), 'MyModel.pt') Explanation: <img src="../Pierian-Data-Logo.PNG"> <br> <strong><center>Copyright 2019. Created by Jose Marcial Portilla.</center></strong> Saving and Loading Trained Models Refer back to this notebook as a refresher on saving and loading models. Saving a trained...
3,248
Given the following text description, write Python code to implement the functionality described below step by step Description: ATTO550, ATT0647N specs ATTO550 Step1: To obtain the absorption cross-section we need to normalize by the extinctyion coefficient Step2: Absorption cross-section @ 532 nm
Python Code: atto550_ext_coeff = 1.2*1e5 # 1 / ( mol cm ) atto647N_ext_coeff = 1.5*1e5 # 1 / ( mol cm ) %matplotlib inline import matplotlib.pyplot as plt import pandas as pd a550 = pd.read_excel('ATTO550.xlsx', 'Tabelle1', index_col=None, na_values=['NA']) a647N = pd.read_excel('ATTO647N.xlsx', 'Tabelle1', index_co...
3,249
Given the following text description, write Python code to implement the functionality described below step by step Description: Transform EEG data using current source density (CSD) This script shows an example of how to use CSD Step1: Load sample subject data Step2: Plot the raw data and CSD-transformed raw data S...
Python Code: # Authors: Alex Rockhill <aprockhill@mailbox.org> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import sample print(__doc__) data_path = sample.data_path() Explanation: Transform EEG data using current source density (CSD) This script shows an e...
3,250
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', 'cams', 'sandbox-1', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: CAMS Source ID: SANDBOX-1 Topic: Aerosol Sub-Topics: Transport, Emissions...
3,251
Given the following text description, write Python code to implement the functionality described below step by step Description: Vectors A vector is just a point in some finite-dimensional space. In Python, we can represent a vector as a list of numbers Step5: Now we will build functions to perform vector arithmetic....
Python Code: height_weight_age = [70, # inches 170, # pounds 40] # years grades = [95, # exam1 80, # exam2 75, # exam3 62] # exam4 Explanation: Vectors A vector is just a point in some finite-dimensional space. In Python, we can represent a vecto...
3,252
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting Started Magma is a hardware construction language written in Python 3. The central abstraction in Magma is a Circuit, which is analagous to a verilog module. A circuit is a set of fu...
Python Code: import magma as m m.set_mantle_target("ice40") Explanation: Getting Started Magma is a hardware construction language written in Python 3. The central abstraction in Magma is a Circuit, which is analagous to a verilog module. A circuit is a set of functional units that are wired together. Magma is designed...
3,253
Given the following text description, write Python code to implement the functionality described below step by step Description: APS 5 - Questões com auxílio do Pandas Nome Step1: Liste as primeiras linhas do DataFrame Step2: Q1 - Manipulando o DataFrame Crie uma coluna chamada Hemisfério baseada na Latitude A regr...
Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.stats import expon from numpy import arange import scipy.stats as stats #Abrir o arquivo df = pd.read_csv('earthquake.csv') #listar colunas print(list(df)) Explanation: APS 5 - Questões com auxílio do Panda...
3,254
Given the following text description, write Python code to implement the functionality described below step by step Description: <span style="color Step7: Vhanilla RNN class and functions Step8: Placeholder and initializers Step9: Models Step10: Dataset Preparation
Python Code: import numpy as np import tensorflow as tf from sklearn.datasets import load_digits from sklearn.cross_validation import train_test_split import pylab as pl from IPython import display import sys %matplotlib inline Explanation: <span style="color:green"> VANILLA RNN ON 8*8 MNIST DATASET TO PREDICT TEN CLA...
3,255
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id='beginning'></a> <!--\label{beginning}--> * Outline * Glossary * 4. The Visibility Space * Previous Step1: Import section specific modules Step2: 4.5.1 UV coverage Step3: Let's...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS Explanation: <a id='beginning'></a> <!--\label{beginning}--> * Outline * Glossary * 4. The Visibility Space * Previous: 4.4 The Visibility Function ...
3,256
Given the following text description, write Python code to implement the functionality described below step by step Description: K Nearest Neighbors Classifiers So far we've covered learning via probability (naive Bayes) and learning via errors (regression). Here we'll cover learning via similarity. This means we look...
Python Code: music = pd.DataFrame() # Some data to play with. music['duration'] = [184, 134, 243, 186, 122, 197, 294, 382, 102, 264, 205, 110, 307, 110, 397, 153, 190, 192, 210, 403, 164, 198, 204, 253, 234, 190, 182, 401, 376, 102] music['loudness'] = [18, 34, 43, 36, 22, 9, ...
3,257
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...
3,258
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', 'mri', 'sandbox-1', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: MRI Source ID: SANDBOX-1 Topic: Ocnbgchem Sub-Topics: Tracers. Proper...
3,259
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Python Jupyter Welcome to Jupyter, through this interface I will be showing you the following Step1: Cleaning Up The Full Text In order for better results from our analysis ...
Python Code: import json import requests apiResponse = requests.get('https://oc-index.library.ubc.ca/collections/bcbooks/items/1.0059569').json() item = apiResponse['data'] fullText = item['FullText'][0]['value'] print(fullText) Explanation: Introduction to Python Jupyter Welcome to Jupyter, through this interface I wi...
3,260
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] Explanation: TV Script Generation In this project, you'll generate your own Simpsons TV script...
3,261
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting Started This is an Notebook containing the examples from the Getting Started section in the documentation. Refer to the documentation for very verbose description of this code. Optim...
Python Code: # import the classes we need from SafeRLBench.envs import LinearCar from SafeRLBench.policy import LinearPolicy from SafeRLBench.algo import PolicyGradient # get an instance of `LinearCar` with the default arguments. linear_car = LinearCar() # we need a policy which maps R^2 to R policy = LinearPolicy(2, 1...
3,262
Given the following text description, write Python code to implement the functionality described below step by step Description: Basics Thunder provides data structures, read/write patterns, and simple processing of spatial and temporal data. All operations in Thunder are designed to scale to very large data sets thro...
Python Code: import thunder as td series = td.series.fromexample('fish') Explanation: Basics Thunder provides data structures, read/write patterns, and simple processing of spatial and temporal data. All operations in Thunder are designed to scale to very large data sets through the distributed comptuing engine Spark, ...
3,263
Given the following text description, write Python code to implement the functionality described below step by step Description: Running pyqz I A) Installing and importing pyqz Installing pyqz is best done via pip. You should then be able to import the package and check its version from within any Python shell Step1: ...
Python Code: %matplotlib inline import pyqz import numpy as np Explanation: Running pyqz I A) Installing and importing pyqz Installing pyqz is best done via pip. You should then be able to import the package and check its version from within any Python shell: End of explanation import pyqz.pyqz_plots as pyqzp Explanati...
3,264
Given the following text description, write Python code to implement the functionality described below step by step Description: Adding new passbands to PHOEBE In this tutorial we will show you how to add your own passband to PHOEBE. Adding a custom passband involves Step1: If you plan on computing model atmosphere i...
Python Code: #!pip install -I "phoebe>=2.4,<2.5" Explanation: Adding new passbands to PHOEBE In this tutorial we will show you how to add your own passband to PHOEBE. Adding a custom passband involves: downloading and setting up model atmosphere tables; providing a passband transmission function; defining and registeri...
3,265
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">Logistic Regression in TensorFlow</h1> In this notebook, we illustrate the basics of Logistic Regression using TensorFlow, on the <a href="https Step1: Feature Informatio...
Python Code: import numpy as np import pandas as pd %pylab inline pylab.style.use('ggplot') url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data' pima_df = pd.read_csv(url, header=None) Explanation: <h1 align="center">Logistic Regression in TensorFlow</h1> In...
3,266
Given the following text description, write Python code to implement the functionality described below step by step Description: 20. 자연어처리 1) 워드 클라우드 단어의 크기를 단어의 빈도 수에 비례하도록 하여 단어를 아름답게 배치 Step2: 아주 멋있어 보이기는 하지만, 딱히 어떤 정보를 제공하지는 않는다. 단어가 구인 광고에 등장하는 빈도를 가로축, 단어가 이력서에 등장하는 빈도를 세로축 Step3: 2) n-gram 모델 Step4: bigram ...
Python Code: import math, random, re from collections import defaultdict, Counter from bs4 import BeautifulSoup import requests import matplotlib.pyplot as plt #데이터 과학 관련 키워드목록, 빈도 0~100 data = [ ("big data", 100, 15), ("Hadoop", 95, 25), ("Python", 75, 50), ("R", 50, 40), ("machine learning", 80, 20), ("stati...
3,267
Given the following text description, write Python code to implement the functionality described below step by step Description: Examples of split A split agent has a single input stream and two or more output streams. Step1: split_element <b>split_element(func, in_stream, out_streams)</b> <br> <br> where <ol> <l...
Python Code: import os import sys sys.path.append("../") from IoTPy.core.stream import Stream, run from IoTPy.agent_types.split import split_element, split_list, split_window from IoTPy.agent_types.split import unzip, separate, timed_unzip from IoTPy.agent_types.basics import split_e, fsplit_2e from IoTPy.helper_functi...
3,268
Given the following text description, write Python code to implement the functionality described below step by step Description: Interpolation Exercise 1 Step1: 2D trajectory interpolation The file trajectory.npz contains 3 Numpy arrays that describe a 2d trajectory of a particle as a function of time Step2: Use the...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import numpy as np from scipy.interpolate import interp1d Explanation: Interpolation Exercise 1 End of explanation dictionary = np.load('trajectory.npz') y = dictionary.items()[0][1] t = dictionary.items()[1][1] x = dictionary.items()...
3,269
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...
3,270
Given the following text description, write Python code to implement the functionality described below step by step Description: Split matrix randomly into train, valid and test sets Step1: Select random batch This can be used for mini-batch training. Step2: Using sklearn Scikit-learn has a train_test_split function...
Python Code: import numpy as np # matrix dimensions N = 100 M = 20 # train-valid-test ratio, let's use 80-10-10 train_ratio = 0.8 valid_ratio = 0.1 test_ratio = 1.0 - train_ratio - valid_ratio # this is never used # array indices train_split = int(train_ratio * N) valid_split = int(valid_ratio * N) # create a random m...
3,271
Given the following text description, write Python code to implement the functionality described below step by step Description: 用不到 50 行代码训练 GAN(基于 PyTorch 本文作者为前谷歌高级工程师、AI 初创公司 Wavefront 创始人兼 CTO Dev Nag,介绍了他是如何用不到五十行代码,在 PyTorch 平台上完成对 GAN 的训练。 什么是 GAN? 在进入技术层面之前,为照顾新入门的开发者,先来介绍下什么是 GAN。 2014 年,Ian Goodfellow 和他在蒙特...
Python Code: # Generative Adversarial Networks (GAN) example in PyTorch. # See related blog post at https://medium.com/@devnag/generative-adversarial-networks-gans-in-50-lines-of-code-pytorch-e81b79659e3f#.sch4xgsa9 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim...
3,272
Given the following text description, write Python code to implement the functionality described below step by step Description: Object Model bqplot is based on Grammar of Graphics paradigm. The Object Model in bqplot gives the user the full flexibility to build custom plots. This means the API is verbose but fully cu...
Python Code: from bqplot import ( LinearScale, Axis, Figure, OrdinalScale, LinearScale, Bars, Lines, Scatter, ) # first, let's create two vectors x and y to plot using a Lines mark import numpy as np x = np.linspace(-10, 10, 100) y = np.sin(x) # 1. Create the scales xs = LinearScale() ys...
3,273
Given the following text description, write Python code to implement the functionality described below step by step Description: TensorFlow Tutorial #12 Adversarial Noise for MNIST by Magnus Erik Hvass Pedersen / GitHub / Videos on YouTube Introduction The previous Tutorial #11 showed how to find so-called adversarial...
Python Code: from IPython.display import Image Image('images/12_adversarial_noise_flowchart.png') Explanation: TensorFlow Tutorial #12 Adversarial Noise for MNIST by Magnus Erik Hvass Pedersen / GitHub / Videos on YouTube Introduction The previous Tutorial #11 showed how to find so-called adversarial examples for a sta...
3,274
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('../sentiment-network/reviews.txt', 'r') as f: reviews = f.read() with open('../sentiment-network/labels.txt', 'r') as f: labels = f.read() reviews[:2000] Explanation: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent ...
3,275
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: Actor-Learner API를 사용한 SAC minitaur <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: 설정 먼저 필요...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
3,276
Given the following text description, write Python code to implement the functionality described below step by step Description: Here we will test parameter recovery and model comparison for Rescorla-Wagner (RW), Hierarchical Gaussian Filters (HGF), and Switching Gaussian Filters (SGF) models of the social influence t...
Python Code: import numpy as np from scipy import io import matplotlib.pyplot as plt import seaborn as sns import pandas as pd sns.set(style = 'white', color_codes = True) %matplotlib inline import sys import os import os cwd = os.getcwd() sys.path.append(cwd[:-len('befit/examples/social_influence')]) Explanation: Here...
3,277
Given the following text description, write Python code to implement the functionality described below step by step Description: Differentially Private Histograms Plotting the distribution of ages in Adult Step1: We first read in the list of ages in the Adult UCI dataset (the first column). Step2: Using Numpy's nati...
Python Code: import numpy as np from diffprivlib import tools as dp import matplotlib.pyplot as plt Explanation: Differentially Private Histograms Plotting the distribution of ages in Adult End of explanation ages_adult = np.loadtxt("https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data", ...
3,278
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Land MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify do...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nerc', 'ukesm1-0-ll', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: NERC Source ID: UKESM1-0-LL Topic: Land Sub-Topics: Soil, Snow, Vegetation, E...
3,279
Given the following text description, write Python code to implement the functionality described below step by step Description: Fluxing with PYPIT [v2] Step1: For the standard User (Running the script) Generate the sensitivity function from an extracted standard star Here is an example fluxing file (see the fluxing ...
Python Code: %matplotlib inline # import from importlib import reload import os from matplotlib import pyplot as plt import glob import numpy as np from astropy.table import Table from pypeit import fluxspec from pypeit.spectrographs.util import load_spectrograph Explanation: Fluxing with PYPIT [v2] End of explanation ...
3,280
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: My sample df has four columns with NaN values. The goal is to concatenate all the kewwords rows from end to front while excluding the NaN values.
Problem: import pandas as pd import numpy as np df = pd.DataFrame({'users': ['Hu Tao', 'Zhongli', 'Xingqiu'], 'keywords_0': ["a", np.nan, "c"], 'keywords_1': ["d", "e", np.nan], 'keywords_2': [np.nan, np.nan, "b"], 'keywords_3': ["f", np.nan, "...
3,281
Given the following text description, write Python code to implement the functionality described below step by step Description: License Copyright 2017 J. Patrick Hall, jphall@gwu.edu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "...
Python Code: # imports import h2o import operator import numpy as np import pandas as pd from h2o.estimators.glm import H2OGeneralizedLinearEstimator from h2o.estimators.gbm import H2OGradientBoostingEstimator # start h2o h2o.init() h2o.remove_all() Explanation: License Copyright 2017 J. Patrick Hall, jphall@gwu.edu P...
3,282
Given the following text description, write Python code to implement the functionality described below step by step Description: Intro to Neural Networks Handwritten Digits Recognization <img src = './img/neuralnetwork/neuron2.png' width = 700 align = 'left'> <img src = './img/neuralnetwork/synapse.jpg' width = 150 al...
Python Code: 1*0.25 + 0.5*(-1.5) Explanation: Intro to Neural Networks Handwritten Digits Recognization <img src = './img/neuralnetwork/neuron2.png' width = 700 align = 'left'> <img src = './img/neuralnetwork/synapse.jpg' width = 150 align = 'right'> The Neuron: A Biological Information Processor dentrites - the rece...
3,283
Given the following text description, write Python code to implement the functionality described below step by step Description: Twitter API rate limits Step1: Calculating remaining time (in mins) before api limits reset I find it helpful to check how many more minutes I have to wait before trying again Step2: Key f...
Python Code: ### checking rate limit - friends list limit = api.rate_limit_status() limit['resources']['friends']['/friends/list']['remaining'] limit['resources']['friends']['/friends/list'] Explanation: Twitter API rate limits End of explanation import datetime as dt given_date =dt.datetime.fromtimestamp( int(...
3,284
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Step1: As always, let's do imports and initialize a logger and a new Bundle. See Building a System for more details. Step2: And we'll attach some dummy datasets. See Datasets fo...
Python Code: !pip install -I "phoebe>=2.2,<2.3" Explanation: Advanced: Alternate Backends Setup Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End of explanation import ph...
3,285
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Without getting too detailed Lab is about a simple technique for either increasing or decreasing the playing time of a sound array, without altering the sound's pitch. Increasin...
Python Code: Image('images/PyAudio_RT_flow@300dpi.png',width='80%') pah.available_devices() Explanation: Introduction Without getting too detailed Lab is about a simple technique for either increasing or decreasing the playing time of a sound array, without altering the sound's pitch. Increasing the rate refers to decr...
3,286
Given the following text description, write Python code to implement the functionality described below step by step Description: <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step1: We define the model, adapted from the Keras CIFAR-10 example Step2: We train the model us...
Python Code: import tensorflow as tf # Check that GPU is available: cf. https://colab.research.google.com/notebooks/gpu.ipynb assert(tf.test.gpu_device_name()) tf.keras.backend.clear_session() tf.config.optimizer.set_jit(False) # Start with XLA disabled. def load_data(): (x_train, y_train), (x_test, y_test) = tf.kera...
3,287
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] Explanation: TV Script Generation In this project, you'll generate your own Simpsons TV script...
3,288
Given the following text description, write Python code to implement the functionality described below step by step Description: Protein binding & undfolding – a four-state model In this notebook we will look into a the kinetics of a model system describing competing protein folding, aggregation and ligand binding. Us...
Python Code: import logging; logger = logging.getLogger('matplotlib'); logger.setLevel(logging.INFO) # or notebook filled with logging from collections import OrderedDict, defaultdict import math import re import time from IPython.display import Image, Latex, display import matplotlib.pyplot as plt import sympy from p...
3,289
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Model Averaging <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Build Model Step3: Prepare...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
3,290
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating a custom prediction routine with scikit-learn <table align="left"> <td> <a href="https Step1: Authenticate your GCP account If you are using AI Platform Notebooks, your envir...
Python Code: PROJECT_ID = "<your-project-id>" #@param {type:"string"} ! gcloud config set project $PROJECT_ID Explanation: Creating a custom prediction routine with scikit-learn <table align="left"> <td> <a href="https://cloud.google.com/ml-engine/docs/scikit/custom-prediction-routine-scikit-learn"> <img sr...
3,291
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Getting started with TensorFlow </h1> In this notebook, you play around with the TensorFlow Python API. Step1: <h2> Adding two tensors </h2> First, let's try doing this using numpy, th...
Python Code: import tensorflow as tf import numpy as np print(tf.__version__) Explanation: <h1> Getting started with TensorFlow </h1> In this notebook, you play around with the TensorFlow Python API. End of explanation a = np.array([5, 3, 8]) b = np.array([3, -1, 2]) c = np.add(a, b) print(c) Explanation: <h2> Adding t...
3,292
Given the following text description, write Python code to implement the functionality described below step by step Description: Matplotlib Exercise 2 Imports Step1: Exoplanet properties Over the past few decades, astronomers have discovered thousands of extrasolar planets. The following paper describes the propertie...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import math Explanation: Matplotlib Exercise 2 Imports End of explanation !head -n 30 open_exoplanet_catalogue.txt Explanation: Exoplanet properties Over the past few decades, astronomers have discovered thousands of extrasolar planets. ...
3,293
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have a dataframe with one of its column having a list at each index. I want to concatenate these lists into one string like '1,2,3,4,5'. I am using
Problem: import pandas as pd df = pd.DataFrame(dict(col1=[[1, 2, 3]] * 2)) def g(df): L = df.col1.sum() L = map(lambda x:str(x), L) return ','.join(L) result = g(df.copy())
3,294
Given the following text description, write Python code to implement the functionality described below step by step Description: Latitude-dependent grey radiation Here is a quick example of using the climlab.GreyRadiationModel with a latitude dimension and seasonally varying insolation. Step1: Testing out multi-dimen...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import climlab from climlab import constants as const model = climlab.GreyRadiationModel(name='Grey Radiation', num_lev=30, num_lat=90) print(model) model.to_xarray() insolation = climlab.radiation.DailyInsolation(domains=model.Ts.domain...
3,295
Given the following text description, write Python code to implement the functionality described below step by step Description: Classification - MNIST dataset Exploring the popular MNIST dataset. Tensorflow provides a function to ingest the data. Step1: A little exploration Step2: Lets look at a random image and i...
Python Code: # Necessary imports import time from IPython import display import numpy as np from matplotlib.pyplot import imshow from PIL import Image, ImageOps import tensorflow as tf %matplotlib inline from tensorflow.examples.tutorials.mnist import input_data # Read the mnist dataset mnist = input_data.read_data_set...
3,296
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t...
3,297
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook was created by Sergey Tomin for Workshop Step1: Tutorials Preliminaries Step2: <a id="tutorial1"></a> Tutorial N1. Double Bend Achromat. We designed a simple lattice to demon...
Python Code: from IPython.display import Image #Image(filename='gui_example.png') Explanation: This notebook was created by Sergey Tomin for Workshop: Designing future X-ray FELs. Source and license info is on GitHub. August 2016. An Introduction to Ocelot Ocelot is a multiphysics simulation toolkit designed for studyi...
3,298
Given the following text description, write Python code to implement the functionality described below step by step Description: 2016 NHL Hockey Data Set - Sasha Kandrach Step1: Here's all of our data Step2: Here are each of the columns in the data set Step3: Let's count how many players are from each country Step4...
Python Code: import pandas as pd import matplotlib.pyplot as plt %matplotlib inline df= pd.read_excel("NHL 2014-15.xls") !pip install xlrd df.columns.value_counts() Explanation: 2016 NHL Hockey Data Set - Sasha Kandrach End of explanation df.head() Explanation: Here's all of our data: End of explanation df.columns Ex...
3,299
Given the following text description, write Python code to implement the functionality described below step by step Description: En este documento se describen los pasos llevados a cabo para estandarizar los datos disponibles desde la encuesta intercensal y utilizarlos para la construcción de parámetros. Las limpieza ...
Python Code: # Librerias utilizadas import pandas as pd import sys import urllib import os import numpy as np # Configuracion del sistema print('Python {} on {}'.format(sys.version, sys.platform)) print('Pandas version: {}'.format(pd.__version__)) import platform; print('Running on {} {}'.format(platform.system(), plat...