Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
5,100
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Assignment 3b Step2: Encoding issues with txt files For Windows users, the file “AnnaKarenina.txt” gets the encoding cp1252. In order to open the file, you have to add encoding='utf...
Python Code: # Downloading data - you get this for free :-) import requests import os def download_book(url): Download book given a url to a book in .txt format and return it as a string. text_request = requests.get(url) text = text_request.text return text book_urls = dict() book_urls['HuckF...
5,101
Given the following text description, write Python code to implement the functionality described below step by step Description: Data generation Step1: Preparing data set sweep First, we're going to define the data sets that we'll sweep over. The following cell does not need to be modified unless if you wish to chang...
Python Code: from os.path import join, expandvars from joblib import Parallel, delayed from glob import glob from os import system from tax_credit.framework_functions import (parameter_sweep, generate_per_method_biom_tables, move_r...
5,102
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: train-test split evaluation random forest on the housing dataset
Python Code:: from pandas import read_csv from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_absolute_error # load dataset url = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/housing.csv' dataframe = read_csv(url, heade...
5,103
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to BASS! Version Step1: Instructions For help, check out the wiki Step2: OPTIONAL GRAPHS AND ANALYSIS The following blocks are optional calls to other figures and analysis Display ...
Python Code: from BASS import * Explanation: Welcome to BASS! Version: Beta 2.0 Created by Abigail Dobyns and Ryan Thorpe BASS: Biomedical Analysis Software Suite for event detection and signal processing. Copyright (C) 2015 Abigail Dobyns This program is free software: you can redistribute it and/or modify it under t...
5,104
Given the following text description, write Python code to implement the functionality described below step by step Description: GPU and CPU settings If GPU is not available, comment out the bottom block. Step1: Plot training and test accuracy
Python Code: # If GPU is not available: # GPU_USE = '/cpu:0' # config = tf.ConfigProto(device_count = {"GPU": 0}) # If GPU is available: config = tf.ConfigProto() config.log_device_placement = True config.allow_soft_placement = True config.gpu_options.allocator_type = 'BFC' # Limit the maximum memory used config.gpu_...
5,105
Given the following text description, write Python code to implement the functionality described below step by step Description: Hello World! Python Workshops @ Think Coffee 3-5pm, 7/30/17 Day 3, Alice NLP generator @python script author (original content) Step1: Setting params for model setup and build. Step2: Load...
Python Code: from __future__ import print_function from keras.models import Model from keras.layers import Dense, Activation, Embedding from keras.layers import LSTM, Input from keras.layers.merge import concatenate from keras.optimizers import RMSprop, Adam from keras.utils.data_utils import get_file from keras.layers...
5,106
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial 4 Step1: Plotting the results
Python Code: import logging import sys import espressomd import espressomd.accumulators import espressomd.lb import espressomd.observables logging.basicConfig(level=logging.INFO, stream=sys.stdout) # Constants LOOPS = 40000 STEPS = 10 # System setup system = espressomd.System(box_l=[16] * 3) system.time_step = 0.01 sys...
5,107
Given the following text description, write Python code to implement the functionality described below step by step Description: Pagination and encapsulation Step1: Path parameters OAS3 allows to specify path parameters Step2: Exercise Step3: Exercise Step4: Now run the spec in a terminal using cd /code/notebooks...
Python Code: # Use this cell to test the output !curl http://localhost:5000/datetime/v1/timezones -vk Explanation: Pagination and encapsulation: In our standardization policy, we defined a common set of pagination parameters. Moreover we stated that responses should always be enclosed in json objects, eg: always return...
5,108
Given the following text description, write Python code to implement the functionality described below step by step Description: Step5: Project on frame buckling Define a new class Frame_Buckling as a child of the class LinearFrame provided in frame.py. Add in this class methods to extract the normal stress $\bar N_0$...
Python Code: %matplotlib inline from sympy.interactive import printing printing.init_printing() from frame import * import sympy as sp import numpy as np import scipy.sparse as sparse import scipy.sparse.linalg as linalg class Frame_Buckling(LinearFrame): def N_local_stress(self,element): Returns...
5,109
Given the following text description, write Python code to implement the functionality described below step by step Description: Teorema de Norton Jupyter Notebook desenvolvido por Gustavo S.S. O teorema de Norton afirma que um circuito linear de dois terminais pode ser substituído por um circuito equivalente formado ...
Python Code: print("Exemplo 4.11") #Superposicao #Analise Fonte de Tensao #Req1 = 4 + 8 + 8 = 20 #i1 = 12/20 = 3/5 A #Analise Fonte de Corrente #i2 = 2*4/(4 + 8 + 8) = 8/20 = 2/5 A #in = i1 + i2 = 1A In = 1 #Req2 = paralelo entre Req 1 e 5 #20*5/(20 + 5) = 100/25 = 4 Rn = 4 print("Corrente In:",In,"A") print("Resistênc...
5,110
Given the following text description, write Python code to implement the functionality described below step by step Description: Lyzenga Method I want to apply the Lyzenga 2006 method for comparison. Step1: Preprocessing That happened here. Step2: Depth Limit Lyzenga et al methods for determining shallow water don't...
Python Code: %pylab inline import geopandas as gpd import pandas as pd from OpticalRS import * from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error from sklearn.cross_validation import train_test_split import itertools import statsmodels.formula.api as smf from collections im...
5,111
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploring netCDF Datasets Using the xarray Package This notebook provides discussion, examples, and best practices for working with netCDF datasets in Python using the xarray package. Topics...
Python Code: import numpy as np import xarray as xr Explanation: Exploring netCDF Datasets Using the xarray Package This notebook provides discussion, examples, and best practices for working with netCDF datasets in Python using the xarray package. Topics include: The xarray package Reading netCDF datasets into Python ...
5,112
Given the following text description, write Python code to implement the functionality described below step by step Description: The Sequential model is a linear stack of layers. You can create a Sequential model by passing a list of layer instances to the constructor Step1: You can also simply add layers via the .ad...
Python Code: from keras.models import Sequential from keras.layers import Dense, Activation model = Sequential([ Dense(32, input_shape=(784,)), Activation('relu'), Dense(10), Activation('softmax'), ]) Explanation: The Sequential model is a linear stack of layers. You can create a Sequential model by pas...
5,113
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting started with mne.Report This tutorial covers making interactive HTML summaries with Step1: Before getting started with Step2: This report yields a textual summary of the Step3: ...
Python Code: import os import mne Explanation: Getting started with mne.Report This tutorial covers making interactive HTML summaries with :class:mne.Report. :depth: 2 As usual we'll start by importing the modules we need and loading some example data <sample-dataset>: End of explanation path = mne.datasets.sa...
5,114
Given the following text description, write Python code to implement the functionality described below step by step Description: LAB 01 Step1: The source dataset Our dataset is hosted in BigQuery. The taxi fare data is a publically available dataset, meaning anyone with a GCP account has access. Click here to acess t...
Python Code: %%bash export PROJECT=$(gcloud config list project --format "value(core.project)") echo "Your current GCP Project Name is: "$PROJECT Explanation: LAB 01: Basic Feature Engineering in BQML Learning Objectives Create SQL statements to evaluate the model Extract temporal features Perform a feature cross on t...
5,115
Given the following text description, write Python code to implement the functionality described below step by step Description: Please find torch implementation of this notebook here Step2: Implementation Utility functions. Step6: Main function. Step7: Example The shape of the multi-head attention output is (batch...
Python Code: import jax import jax.numpy as jnp # JAX NumPy from jax import lax import math from IPython import display try: from flax import linen as nn # The Linen API except ModuleNotFoundError: %pip install -qq flax from flax import linen as nn # The Linen API from flax.training import train_state #...
5,116
Given the following text description, write Python code to implement the functionality described. Description: Count pairs of nodes having minimum distance between them equal to the difference of their distances from root Stores the count of pairs ; Store the adjacency list of the connecting vertex ; Function for theto...
Python Code: ans = 0 adj =[[ ] for i in range(10 ** 5 + 1 ) ] def dfsUtil(u , par , depth ) : global adj , ans for it in adj[u ] : if(it != par ) : dfsUtil(it , u , depth + 1 )   ans += depth  def dfs(u , par , depth ) : global ans dfsUtil(u , par , depth ) print(ans )  def countPairs(ed...
5,117
Given the following text description, write Python code to implement the functionality described below step by step Description: A Simple Autoencoder We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed represen...
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) Explanation: A Simple Autoencoder We'll start off by building a simple autoencoder to c...
5,118
Given the following text description, write Python code to implement the functionality described below step by step Description: django-postgre-copy speed tests By Ben Welsh This notebook tests the effect of dropping database constraints and indexes prior to loading a large data file. The official PostgreSQL documenta...
Python Code: import os import sys import csv import calculate import scipy as sp import pandas as pd import scipy.optimize from pprint import pprint import matplotlib as mpl from matplotlib import rcParams rcParams['font.family'] = 'monospace' import matplotlib.pyplot as plt import matplotlib.ticker as mtick import mat...
5,119
Given the following text description, write Python code to implement the functionality described below step by step Description: San Diego Burrito Analytics Step1: Load data Step2: Brief metadata Step3: What types of burritos have been rated? Step4: Progress in number of burritos rated Step5: Burrito dimension di...
Python Code: %config InlineBackend.figure_format = 'retina' %matplotlib inline import numpy as np import scipy as sp import matplotlib.pyplot as plt import pandas as pd import seaborn as sns sns.set_style("white") Explanation: San Diego Burrito Analytics: Data characterization Scott Cole 21 May 2016 This notebook chara...
5,120
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: PYT-DS Step3: This is not quite how we want to see the data. We need to flip it, or swap axes. Transpose will do. Then lets change the column names. Finally, we'll sort.
Python Code: import pandas as pd import numpy as np Created on Thu Jun 29 10:17:02 2017 Rewritten for get_data package on Oct 25, 2017 @author: Kirby Urner Decorated generator used IN PLACE OF: class Url: def __init__(self, the_url): self.url = the_url def __enter__(self): sel...
5,121
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: <H1>Solving 1st order ODEs</H1> The logistic equation is a first-order non-linear differential equation that describes the evolution of a population as a function of the population si...
Python Code: def diff(p, generation): Returns the as size of the population as a function of the generation defined in the following differential equation: dp/dg = p*(k-p)/tau, where p is the population size, g is the generation index, k is the maximal population size (fixed to 1000)...
5,122
Given the following text description, write Python code to implement the functionality described below step by step Description: Feature Engineering |Session | Session | |-----------|---------| |Feature Engineering I | Feature Transformation and Dimension Reduction (PCA)| |Feature Engineering II | Nonlinear Dim...
Python Code: from IPython.display import Image import matplotlib.pyplot as plt import numpy as np import pandas as pd import time %matplotlib inline Explanation: Feature Engineering |Session | Session | |-----------|---------| |Feature Engineering I | Feature Transformation and Dimension Reduction (PCA)| |Feature E...
5,123
Given the following text description, write Python code to implement the functionality described below step by step Description: Cahn-Hilliard Example This example demonstrates how to use PyMKS to solve the Cahn-Hilliard equation. The first section provides some background information about the Cahn-Hilliard equation ...
Python Code: %matplotlib inline %load_ext autoreload %autoreload 2 import numpy as np import matplotlib.pyplot as plt Explanation: Cahn-Hilliard Example This example demonstrates how to use PyMKS to solve the Cahn-Hilliard equation. The first section provides some background information about the Cahn-Hilliard equation...
5,124
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Land MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify do...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'miroc', 'sandbox-2', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: MIROC Source ID: SANDBOX-2 Topic: Land Sub-Topics: Soil, Snow, Vegetation, Ene...
5,125
Given the following text description, write Python code to implement the functionality described below step by step Description: Display Exercise 1 Imports Put any needed imports needed to display rich output the following cell Step1: Basic rich display Find a Physics related image on the internet and display it in t...
Python Code: from IPython.display import HTML from IPython.display import Image from IPython.display import IFrame assert True # leave this to grade the import statements Explanation: Display Exercise 1 Imports Put any needed imports needed to display rich output the following cell: End of explanation Image(url = "http...
5,126
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align = 'center'> Neural Networks Demystified </h1> <h2 align = 'center'> Part 7 Step1: Last time, we trained our Neural Network, and it made suspiciously good predictions of your test ...
Python Code: from IPython.display import YouTubeVideo YouTubeVideo('S4ZUwgesjS8') Explanation: <h1 align = 'center'> Neural Networks Demystified </h1> <h2 align = 'center'> Part 7: Overfitting, Testing, and Regularization </h2> <h4 align = 'center' > @stephencwelch </h4> End of explanation %pylab inline from partSix im...
5,127
Given the following text description, write Python code to implement the functionality described below step by step Description: Я запустил алгоритм на случайных тестах, размера начиная с 2 и он обсчитывает по 10 тестов одного размера. Я хочу попробовать проанализировать данные, которые получу в результате его работы....
Python Code: class Node: def __init__(self, number, cost, time, answer): self.number = int(number) self.cost = float(cost) self.time = float(time) / 10**9 self.size = self.number / 100 self.answer = answer def write(self): print("n = ", self.number," \n") ...
5,128
Given the following text description, write Python code to implement the functionality described below step by step Description: <h2>Assignment 1 – Problem 2 Step1: <h3>Michell Structure Geometry</h3> I approach generating the Michell structure by repeating a series of steps <b><i>up</i></b> and <b><i>across</i></b>....
Python Code: import numpy as np from scipy import integrate from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.colors import LinearSegmentedColormap from scipy.optimize import fsolve import scipy.spatial.distance as dist import math from frame3dd import Frame, NodeData, Reacti...
5,129
Given the following text description, write Python code to implement the functionality described below step by step Description: Sebastian Raschka, 2015 Python Machine Learning Essentials Chapter 11 - Working with Unlabeled Data – Clustering Analysis Note that the optional watermark extension is a small IPython notebo...
Python Code: %load_ext watermark %watermark -a 'Sebastian Raschka' -u -d -v -p numpy,pandas,matplotlib,scipy,scikit-learn # to install watermark just uncomment the following line: #%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py Explanation: Sebastian Raschka, 2015 Python Machine Lear...
5,130
Given the following text description, write Python code to implement the functionality described below step by step Description: Author Step1: First let's check if there are new or deleted files (only matching by file names). Step2: So we have the same set of files in both versions Step3: Let's make sure the struct...
Python Code: import collections import glob import os from os import path import matplotlib_venn import pandas as pd rome_path = path.join(os.getenv('DATA_FOLDER'), 'rome/csv') OLD_VERSION = '337' NEW_VERSION = '338' old_version_files = frozenset(glob.glob(rome_path + '/*{}*'.format(OLD_VERSION))) new_version_files = f...
5,131
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Chapter 10 - Dictionaries This notebook uses code snippets and explanation from this course The last type of container we will introduce in this topic is dictionaries....
Python Code: %%capture !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Data.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/images.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Extra_Material.zip !unzip Data.zip -d ../ !unzip images.zip -d ....
5,132
Given the following text description, write Python code to implement the functionality described below step by step Description: First, we need to set up our test data. We'll use two relaxation modes that are themselves log-normally distributed. Step1: Now, let's construct the moduli. We'll have both a true version a...
Python Code: def H(tau): g1 = 1; tau1 = 0.03; sd1 = 0.5; g2 = 7; tau2 = 10; sd2 = 0.5; term1 = g1/np.sqrt(2*sd1**2*np.pi) * np.exp(-(np.log10(tau/tau1)**2)/(2*sd1**2)) term2 = g2/np.sqrt(2*sd2**2*np.pi) * np.exp(-(np.log10(tau/tau2)**2)/(2*sd2**2)) return term1 + term2 Nfreq = 50 Nmodes = 30 w = np....
5,133
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook Title <a class="tocSkip"> Make some notes here for the thought process, steps taken, TODOs. Imports Import deps Map all dependencies under categories, for easier tracking / readabil...
Python Code: # BASE ------------------------------------ from datetime import datetime as dt nb_start = dt.now() # Be mindful when you have this activated. # import warnings # warnings.filterwarnings('ignore') import json from pathlib import Path from time import sleep # Display libs from IPython.display import display...
5,134
Given the following text description, write Python code to implement the functionality described below step by step Description: Plot RBM maps to start, just plot the RBM maps, shows what is going on here Step1: Calculate On Counts and Acceptance This is done by reading in the on counts and integral acceptance maps a...
Python Code: if plot: fig = plt.figure(figsize=(12, 12)) fig1 = aplpy.FITSFigure(fitsF, figure=fig, subplot=(2,3,1), hdu=5) fig1.show_colorscale() standard_setup(fig1) fig1.set_title("Acceptance") fig1 = aplpy.FITSFigure(fitsF, figure=fig, subplot=(2,3,2), hdu=7) fig1.show_colorscale() ...
5,135
Given the following text description, write Python code to implement the functionality described below step by step Description: Executed Step1: Load software and filenames definitions Step2: Data folder Step3: List of data files Step4: Data load Initial loading of the data Step5: Load the leakage coefficient fro...
Python Code: ph_sel_name = "None" data_id = "17d" # data_id = "7d" Explanation: Executed: Mon Mar 27 11:38:52 2017 Duration: 7 seconds. usALEX-5samples - Template This notebook is executed through 8-spots paper analysis. For a direct execution, uncomment the cell below. End of explanation from fretbursts import * init_...
5,136
Given the following text description, write Python code to implement the functionality described below step by step Description: Cyclical figurate numbers Problem 61 Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated by the following formul...
Python Code: from euler import timer, Seq, fst, snd def p061(): values = ([lambda n: n*(n+1)/2, lambda n: n*n, lambda n: n*(3*n-1)/2, lambda n: n*(2*n-1), lambda n: n*(5*n-3)/2, lambda n: n*(3*n-2)] >> Seq.mapi(lambda n: n) >> Seq.collect(lambda (i,fun): ...
5,137
Given the following text description, write Python code to implement the functionality described below step by step Description: MongoBase starting guide Step1: ObjectId First, let's talk about ObjectId. Step2: Actually, ObjectId is usuful. It is unique, sortable and memory efficient. http Step3: The __structure__ ...
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline import sys import time import threading import multiprocessing import datetime as dt from mongobase.mongobase import MongoBase, db_context from bson import ObjectId Explanation: MongoBase starting guide End of explanation x = ObjectId() time.sleep(1) y ...
5,138
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex client library Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Once you've installed the Vertex client library and Google clo...
Python Code: import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG Explanation: Vertex client library: AutoML image classification model for export to edge <table al...
5,139
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook I'll show probabilistic interpretation of the nearest neighbours algorith as a mixture of Gaussians. Following Barber 2012. First I'll give an example of ... Next, I'll show...
Python Code: import scipy.io as sio nndata = sio.loadmat('/Users/gm/Downloads/BRMLtoolkit/data/NNdata.mat') nndata Explanation: In this notebook I'll show probabilistic interpretation of the nearest neighbours algorith as a mixture of Gaussians. Following Barber 2012. First I'll give an example of ... Next, I'll show h...
5,140
Given the following text description, write Python code to implement the functionality described below step by step Description: SPDX-FileCopyrightText Step1: Initialize wind farm To initialize a specific wind farm you need to provide a wind turbine fleet specifying the wind turbines and their number or total install...
Python Code: import pandas as pd import modelchain_example as mc_e from windpowerlib import TurbineClusterModelChain, WindTurbineCluster, WindFarm import logging logging.getLogger().setLevel(logging.DEBUG) # Get weather data weather = mc_e.get_weather_data('weather.csv') print(weather[['wind_speed', 'temperature', 'pre...
5,141
Given the following text description, write Python code to implement the functionality described below step by step Description: Compare speed python list vs numpy ops Let's implement standard deviation function. And compare computation time for 10 million numbers. Step1: As we can see numpy function much fater than ...
Python Code: n = 10 ** 7 # Implementation using python list def std(x:list): x_mean = sum(x)/len(x) y = sum([(v - x_mean) ** 2 for v in x])/len(x) return y**0.5 %time std(range(n)) # Implementation using numpy array function def std_np(x): x_mean = np.sum(x)/len(x) return (((x - x_mean) ** 2).mean()...
5,142
Given the following text description, write Python code to implement the functionality described below step by step Description: Download lists of experiments by injection hemisphere, mouse cre line, and injection structure Download Pvalb experiments injected in the left hemisphere VISp Step1: Download grid data for ...
Python Code: # Get the atlas id def query_atlases(search_pattern): return rma.build_query_url(rma.model_stage('Atlas', criteria="[name$il'%s']" % (search_pattern), only=['id', 'name'])) atlases = o.do_query(query_atlases, ...
5,143
Given the following text description, write Python code to implement the functionality described below step by step Description: The idea In my previous blog post, we got to know the idea of "indentation-based complexity". We took a static view on the Linux kernel to spot the most complex areas. This time, we wanna tr...
Python Code: import pandas as pd diff_raw = pd.read_csv( "../../buschmais-spring-petclinic_fork/git_diff.log", sep="\n", names=["raw"]) diff_raw.head(16) Explanation: The idea In my previous blog post, we got to know the idea of "indentation-based complexity". We took a static view on the Linux kernel to sp...
5,144
Given the following text description, write Python code to implement the functionality described below step by step Description: Boundary conditions This example shows solutions to time-dependent diffusion equations formulated with different boundary conditions. Isolated, Dirichlet (prescribed value) and periodic boun...
Python Code: %matplotlib inline import matplotlib.pylab as plt from oedes import * init_notebook() from matplotlib import ticker Explanation: Boundary conditions This example shows solutions to time-dependent diffusion equations formulated with different boundary conditions. Isolated, Dirichlet (prescribed value) and p...
5,145
Given the following text description, write Python code to implement the functionality described below step by step Description: DFF and TFF (Toggle Flip-Flop) In this example we create a toggle flip-flop (TFF) from a d-flip-flop (DFF). In Magma, finite state machines can be constructed by composing combinational logi...
Python Code: import magma as m from mantle import DFF class TFF(m.Circuit): io = m.IO(O=m.Out(m.Bit)) + m.ClockIO() # instance a dff to hold the state of the toggle flip-flop - this needs to be done first dff = DFF() # compute the next state as the not of the old state ff.O io.O <= dff(~dff.O) ...
5,146
Given the following text description, write Python code to implement the functionality described below step by step Description: NBA Player Statistics Workshop Given a dataset of NBA players performance and salary in 2014, use Python to load the dataset and compute the summary statistics for the SALARY field Step2: F...
Python Code: # Imports - you'll need some of these later, but it's traditional to put them all at the beginning. import os import csv import json import urllib2 from collections import Counter from operator import itemgetter Explanation: NBA Player Statistics Workshop Given a dataset of NBA players performance and sala...
5,147
Given the following text description, write Python code to implement the functionality described below step by step Description: AI Explanations Step1: Region You can also change the REGION variable, which is used for operations throughout the rest of this notebook. Make sure to choose a region where Cloud AI Platfor...
Python Code: PROJECT_ID = "[your-project-id]" #@param {type:"string"} if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]": # Get your GCP project id from gcloud shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Pr...
5,148
Given the following text description, write Python code to implement the functionality described below step by step Description: apsis on the BRML cluster Generally, apsis consists of a server, whose task it is to generate new candidates and receive updates, and several worker processes, who evaluate the actual machin...
Python Code: from apsis_client.apsis_connection import Connection conn = Connection(server_address="http://localhost:5000") Explanation: apsis on the BRML cluster Generally, apsis consists of a server, whose task it is to generate new candidates and receive updates, and several worker processes, who evaluate the actual...
5,149
Given the following text description, write Python code to implement the functionality described below step by step Description: Multivariate Regression Let's grab a small little data set of Blue Book car values Step1: We can use pandas to split up this matrix into the feature vectors we're interested in, and the val...
Python Code: import pandas as pd df = pd.read_excel('http://cdn.sundog-soft.com/Udemy/DataScience/cars.xls') df.head() Explanation: Multivariate Regression Let's grab a small little data set of Blue Book car values: End of explanation import statsmodels.api as sm df['Model_ord'] = pd.Categorical(df.Model).codes X = df[...
5,150
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning with TensorFlow Credits Step1: First reload the data we generated in notmist.ipynb. Step2: Reformat into a shape that's more adapted to the models we're going to train Step3:...
Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. import cPickle as pickle import numpy as np import tensorflow as tf Explanation: Deep Learning with TensorFlow Credits: Forked from TensorFlow by Google Setup Refer to the setup instructions. Exerci...
5,151
Given the following text description, write Python code to implement the functionality described below step by step Description: Latent Dirichlet Allocation for Text Data In this assignment you will apply standard preprocessing techniques on Wikipedia text data use GraphLab Create to fit a Latent Dirichlet allocation ...
Python Code: import graphlab as gl import numpy as np import matplotlib.pyplot as plt %matplotlib inline '''Check GraphLab Create version''' from distutils.version import StrictVersion assert (StrictVersion(gl.version) >= StrictVersion('1.8.5')), 'GraphLab Create must be version 1.8.5 or later.' # import wiki data wik...
5,152
Given the following text description, write Python code to implement the functionality described below step by step Description: Stage 1 Step1: In the code bellow, resize image into the special resolution Step2: 1.1 Create a standard training dataset Step4: Generate tfrecords Step5: Read a batch images Step6: Exa...
Python Code: %matplotlib inline import glob import os import numpy as np from scipy.misc import imread, imresize import matplotlib.pyplot as plt import tensorflow as tf raw_image = imread('model/datasets/nudity_dataset/3.jpg') # Define a tensor placeholder to store an image image = tf.placeholder("uint8", [None, None, ...
5,153
Given the following text description, write Python code to implement the functionality described below step by step Description: Step7: Arbres binaires Le but de ce TP est d'implanter les fonctions usuelles telles que la génération exhaustive (fabriquer tous les éléments de l'ensemble), rank et unrank sur l'ensemble d...
Python Code: class BinaryTree(): def __init__(self, children = None): A binary tree is either a leaf or a node with two subtrees. INPUT: - children, either None (for a leaf), or a list of size excatly 2 of either two binary trees or 2 obje...
5,154
Given the following text description, write Python code to implement the functionality described below step by step Description: Hello world! The beginning of almost everything in computer programming Step1: <a id='Jupyter'></a> 2. Interacting with Jupyter Notebook This interface (what you are reading now) is know a...
Python Code: !python -c "print('Hello world!')" Explanation: Hello world! The beginning of almost everything in computer programming :-) Let's see different alternatives to run Python code. Contents "Batch" running of single commands. Interacting with Jupyter Notebooks. Interacting with Python interpreters. "Batch" run...
5,155
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Creating a custom Word2Vec embedding on your data </h1> This notebook illustrates Step2: Creating a training dataset The training dataset simply consists of a bunch of words separated ...
Python Code: # change these to try this notebook out BUCKET = 'alexhanna-dev-ml' PROJECT = 'alexhanna-dev' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION Explanation: <h1> Creating a custom Word2Vec embedding on your data </h1> This notebook ...
5,156
Given the following text description, write Python code to implement the functionality described below step by step Description: BEM++ overview https Step1: Q Step2: What mean these arguments? The first argument is always grid object The second argument can be discontinious polynomial ("DP"), polynomial ("P") or som...
Python Code: import bempp.api import numpy as np grid = bempp.api.shapes.regular_sphere(3) grid.plot() Explanation: BEM++ overview https://bempp.com/ Overview Overview presentation here. Applicable only for 3D problems Support Laplace, Helmholtz and Maxwell equations with Dirichlet and Neumann boundary conditions Suppo...
5,157
Given the following text description, write Python code to implement the functionality described below step by step Description: DV360 Automation Step1: 0.2 Setup your GCP project To utilise the DV360 API, you need a Google Cloud project. For the purpose of this workshop, we've done this for you, but normally you'd h...
Python Code: !pip install google-api-python-client !pip install google-cloud-vision import csv import datetime import io import json import pprint from google.api_core import retry from google.cloud import vision from google.colab import files from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient ...
5,158
Given the following text description, write Python code to implement the functionality described below step by step Description: Sprachenvielfalt Figures for https Step1: Sprachenvielfalt http Step2: Prozentualer Anteil der Bevölkerung Step3: Analphabetismus in Prozent Step4: Karte Analphabetismus Step5: Karte in...
Python Code: import numpy as np import travelmaps2 as tm import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from matplotlib import cm, colors, rcParams plt.style.use('ggplot') # Adjust dpi, so figure on screen and savefig looks the same dpi = 100 rcParams['figure.dpi'] = dpi rcParams['savefig.dpi'...
5,159
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning with MNIST This is the mnist_mlp code with all the blanks filled in for you. The original Keras example is here Step1: Each of our 60,000 handwritten digits comes prepackaged...
Python Code: from __future__ import print_function import numpy as np np.random.seed(1337) # for reproducibility from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.optimizers import SGD, Adam, RMSprop from keras.utils import np_utils...
5,160
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: 图像分类 在此项目中,你将对 CIFAR-10 数据集 中的图片进行分类。该数据集包含飞机、猫狗和其他物体。你需要预处理这些图片,然后用所有样本训练一个卷积神经网络。图片需要标准化(normalized),标签需要采用 one-hot 编码。你需要应用所学的知识构建卷积的、最大池化(max pooling)、丢弃(dropout)和完全连接(fully conne...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if present floyd_cifa...
5,161
Given the following text description, write Python code to implement the functionality described below step by step Description: Sistema Nacional de Información e Indicadores de Vivienda ID |Descripción ---| Step1: 2. Descarga de datos Los datos se descargan por medio de una conexión a un servicio SOAP proporcionado ...
Python Code: descripciones = { 'P0405': 'Viviendas Verticales', 'P0406': 'Viviendas urbanas en PCU U1 y U2', 'P0411': 'Subsidios CONAVI' } # Librerias utilizadas import pandas as pd import sys import urllib import os import csv import zeep import requests from lxml import etree import xmltodict import ast i...
5,162
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 2 continued regular expressions Provides a way to search text. Looking for matching patterns Step3: Object-oriented programming Creating classes of objects with data and methods(fun...
Python Code: import re print all([ not re.match("a","cat"), re.search("a","cat"), not re.search("c","dog"), 3 == len(re.split("[ab]","carbs")), "R-D-" == re.sub("[0-9]","-","R2D2") ]) # prints true if all are true Explanation: Lecture 2 continued regular expressions Provides a way to search text. L...
5,163
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have my data in a pandas DataFrame, and it looks like the following:
Problem: import pandas as pd df = pd.DataFrame({'cat': ['A', 'B', 'C'], 'val1': [7, 10, 5], 'val2': [10, 2, 15], 'val3': [0, 1, 6], 'val4': [19, 14, 16]}) def g(df): df = df.set_index('cat') res = df.div(df.sum(axis=1), axis=0) retu...
5,164
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have dfs as follows:
Problem: import pandas as pd df1 = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'city': ['bj', 'bj', 'sh', 'sh', 'sh'], 'district': ['ft', 'ft', 'hp', 'hp', 'hp'], 'date': ['2019/1/1', '2019/1/1', '2019/1/1', '2019/1/1', '2019/1/1'], 'value': [1, 5, 9,...
5,165
Given the following text description, write Python code to implement the functionality described below step by step Description: Logistic Regression In this note, I am going to train a logistic regression model with gradient decent estimation. Logistic regression model can be thought as a neural network without hidden...
Python Code: import numpy as np # Matrix and vector computation package np.seterr(all='ignore') # ignore numpy warning like multiplication of inf import matplotlib.pyplot as plt # Plotting library from matplotlib.colors import colorConverter, ListedColormap # some plotting functions from matplotlib import cm # Colorma...
5,166
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 6 Step1: Problem set #2 Step2: Problem set #3 Step3: Problem set #4 Step4: Problem set #5 Step5: Specifying a field other than name, area or elevation for the sort parameter sh...
Python Code: import requests data = requests.get('http://localhost:5000/lakes').json() print(len(data), "lakes") for item in data[:10]: print(item['name'], "- elevation:", item['elevation'], "m / area:", item['area'], "km^2 / type:", item['type']) Explanation: Homework 6: Web Applications For this homework, you're ...
5,167
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 Google LLC 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 Licens...
Python Code: import pandas as pd import tensorflow as tf import numpy as np pd.set_option('expand_frame_repr', True) pd.set_option("display.max_rows", 100) pd.set_option('max_colwidth',90) Explanation: Copyright 2021 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file ex...
5,168
Given the following text description, write Python code to implement the functionality described below step by step Description: Graph Gmail inbox data with IPython notebook Step1: Download your Gmail inbox as a ".mbox" file by clicking on "Account" under your Gmail user menu, then "Download data" Install the Python ...
Python Code: from IPython.display import Image Image('http://i.imgur.com/SYija2N.png') Explanation: Graph Gmail inbox data with IPython notebook End of explanation import mailbox from email.utils import parsedate from dateutil.parser import parse import itertools import plotly.plotly as py from plotly.graph_objs import...
5,169
Given the following text description, write Python code to implement the functionality described below step by step Description: Zillow’s Home Value Prediction (Zestimate) Zillow's Zestimate is created to give consumers as much information as possible about homes and the housing market, marking consumers had access to...
Python Code: import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import numpy as np import missingno as msno import xgboost as xgb from sklearn.preprocessing import scale from xgboost.sklearn import XGBRegressor from sklearn.linear_model import Ridge from sklearn import cross_validation, metrics #A...
5,170
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 numpy as np import pandas as pd from h2o.estimators.gbm import H2OGradientBoostingEstimator # start h2o h2o.init() h2o.remove_all() Explanation: License Copyright 2017 J. Patrick Hall, jphall@gwu.edu Permission is hereby granted, free of charge, to any person obtaining a copy o...
5,171
Given the following text description, write Python code to implement the functionality described below step by step Description: Inverted encoding model Step1: In this example, we will assume that the stimuli are patches of different motion directions. These stimuli span a 360-degree, circular feature space. We will ...
Python Code: import numpy as np from brainiak.reconstruct import iem as IEM import matplotlib.pyplot as plt import numpy.matlib as matlib import scipy.signal Explanation: Inverted encoding model End of explanation # Set up parameters n_channels = 6 cos_exponent = 5 range_start = 0 range_stop = 360 feature_resolution = ...
5,172
Given the following text description, write Python code to implement the functionality described below step by step Description: Week 1 Step1: Make a vector with 6 elements Step2: Get some information about the vector Step3: Create a matrix like this Step4: Get some information about the matrix Step5: A very powe...
Python Code: import numpy as np Explanation: Week 1: Getting Started with Jupyter Notebooks In this notebook, we will make sure all the packages required for this course are properly installed and working. To use this notebook, select the input cells (shown as In [x]) in order and press Shift-Enter to execute the code...
5,173
Given the following text description, write Python code to implement the functionality described below step by step Description: Content and Objectives Show effects of multipath on a pulse and on a pulse-shaped data signal for random data Import Step1: Function for determining the impulse response of an RC filter Ste...
Python Code: # importing import numpy as np import matplotlib.pyplot as plt import matplotlib # showing figures inline %matplotlib inline # plotting options font = {'size' : 20} plt.rc('font', **font) plt.rc('text', usetex=True) matplotlib.rc('figure', figsize=(18, 10) ) Explanation: Content and Objectives Show effe...
5,174
Given the following text description, write Python code to implement the functionality described below step by step Description: Testing Nsaba Functionality Current Methods get_aba_ge() ge_ratio() get_ns_act() make_ge_ns_mat() coords_to_ge() Step1: Coordinates to gene expression Step2: Visualization Methods (testing...
Python Code: %matplotlib inline from nsaba.nsaba import Nsaba from nsaba.nsaba.visualizer import NsabaVisualizer import numpy as np import os import matplotlib.pyplot as plt import pandas as pd import itertools %load_ext line_profiler # Simon Path IO data_dir = '../../data_dir' os.chdir(data_dir) Nsaba.aba_load() Nsaba...
5,175
Given the following text description, write Python code to implement the functionality described below step by step Description: xlsxWriter tutorial install sudo pip install XlsxWriter 아나콘다 설치시 기본적으로 내장되어 있음 Step1: tutorial 1 Step2: <img src="https Step3: Tutorial 2 Step4: Tutorial 3 Step5: write() method 여기에 더 ...
Python Code: import xlsxwriter workbook = xlsxwriter.Workbook('hello.xlsx') worksheet = workbook.add_worksheet() worksheet.write('A1', 'Hello world') workbook.close() Explanation: xlsxWriter tutorial install sudo pip install XlsxWriter 아나콘다 설치시 기본적으로 내장되어 있음 End of explanation expenses = ( ['Rent', 1000], ['Gas...
5,176
Given the following text description, write Python code to implement the functionality described below step by step Description: Analysis of Seattle Fremont Bridge Bike Traffic Step1: Get Data Step2: Shows a graph of data on a weekly basis. Let's investigate what the pattern is when we look at hourly rates on indivi...
Python Code: %matplotlib inline import matplotlib.pyplot as plt; from jubiiworkflow.data import get_data import pandas as pd import numpy as np from sklearn.decomposition import PCA from sklearn.mixture import GaussianMixture plt.style.use('seaborn'); Explanation: Analysis of Seattle Fremont Bridge Bike Traffic End of ...
5,177
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Tuples Reference Table of contents <a href="#1.-Creation">Creation</a> <a href="#2.-Basic-Operations">Basic Operations</a> <a href="#3.-Unpacking">Unpacking</a> <a href="#4.-Comparing...
Python Code: # Create a tuple directly digits = (0, 1, 'two') digits # Create a tuple from a list digits = tuple([0, 1, 'two']) digits # For a single item tuple, a trailing comma is required to tell the intepreter its a tuple zero = (0,) zero Explanation: Python Tuples Reference Table of contents <a href="#1.-Creation"...
5,178
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 4 Step1: Now, let's connect to your Postgres database. On your Heroku Postgres details, look at the credentials for the database. Take the long URI in the credentials and replace t...
Python Code: import numpy as np import pandas as pd %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import sqlalchemy !pip install -U okpy from client.api.notebook import Notebook ok = Notebook('hw4.ok') Explanation: Homework 4: SQL, FEC Data, and Small Donors Due: 11:59pm Tuesday, March 14 Not...
5,179
Given the following text description, write Python code to implement the functionality described below step by step Description: Example plot for LFPy Step1: Fetch Mainen&Sejnowski 1996 model files Step2: Main script, set parameters and create cell, synapse and electrode objects Step3: Plot simulation output
Python Code: import LFPy import numpy as np import os import sys from urllib.request import urlopen import ssl import zipfile import matplotlib.pyplot as plt from matplotlib.collections import PolyCollection from os.path import join Explanation: Example plot for LFPy: Single-synapse contribution to the LFP Copyright (C...
5,180
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook provides an interactive overview to some if the ideas developed in a paper entitled "Error Statistics", by Mayo and Spanos. Goals For a sample of data Step1: All hypotheses di...
Python Code: from scipy.stats import norm # properties of the distribution from numpy.random import normal # samples from the distribution import numpy as np import scipy from matplotlib import pyplot as plt %matplotlib inline Explanation: This notebook provides an interactive overview to some if the ideas developed in...
5,181
Given the following text description, write Python code to implement the functionality described below step by step Description: Script to copy files to Anaconda paths so can import and use scripts Step1: find main path for install Step2: make list of paths need to copy files to & add main path Step3: add paths to ...
Python Code: module_name = 'bradlib' Explanation: Script to copy files to Anaconda paths so can import and use scripts End of explanation from distutils.sysconfig import get_python_lib #; print(get_python_lib()) path_main = get_python_lib() path_main path_main.split('Anaconda3') Explanation: find main path for install ...
5,182
Given the following text description, write Python code to implement the functionality described below step by step Description: scikit-learn-linear-reg Credits Step1: Linear Regression Linear Regression is a supervised learning algorithm that models the relationship between a scalar dependent variable y and one or m...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import seaborn; from sklearn.linear_model import LinearRegression import pylab as pl seaborn.set() Explanation: scikit-learn-linear-reg Credits: Forked from PyCon 2015 Scikit-learn Tutorial by Jake VanderPlas Linear Regression End of ex...
5,183
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Given the following example:
Problem: import numpy as np from sklearn.feature_selection import SelectKBest from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline import pandas as pd data, target = load_data() pipe = Pipeline(steps=[ ('select', SelectKBest(k=2)), ('clf', LogisticRegression())] ) select_out...
5,184
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Functions Test Solutions For this test, you should use the built-in functions to be able to write the requested functions in one line. Problem 1 Use map to create a function which f...
Python Code: def word_lengths(phrase): return list(map(len, phrase.split())) word_lengths('How long are the words in this phrase') Explanation: Advanced Functions Test Solutions For this test, you should use the built-in functions to be able to write the requested functions in one line. Problem 1 Use map to cr...
5,185
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 11. Null Hypothesis Significance Testing Exercise 11.1 Exercise 11.2 Exercise 11.3 Exercise 11.1 Purpose Step1: Part B fixed z Step2: Exercise 11.2 Purpose Step3: Part A fixed N S...
Python Code: import numpy as np from scipy.misc import factorial N = 45 z = 3 theta = 1/6 def binomial(theta, N, z): coef = factorial(N) / factorial(N-z) / factorial(z) p = coef * theta**z * (1 - theta)**(N-z) return p tail = np.arange(z+1) tail p = binomial(theta, N, tail).sum() * 2 # left and right tail p...
5,186
Given the following text description, write Python code to implement the functionality described below step by step Description: https Step1: https Step2: Symmetric Difference https
Python Code: # Это единственный комментарий который имеет смысл # I s def find_index(m,a): try: return a.index(m) except : return -1 def find_two_sum(a, s): ''' >>> (3, 5) == find_two_sum([1, 3, 5, 7, 9], 12) True ''' if len(a)<2: return (-1,-1) idx = d...
5,187
Given the following text description, write Python code to implement the functionality described below step by step Description: PROV Templates in Python Author Step1: Generate an example prov template and print (and store) it's provn representation Step2: Generate an example binding from a python dictionaries (one...
Python Code: # Define namespaces used and generate a new empty # python prov template instance # Define the variable settings in the template as a dictionary from provtemplates import provconv import prov.model as prov import six import itertools ns_dict = { 'prov':'http://www.w3.org/ns/prov#', 'var':'http://o...
5,188
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: 检查 TensorFlow 图 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: 定义一个 Keras 模型 在此示例中,分类器是一个简...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
5,189
Given the following text description, write Python code to implement the functionality described below step by step Description: Non-parametric 1 sample cluster statistic on single trial power This script shows how to estimate significant clusters in time-frequency power estimates. It uses a non-parametric statistical...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne.time_frequency import tfr_morlet from mne.stats import permutation_cluster_1samp_test from mne.datasets import sample print(__doc__) Exp...
5,190
Given the following text description, write Python code to implement the functionality described below step by step Description: Inital setup Step1: loading summary file that I previously created by scanning through L1A darks. Step2: These are the columns I have available in this dataset Step3: Correct mean DN for ...
Python Code: %matplotlib inline plt.rcParams['figure.figsize'] = (10,10) from matplotlib.pyplot import subplots Explanation: Inital setup End of explanation import pandas as pd df = pd.read_hdf('/home/klay6683/to_keep/l1a_dark_stats.h5','df') df.DET_TEMP.plot( Explanation: loading summary file that I previously created...
5,191
Given the following text description, write Python code to implement the functionality described below step by step Description: Objective Overview of ML Model Build Process Logistic Regression Introduction Model Evaluations Step1: Model Building Process Step2: Dataset Step3: Logistic Regression - Model Take a weig...
Python Code: from __future__ import print_function # Python 2/3 compatibility from IPython.display import Image import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline Explanation: Objective Overview of ML Model Build Process Logistic Regression Introduction Model Evaluations End of e...
5,192
Given the following text description, write Python code to implement the functionality described below step by step Description: Training Collaborative Experts on MSR-VTT This notebook shows how to download code that trains a Collaborative Experts model with GPT-1 + NetVLAD on the MSR-VTT Dataset. Setup Download Code ...
Python Code: %tensorflow_version 2.x !git clone https://github.com/googleinterns/via-content-understanding.git %cd via-content-understanding/videoretrieval/ !pip install -r requirements.txt !pip install --upgrade tensorflow_addons Explanation: Training Collaborative Experts on MSR-VTT This notebook shows how to downloa...
5,193
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Hi I've read a lot of question here on stackoverflow about this problem, but I have a little different task.
Problem: import pandas as pd df = pd.DataFrame({'DateTime': ['2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07', '2000-01-08'], 'Close': [1460, 1470, 1480, 1480, 1450]}) df['DateTime'] = pd.to_datetime(df['DateTime']) def g(df): label = [] for i in range(len(df)-1): if df.loc[i, '...
5,194
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Analysis - Text Classification with Universal Embeddings Textual data in spite of being highly unstructured, can be classified into two major types of documents. - Factual documen...
Python Code: !pip install tensorflow-hub Explanation: Sentiment Analysis - Text Classification with Universal Embeddings Textual data in spite of being highly unstructured, can be classified into two major types of documents. - Factual documents which typically depict some form of statements or facts with no specific ...
5,195
Given the following text description, write Python code to implement the functionality described below step by step Description: Speed Step1: prior to trying to fix #217
Python Code: %%timeit -n 15 lasio.examples.open("6038187_v1.2.las") Explanation: Speed End of explanation import pickle las = lasio.examples.open("logging_levels.las") len(pickle.dumps(las)) las = lasio.examples.open("6038187_v1.2.las") len(pickle.dumps(las)) Explanation: prior to trying to fix #217: 6038187_v1...
5,196
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Logistic-Regression" data-toc-modified-id="Logistic-Regression-1"><span clas...
Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', 'notebook_format')) from formats import load_style load_style(plot_style = False) os.chdir(path) # 1. magic for inline plot # 2. magic to print...
5,197
Given the following text description, write Python code to implement the functionality described below step by step Description: Decision Trees and Random Forests in Python Learning Objectives Explore and analyze data using a Pairplot Train a single Decision Tree Predict and evaluate the Decision Tree Compare the Deci...
Python Code: !pip install scikit-learn==0.22.2 Explanation: Decision Trees and Random Forests in Python Learning Objectives Explore and analyze data using a Pairplot Train a single Decision Tree Predict and evaluate the Decision Tree Compare the Decision Tree model to a Random Forest Introduction In this lab, you explo...
5,198
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmos MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cnrm-cerfacs', 'cnrm-esm2-1', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: CNRM-CERFACS Source ID: CNRM-ESM2-1 Topic: Atmos Sub-Topics: Dynami...
5,199
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 1. Introduction to Tensorflow Deep Learning Library Theano, Torch, Tensorflow가 가장 많이 사용되는 lib | Software | Creator |Opensource | I...
Python Code: # Load Module import numpy as np from sklearn import datasets from sklearn import metrics from sklearn import model_selection import tensorflow as tf # Load dataset. iris = datasets.load_iris() # 총 150개의 붓꽃 사진과 class load x_train, x_test, y_train, y_test = model_selection.train_test_split(iris.data, iris.t...