Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
15,100
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Image Classification In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images...
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' class DLProgress(tqdm): last_block = 0 def h...
15,101
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting In order to do inline plotting within a notebook, ipython needs a magic command, commands that start with the % Step1: Importing some modules (libraries) and giving them short name...
Python Code: %matplotlib inline Explanation: Plotting In order to do inline plotting within a notebook, ipython needs a magic command, commands that start with the % End of explanation import numpy as np import matplotlib.pyplot as plt Explanation: Importing some modules (libraries) and giving them short names such as ...
15,102
Given the following text description, write Python code to implement the functionality described below step by step Description: How to import the data 1. Define search filters. This is needed if some data has to be filtered out. 2. Import data from ase databases. 3. Store references and calculate formation energies. ...
Python Code: # Import and instantiate energy_landscape object. from catmap.api.ase_data import EnergyLandscape energy_landscape = EnergyLandscape() # Import all gas phase species from db. search_filter_gas = [] energy_landscape.get_molecules('molecules.db', selection=search_filter_gas) # Import all adsorbates and slabs...
15,103
Given the following text description, write Python code to implement the functionality described below step by step Description: 디리클레 분포 2차원 히스토그램이라고 보면 된다. 진하기로 표시하면 된다. 6각형으로 해야 원에 가깝기 때문에 이렇게 만들었다. 모드값만 외우면 된다. 분산에서는 밑에가 3차수. 그래서 분산값이 작아진다. 모수를 찾아가는 과정이다. 베이지안에서. 샘플의 수가 부족하기 때문에. 샘플이 무한대로 있으면 분산을 0으로 보낼 수가 있다. α 가...
Python Code: from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection fig = plt.figure() ax = Axes3D(fig) x = [1, 0, 0] y = [0, 1, 0] z = [0, 0, 1] verts = [zip(x, y, z)] ax.add_collection3d(Poly3DCollection(verts, edgecolor="k", lw=5, alpha=0.4)) ax.text(1, 0, 0, "(1,0,0)", posit...
15,104
Given the following text description, write Python code to implement the functionality described below step by step Description: Enable GPU This notebook and pretty much every other notebook in this repository will run faster if you are using a GPU. On Colab Step1: Image and patch generation functions Step2: Train ...
Python Code: import tensorflow as tf print(tf.version.VERSION) device_name = tf.test.gpu_device_name() if device_name != '/device:GPU:0': raise SystemError('GPU device not found') print('Found GPU at: {}'.format(device_name)) Explanation: Enable GPU This notebook and pretty much every other notebook in this repositor...
15,105
Given the following text description, write Python code to implement the functionality described below step by step Description: Messy Sensor Data Step1: The file seems to be tab seperated. There are dates, and some empty items. Can we read it more clearly? pandas.read_csv() is very versatile with keyword arguments....
Python Code: import pandas as pd # Open a comma-separated values (CSV) file as a DataFrame weather_observations = pd.read_csv('observations/Canberra_observations.csv') # Print the first 5 entries weather_observations.head() Explanation: Messy Sensor Data: A Programmer's Cleaning Guide @Xavier_Ho, #pyconau <small>Feel f...
15,106
Given the following text description, write Python code to implement the functionality described below step by step Description: Read CIFAR10 dataset Step1: Normalize data This maps all values in trn. and tst. data to range <-0.5,0.5>. Some kind of value normalization is preferable to provide consistent behavior acc...
Python Code: from tools import readCIFAR, mapLabelsOneHot # First run ../data/downloadCIFAR.sh # This reads the dataset trnData, tstData, trnLabels, tstLabels = readCIFAR('../data/cifar-10-batches-py') plt.subplot(1, 2, 1) img = collage(trnData[:16]) print(img.shape) plt.imshow(img) plt.subplot(1, 2, 2) img = collage(...
15,107
Given the following text description, write Python code to implement the functionality described below step by step Description: Similarity Queries using Annoy Tutorial This tutorial is about using the Annoy(Approximate Nearest Neighbors Oh Yeah) library for similarity queries in gensim Why use Annoy? The current impl...
Python Code: #Set up the model and vector that we are using in the comparison from gensim.similarities.index import AnnoyIndexer from gensim.models.word2vec import Word2Vec model = Word2Vec.load("/tmp/leemodel") model.init_sims() vector = model.syn0norm[0] annoy_index = AnnoyIndexer(model, 500) %%time #Traditional impl...
15,108
Given the following text description, write Python code to implement the functionality described below step by step Description: Load the data Step4: Computing the Cost Function Fill in the compute_cost function below Step6: Grid Search Fill in the function grid_search() below Step7: Let us play with the grid searc...
Python Code: import datetime from helpers import * height, weight, gender = load_data(sub_sample=False, add_outlier=False) x, mean_x, std_x = standardize(height) y, tx = build_model_data(x, weight) y.shape, tx.shape Explanation: Load the data End of explanation def calculate_mse(e): Calculate the mse for vector e. ...
15,109
Given the following text description, write Python code to implement the functionality described below step by step Description: <div style="width Step1: Creating the file and dimensions The first step is to create a new file and set up the shared dimensions we'll be using in the file. We'll be using the netCDF4-pyth...
Python Code: # Import some useful Python tools from datetime import datetime, timedelta import numpy as np # Twelve hours of hourly output starting at 22Z today start = datetime.utcnow().replace(hour=22, minute=0, second=0, microsecond=0) times = np.array([start + timedelta(hours=h) for h in range(13)]) # 3km spacing i...
15,110
Given the following text description, write Python code to implement the functionality described. Description: This function takes two positive numbers x and y and returns the biggest even integer number that is in the range [x, y] inclusive. If there's no such number, then the function should return -1. F...
Python Code: def choose_num(x, y): if x > y: return -1 if y % 2 == 0: return y if x == y: return -1 return y - 1
15,111
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: TensorBoard 性能分析 Step2: 确认 TensorFlow 可以看到 GPU。 Step7: 使用 TensorBoard callback 运行一个简单的模型 你将使用 Keras 来构建一个使用 ResNet56 (参考 Step8: 从 TensorFlow...
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...
15,112
Given the following text description, write Python code to implement the functionality described below step by step Description: Data from H2Cooling with Gravity Step1: $$ \rho_{BE} (r) = \frac{C_s^2}{4 \pi G r^2} =\frac{L_0^2 \rho _0 t_0}{t_0^2 L_0^2} $$ Step2: Simulate Profile Step3: $$ 4\pi \rho_0 \int _0 ^R \...
Python Code: #HCG=np.load('../Data/H2CoolingG512.npz') HCG=np.load('../Data/TabulatedG.npz') f.quadruple(HCG,np.log10(HCG['RHO']),rows=2,nn=0,tlim=26,Save_Figure='H2CoolGRquad') f.pprofile(HCG,'RHO',steps=4,itlim=26,tdk='Myrs',Save_Figure='H2CoolGRHOprofile',sc2='log',xlim=[0,20],yprop=256) f.pprofile(HCG,'Temp',steps=...
15,113
Given the following text description, write Python code to implement the functionality described below step by step Description: <p><font size="4"> MOOC Step1: 2) Letting $K$ range from 1 to 11, plot the loss probability for $\lambda = 4$ and for $\lambda = 10$ (and $\mu=5$). Remarks ? Compare it to the theoretical ...
Python Code: %matplotlib inline from pylab import * def MM1K(K=3,lambda_ = 4.,mu = 5.,N0 = 2,Tmax=100): N0 = min(N0,K)# enforcing buffer length constraint p = lambda_/(mu+lambda_) # probability that the next event is an arrival when N(t) > 0 T = [0] # list of ins...
15,114
Given the following text description, write Python code to implement the functionality described below step by step Description: Sympy (sympy.org) is a Python package used for solving equations with symbolic math. Using Python and SymPy we can write and solve equations that come up in Engineering. The example problem...
Python Code: from sympy import symbols, nonlinsolve Explanation: Sympy (sympy.org) is a Python package used for solving equations with symbolic math. Using Python and SymPy we can write and solve equations that come up in Engineering. The example problem below contains two equations with two unknown variables. You cou...
15,115
Given the following text description, write Python code to implement the functionality described below step by step Description: Testing TRICERATOPS EB modeling vs. isochrones We want to test how the luminosity-scaling method compares to physical modeling based on colors & parallax. This is the layout of the test Step...
Python Code: from isochrones import get_ichrone mist = get_ichrone('mist', bands=['TESS', 'V', 'K']) mass, age, feh = (0.8, 9.7, 0.0) distance = 10 # pc AV = 0.0 simulated_props = mist.generate(mass, age, feh, distance=distance, AV=AV) simulated_props[['mass', 'radius', 'TESS_mag', 'V_mag', 'K_mag']] Explanation: Test...
15,116
Given the following text description, write Python code to implement the functionality described. Description: Find sub Python implementation of the approach ; Function to return the sum of the sub - matrix ; Function that returns true if it is possible to find the sub - matrix with required sum ; 2 - D array to store ...
Python Code: N = 4 def getSum(r1 , r2 , c1 , c2 , dp ) : return dp[r2 ][c2 ] - dp[r2 ][c1 ] - dp[r1 ][c2 ] + dp[r1 ][c1 ]  def sumFound(K , S , grid ) : dp =[[ 0 for i in range(N + 1 ) ] for j in range(N + 1 ) ] for i in range(N ) : for j in range(N ) : dp[i + 1 ][j + 1 ] = dp[i + 1 ][j ] + dp[i ][j ...
15,117
Given the following text description, write Python code to implement the functionality described below step by step Description: Decision Tree Classifier - random_state In the previous notebook we got an accuracy score of just over 40%. Lets just do that again. Step1: and again. Step2: one more time Step3: We see ...
Python Code: # Imports from sklearn import metrics from sklearn.tree import DecisionTreeClassifier import pandas as pd # Training Data training_raw = pd.read_table("../data/training_data.dat") df_training = pd.DataFrame(training_raw) # test Data test_raw = pd.read_table("../data/test_data.dat") df_test = pd.DataFrame(t...
15,118
Given the following text description, write Python code to implement the functionality described below step by step Description: <small><i>This notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small> Introduction to Scikit-Learn Step1: This may seem like a trivial task, but it ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn') # Import the example plot from the figures directory from fig_code import plot_sgd_separator plot_sgd_separator() Explanation: <small><i>This notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></...
15,119
Given the following text description, write Python code to implement the functionality described below step by step Description: Orbital Elements We can add particles to a simulation by specifying cartesian components Step1: Any components not passed automatically default to 0. REBOUND can also accept orbital elemen...
Python Code: import rebound sim = rebound.Simulation() sim.add(m=1., x=1., vz = 2.) Explanation: Orbital Elements We can add particles to a simulation by specifying cartesian components: End of explanation sim.add(m=1., a=1.) sim.status() Explanation: Any components not passed automatically default to 0. REBOUND can a...
15,120
Given the following text description, write Python code to implement the functionality described below step by step Description: DataFrame A DataFrame is a Dataset organized into named columns. It is conceptually equivalent to a table in a relational database or a data frame in R/Python, but with richer optimizations ...
Python Code: from pyspark.sql import SQLContext sqlContext = SQLContext(sc) from pyspark.sql import Row csv_data = raw.map(lambda l: l.split(",")) row_data = csv_data.map(lambda p: Row( duration=int(p[0]), protocol_type=p[1], service=p[2], flag=p[3], src_bytes=int(p[4]), dst_bytes=int(p[5]) ...
15,121
Given the following text description, write Python code to implement the functionality described below step by step Description: Iterative Deepening The function search takes three arguments to solve a search problem Step1: The function depth_limited_search tries to find a solution to the search problem $$ \langle Q,...
Python Code: def search(start, goal, next_states): limit = 36 while True: Path = depth_limited_search(start, goal, next_states, [start], { start }, limit) if Path is not None: return Path limit += 1 print(f'limit = {limit}') Explanation: Iterative Deepening The functi...
15,122
Given the following text description, write Python code to implement the functionality described below step by step Description: Sensors Hi ha quatre sensors diferents montats i connectats al robot Step1: Sensor de tacte És un polsador, que segons estiga polsat o no, donarà un valor vertader (True) o fals (False). Pe...
Python Code: from functions import connect, touch, light, sound, ultrasonic, disconnect, next_notebook connect() Explanation: Sensors Hi ha quatre sensors diferents montats i connectats al robot: <img src="img/sensors.jpg" width=400> Els de la figura corresponen al model NXT, però els de l'EV3 són equivalents. Anem a c...
15,123
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 Google LLC. Step1: Case Study Step2: Understanding the Data Format Each row represents one labeled example. Column 0 represents the label that a human rater has assigned for...
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...
15,124
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,...
15,125
Given the following text description, write Python code to implement the functionality described below step by step Description: A strawberry flavour gene vector for Saccharomyces cerevisiae This Jupyter notebook describes the simulated cloning of the strawberry Fragaria × ananassa alcohol acyltransferase SAAT gene a...
Python Code: # Import the pydna package functions from pydna.all import * # Give your email address to Genbank, so they can contact you. # This is a requirement for using their services gb=Genbank("bjornjobb@gmail.com") # download the SAAT CDS from Genbank # We know from inspecting the saat = gb.nucleotide("AF193791 R...
15,126
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 13 Step1: The try instruction allows exception handling in Python. If an exception occurs in a block marked by try, it is possible to handle the exception through the instruction ex...
Python Code: print (10/0) Explanation: Chapter 13: Exceptions When a failure occurs in the program (such as division by zero, for example) at runtime, an exception is generated. If the exception is not handled, it will be propagated through function calls to the main program module, interrupting execution. End of expla...
15,127
Given the following text description, write Python code to implement the functionality described below step by step Description: Display objects A striplog depends on a hierarchy of objects. This notebook shows the objects related to display Step1: A Decor attaches a display style to a Rock. From the docs Step2: Lik...
Python Code: from striplog import Decor Explanation: Display objects A striplog depends on a hierarchy of objects. This notebook shows the objects related to display: Decor: One element from a legend — describes how to display a Rock. Legend: A set of Decors — describes how to display a set of Rocks or a Striplog. <hr ...
15,128
Given the following text description, write Python code to implement the functionality described below step by step Description: Solvers A constraints-based reconstruction and analysis model for biological systems is actually just an application of a class of discrete optimization problems typically solved with linear...
Python Code: import cobra.test model = cobra.test.create_test_model('textbook') model.solver = 'glpk' # or if you have cplex installed model.solver = 'cplex' Explanation: Solvers A constraints-based reconstruction and analysis model for biological systems is actually just an application of a class of discrete optimizat...
15,129
Given the following text description, write Python code to implement the functionality described below step by step Description: Assessing classifiers using GO in Shalek2013 For the GO analysis, we'll need a few other packages Step2: Utility functions for gene ontology Step3: Read in the Shalek2013 data and classify...
Python Code: # Alphabetical order is standard # We're doing "import superlongname as abbrev" for our laziness - this way we don't have to type out the whole thing each time. import collections # Python plotting library import matplotlib.pyplot as plt # Numerical python library (pronounced "num-pie") import numpy as np ...
15,130
Given the following text description, write Python code to implement the functionality described below step by step Description: Reprise pour proof of concept du pdf PythonEdu Amiens Passer par un logiciel Windows alors que jupyter et jupyterhub existent me semble une grossière erreur d'aiguillage. Je vais tenter de d...
Python Code: #solution de l'équation ax = b pour a = 2 et b = 6 a=2 b=6 print("la solution solution de ",a,"* x = ",b,"est :") print("x =",b/a) #résoudre l'équation ax=b pour a≠0 a = int(input("entrez une valeur pour a ≠ 0 : ")) #on s'assure que a est bien différent de 0 if a==0: #on redemande la saisie de a ...
15,131
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise Step1: Part 2 Use indexing (not a for loop) to find the 9 values representing $y_{i}+y_{i-1}$ for $i$ between 1 and 10. Hint Step2: Part 3 Write a function trapz(x, y), that appli...
Python Code: import numpy as np x = np.linspace(0, 3, 10) y = x ** 2 print(x) print(y) Explanation: Exercise: trapezoidal integration In this exercise, you are tasked with implementing the simple trapezoid rule formula for numerical integration. If we want to compute the definite integral $$ \int_{a}^{b}f(x)dx $$ ...
15,132
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing Encoder-Decoders Analysis Model Architecture Step1: Perplexity on Each Dataset Step2: Loss vs. Epoch Step3: Perplexity vs. Epoch Step4: Generations Step5: BLEU Analysis Step6:...
Python Code: report_files = ["/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing6_200_512_04drb/encdec_noing6_200_512_04drb.json", "/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing10_200_512_04drb/encdec_noing10_200_512_04drb.json", "/Users/bking/IdeaProjects/LanguageMo...
15,133
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.algo - Arbre et Trie (correction) Correction. Step1: Exercice 1 Step2: Exercice 2 Step3: Avec %timeit Step4: Exercice 3 Step5: Exercice 4 Step6: Soit $N$ le nombre de mots dans la...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 1A.algo - Arbre et Trie (correction) Correction. End of explanation import random def mot_alea (l) : l = [ chr(97+random.randint(0,25)) for i in range(l) ] return "".join(l) taille = 20 N = 10000 mots = [ mot_ale...
15,134
Given the following text description, write Python code to implement the functionality described below step by step Description: Abstract In this work we will to take a look at a data visualization using Python and the Titanic dataset. It's not intended to be the most accurate Titanic dataset analysis about Titanic, i...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt Explanation: Abstract In this work we will to take a look at a data visualization using Python and the Titanic dataset. It's not intended to be the most accurate Titanic dataset analysis about Titanic, it's a project resultant of the co...
15,135
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial 07 Step1: 1. Running a Default Simulation In order to create a scenario object in Flow with network features depicted from OpenStreetMap, we will use the base Scenario class. This ...
Python Code: # the TestEnv environment is used to simply simulate the network from flow.envs import TestEnv # the Experiment class is used for running simulations from flow.core.experiment import Experiment # all other imports are standard from flow.core.params import VehicleParams from flow.core.params import NetParam...
15,136
Given the following text description, write Python code to implement the functionality described below step by step Description: Loops During the course of solving client requirements, comes across situations where group of some data needs to be processed against a defined set of instructions. Loops help in resolving...
Python Code: for x in "Manish Gupta": print(x, end="^~", flush=True) Explanation: Loops During the course of solving client requirements, comes across situations where group of some data needs to be processed against a defined set of instructions. Loops help in resolving situations where a piece of code needs to b...
15,137
Given the following text description, write Python code to implement the functionality described below step by step Description: CNN HandsOn with Keras Problem Definition Recognize handwritten digits Data The MNIST database (link) has a database of handwritten digits. The training set has $60,000$ samples. The test ...
Python Code: import numpy as np import keras from keras.datasets import mnist import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152 os.environ["CUDA_VISIBLE_DEVICES"] = "" # Load the datasets (X_train, y_train), (X_test, y_test) = mnist.load_data() Explanation: CNN HandsOn with Keras Problem Defin...
15,138
Given the following text description, write Python code to implement the functionality described below step by step Description: Atmospheres & Passbands 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 wan...
Python Code: !pip install -I "phoebe>=2.2,<2.3" Explanation: Atmospheres & Passbands 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 %matplotlib in...
15,139
Given the following text description, write Python code to implement the functionality described below step by step Description: Matplotlib Exercise 3 Imports Step2: Contour plots of 2d wavefunctions The wavefunction of a 2d quantum well is Step3: The contour, contourf, pcolor and pcolormesh functions of Matplotlib ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np Explanation: Matplotlib Exercise 3 Imports End of explanation def well2d(x, y, nx, ny, L=1.0): Compute the 2d quantum well wave function. # YOUR CODE HERE raise NotImplementedError() psi = well2d(np.linspace(0,1,10), np.linsp...
15,140
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="https Step1: MCMC (emcee) MCMC is a convenient tool for drawing a sample from a given probability distribution. Therefore, is mostly used to estimate parameters in Bayesian way. e...
Python Code: %pylab inline np.random.seed(0) p = [3.2, 5.6, 9.2] x = np.arange(-8., 5., 0.1) y = np.polyval(p, x) + np.random.randn(x.shape[0])*1. plt.plot(x, y); # STEP 1 - define your model def my_model(p, x): return np.polyval(p, x) # STEP 2 - define your cost function def my_costfun(p, x, y): return np.sum(...
15,141
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Image Classification In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images...
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...
15,142
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Fully-Connected Neural Nets In the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since t...
Python Code: # As usual, a bit of setup from __future__ import print_function import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array fro...
15,143
Given the following text description, write Python code to implement the functionality described below step by step Description: PyMC Geomod 1 Step1: Simplest case Step2: Tha axis here represent the number of cells not the real values of geomodeller Step3: Setting Bayes Model Step4: Plotting Posteriors Step5: Ext...
Python Code: %matplotlib inline from IPython.core.display import Image import numpy as np import matplotlib.pyplot as plt import sys, os import shutil #import geobayes_simple as gs import pymc as pm # PyMC 2 from pymc.Matplot import plot from pymc import graph as gr import numpy as np #import daft from IPython.core.pyl...
15,144
Given the following text description, write Python code to implement the functionality described below step by step Description: Step function DGP papers have often demonstrated a step function, as this cannot be well captured by GP with a stationary kernel. We'll do that here also Step1: We'll now use a 2 layer DGP ...
Python Code: import numpy as np import tensorflow as tf import matplotlib.pyplot as plt %matplotlib inline from gpflow.likelihoods import Gaussian from gpflow.kernels import RBF, White from gpflow.models.gpr import GPR from gpflow.training import AdamOptimizer, ScipyOptimizer from doubly_stochastic_dgp.dgp import DGP n...
15,145
Given the following text description, write Python code to implement the functionality described below step by step Description: <table align="left"> <td> <a href="https Step1: Set up your GCP project The following steps are required, regardless of your notebook environment. Select or create a GCP project.. Whe...
Python Code: !pip install google-cloud-bigquery # Automatically restart kernel after installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) Explanation: <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/analytics-componentized-patter...
15,146
Given the following text description, write Python code to implement the functionality described below step by step Description: A Neural Network using Numpy on Bike Sharing Time Series dataset In this project, we'll build a neural network and use it to predict daily bike rental ridership. Step1: Load and prepare the...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: A Neural Network using Numpy on Bike Sharing Time Series dataset In this project, we'll build a neural network and use it to predict daily bike rental riders...
15,147
Given the following text description, write Python code to implement the functionality described below step by step Description: Document retrieval from wikipedia data Fire up GraphLab Create Step1: Load some text data - from wikipedia, pages on people Step2: Data contains Step3: Explore the dataset and checkout th...
Python Code: import graphlab Explanation: Document retrieval from wikipedia data Fire up GraphLab Create End of explanation people = graphlab.SFrame('people_wiki.gl/') Explanation: Load some text data - from wikipedia, pages on people End of explanation people.head() len(people) Explanation: Data contains: link to wik...
15,148
Given the following text description, write Python code to implement the functionality described below step by step Description: We will train a model to predict drug resistance values from sequence. This is the other general variant of supervised learning - where instead of predicting a "label" for a class (classific...
Python Code: # Load the sequence data as a Pandas dataframe. seqids = [s.id for s in SeqIO.parse('data/hiv-protease-sequences-expanded.fasta', 'fasta')] sequences = [s for s in SeqIO.parse('data/hiv-protease-sequences-expanded.fasta', 'fasta')] sequences = MultipleSeqAlignment(sequences) sequences = pd.DataFrame(np.arr...
15,149
Given the following text description, write Python code to implement the functionality described below step by step Description: Using tf.keras This Colab is about how to use Keras to define and train simple models on the data generated in the last Colab 1_data.ipynb Step2: Attention Step3: Linear model Step4: Conv...
Python Code: # In Jupyter, you would need to install TF 2.0 via !pip. %tensorflow_version 2.x import tensorflow as tf import json, os # Tested with TensorFlow 2.1.0 print('version={}, CUDA={}, GPU={}, TPU={}'.format( tf.__version__, tf.test.is_built_with_cuda(), # GPU attached? len(tf.config.list_physical_d...
15,150
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 display from IPython.display import Image from IPython.display import HTML 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='https...
15,151
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook is intended to demonstrate the basic features of the Python API for constructing input files and running OpenMC. In it, we will show how to create a basic reflective pin-cell m...
Python Code: %matplotlib inline import openmc Explanation: This notebook is intended to demonstrate the basic features of the Python API for constructing input files and running OpenMC. In it, we will show how to create a basic reflective pin-cell model that is equivalent to modeling an infinite array of fuel pins. If ...
15,152
Given the following text description, write Python code to implement the functionality described below step by step Description: Computing a covariance matrix Many methods in MNE, including source estimation and some classification algorithms, require covariance estimations from the recordings. In this tutorial we cov...
Python Code: import os.path as op import mne from mne.datasets import sample Explanation: Computing a covariance matrix Many methods in MNE, including source estimation and some classification algorithms, require covariance estimations from the recordings. In this tutorial we cover the basics of sensor covariance compu...
15,153
Given the following text description, write Python code to implement the functionality described below step by step Description: Dealing with Lookahead Conflicts This notebook discusses conflicts that have their origin in insufficient looakahead. We will discuss the following grammar Step1: Specification of the Parse...
Python Code: import ply.lex as lex tokens = [ 'USELESS' ] literals = ['U', 'V', 'W', 'X'] def t_USELESS(t): r'This will never be used.' __file__ = 'main' lexer = lex.lex() Explanation: Dealing with Lookahead Conflicts This notebook discusses conflicts that have their origin in insufficient looakahead. We will dis...
15,154
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Ingestion & Exploratory Analysis of the UFO Database Unidentified Flying Objects (UFOs) have been an interesting topic for most enthusiasts and hence people all over the United States r...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import statsmodels.api as sm import pandas as pd import numpy as np import geocoder import re import math Explanation: Data Ingestion & Exploratory Analysis of the UFO Database Unidentified Flying Objects (UFOs) have been an interesti...
15,155
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating Labeled Data from a Planet Mosaic with Label Maker In this notebook, we create labeled data for training a machine learning algorithm. As inputs, we use OpenStreetMap as the ground ...
Python Code: import json import os import ipyleaflet as ipyl import ipywidgets as ipyw from IPython.display import Image import numpy as np Explanation: Creating Labeled Data from a Planet Mosaic with Label Maker In this notebook, we create labeled data for training a machine learning algorithm. As inputs, we use OpenS...
15,156
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Landice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mri', 'sandbox-1', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: MRI Source ID: SANDBOX-1 Topic: Landice Sub-Topics: Glaciers, Ice. Proper...
15,157
Given the following text description, write Python code to implement the functionality described below step by step Description: Major League Baseball's Billion Dollar Problem A study of MLB pitching injuries at the NYU Stern School of Business Written by Isaac Gammal (isaac.gammal@stern.nyu.edu) Background Since the ...
Python Code: '''Data were imported from referenced sources and stored locally''' 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 n...
15,158
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Apache Spark Spark applications run as independent sets of processes on a cluster, coordinated by the SparkContext object in your main program (called the driver program). SparkContext...
Python Code: import pyspark sc = pyspark.SparkContext(appName="my_spark_app") sc Explanation: Using Apache Spark Spark applications run as independent sets of processes on a cluster, coordinated by the SparkContext object in your main program (called the driver program). SparkContext allocate resources across applicati...
15,159
Given the following text description, write Python code to implement the functionality described below step by step Description: Тест. Доверительные интервалы для среднего Step1: Для 61 большого города в Англии и Уэльсе известны средняя годовая смертность на 100000 населения (по данным 1958–1964) и концентрация кальц...
Python Code: import pandas as pd import numpy as np from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" Explanation: Тест. Доверительные интервалы для среднего End of explanation water_data = pd.read_table('water.txt') water_data.info() water_data.describe() water_...
15,160
Given the following text description, write Python code to implement the functionality described below step by step Description: First, load the UKDALE dataset into NILMTK. Here we are loading the HDF5 version of UKDALE which you can download by following the instructions on the UKDALE website. Step1: Next, to speed...
Python Code: dataset = nilmtk.DataSet('/data/mine/vadeec/merged/ukdale.h5') Explanation: First, load the UKDALE dataset into NILMTK. Here we are loading the HDF5 version of UKDALE which you can download by following the instructions on the UKDALE website. End of explanation dataset.set_window("2014-06-01", "2014-07-01...
15,161
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: working with numpy arrays This notebook demonstrates how to use differences and sums to calculate derivatives and integrals and make some simple plots using the matplotlib module. If...
Python Code: import numpy as np from matplotlib import pyplot as plt def cubeit(x,a,b): construct cubic polynomial of the form y = ax^3 + b Parameters ---------- x: vector or float x values a: float coefficient to multiply b: float coefficie...
15,162
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Batch Normalization One way to make deep networks easier to train is to use more sophisticated optimization procedures such as SGD+momentum, RMSProp, or Adam. Another strategy is to c...
Python Code: # As usual, a bit of setup import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplot...
15,163
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook-8 Step1: At the danger of repeating ourselves (but to make the point!) Step2: This doesn't work because you can't use a list (["key1",1]) as a key, though as you saw above you can...
Python Code: myDict = { "key1": "Value 1", 3: "3rd Value", "key2": "2nd Value", "Fourth Key": [4.0, 'Jon'] } print(myDict) Explanation: Notebook-8: Dictionaries Lesson Content In this lesson, we'll continue our exploration of more advanced data structures. Last time we took a peek at a way to represent ...
15,164
Given the following text description, write Python code to implement the functionality described below step by step Description: Possible Solution Step1: Explaining my code Okay guys, my code is a bit complicated to understand at first glance, but I'm going to talk you through it. board_temp = ["B"] * bomb_count + [n...
Python Code: import random def build_board(num_rows, num_cols, bomb_count=0, non_bomb_character="-"): board_temp = ["B"] * bomb_count + [non_bomb_character] * (num_rows * num_cols - bomb_count) if bomb_count: random.shuffle(board_temp) board = [] for i in range(0, num_rows*num_cols, num_cols): ...
15,165
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create Population Data From Non-Normal Distribution Step2: View the True Mean Of Population Step3: Take A Sample Mean, Repeat 1000 Times Step4: Plot The Sample Means Of All ...
Python Code: # Import packages import pandas as pd import numpy as np # Set matplotlib as inline %matplotlib inline Explanation: Title: Demonstrate The Central Limit Theorem Slug: demonstrate_the_central_limit_theorem Summary: Python introduction to the central limit theorem Date: 2016-05-01 12:00 Category: Statistic...
15,166
Given the following text description, write Python code to implement the functionality described below step by step Description: Graph format The EDeN library allows the vectorization of graphs, i.e. the transformation of graphs into sparse vectors. The graphs that can be processed by the EDeN library have the followi...
Python Code: %matplotlib inline import pylab as plt import networkx as nx G=nx.Graph() G.add_node(0, label='A') G.add_node(1, label='B') G.add_node(2, label='C') G.add_edge(0,1, label='x') G.add_edge(1,2, label='y') G.add_edge(2,0, label='z') from eden.util import display print display.serialize_graph(G) from eden.util...
15,167
Given the following text description, write Python code to implement the functionality described below step by step Description: Topic 2 Step1: Creating a Reddit Application Go to https Step2: Capturing Reddit Posts Now for a given subreddit, we can get the newest posts to that sub. Post titles are generally short,...
Python Code: # For our first piece of code, we need to import the package # that connects to Reddit. Praw is a thin wrapper around reddit's # web APIs and works well import praw Explanation: Topic 2: Collecting Social Media Data This notebook contains examples for using web-based APIs (Application Programmer Interfac...
15,168
Given the following text description, write Python code to implement the functionality described below step by step Description: Word2Vec Tutorial In case you missed the buzz, word2vec is a widely featured as a member of the “new wave” of machine learning algorithms based on neural networks, commonly referred to as "d...
Python Code: # import modules & set up logging import gensim, logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) sentences = [['first', 'sentence'], ['second', 'sentence']] # train word2vec on the two sentences model = gensim.models.Word2Vec(sentences, min_count=1) Expla...
15,169
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Landice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'bcc', 'sandbox-2', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: BCC Source ID: SANDBOX-2 Topic: Landice Sub-Topics: Glaciers, Ice. Proper...
15,170
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. I want to make sure my Plate ID is a string. Can't lose the leading zeroes! 2. I don't think anyone's car was built in 0AD. Discard the '0's as NaN. 3. I want the dates to be dates! Read ...
Python Code: import pandas as pd #import pandas as pd import datetime import datetime as dt # import datetime # import datetime as dt dt.datetime.strptime('08/04/2013', '%m/%d/%Y') datetime.datetime(2013, 8, 4, 0, 0) parser = lambda date: pd.datetime.strptime(date, '%m/%d/%Y') !head -n 10000 violations.csv > small-viol...
15,171
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute distance to roads This notebook computes the distance to each of the nearest road types in a 'roads' vector map from a vector map of 'points' (sample locations). This notebook uses G...
Python Code: points = 'sample_points_field' roads = 'highway' road_type_field = 'Type' distance_table_filename = "" Explanation: Compute distance to roads This notebook computes the distance to each of the nearest road types in a 'roads' vector map from a vector map of 'points' (sample locations). This notebook uses GR...
15,172
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 6 Imports Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell. Step1: Exploring the Fermi distribution In quantum statistics, the ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.display import Image from IPython.html.widgets import interact, interactive, fixed Explanation: Interact Exercise 6 Imports Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell. End of...
15,173
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute MxNE with time-frequency sparse prior The TF-MxNE solver is a distributed inverse method (like dSPM or sLORETA) that promotes focal (sparse) sources (such as dipole fitting technique...
Python Code: # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import mne from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse from mne.inverse_sparse import tf_mixed_norm from mne.viz import plot_sparse_source_estimates print...
15,174
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: <h1>Audio Applications</h1> <BR> Now that we have established the theory behind the geometry of 1D time series sliding window embeddings, we will look at our first real applications S...
Python Code: ##Do all of the imports and setup inline plotting %matplotlib notebook import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA from scipy.interpolate import InterpolatedUnivariateSpline from ripser import ripser from persim import plot_diagrams import scipy.io.wavfile from ...
15,175
Given the following text description, write Python code to implement the functionality described below step by step Description: Setup Step1: Sometimes it's useful to have a zero value in the dataset, e.g. for padding Step2: 3 char model Step3: RNN Step4: The first character of each sequence goes through dense_in(...
Python Code: path = get_file('nietzsche.txt', origin="https://s3.amazonaws.com/text-datasets/nietzsche.txt") text = open(path).read() print('corpus length:', len(text)) text chars = sorted(list(set(text))) vocab_size = len(chars)+1 print('total chars:', vocab_size) chars Explanation: Setup End of explanation chars.inse...
15,176
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Dropout Dropout [1] is a technique for regularizing neural networks by randomly setting some features to zero during the forward pass. In this exercise you will implement a dropout la...
Python Code: # As usual, a bit of setup import sys import os sys.path.insert(0, os.path.abspath('..')) import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_num...
15,177
Given the following text description, write Python code to implement the functionality described below step by step Description: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about emb...
Python Code: import time import numpy as np import tensorflow as tf import utils from collections import Counter import random Explanation: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn...
15,178
Given the following text description, write Python code to implement the functionality described below step by step Description: Example of Pythran Usage Within a Full Project This notebook covers the creation of a simple, distutils-powered, project that ships a pythran kernel. But first some cleanup Step2: Project l...
Python Code: !rm -rf hello setup.py && mkdir hello Explanation: Example of Pythran Usage Within a Full Project This notebook covers the creation of a simple, distutils-powered, project that ships a pythran kernel. But first some cleanup End of explanation %%file hello/hello.py #pythran export hello() def hello(): ...
15,179
Given the following text description, write Python code to implement the functionality described below step by step Description: Quick overview Here are some quick examples of what you can do with xarray.DataArray objects. Everything is explained in much more detail in the rest of the documentation. To begin, import n...
Python Code: import numpy as np import pandas as pd import xarray as xr Explanation: Quick overview Here are some quick examples of what you can do with xarray.DataArray objects. Everything is explained in much more detail in the rest of the documentation. To begin, import numpy, pandas and xarray using their customary...
15,180
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise 17 Analyze how travelers expressed their feelings on Twitter A sentiment analysis job about the problems of each major U.S. airline. Twitter data was scraped from February of 2015 ...
Python Code: import pandas as pd import numpy as np %matplotlib inline import matplotlib.pyplot as plt # read the data and set the datetime as the index tweets = pd.read_csv('https://github.com/albahnsen/PracticalMachineLearningClass/raw/master/datasets/Tweets.zip', index_col=0) tweets.head() tweets.shape Explanation: ...
15,181
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: 過学習と学習不足について知る <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Higgs データセット このチュートリアルの目的は素粒...
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...
15,182
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1><center>[Notebooks](../) - [Numerical Cartography](../numerical cartography)</center></h1> Geodetic datum transformations Is common practice in Geospatial data science to work with datas...
Python Code: #import the pyproj and numpy library import pyproj import numpy as np # set a reference point P with coordinates: P = (-70.93931369842528, 43.13567095719326) # define projection UTM 19 N: # UTM zone 19, WGS84 ellipse, WGS84 datum, defined by epsg code 32619 p1 = pyproj.Proj(init='epsg:32619') #Find UT...
15,183
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 10 – Introduction to Artificial Neural Networks This notebook contains all the sample code and solutions to the exercises in chapter 10. Setup First, let's make sure this notebook wo...
Python Code: # To support both python 2 and python 3 from __future__ import division, print_function, unicode_literals # Common imports import numpy as np import os # to make this notebook's output stable across runs def reset_graph(seed=42): tf.reset_default_graph() tf.set_random_seed(seed) np.random.seed(...
15,184
Given the following text description, write Python code to implement the functionality described below step by step Description: Generation Flow of Fragment Mechanism Steps Step1: 0. helper methods Step2: 1. load text-format fragment mech Step3: 2. get thermo and kinetics Step4: 2.1 correct entropy for certain fra...
Python Code: import os from tqdm import tqdm from rmgpy import settings from rmgpy.data.rmg import RMGDatabase from rmgpy.kinetics import KineticsData from rmgpy.rmg.model import getFamilyLibraryObject from rmgpy.data.kinetics.family import TemplateReaction from rmgpy.data.kinetics.depository import DepositoryReaction ...
15,185
Given the following text description, write Python code to implement the functionality described below step by step Description: intakeOutput Intake and output recorded for patients. Entered from the nursing flowsheet (either manually or interfaced into the hospital system). Step2: Examine a single patient Step3: Ab...
Python Code: # Import libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import psycopg2 import getpass import pdvega # for configuring connection from configobj import ConfigObj import os %matplotlib inline # Create a database connection using settings from config file config='../db/conf...
15,186
Given the following text description, write Python code to implement the functionality described below step by step Description: Smooth Overlap of Atomic Positions SOAP is a local descriptor, that maps the local environment around a point very accurately. It eliminates rotational, and permutation redundancies by integ...
Python Code: # --- INITIAL DEFINITIONS --- import numpy, math, random from visualise import view from ase import Atoms import sys sys.path.insert(0, './data/descriptor_codes/') sys.path.insert(0, './data/descriptor_codes/src') from dscribe.descriptors import SOAP Explanation: Smooth Overlap of Atomic Positions SOAP is ...
15,187
Given the following text description, write Python code to implement the functionality described below step by step Description: <h2 align="center">点击下列图标在线运行HanLP</h2> <div align="center"> <a href="https Step1: 加载模型 HanLP的工作流程是先加载模型,模型的标示符存储在hanlp.pretrained这个包中,按照NLP任务归类。 Step2: 调用hanlp.load进行加载,模型会自动下载到本地缓存。自...
Python Code: !pip install hanlp -U Explanation: <h2 align="center">点击下列图标在线运行HanLP</h2> <div align="center"> <a href="https://colab.research.google.com/github/hankcs/HanLP/blob/doc-zh/plugins/hanlp_demo/hanlp_demo/zh/dep_mtl.ipynb" target="_blank"><img src="https://colab.research.google.com/assets/colab-badge.svg" ...
15,188
Given the following text description, write Python code to implement the functionality described below step by step Description: Scikit-Learn singalong Step1: Download EEG Data The following code downloads a copy of the EEG Eye State dataset. All data is from one continuous EEG measurement with the Emotiv EEG Neuroh...
Python Code: import pandas as pd import numpy as np from collections import Counter Explanation: Scikit-Learn singalong: EEG Eye State Classification Author: Kevin Yang Contact: kyang@h2o.ai This tutorial replicates Erin LeDell's oncology demo using Scikit Learn and Pandas, and is intended to provide a comparison of th...
15,189
Given the following text description, write Python code to implement the functionality described below step by step Description: Word2Vec Example (C) 2018 by Damir Cavar Version Step1: Using One-Hot Vectors We can create a one-hot vector that selects the 3rd row Step2: Let us create a matrix $A$ of four rows Step3: ...
Python Code: import numpy as np Explanation: Word2Vec Example (C) 2018 by Damir Cavar Version: 1.1, November 2018 License: Creative Commons Attribution-ShareAlike 4.0 International License (CA BY-SA 4.0) This is a tutorial related to the L665 course on Machine Learning for NLP focusing on Deep Learning, Spring and Fall...
15,190
Given the following text description, write Python code to implement the functionality described below step by step Description: Writing an algorithm (using Spark/Thunder) In this notebook, we show how to write an algorithm and put it in a function that can be submitted to the NeuroFinder challenge. In these examples,...
Python Code: %matplotlib inline from thunder import Colorize image = Colorize.image tile = Colorize.tile Explanation: Writing an algorithm (using Spark/Thunder) In this notebook, we show how to write an algorithm and put it in a function that can be submitted to the NeuroFinder challenge. In these examples, the algorit...
15,191
Given the following text description, write Python code to implement the functionality described below step by step Description: Unit Tests Overview and Principles Testing is the process by which you exercise your code to determine if it performs as expected. The code you are testing is referred to as the code under t...
Python Code: import numpy as np # Code Under Test def entropy(ps): if not np.isclose(np.sum(ps), 1.0): raise ValueError("Probability is not 1.") items = ps * np.log(ps) return -np.sum(items) # Smoke test probs = [ [0.1, 0.8, 0.1], [0.1, 0.9], [0.5, 0.5], [1.0] ] for prob in probs: ...
15,192
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Define a function maximum that takes two numbers as arguments and returns the largest of them. Use the if-then-else construct available in Python. (It is true that Python has the max() fu...
Python Code: assert maximum(3, 3) == 3 assert maximum(1, 2) == 2 assert maximum(3, 2) == 3 Explanation: 1. Define a function maximum that takes two numbers as arguments and returns the largest of them. Use the if-then-else construct available in Python. (It is true that Python has the max() function built in, but writi...
15,193
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: 텐서플로로 분산 훈련하기 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: 전략의 종류 tf.distribute.Strategy...
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...
15,194
Given the following text description, write Python code to implement the functionality described below step by step Description: Prediction using normal score for wall street columns using the same data clusters. Here we will test how the prediction between using mixed receptive fields in time compares with non-time m...
Python Code: import numpy as np from sklearn import svm, cross_validation import h5py import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline import sys sys.path.append("../") Explanation: Prediction using normal score for wall street columns using the same data clusters. Here we will test how the pred...
15,195
Given the following text description, write Python code to implement the functionality described below step by step Description: Algebra and Functions Step1: Contents 1.Laws of Indices - Multiplication - Division - Raising to power - Taking a root - Fraction Indices - Zero indices - Negative indices 2.Surds - Additio...
Python Code: import numpy as np import matplotlib.pyplot as plt import math Explanation: Algebra and Functions End of explanation # sample x values x = np.linspace(-10, 10, 2001).astype(np.float32) # known variables a = 2.0 b = 5.0 c = -12.0 # quadratic equation def eq(x,a,b,c): return a*x**2 + b*x + c y = eq(x,a,b...
15,196
Given the following text description, write Python code to implement the functionality described below step by step Description: How many movies are listed in the titles dataframe? Step1: What are the earliest two films listed in the titles dataframe? Step2: How many movies have the title "Hamlet"? Step3: How many ...
Python Code: titles.shape[0] Explanation: How many movies are listed in the titles dataframe? End of explanation titles.sort(columns='year')[0:2] Explanation: What are the earliest two films listed in the titles dataframe? End of explanation titles[titles['title']=='Hamlet'].shape[0] Explanation: How many movies have t...
15,197
Given the following text description, write Python code to implement the functionality described below step by step Description: Step4: 1T_Pandas로 배우는 SQL 시작하기 (1) - WHERE, ORDER BY 갯수 세기 (COUNT) 칼럼명 변경하기 (AS) 정렬 (ORDER BY) 특정 조건에 대한 필터링(WHERE) Pandas에서는 JOIN ( merge ) ( * ) GROUP BY ( * ) 잠시 주석에 대해서 Step7: SQL(Struc...
Python Code: def hello(): 주석입니다, docstring => 파이썬 코드를 문서화 pass # 샵 이것도 주석 a = #Multiline String입니다. a = "여러줄 텍스트" a = "여러줄\ 텍스트" a a = 안녕하세요. 저는 김기표입니다. a a.strip() a.replace("\n", " ") a.replace("\n", " ").strip() import pymysql db = pymysql.connect( "db.fastcamp.us", "root", ...
15,198
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Machine Learning with scikit-learn Lab 2 Step1: In the following cell, we are just defining what is needed to train the classifier and display it Step2: Binary Support Vect...
Python Code: %matplotlib inline import numpy as np # class '0' features_0 = [-1.5, 0] + np.random.randn(100, 2) labels_0 = np.zeros(100) # class '1' features_1 = [+1.5, 0] + np.random.randn(100, 2) labels_1 = np.ones(100) # show the training set with matplotlib import matplotlib.pyplot as plt plt.figure() plt.plot(feat...
15,199
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Analysis on Movie Reviews Using Logistic Regression, SGD, Naive Bayes, OneVsOne Models 0 - negative 1 - somewhat negative 2 - neutral 3 - somewhat positive 4 - positive Load Librar...
Python Code: import nltk import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression, SGDClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.naive_ba...