Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
7,200
Given the following text description, write Python code to implement the functionality described below step by step Description: STA 208 Step3: The response variable is quality. Step4: Exercise 2.1 (5 pts) Compare the leave-one-out risk with the empirical risk for linear regression, on this dataset. Step5: Exercise...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import LeaveOneOut from sklearn import linear_model, neighbors %matplotlib inline plt.style.use('ggplot') # dataset path data_dir = "." sample_data = pd.read_csv(data_dir+"/hw1.csv", delimiter=',') sample_da...
7,201
Given the following text description, write Python code to implement the functionality described below step by step Description: Dataframes ( Pandas ) and Plotting ( Matplotlib/Seaborn ) Written by Jin Cheong & Luke Chang In this lab we are going to learn how to load and manipulate datasets in a dataframe format using...
Python Code: # matplotlib inline is an example of 'cell magic' and # enables plotting IN the notebook and not opening another window. %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns Explanation: Dataframes ( Pandas ) and Plotting ( Matplotlib/Seaborn ) W...
7,202
Given the following text description, write Python code to implement the functionality described below step by step Description: <img style='float Step1: Skill 1 Step2: Skill 2 Step3: Skill 3 Step4: Normalized Taylor diagrams The radius is model standard deviation error divided by observations deviation, azimuth ...
Python Code: import os try: import cPickle as pickle except ImportError: import pickle run_name = '2015-08-17' fname = os.path.join(run_name, 'config.pkl') with open(fname, 'rb') as f: config = pickle.load(f) import numpy as np from pandas import DataFrame, read_csv from utilities import to_html, save_html,...
7,203
Given the following text description, write Python code to implement the functionality described below step by step Description: Microbiome machine learning analysis Setup Import the calour module Step1: Regression Loading the data We will use the data from Qitta study 103 (https Step2: Process the data Get rid of t...
Python Code: from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier from sklearn.model_selection import RepeatedStratifiedKFold from calour.training import plot_scatter, plot_roc, plot_cm import calour as ca %matplotlib notebook Explanation: Microbiome machine learning analysis Setup Import the calo...
7,204
Given the following text description, write Python code to implement the functionality described below step by step Description: 主题模型 王成军 wangchengjun@nju.edu.cn 计算传播网 http Step1: Download data http Step2: Build the topic model Step3: We can see the list of topics a document refers to by using the model[doc] syntax...
Python Code: %matplotlib inline from __future__ import print_function from wordcloud import WordCloud from gensim import corpora, models, similarities, matutils import matplotlib.pyplot as plt import numpy as np Explanation: 主题模型 王成军 wangchengjun@nju.edu.cn 计算传播网 http://computational-communication.com 2014年高考前夕,百度“基于海...
7,205
Given the following text description, write Python code to implement the functionality described below step by step Description: Multi-indexing When dealing with Series data, it is often useful to index each element of the series with multiple labels and then select and aggregrate data based on these indices. For exam...
Python Code: from thunder import Series from numpy import arange, array data = tsc.loadSeriesFromArray(arange(12)) data.first() Explanation: Multi-indexing When dealing with Series data, it is often useful to index each element of the series with multiple labels and then select and aggregrate data based on these indice...
7,206
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 1_notmist.ipynb. Step2: Reformat into a shape that's more adapted to the models we're going to train Step...
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...
7,207
Given the following text description, write Python code to implement the functionality described below step by step Description: Sveučilište u Zagrebu Fakultet elektrotehnike i računarstva Strojno učenje 2018/2019 http Step1: 1. Klasifikator stroja potpornih vektora (SVM) (a) Upoznajte se s razredom svm.SVC, koja u...
Python Code: import numpy as np import scipy as sp import pandas as pd import mlutils import matplotlib.pyplot as plt %pylab inline Explanation: Sveučilište u Zagrebu Fakultet elektrotehnike i računarstva Strojno učenje 2018/2019 http://www.fer.unizg.hr/predmet/su Laboratorijska vježba 3: Stroj potpornih vektora i al...
7,208
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> Chukwuemeka Mba-Kalu </center> <center> Joseph Onwughalu </center> <center> An Analysis of the Brazilian Economy between 2000 and 2012 </center> <center> Final Project In Partial Fu...
Python Code: # Inportant Packages import pandas as pd import matplotlib.pyplot as plt import sys import datetime as dt print('Python version is:', sys.version) print('Pandas version:', pd.__version__) print('Date:', dt.date.today()) Explanation: <center> Chukwuemeka Mba-Kalu </center> <center> Joseph Onwughalu </center...
7,209
Given the following text description, write Python code to implement the functionality described below step by step Description: Test external lookup table (multi-dimensional np array) code for rule 18 Step1: External transduction of CA.get_spacetime()
Python Code: A = 2 r = 1 table = lookup_table(18, 2, 1) R = 2*r + 1 scan = tuple(np.arange(0,A)[::-1]) for a in product(scan, repeat = R): print a, table[a] x = [0,1,1,0] print neighborhood(x, 1) for item in neighborhood(x, 1): print item print max_rule(2,1) print example.current_state() example.evolve(1) print...
7,210
Given the following text description, write Python code to implement the functionality described below step by step Description: Precipitation in the Meteorology component Goal Step1: Programmatically create a file holding the precipitation rate time series. This will mimic what I'll need to do in WMT, where I'll hav...
Python Code: mps_to_mmph = 1000 * 3600 Explanation: Precipitation in the Meteorology component Goal: In this example, I give the Meteorology component a time series of precipitation values and check whether it produces output when the model state is updated. Define a helpful constant: End of explanation import numpy as...
7,211
Given the following text description, write Python code to implement the functionality described below step by step Description: Lower Star Filtrations Step1: Overview of 0D Persistence for Point Clouds Step2: Piecewise Linear Lower Star Filtrations First, we define a lower star time series filtration function. The...
Python Code: %matplotlib notebook import numpy as np from scipy import ndimage from ripser import ripser from persim import plot_diagrams as plot_dgms import matplotlib.pyplot as plt from scipy import sparse import time import PIL from mpl_toolkits.mplot3d import Axes3D import sys import ipywidgets as widgets from IPy...
7,212
Given the following text description, write Python code to implement the functionality described below step by step Description: TLS handshake overview This is the standard, modern TLS 1.2 handshake Step1: (C) ---> (S) ClientHello Step2: (C) <--- (S) ServerHello Step3: (C) <--- (S) Certificate Step4: (C) <--- (S) ...
Python Code: # We're going to parse several successive records from the passive listening of a standard TLS handshake from scapy.all import * load_layer('tls') Explanation: TLS handshake overview This is the standard, modern TLS 1.2 handshake: <img src="images/handshake_tls12.png" alt="Handshake TLS 1.2" width="400"/> ...
7,213
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting Life Step1: <h2>What is a Random Forest? </h2> As with all the important questions in life, this is best deferred to the Wikipedia page. A random forest is an ensemble of decisio...
Python Code: import pandas as pd import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.preprocessing import normalize import random test=pd.read_csv("test.csv") test.head() mData=pd.read_csv("train.csv") mData.head() mData = mData.drop(["Passenger...
7,214
Given the following text description, write Python code to implement the functionality described below step by step Description: Additional forces REBOUND is a gravitational N-body integrator. But you can also use it to integrate systems with additional, non-gravitational forces. This tutorial gives you a very quick o...
Python Code: import rebound rebound.reset() rebound.integrator = "whfast" rebound.add(m=1.) rebound.add(m=1e-6,a=1.) rebound.move_to_com() # Moves to the center of momentum frame Explanation: Additional forces REBOUND is a gravitational N-body integrator. But you can also use it to integrate systems with additional, n...
7,215
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: DDSP Processor Demo This notebook provides an introduction to the signal Processor() object. The main object type in the DDSP library, it is the base class used for Sy...
Python Code: # Copyright 2021 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
7,216
Given the following text description, write Python code to implement the functionality described. Description: Program to implement Simpson 's 3/8 rule Given function to be integrated ; Function to perform calculations ; Calculates value till integral limit ; driver function
Python Code: def func(x ) : return(float(1 ) /(1 + x * x ) )  def calculate(lower_limit , upper_limit , interval_limit ) : interval_size =(float(upper_limit - lower_limit ) / interval_limit ) sum = func(lower_limit ) + func(upper_limit ) ; for i in range(1 , interval_limit ) : if(i % 3 == 0 ) : sum =...
7,217
Given the following text description, write Python code to implement the functionality described below step by step Description: My playing with the Kaggle titanic challenge. I got lots of the ideas for this first Kaggle advanture from here Step1: Let's see where they got on Step2: OK, so clearly there were more peo...
Python Code: import pandas as pd from pandas import Series, DataFrame import numpy as np import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns sns.set_style("whitegrid") train_df = pd.read_csv("train.csv",dtype={"Age":np.float64},) train_df.head() # find how many ages train_df['Age'].count() # how m...
7,218
Given the following text description, write Python code to implement the functionality described below step by step Description: K-Means Goal Unsupervised learning algorithms look for structure in unlabelled data. One of the common objective is to find clusters. Clusters are groups of data that are similar according t...
Python Code: import random import time import matplotlib.pyplot as plt import numpy as np import pandas as pd from fct import normalize_min_max, plot_2d, plot_clusters Explanation: K-Means Goal Unsupervised learning algorithms look for structure in unlabelled data. One of the common objective is to find clusters. Clust...
7,219
Given the following text description, write Python code to implement the functionality described below step by step Description: Control Ops Tutorial In this tutorial we show how to use control flow operators in Caffe2 and give some details about their underlying implementations. Conditional Execution Using NetBuilder...
Python Code: from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import workspace from caffe2.python.core import Plan, to_execution_step, Net from caffe2.python.net_builder import ops, NetBuilder Explanat...
7,220
Given the following text description, write Python code to implement the functionality described below step by step Description: Signal denoising using RNNs in PyTorch In this post, I'll use PyTorch to create a simple Recurrent Neural Network (RNN) for denoising a signal. I started learning RNNs using PyTorch. However...
Python Code: import numpy as np import math, random import matplotlib.pyplot as plt %matplotlib inline np.random.seed(0) Explanation: Signal denoising using RNNs in PyTorch In this post, I'll use PyTorch to create a simple Recurrent Neural Network (RNN) for denoising a signal. I started learning RNNs using PyTorch. How...
7,221
Given the following text description, write Python code to implement the functionality described below step by step Description: Training at scale with the Vertex AI Training Service Learning Objectives Step1: Change the following cell as necessary Step2: Confirm below that the bucket is regional and its region equa...
Python Code: import os from google.cloud import bigquery Explanation: Training at scale with the Vertex AI Training Service Learning Objectives: 1. Learn how to organize your training code into a Python package 1. Train your model using cloud infrastructure via Google Cloud Vertex AI Training Service 1. (optional...
7,222
Given the following text description, write Python code to implement the functionality described below step by step Description: Independent Analysis - Srinivas (handle Step1: we've now dropped the last of the discrete numerical inexplicable data, and removed children from the mix Extracting the samples we are intere...
Python Code: # Standard import pandas as pd import numpy as np %matplotlib inline import matplotlib.pyplot as plt # Dimensionality reduction and Clustering from sklearn.decomposition import PCA from sklearn.cluster import KMeans from sklearn.cluster import MeanShift, estimate_bandwidth from sklearn import manifold, dat...
7,223
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook is a revised version of notebook from Amy Wu E2E ML on GCP Step1: Restart the kernel After you install the additional packages, you need to restart the notebook kernel so it can fi...
Python Code: import os # The Vertex AI Workbench Notebook product has specific requirements IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME") IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists( "/opt/deeplearning/metadata/env_version" ) # Vertex AI Notebook requires dependencies to be installed with '--user' U...
7,224
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 3 Imports Step2: Using interact for animation with data A soliton is a constant velocity wave that maintains its shape as it propagates. They arise from non-linear wave eq...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display Explanation: Interact Exercise 3 Imports End of explanation def soliton(x, t, c, a): Return phi(x, t) for a soliton wave with cons...
7,225
Given the following text description, write Python code to implement the functionality described. Description: Remove all nodes which don 't lie in any path with sum>= k A utility function to create a new Binary Tree node with given data ; print the tree in LVR ( Inorder traversal ) way . ; Main function which truncate...
Python Code: class newNode : def __init__(self , data ) : self . data = data self . left = self . right = None   def Print(root ) : if(root != None ) : Print(root . left ) print(root . data , end = "▁ ") Print(root . right )   def pruneUtil(root , k , Sum ) : if(root == None ) : return N...
7,226
Given the following text description, write Python code to implement the functionality described below step by step Description: Głęboka sieć neuronowa w aspektowej analizie wydźwięku Tomek Korbak 24 maja 2016 Problem Wytrenować klasyfikator, który dostając na wejściu zdanie języka polskiego, zwróci jego wydźwięk, to ...
Python Code: import json from itertools import chain from pprint import pprint from time import time import os import numpy as np %matplotlib inline import matplotlib.pyplot as plt from sklearn.metrics import accuracy_score from gensim.models import Word2Vec from gensim.corpora.dictionary import Dictionary os.environ['...
7,227
Given the following text description, write Python code to implement the functionality described below step by step Description: Recursive least squares Recursive least squares is an expanding window version of ordinary least squares. In addition to availability of regression coefficients computed recursively, the rec...
Python Code: %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt from pandas_datareader.data import DataReader np.set_printoptions(suppress=True) Explanation: Recursive least squares Recursive least squares is an expanding window version of ordinary lea...
7,228
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Introduction There are multiple reasons for analyzing a version control system like your Git repository. See for example Adam Tornhill's book "Your Code as a Crime Scene" or his...
Python Code: import git GIT_REPO_PATH = r'../../spring-petclinic/' repo = git.Repo(GIT_REPO_PATH) git_bin = repo.git git_bin Explanation: Introduction Introduction There are multiple reasons for analyzing a version control system like your Git repository. See for example Adam Tornhill's book "Your Code as a Crime Scen...
7,229
Given the following text description, write Python code to implement the functionality described below step by step Description: Session 0 Step1: Now press 'a' or 'b' to create new cells. You can also use the toolbar to create new cells. You can also use the arrow keys to move up and down. <a name="kernel"></a> Ker...
Python Code: 4*2 Explanation: Session 0: Preliminaries with Python/Notebook <p class="lead"> Parag K. Mital<br /> <a href="https://www.kadenze.com/courses/creative-applications-of-deep-learning-with-tensorflow/info">Creative Applications of Deep Learning w/ Tensorflow</a><br /> <a href="https://www.kadenze.com/partners...
7,230
Given the following text description, write Python code to implement the functionality described below step by step Description: Example Step1: Say $f(t) = t * exp(- t)$, and $F(s)$ is the Laplace transform of $f(t)$. Let us first evaluate this transform using sympy. Step2: Suppose we are confronted with a dataset $...
Python Code: from symfit import ( variables, parameters, Model, Fit, exp, laplace_transform, symbols, MatrixSymbol, sqrt, Inverse, CallableModel ) import numpy as np import matplotlib.pyplot as plt Explanation: Example: Matrix Equations using Tikhonov Regularization This is an example of the use of matrix expressio...
7,231
Given the following text description, write Python code to implement the functionality described below step by step Description: Character level language model - Dinosaurus land Welcome to Dinosaurus Island! 65 million years ago, dinosaurs existed, and in this assignment they are back. You are in charge of a special t...
Python Code: import numpy as np from utils import * import random from random import shuffle Explanation: Character level language model - Dinosaurus land Welcome to Dinosaurus Island! 65 million years ago, dinosaurs existed, and in this assignment they are back. You are in charge of a special task. Leading biology res...
7,232
Given the following text description, write Python code to implement the functionality described below step by step Description: Tensorflow Image Recognition Tutorial This tutorial shows how we can use MLDB's TensorFlow integration to do image recognition. TensorFlow is Google's open source deep learning library. We...
Python Code: from pymldb import Connection mldb = Connection() Explanation: Tensorflow Image Recognition Tutorial This tutorial shows how we can use MLDB's TensorFlow integration to do image recognition. TensorFlow is Google's open source deep learning library. We will load the Inception-v3 model to generate descript...
7,233
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: オブジェクト検出 <table class="tfo-notebook-buttons" align="left"> <td><a target=...
Python Code: # Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
7,234
Given the following text description, write Python code to implement the functionality described below step by step Description: Deploying a Model and Predicting with Cloud Machine Learning Engine This notebook is the final step in a series of notebooks for doing machine learning on cloud. The previous notebook, demon...
Python Code: import google.datalab as datalab import google.datalab.ml as ml import mltoolbox.regression.dnn as regression import os import requests import time Explanation: Deploying a Model and Predicting with Cloud Machine Learning Engine This notebook is the final step in a series of notebooks for doing machine lea...
7,235
Given the following text description, write Python code to implement the functionality described below step by step Description: Plot bike-share data with Matplotlib Step1: Question 1 Step2: Question 2 Step3: Question 3 Step4: Question 4
Python Code: from pandas import DataFrame, Series import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline weather = pd.read_table('daily_weather.tsv') usage = pd.read_table('usage_2012.tsv') stations = pd.read_table('stations.tsv') newseasons = {'Summer': 'Spring', 'Spring': 'Winter', ...
7,236
Given the following text description, write Python code to implement the functionality described below step by step Description: MP2 theory for a closed-shell reference In this notebook we will use wicked to generate equations for the MP2 method using an orbital-invariant formalism Step1: Here we define the operator ...
Python Code: import wicked as w w.reset_space() w.add_space("o", "fermion", "occupied", ["i", "j", "k", "l", "m", "n"]) w.add_space("v", "fermion", "unoccupied", ["a", "b", "c", "d", "e", "f"]) Explanation: MP2 theory for a closed-shell reference In this notebook we will use wicked to generate equations for the MP2 met...
7,237
Given the following text description, write Python code to implement the functionality described below step by step Description: Feature Step1: Config Automatically discover the paths to various data folders and compose the project structure. Step2: Identifier for storing these features on disk and referring to them...
Python Code: from pygoose import * import os import warnings import gensim from fuzzywuzzy import fuzz from nltk import word_tokenize from nltk.corpus import stopwords from scipy.stats import skew, kurtosis from scipy.spatial.distance import cosine, cityblock, jaccard, canberra, euclidean, minkowski, braycurtis Explana...
7,238
Given the following text description, write Python code to implement the functionality described below step by step Description: Build a histogram with percentages correct for each category Step1: Stats of text length for correct and incorrect
Python Code: df_test = df[(df["is_test"] == True)] df_test["prediction"] = predictions #print df_test.head() # Compare the percent correct to the results from earlier to make sure things are lined up right print "Calculated accuracy:", sum(df_test["label"] == df_test["prediction"]) / float(len(df_test)) print "Model ac...
7,239
Given the following text description, write Python code to implement the functionality described below step by step Description: All About Step1: Graphic Interpretation The graphic above illustrates the pattern of follow-ups in the CMMI data set for each of the 1,640 unique patients. Using your cursor, you can hover ...
Python Code: from IPython.core.display import display, HTML;from string import Template; HTML('<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>') css_text2 = ''' #main { float: left; width: 750px;}#sidebar { float: right; width: 100px;}#sequence { width: 600px; height: 70px;}#legend { padding: 10p...
7,240
Given the following text description, write Python code to implement the functionality described below step by step Description: ``` Copyright 2020 The IREE Authors Licensed under the Apache License v2.0 with LLVM Exceptions. See https Step1: 2. Import TensorFlow and Other Dependencies Step2: 3. Load the MNIST Datas...
Python Code: %%capture !python -m pip install iree-compiler iree-runtime iree-tools-tf -f https://github.com/google/iree/releases # Import IREE's TensorFlow Compiler and Runtime. import iree.compiler.tf import iree.runtime Explanation: ``` Copyright 2020 The IREE Authors Licensed under the Apache License v2.0 with LLVM...
7,241
Given the following text description, write Python code to implement the functionality described. Description: Find two non Function to check if two non - intersecting subarrays with equal sum exists or not ; Sort the given array ; Traverse the array ; Check for duplicate elements ; If no duplicate element is present i...
Python Code: def findSubarrays(arr , N ) : arr . sort() ; i = 0 ; for i in range(N - 1 ) : if(arr[i ] == arr[i + 1 ] ) : print("YES ") ; return ;   print("NO ") ;  if __name__== ' __main __' : arr =[4 , 3 , 0 , 1 , 2 , 0 ] ; N = len(arr ) ; findSubarrays(arr , N ) ; 
7,242
Given the following text description, write Python code to implement the functionality described below step by step Description: Some remarks on sorting You can either use the sorted() Python built-in function which will produce a sorted version of anything you can iterate over. Lists have a .sort() method which sorts...
Python Code: l1=[3,1,4,6,7] l2=sorted(l1) print(l1,l2) #l2 is a different list from l1 l1.sort() #now l1 is sorted in-place print(l1) Explanation: Some remarks on sorting You can either use the sorted() Python built-in function which will produce a sorted version of anything you can iterate over. Lists have a .sort() m...
7,243
Given the following text description, write Python code to implement the functionality described below step by step Description: Parallelize image filters with dask This notebook will show how to parallize CPU-intensive workload using dask array. A simple uniform filter (equivalent to a mean filter) from scipy.ndimage...
Python Code: %pylab inline from scipy.ndimage import uniform_filter import dask.array as da def mean(img): "ndimage.uniform_filter with `size=51`" return uniform_filter(img, size=51) Explanation: Parallelize image filters with dask This notebook will show how to parallize CPU-intensive workload using dask array...
7,244
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> <h1> ILI285 - Computación Científica I / INF285 - Computación Científica </h1> <h2> Interpolation Step1: <div id='intro' /> Introduction Previously in our jupyter notebook...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline import scipy as sp from scipy import interpolate import ipywidgets as widgets import matplotlib as mpl mpl.rcParams['font.size'] = 14 mpl.rcParams['axes.labelsize'] = 20 mpl.rcParams['xtick.labelsize'] = 14 mpl.rcParams['ytick.labelsize'...
7,245
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook uses the March Madness dataset provided by Kaggel.com. Pleas use kaggle.com to access that data. I put the flat data into a SQLite database on my local, for the notebook expla...
Python Code: # imports import sqlite3 as sql from sklearn import datasets from sklearn import metrics import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline Explanation: This notebook uses the March Madness dataset provided by Kaggel.com. Pleas use kaggle.com to...
7,246
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial 11 Step1: 1. New parameters in additional_net_params There are a few unique additions for the grid envs to additional_net_params to be aware of. grid_array grid_array passes infor...
Python Code: from flow.core.params import NetParams from flow.scenarios.grid import SimpleGridScenario from flow.core.params import TrafficLightParams from flow.core.params import SumoParams, EnvParams, InitialConfig, NetParams, \ InFlows, SumoCarFollowingParams from flow.core.params import VehicleParams import num...
7,247
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting the full vector-valued MNE solution The source space that is used for the inverse computation defines a set of dipoles, distributed across the cortex. When visualizing a source esti...
Python Code: # Author: Marijn van Vliet <w.m.vanvliet@gmail.com> # # License: BSD-3-Clause import numpy as np import mne from mne.datasets import sample from mne.minimum_norm import read_inverse_operator, apply_inverse print(__doc__) data_path = sample.data_path() subjects_dir = data_path / 'subjects' smoothing_steps =...
7,248
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple CNN We are going to define a simple Convolutional Network and we are going to train it from scrath on the dataset. The results of this model is going to be our benchmark We are going ...
Python Code: %autosave 0 IMAGE_SIZE = (360,404) # The dimensions to which all images found will be resized. BATCH_SIZE = 32 NUMBER_EPOCHS = 8 TENSORBOARD_DIRECTORY = "../logs/simple_model/tensorboard" TRAIN_DIRECTORY = "../data/train/" VALID_DIRECTORY = "../data/valid/" TEST_DIRECTORY = "../data/test/" NUMBER_TRAIN_SAM...
7,249
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning Assignment 5 The goal of this assignment is to train a Word2Vec skip-gram model over Text8 data. Step2: Download the data from the source website if necessary. Step4: Read th...
Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. %matplotlib inline from __future__ import print_function import collections import math import numpy as np import os import random import tensorflow as tf import zipfile from matplotlib import pylab...
7,250
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: While nan == nan is always False, in many cases people want to treat them as equal, and this is enshrined in pandas.DataFrame.equals:
Problem: import pandas as pd import numpy as np np.random.seed(10) df = pd.DataFrame(np.random.randint(0, 20, (10, 10)).astype(float), columns=["c%d"%d for d in range(10)]) df.where(np.random.randint(0,2, df.shape).astype(bool), np.nan, inplace=True) def g(df): cols = (df.columns[df.iloc[0,:].fillna('Nan') != df.il...
7,251
Given the following text description, write Python code to implement the functionality described below step by step Description: Algorithms Exercise 2 Imports Step2: Peak finding Write a function find_peaks that finds and returns the indices of the local maxima in a sequence. Your function should Step3: Here is a st...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import seaborn as sns import numpy as np Explanation: Algorithms Exercise 2 Imports End of explanation def find_peaks(a): Find the indices of the local maxima in a sequence. peaks = [] for i in range(len(a)): if i==0: i...
7,252
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> <h1> ILI286 - Computación Científica II </h1> <h2> Valores y Vectores Propios </h2> <h2> <a href="#acknowledgements"> [S]cientific [C]omputing [T]eam </a> </h2> <h2...
Python Code: import numpy as np from scipy import linalg from matplotlib import pyplot as plt %matplotlib inline Explanation: <center> <h1> ILI286 - Computación Científica II </h1> <h2> Valores y Vectores Propios </h2> <h2> <a href="#acknowledgements"> [S]cientific [C]omputing [T]eam </a> </h2> <h2> Ve...
7,253
Given the following text description, write Python code to implement the functionality described below step by step Description: <h3>Current School Panda</h3> Working with directory school data Creative Commons in all schools This script uses a csv file from Creative Commons New Zealand and csv file from Ministry of E...
Python Code: crcom = pd.read_csv('/home/wcmckee/Downloads/List of CC schools - Sheet1.csv', skiprows=5, index_col=0, usecols=[0,1,2]) Explanation: <h3>Current School Panda</h3> Working with directory school data Creative Commons in all schools This script uses a csv file from Creative Commons New Zealand and csv file f...
7,254
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Toplevel MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specif...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'pcmdi', 'sandbox-1', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: PCMDI Source ID: SANDBOX-1 Sub-Topics: Radiative Forcings. Properties...
7,255
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id='beginning'></a> <!--\label{beginning}--> * Outline * Glossary * 4. The Visibility space * Previous Step1: Import section specific modules Step2: 4.5.2 $uv$ coverage Step3: Fro...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS Explanation: <a id='beginning'></a> <!--\label{beginning}--> * Outline * Glossary * 4. The Visibility space * Previous: 4.5.1 UV Coverage: UV tracks ...
7,256
Given the following text description, write Python code to implement the functionality described below step by step Description: Evaluating an Exam Using Ply This notebook shows how we can use the package ply to implement a scanner. Our goal is to implement a program that can be used to evaluate the results of an exa...
Python Code: data = '''Class: Algorithms and Complexity Group: TIT09AID MaxPoints = 60 Exercise: 1. 2. 3. 4. 5. 6. Jim Smith: 9 12 10 6 6 0 John Slow: 4 4 2 0 - - Susi Sorglos: 9 12 12 9 9 6 ''' Explanation: Evaluating an Ex...
7,257
Given the following text description, write Python code to implement the functionality described below step by step Description: Препроцессинг фич Step1: Обучение моделей Step2: XGBoost Step3: LightGBM Step4: Vowpal Wabbit Step5: Lasso Step6: Submission Step7: XGBoost Step8: LightGBM Step9: Lasso Step10: Ens...
Python Code: def align_to_lb_score(df): # https://www.kaggle.com/c/sberbank-russian-housing-market/discussion/32717 df = df.copy() trainsub = df[df.timestamp < '2015-01-01'] trainsub = trainsub[trainsub.product_type=="Investment"] ind_1m = trainsub[trainsub.price_doc <= 1000000].index ind_2m = t...
7,258
Given the following text description, write Python code to implement the functionality described below step by step Description: Now create the DrawControl and add it to the Map using add_control. We also register a handler for draw events. This will fire when a drawn path is created, edited or deleted (there are the ...
Python Code: dc = DrawControl(marker={'shapeOptions': {'color': '#0000FF'}}, rectangle={'shapeOptions': {'color': '#0000FF'}}, circle={'shapeOptions': {'color': '#0000FF'}}, circlemarker={}, ) def handle_draw(target, action, geo_json): print(action...
7,259
Given the following text description, write Python code to implement the functionality described below step by step Description: ACM Digital Library bibliometric analysis of legacy software An incomplete bibliographical inquiry into what the ACM Digital Library has to say about legacy. Basically two research questions...
Python Code: import pandas as pd import networkx as nx import community import itertools import matplotlib.pyplot as plt import numpy as np import re %matplotlib inline Explanation: ACM Digital Library bibliometric analysis of legacy software An incomplete bibliographical inquiry into what the ACM Digital Library has t...
7,260
Given the following text description, write Python code to implement the functionality described below step by step Description: Integration Exercise 2 Imports Step1: Indefinite integrals Here is a table of definite integrals. Many of these integrals has a number of parameters $a$, $b$, etc. Find five of these integr...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy import integrate Explanation: Integration Exercise 2 Imports End of explanation def integrand(x, a): return 1.0/(x**2 + a**2) def integral_approx(a): # Use the args keyword argument to feed extra ...
7,261
Given the following text description, write Python code to implement the functionality described below step by step Description: Explicit 1D Benchmarks This file demonstrates how to generate, plot, and output data for 1d benchmarks Choose from Step1: Generate the data with noise Step2: Plot inline and save image Ste...
Python Code: from pypge.benchmarks import explicit import numpy as np # visualization libraries import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # plot the visuals in ipython %matplotlib inline Explanation: Explicit 1D Benchmarks This file demonstrates how to generate, plot, and output data for 1...
7,262
Given the following text description, write Python code to implement the functionality described below step by step Description: Find the best $\alpha$ for $p = 7, N_y = 256, N_z = 2048$ Step1: Find the best $\alpha$ for $p = 15, N_y = 128, N_z = 1024$ Step2: Find the best $\alpha$ for $p = 31, N_y = 64, N_z = 512$
Python Code: alphs = list(np.linspace(0,pi/2, 16, endpoint=False)) Re=2000; N = 7 Nl = 257 Nz = 2049 yms = []; y1s = []; y10s = []; zms = [] for alph in alphs: yl=mesh(alph, Nl) ym, y1, y10, zm, cm = wall_units(yl,Nz, N,Re) yms.append(ym) y1s.append(y1) y10s.append(y10) zms.append(zm) alpha = 0....
7,263
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Introduction and Foundations Project 0 Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the s...
Python Code: import numpy as np import pandas as pd # RMS Titanic data visualization code from titanic_visualizations import survival_stats from IPython.display import display %matplotlib inline # Load the dataset in_file = 'titanic_data.csv' full_data = pd.read_csv(in_file) # Print the first few entries of the RMS Ti...
7,264
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>lcacoffee</h1> script that displays coffees sold by hour at lca2015. Currently it opens a .json file and converts it into a python dict. It's missing monday data. sale by hour is Step1:...
Python Code: import json import os import pandas import getpass theuser = getpass.getuser() Explanation: <h1>lcacoffee</h1> script that displays coffees sold by hour at lca2015. Currently it opens a .json file and converts it into a python dict. It's missing monday data. sale by hour is: key - the hour (24hr). Value i...
7,265
Given the following text description, write Python code to implement the functionality described below step by step Description: Prerequisites This notebook contains examples which are expected to be run with exactly 4 MPI processes; not because they wouldn't work otherwise, but simply because it's what their descript...
Python Code: import ipyparallel as ipp c = ipp.Client(profile='mpi') Explanation: Prerequisites This notebook contains examples which are expected to be run with exactly 4 MPI processes; not because they wouldn't work otherwise, but simply because it's what their description assumes. For this, you need to: Install an M...
7,266
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id="top"></a> Cloud Statistics <hr> Notebook Summary This notebook explores Landsat 7 and Landsat 8 Data Cubes and reports cloud statistics for selected regions within a cube. This is va...
Python Code: # Enable importing of utilities. import sys import os sys.path.append(os.environ.get('NOTEBOOK_ROOT')) import numpy as np import xarray as xr import pandas as pd import matplotlib.pyplot as plt # Load Data Cube Configuration import datacube import utils.data_cube_utilities.data_access_api as dc_api api =...
7,267
Given the following text description, write Python code to implement the functionality described below step by step Description: 1st Order ODE Let's solve Step1: Try smaller timestep Step2: Our numeric result is more accurate when we use a smaller timestep, but it's still not perfect 2nd Order ODE Let's solve Step3:...
Python Code: y_0 = 1 t_0 = 0 t_f = 10 def dy_dt(y): return .5*y def analytic_solution_1st_order(t): return np.exp(.5*t) dt = .5 t_array = np.arange(t_0, t_f, dt) y_array = np.empty_like(t_array) y_array[0] = y_0 for i in range(len(y_array)-1): y_array[i+1] = y_array[i] + (dt * dy_dt(y_array[i])) plt.pl...
7,268
Given the following text description, write Python code to implement the functionality described below step by step Description: Pattern Mining - Association Rule Mining A frequent pattern is a substructure that appears frequently in a dataset. Finding the frequent patterns of a dataset is a essential step in data min...
Python Code: import graphlab as gl from graphlab import aggregate as agg from visualization_helper_functions import * Explanation: Pattern Mining - Association Rule Mining A frequent pattern is a substructure that appears frequently in a dataset. Finding the frequent patterns of a dataset is a essential step in data mi...
7,269
Given the following text description, write Python code to implement the functionality described below step by step Description: Convolutional Neural Networks with 17flowers A simple deep learning example on how to start classifying images with your own data. This notebook is expected to be executed after 17flowers_da...
Python Code: from __future__ import division, print_function %matplotlib inline path = "data/17flowers/" import os, json from glob import glob import numpy as np np.set_printoptions(precision=4, linewidth=100) from matplotlib import pyplot as plt # check that ~/.keras/keras.json is set for Theano and includes "image_da...
7,270
Given the following text description, write Python code to implement the functionality described below step by step Description: Tarea 2 Step1: Realizar y verificar la descomposición SVD Step2: Para alguna imagen de su elección, elegir distintos valores de aproximación a la imagen original Step3: Ejercicio 2 Step4:...
Python Code: from PIL import Image import matplotlib.pyplot as plt import numpy as np #url = sys.argv[1] url = 'pikachu.png' img = Image.open(url) imggray = img.convert('LA') Explanation: Tarea 2: Álgebra Lineal y Descomposición SVD Teoría de Algebra Lineal y Optimización 1. ¿Por qué una matriz equivale a una transform...
7,271
Given the following text description, write Python code to implement the functionality described below step by step Description: Get the text we want to process Step1: Let's take a smaller chunk from the text Step2: Tokenizing text Tokens are meaningful chunks of text Step3: Stop words Stop words are words that you...
Python Code: with open('book.txt', 'r') as file: text = file.readlines() Explanation: Get the text we want to process End of explanation # using a list comprehension to simplify iterating over the the text structure snippet = " ".join(block.strip() for block in text[175:200]) snippet # alternative with for-loop oth...
7,272
Given the following text description, write Python code to implement the functionality described below step by step Description: Finite Time of Integration (fti) Setup Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your installation or ...
Python Code: !pip install -I "phoebe>=2.0,<2.1" Explanation: Finite Time of Integration (fti) Setup Let's first make sure we have the latest version of PHOEBE 2.0 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 %matp...
7,273
Given the following text description, write Python code to implement the functionality described below step by step Description: Electron Plasma Waves Created by Rui Calado and Jorge Vieira, 2018 In this notebook, we are going to study the dispersion relation for electron plasma waves. Theory Electron plasma waves are...
Python Code: import em1ds as zpic #v_the = 0.001 v_the = 0.02 #v_the = 0.20 electrons = zpic.Species( "electrons", -1.0, ppc = 64, uth=[v_the,v_the,v_the]) sim = zpic.Simulation( nx = 500, box = 50.0, dt = 0.0999/2, species = electrons ) sim.filter_set("sharp", ck = 0.99) #sim.filter_set("gaussian", ck = 50.0) Explanat...
7,274
Given the following text description, write Python code to implement the functionality described below step by step Description: Ch 2. 자료의 정리 변수와 자료 도수분포표 1. 변수 ( variable, feature ) 양적변수 ( quantitative variable, real value ) 수치로 나타낼 수 있는 변수 - 이산변수 ( discrete ) - 정숫값을 취한 수 있는 변수 - ex. 자녀수, 자동차판매대수 등 - 연속변수 ( c...
Python Code: import pandas as pd import numpy as np np.random.seed(0) data = np.random.randint(50, 100, size=(8, 5)) data[0][0] = 12 data np.sort(data.flatten()) Explanation: Ch 2. 자료의 정리 변수와 자료 도수분포표 1. 변수 ( variable, feature ) 양적변수 ( quantitative variable, real value ) 수치로 나타낼 수 있는 변수 - 이산변수 ( discrete ) - 정숫값을 취...
7,275
Given the following text description, write Python code to implement the functionality described below step by step Description: Pre-processing and training LDA The purpose of this tutorial is to show you how to pre-process text data, and how to train the LDA model on that data. This tutorial will not explain you the ...
Python Code: # Read data. import os from smart_open import smart_open # Folder containing all NIPS papers. data_dir = 'nipstxt/' # Folders containin individual NIPS papers. yrs = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] dirs = ['nips' + yr for yr in yrs] # Read all texts into a lis...
7,276
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="../Pierian-Data-Logo.PNG"> <br> <strong><center>Copyright 2019. Created by Jose Marcial Portilla.</center></strong> CIFAR Code Along with CNN The <a href='https Step1: Load the CI...
Python Code: import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from torchvision import datasets, transforms from torchvision.utils import make_grid import numpy as np import pandas as pd import seaborn as sn # for heatmaps from sklearn.metrics import confusion_m...
7,277
Given the following text description, write Python code to implement the functionality described below step by step Description: <center><h1>CNN 多通道情感分析</h1></center> 一个有三个通道,分别是word embedding,POS 标签 embedding, 词的情感极性强度embedding Step1: POS当作一个通道。 Tag word 的方法: http Step2: 情感极性当作一个通道。 读取情感强度文件,构建字典 Step3: 构建情感极性强度通道...
Python Code: import keras from os.path import join from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense, Dropout,Activation, Lambda,Input from keras.layers import Embedding from keras.layers import Convolution1D from keras.datasets import imdb from keras import b...
7,278
Given the following text description, write Python code to implement the functionality described below step by step Description: GPS tracks http Step1: TODO Step2: Convert the data to Web Mercator Step3: Contextily helper function Step4: Add background tiles to plot Step5: Save selected departments into a GeoJSON...
Python Code: import pandas as pd import geopandas as gpd Explanation: GPS tracks http://geopandas.org/gallery/plotting_basemap_background.html#adding-a-background-map-to-plots https://ocefpaf.github.io/python4oceanographers/blog/2015/08/03/fiona_gpx/ End of explanation df = gpd.read_file("communes-20181110.shp") !head ...
7,279
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualization 1 Step1: Scatter plots Learn how to use Matplotlib's plt.scatter function to make a 2d scatter plot. Generate random data using np.random.randn. Style the markers (color, size...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np Explanation: Visualization 1: Matplotlib Basics Exercises End of explanation ?plt.scatter() from matplotlib import markers markers.MarkerStyle.markers.keys() x = np.random.rand(100) y = np.random.rand(100) plt.scatter(x, y, label = 'The ...
7,280
Given the following text description, write Python code to implement the functionality described below step by step Description: <!--BOOK_INFORMATION--> <a href="https Step1: Generating the training data The first step is to generate some training data. For this, we will use NumPy's random number generator. As discus...
Python Code: import numpy as np import cv2 import matplotlib.pyplot as plt %matplotlib inline plt.style.use('ggplot') Explanation: <!--BOOK_INFORMATION--> <a href="https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv" target="_blank"><img align="left" src="data/cover.jpg" style="width: 76...
7,281
Given the following text description, write Python code to implement the functionality described below step by step Description: Gravitational Redshift (rv_grav) Setup Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or ...
Python Code: !pip install -I "phoebe>=2.1,<2.2" Explanation: Gravitational Redshift (rv_grav) Setup Let's first make sure we have the latest version of PHOEBE 2.1 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 %matp...
7,282
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Exercise 4 Imports Step1: Complete graph Laplacian In discrete mathematics a Graph is a set of vertices or nodes that are connected to each other by edges or lines. If those edges don...
Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns Explanation: Numpy Exercise 4 Imports End of explanation import networkx as nx K_5=nx.complete_graph(5) nx.draw(K_5) Explanation: Complete graph Laplacian In discrete mathematics a Graph is a set of vertices or node...
7,283
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 5.4 Step1: The Data We'll start off by exploring our dataset to see what attributes we have and how the class of the tumor is represented Before we proceed, ensure to include header...
Python Code: import pandas as pd # we use this library to import a CSV of cancer tumor data import numpy as np # we use this library to help us represent traditional Python arrays/lists as matrices/tensors with linear algebra operations from sknn.mlp import Classifier, Layer # we use this library for the actual neural ...
7,284
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) Explanation: Language Translation In this project, you’re going ...
7,285
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Files 2. Create a file in the current working directory called contacts.txt by running the cell below Step2: 3. Open the file and use .read() to save the contents of t...
Python Code: abbr = 'NLP' full_text = 'Natural Language Processing' # Enter your code here: print(f'{abbr} stands for {full_text}') Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> Python Text Basics Assessment - Solutions Welcome to your assessment! Complete the tasks descr...
7,286
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Genetic Algorithm Workshop In this workshop we will code up a genetic algorithm for a simple mathematical optimization problem. Genetic Algorithm is a * Meta-heuristic * Inspired by N...
Python Code: %matplotlib inline # All the imports from __future__ import print_function, division from math import * import random import sys import matplotlib.pyplot as plt # TODO 1: Enter your unity ID here __author__ = "<unity-id>" class O: Basic Class which - Helps dynamic updates - Pretty...
7,287
Given the following text description, write Python code to implement the functionality described below step by step Description: NumPy를 활용한 선형대수 입문 선형대수(linear algebra)는 데이터 분석에 필요한 각종 계산을 위한 기본적인 학문이다. 데이터 분석을 하기 위해서는 실제로 수많은 숫자의 계산이 필요하다. 하나의 데이터 레코드(record)가 수십개에서 수천개의 숫자로 이루어져 있을 수도 있고 수십개에서 수백만개의 이러한 데이터 레코드를 조합...
Python Code: x = np.array([1, 2, 3, 4]) x x = np.array([[1], [2], [3], [4]]) x Explanation: NumPy를 활용한 선형대수 입문 선형대수(linear algebra)는 데이터 분석에 필요한 각종 계산을 위한 기본적인 학문이다. 데이터 분석을 하기 위해서는 실제로 수많은 숫자의 계산이 필요하다. 하나의 데이터 레코드(record)가 수십개에서 수천개의 숫자로 이루어져 있을 수도 있고 수십개에서 수백만개의 이러한 데이터 레코드를 조합하여 계산하는 과정이 필요할 수 있다. 선형대수를 사용하는 첫번째 ...
7,288
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook only contains executable code cells for the examples mentioned in https Step1: The problem Step2: The solution Step3: Using pad_shard_unpad() Step4: Computing metrics in ev...
Python Code: !pip install -q chex einops # tfds.split_for_jax_process() was added in 4.5.1 !pip install -q tensorflow_datasets -U # flax.jax_utils.pad_shard_unpad() is only available at HEAD !pip install -q git+https://github.com/google/flax import collections import chex import einops import jax import jax.numpy as jn...
7,289
Given the following text description, write Python code to implement the functionality described below step by step Description: Analysis of classification results Objective Step1: Load original model Step2: Load sample classification results The implemented classification method does not return a single best-fit mo...
Python Code: from IPython.core.display import HTML css_file = 'pynoddy.css' HTML(open(css_file, "r").read()) import sys, os import matplotlib.pyplot as plt # adjust some settings for matplotlib from matplotlib import rcParams # print rcParams rcParams['font.size'] = 15 # determine path of repository to set paths corret...
7,290
Given the following text description, write Python code to implement the functionality described below step by step Description: Computing the top hashtags (JSON) So you have tweets in a JSON file, and you'd like to get a list of the hashtags, from the most frequently occurring hashtags on down. There are many, many d...
Python Code: !cat 50tweets.json | jq -cr '[.entities.hashtags][0][].text' !cat tweets4hashtags.json | jq -cr '[.entities.hashtags][0][].text' > allhashtags.txt Explanation: Computing the top hashtags (JSON) So you have tweets in a JSON file, and you'd like to get a list of the hashtags, from the most frequently occurri...
7,291
Given the following text description, write Python code to implement the functionality described below step by step Description: Stability map with MEGNO and WHFast In this tutorial, we'll create a stability map of a two planet system using the chaos indicator MEGNO (Mean Exponential Growth of Nearby Orbits) and the s...
Python Code: def simulation(par): a, e = par # unpack parameters rebound.reset() rebound.integrator = "whfast-nocor" rebound.dt = 5. rebound.add(m=1.) # Star rebound.add(m=0.000954, a=5.204, anom=0.600, omega=0.257, e=0.048) rebound.add(m=0.000285, a=a, anom=0.871, omega=1.616, e=e) reb...
7,292
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: First off, I'm no mathmatician. I admit that. Yet I still need to understand how ScyPy's sparse matrices work arithmetically in order to switch from a dense NumPy matrix to a SciPy ...
Problem: import numpy as np from scipy import sparse V = sparse.random(10, 10, density = 0.05, format = 'dok', random_state = 42) x = 99 V._update(zip(V.keys(), np.array(list(V.values())) + x))
7,293
Given the following text description, write Python code to implement the functionality described below step by step Description: I was inspired by @twiecki and his great post about Bayesian neural networks. But I thought that that way of creating BNNs is not obvious and easy for people. That's why I decided to make Ge...
Python Code: %env THEANO_FLAGS=device=cuda0 import matplotlib.pyplot as plt %matplotlib inline import gelato import theano import theano.tensor as tt theano.config.warn_float64 = 'warn' import numpy as np import lasagne import pymc3 as pm Explanation: I was inspired by @twiecki and his great post about Bayesian neural ...
7,294
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create Data Step2: Select Based On The Result Of A Select
Python Code: # Ignore %load_ext sql %sql sqlite:// %config SqlMagic.feedback = False Explanation: Title: Nested Select Slug: nested_select Summary: Nested Select Based On Conditions in SQL. Date: 2017-01-16 12:00 Category: SQL Tags: Basics Authors: Chris Albon Note: This tutorial was written using Catherine Devlin...
7,295
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Was trying to generate a pivot table with multiple "values" columns. I know I can use aggfunc to aggregate values the way I want to, but what if I don't want to max or min both colu...
Problem: import pandas as pd import numpy as np np.random.seed(1) df = pd.DataFrame({ 'A' : ['one', 'one', 'two', 'three'] * 6, 'B' : ['A', 'B', 'C'] * 8, 'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 4, 'D' : np.random.randn(24), 'E' : np.random.randn(24) }) def g...
7,296
Given the following text description, write Python code to implement the functionality described below step by step Description: 1.1 Getting started Prerequisites Installation This tutorial requires signac, so make sure to install the package before starting. The easiest way to do so is using conda Step1: We start by...
Python Code: import signac assert signac.__version__ >= '0.8.0' Explanation: 1.1 Getting started Prerequisites Installation This tutorial requires signac, so make sure to install the package before starting. The easiest way to do so is using conda: $ conda config --add channels conda-forge $ conda install signac or pip...
7,297
Given the following text description, write Python code to implement the functionality described below step by step Description: Model Tuning Step1: basic Usage A couple things are needed by the tuner Step2: prepare the model Step3: start tuning Step4: view the best hyper-parameter set Step5: understading hyper-s...
Python Code: import matchzoo as mz train_raw = mz.datasets.toy.load_data('train') dev_raw = mz.datasets.toy.load_data('dev') test_raw = mz.datasets.toy.load_data('test') Explanation: Model Tuning End of explanation preprocessor = mz.models.DenseBaseline.get_default_preprocessor() train = preprocessor.fit_transform(trai...
7,298
Given the following text description, write Python code to implement the functionality described below step by step Description: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 2</font> Download Step1: Dicionários Step2: Criando dicionários aninhados
Python Code: # Versão da Linguagem Python from platform import python_version print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version()) Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 2</font> Download: http://github.com/dsacademybr End of explanation # Iss...
7,299
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 3 Step1: Visualize initial state Step2: Run simulation and visualize new state Step3: Queries about LAMMPS simulation Step4: Working with LAMMPS Variables Step5: Accessing Atom ...
Python Code: from lammps import IPyLammps L = IPyLammps() # 2d circle of particles inside a box with LJ walls import math b = 0 x = 50 y = 20 d = 20 # careful not to slam into wall too hard v = 0.3 w = 0.08 L.units("lj") L.dimension(2) L.atom_style("bond") L.boundary("f f p") L.lattice("hex", 0.85) L.r...