Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
10,800
Given the following text description, write Python code to implement the functionality described below step by step Description: MNIST MLP You should already have gone through the GettingStartedSequentialModels notebook -- if not you'll be lost here! Step1: We're going to use some examples from https Step2: Typicall...
Python Code: import numpy as np from IPython.display import SVG from keras.utils.vis_utils import model_to_dot Explanation: MNIST MLP You should already have gone through the GettingStartedSequentialModels notebook -- if not you'll be lost here! End of explanation import keras from keras.datasets import mnist # load up...
10,801
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Bootcamp Final Project Step1: Here we have displayed the most basic statistics for each of the MVP canidates, such as points, assists, steals and rebounds a game. As we can see, Westbr...
Python Code: import pandas as pd # data package import matplotlib.pyplot as plt # graphics import datetime as dt # date tools, used to note current date import requests from bs4 import BeautifulSoup import urllib.request from matplotlib.offsetbox import OffsetImage %matplotlib inline #per game...
10,802
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to PyTorch PyTorch is a Python package for performing tensor computation, automatic differentiation, and dynamically defining neural networks. It makes it particularly easy to a...
Python Code: import numpy as np import torch # Create a 3 x 2 array np.ndarray((3, 2)) # Create a 3 x 2 Tensor torch.Tensor(3, 2) Explanation: Introduction to PyTorch PyTorch is a Python package for performing tensor computation, automatic differentiation, and dynamically defining neural networks. It makes it particula...
10,803
Given the following text description, write Python code to implement the functionality described below step by step Description: Unpacking a Sequence into Separate Variables Problem You have an N-element tuple or sequence that you would like to unpack into a collection of N variables. Solution Any sequence (or iterabl...
Python Code: # Example 1 p = (4, 5) x, y = p print x print y Explanation: Unpacking a Sequence into Separate Variables Problem You have an N-element tuple or sequence that you would like to unpack into a collection of N variables. Solution Any sequence (or iterable) can be unpacked into variables using a simple assignm...
10,804
Given the following text description, write Python code to implement the functionality described below step by step Description: El día Pi Esta notebook fue creada originalmente como un blog post por Raúl E. López Briega en Mi blog sobre Python. El contenido esta bajo la licencia BSD. <img alt="día Pi" title="día Pi" ...
Python Code: # Pi utilizando el módulo math import math math.pi # Pi utiizando sympy, dps nos permite variar el número de dígitos de Pi from sympy.mpmath import mp mp.dps = 33 # número de dígitos print(mp.pi) Explanation: El día Pi Esta notebook fue creada originalmente como un blog post por Raúl E. López Briega en Mi...
10,805
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TensorFlow Similarity Authors. Step1: TensorFlow Similarity Supervised Learning Hello World <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank...
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 # dis...
10,806
Given the following text description, write Python code to implement the functionality described below step by step Description: Variational AutoEncoder Author Step2: Create a sampling layer Step3: Build the encoder Step4: Build the decoder Step5: Define the VAE as a Model with a custom train_step Step6: Train th...
Python Code: import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers Explanation: Variational AutoEncoder Author: fchollet<br> Date created: 2020/05/03<br> Last modified: 2020/05/03<br> Description: Convolutional Variational AutoEncoder (VAE) trained on MNIST digits. ...
10,807
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex client library Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Once you've installed the Vertex client library and Google clo...
Python Code: import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG Explanation: Vertex client library: Custom training text binary classification model with pipeline...
10,808
Given the following text description, write Python code to implement the functionality described below step by step Description: Trajectory Recommendation - Test Evaluation Protocol Step1: Run notebook ssvm.ipynb Step2: Sanity check for evaluation protocol 70/30 split for trajectories conform to each query.
Python Code: % matplotlib inline import os, sys, time import math, random import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from joblib import Parallel, delayed Explanation: Trajectory Recommendation - Test Evaluation Protocol End of explanation %run 'ssvm.ipynb' check_protoco...
10,809
Given the following text description, write Python code to implement the functionality described below step by step Description: We will first break out a training and testing set with an 80/20 split Step1: Random Forests Step2: A 94% accuracy with an 95% Precision - recall - f1score is quite high, but how does it c...
Python Code: spamTesting, spamTrain = train_test_split( data, test_size=0.8, random_state=5) len(spamTesting) len(spamTrain) Explanation: We will first break out a training and testing set with an 80/20 split End of explanation RndForClf = RandomForestClassifier(n_jobs=2, n_estimators=100, max_features="auto",rando...
10,810
Given the following text description, write Python code to implement the functionality described below step by step Description: Chromosphere model The chromosphere model, pytransit.ChromosphereModel, implements a transit over a thin-walled sphere, as described by Schlawin et al. (ApJL 722, 2010). The model is paralle...
Python Code: %pylab inline sys.path.append('..') from pytransit import ChromosphereModel seed(0) times_sc = linspace(0.85, 1.15, 1000) # Short cadence time stamps times_lc = linspace(0.85, 1.15, 100) # Long cadence time stamps k, t0, p, a, i, e, w = 0.1, 1., 2.1, 3.2, 0.5*pi, 0.3, 0.4*pi pvp = tile([k, t0, p, a, i...
10,811
Given the following text description, write Python code to implement the functionality described below step by step Description: Sebastian Raschka, 2015 Python Machine Learning Essentials Chapter 6 - Learning Best Practices for Model Evaluation and Hyperparameter Tuning Note that the optional watermark extension is a ...
Python Code: %load_ext watermark %watermark -a 'Sebastian Raschka' -u -d -v -p numpy,pandas,matplotlib,scikit-learn # to install watermark just uncomment the following line: #%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py Explanation: Sebastian Raschka, 2015 Python Machine Learning E...
10,812
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t...
10,813
Given the following text description, write Python code to implement the functionality described below step by step Description: How to use topic model by gensim This document will show you how to use topic model by gensim. The data for this tutorial is from Recruit HotPepper Beauty API. So you need api key of it. If ...
Python Code: # enable showing matplotlib image inline %matplotlib inline # autoreload module %load_ext autoreload %autoreload 2 PROJECT_ROOT = "/" def load_local_package(): import os import sys root = os.path.join(os.getcwd(), "./") sys.path.append(root) # load project root return root PROJECT_ROOT...
10,814
Given the following text description, write Python code to implement the functionality described below step by step Description: Continuous training pipeline with Kubeflow Pipeline and AI Platform Learning Objectives Step6: The pipeline uses a mix of custom and pre-build components. Pre-build components. The pipeline...
Python Code: !grep 'BASE_IMAGE =' -A 5 pipeline/covertype_training_pipeline.py Explanation: Continuous training pipeline with Kubeflow Pipeline and AI Platform Learning Objectives: 1. Learn how to use Kubeflow Pipeline (KFP) pre-build components (BiqQuery, AI Platform training and predictions) 1. Learn how to use KFP l...
10,815
Given the following text description, write Python code to implement the functionality described below step by step Description: Got Scotch? In this notebook, we're going to create a dashboard that recommends scotches based on their taste profiles. Step1: Load Data <span style="float Step2: We now define a get_simil...
Python Code: %matplotlib widget import pandas as pd import seaborn as sns import numpy as np import matplotlib.pyplot as plt import os import ipywidgets as widgets from traitlets import Unicode, List, Instance, link, HasTraits from IPython.display import display, clear_output, HTML, Javascript display(widgets.Button())...
10,816
Given the following text description, write Python code to implement the functionality described below step by step Description: Time Series Analysis One important area of application for information theory is time series analysis. Here, we will demonstrate how to compute the modes of information flow --- intrinsic, s...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline import dit from dit.inference import binned, dist_from_timeseries from dit.multivariate import total_correlation as I, intrinsic_total_correlation as IMI dit.ditParams['repr.print'] = True Explanation: Time Series Analysis One important ...
10,817
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute induced power in the source space with dSPM Returns STC files ie source estimates of induced power for different bands in the source space. The inverse method is linear based on dSPM...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD-3-Clause import matplotlib.pyplot as plt import mne from mne import io from mne.datasets import sample from mne.minimum_norm import read_inverse_operator, source_band_induced_power print(__doc__) Explanation: Compute induced power...
10,818
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploring Climate Data Step1: Above Step2: One way to interface with the GDP is with the interactive web interface, shown below. In this interface, you can upload a shapefile or draw on t...
Python Code: from IPython.core.display import Image Image('http://www-tc.pbs.org/kenburns/dustbowl/media/photos/s2571-lg.jpg') Explanation: Exploring Climate Data: Past and Future Roland Viger, Rich Signell, USGS First presented at the 2012 Unidata Workshop: Navigating Earth System Science Data, 9-13 July. What if you ...
10,819
Given the following text description, write Python code to implement the functionality described below step by step Description: Datasets to download Here we list a few datasets that might be interesting to explore with vaex. New York taxi dataset The very well known dataset containing trip infromation from the iconic...
Python Code: import vaex import warnings; warnings.filterwarnings("ignore") df = vaex.open('/data/yellow_taxi_2009_2015_f32.hdf5') print(f'number of rows: {df.shape[0]:,}') print(f'number of columns: {df.shape[1]}') long_min = -74.05 long_max = -73.75 lat_min = 40.58 lat_max = 40.90 df.plot(df.pickup_longitude, df.pick...
10,820
Given the following text description, write Python code to implement the functionality described below step by step Description: Übung 7 Step1: Aufbau der Basisdaten Laden der Matlab Daten Step2: Darstellung in einer Adjazenzmatrix Zur Erinnerung, innerhalb einer Adjazenzmatrix wird für jede Kante zwischen zwei Knot...
Python Code: import matplotlib import matplotlib.pylab as pl import matplotlib.pyplot as plt import numpy as np import scipy.io import networkx as nx def print_divider(separator='-', length=80): print(''.join([separator for _ in range(length)])) print() def print_heading(msg='', separator='-'): print('...
10,821
Given the following text description, write Python code to implement the functionality described below step by step Description: Author Step1: First let's check if there are new or deleted files (only matching by file names). Step2: So we have the same set of files in both versions Step3: Let's make sure the struct...
Python Code: import collections import glob import os from os import path import matplotlib_venn import pandas as pd rome_path = path.join(os.getenv('DATA_FOLDER'), 'rome/csv') OLD_VERSION = '332' NEW_VERSION = '333' old_version_files = frozenset(glob.glob(rome_path + '/*{}*'.format(OLD_VERSION))) new_version_files = f...
10,822
Given the following text description, write Python code to implement the functionality described below step by step Description: determine_region A notebook to determine what region (e.g. neighborhood, ward, census district) the issue is referring to Step1: Read in neighborhood shapefiles Step3: Now plot the shapefi...
Python Code: import fiona from shapely.geometry import shape import nhrc2 import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from collections import defaultdict import numpy as np from matplotlib.patches import Polygon from shapely.geometry import Point %matplotlib inline #the project root directo...
10,823
Given the following text description, write Python code to implement the functionality described below step by step Description: AF6UY ditDahReader Library Usage The AF6UY ditDahReader python3 library is a morse code (CW) library with its final goal of teach the author (AF6UY) morse code by playing IRC streams in mors...
Python Code: import ditDahReader as dd import numpy as np import matplotlib.pyplot as plt Explanation: AF6UY ditDahReader Library Usage The AF6UY ditDahReader python3 library is a morse code (CW) library with its final goal of teach the author (AF6UY) morse code by playing IRC streams in morse code. Along the way it w...
10,824
Given the following text description, write Python code to implement the functionality described below step by step Description: Model Step2: Standardized and relative regression coefficients (betas) The relative coefficients are intended to show relative contribution of different feature and their primary purpose is...
Python Code: Markdown('Model used: **{}**'.format(model_name)) Markdown('Number of features in model: **{}**'.format(len(features_used))) builtin_ols_models = ['LinearRegression', 'EqualWeightsLR', 'RebalancedLR', 'NNLR', 'LassoFixe...
10,825
Given the following text description, write Python code to implement the functionality described below step by step Description: Building an image retrieval system with deep features Fire up GraphLab Create Step1: Load the CIFAR-10 dataset We will use a popular benchmark dataset in computer vision called CIFAR-10. ...
Python Code: import graphlab Explanation: Building an image retrieval system with deep features Fire up GraphLab Create End of explanation image_train = graphlab.SFrame('image_train_data/') image_test = graphlab.SFrame('image_test_data/') Explanation: Load the CIFAR-10 dataset We will use a popular benchmark dataset in...
10,826
Given the following text description, write Python code to implement the functionality described below step by step Description: Maxpooling Layer In this notebook, we add and visualize the output of a maxpooling layer in a CNN. A convolutional layer + activation function, followed by a pooling layer, and a linear lay...
Python Code: import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'data/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2...
10,827
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', 'hammoz-consortium', 'sandbox-3', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: HAMMOZ-CONSORTIUM Source ID: SANDBOX-3 Sub-Topics: Radiati...
10,828
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Get the Data Read in the College_Data file using read_csv. Figure out how to set the first column as the index. Step2: Check the head of the data Step3: Check the in...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> K Means Clustering Project - Solutions For this project we will attempt to use KMeans Clustering to c...
10,829
Given the following text description, write Python code to implement the functionality described below step by step Description: Circular Regression Step1: Directional statistics, also known as circular statistics or spherical statistics, refers to a branch of statistics dealing with data which domain is the unit cir...
Python Code: import arviz as az import bambi as bmb from matplotlib.lines import Line2D import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy import stats az.style.use("arviz-white") Explanation: Circular Regression End of explanation x = np.linspace(-np.pi, np.pi, 200) mus = [0., 0., 0., -...
10,830
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting Started This tutorial is meant to get you started with writing your tests and tuning scripts using Kernel Tuner. We'll use a simple 2D Convolution kernel as an example kernel, but as...
Python Code: %%writefile convolution_naive.cu __global__ void convolution_kernel(float *output, float *input, float *filter) { int x = blockIdx.x * blockDim.x + threadIdx.x; int y = blockIdx.y * blockDim.y + threadIdx.y; int i, j; float sum = 0.0; if (y < image_height && x < image_width) { f...
10,831
Given the following text description, write Python code to implement the functionality described below step by step Description: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small> Challenge Notebook Problem Step1: Unit Test The following unit test is expected to fa...
Python Code: %run ../linked_list/linked_list.py %load ../linked_list/linked_list.py class MyLinkedList(LinkedList): def is_palindrome(self): # TODO: Implement me pass Explanation: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small> Challenge Notebo...
10,832
Given the following text description, write Python code to implement the functionality described below step by step Description: using pcolormesh to plot an x-z cross section of the cloudsat radar reflectivity This notebook shows how to read in the reflectivity, convert it to dbZe (dbZ equivalent, which means the dbZ ...
Python Code: import h5py import numpy as np import datetime as dt from datetime import timezone as tz from matplotlib import pyplot as plt import pyproj from numpy import ma from a301utils.a301_readfile import download from a301lib.cloudsat import get_geo z_file='2008082060027_10105_CS_2B-GEOPROF_GRANULE_P_R04_E02.h5' ...
10,833
Given the following text description, write Python code to implement the functionality described below step by step Description: Análise das soluções do programa Rampa Esta página apresenta as principais soluções apresentadas no programa Rampa. O objetivo é entender as discrepâncias entre elas e comparar suas vantagen...
Python Code: def rr_indices( lado): import numpy as np r,c = np.indices( (lado, lado), dtype='uint16' ) return c print(rr_indices(11)) Explanation: Análise das soluções do programa Rampa Esta página apresenta as principais soluções apresentadas no programa Rampa. O objetivo é entender as discrepâncias ...
10,834
Given the following text description, write Python code to implement the functionality described below step by step Description: Hello world TensorFlow-Android This notebook focuses on the basics of creating your first Andoird App based on TensorFlow. I've created a small DNN to classify IRIS dataset. I've discussed i...
Python Code: #import desired packages import tensorflow as tf import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import os.path import sys # library for freezing the graph from tensorflow.python.tools import freeze_graph # library for optmising inference from tensorflow.python....
10,835
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify ...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'snu', 'sandbox-2', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: SNU Source ID: SANDBOX-2 Topic: Seaice Sub-Topics: Dynamics, Thermodynamics,...
10,836
Given the following text description, write Python code to implement the functionality described below step by step Description: Fitting PRFs in K2 TPFs from Campaign 9.1 In this simple tutorial we will show how to perform PRF photometry in a K2 target pixel file using PyKE and oktopus. This notebook was created with ...
Python Code: import pyke pyke.__version__ import oktopus oktopus.__version__ Explanation: Fitting PRFs in K2 TPFs from Campaign 9.1 In this simple tutorial we will show how to perform PRF photometry in a K2 target pixel file using PyKE and oktopus. This notebook was created with the following versions of PyKE and oktop...
10,837
Given the following text description, write Python code to implement the functionality described below step by step Description: 자료 안내 Step1: 데이터 불러오기 및 처리 오늘 사용할 데이터는 다음과 같다. 미국 51개 주(State)별 담배(식물) 도매가격 및 판매일자 Step2: read_csv 함수의 리턴값은 DataFrame 이라는 자료형이다. Step3: DataFrame 자료형 자세한 설명은 다음 시간에 추가될 것임. 우선은 아래 사이트를 참조...
Python Code: import numpy as np import pandas as pd from datetime import datetime as dt from scipy import stats Explanation: 자료 안내: 여기서 다루는 내용은 아래 사이트의 내용을 참고하여 생성되었음. https://github.com/rouseguy/intro2stats 안내사항 오늘 다루는 내용은 pandas 모듈의 소개 정도로 이해하고 넘어갈 것을 권장한다. 아래 내용은 엑셀의 스프레드시트지에 담긴 데이터를 분석하여 평균 등을 어떻게 구하는가를 알고 있다면 어렵지 ...
10,838
Given the following text description, write Python code to implement the functionality described below step by step Description: Gaia DR2 variability catalogs Part II Step1: The catalog has many columns. What are they? Step2: Gaia Documentation section 14.3.6 explains that some of the columns are populated with arr...
Python Code: # %load /Users/obsidian/Desktop/defaults.py import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format = 'retina' ! du -hs ../data/dr2/Gaia/gdr2/vari_rotation_modulation/csv df0 = pd.read_csv('../data/dr2/Gaia/gdr2/vari_rotation_modulation/...
10,839
Given the following text description, write Python code to implement the functionality described below step by step Description: Let's pull it all together to do something cool. Let's reuse a lot of our code to make a movie of our travel around San Francisco. We'll first select a bunch of recent scenes, activate, and ...
Python Code: # Basemap Mosaic (v1 API) mosaicsSeries = 'global_quarterly_2017q1_mosaic' # Planet tile server base URL (Planet Explorer Mosaics Tiles) mosaicsTilesURL_base = 'https://tiles0.planet.com/experimental/mosaics/planet-tiles/' + mosaicsSeries + '/gmap/{z}/{x}/{y}.png' # Planet tile server url mosaicsTilesURL =...
10,840
Given the following text description, write Python code to implement the functionality described below step by step Description: Convert our txt files to csv format (internally) You will need to create a .\Groundwater-Composition-csv folder to store results in, which is used later on. Step1: Single File Step2: Loadi...
Python Code: inFolder = r'..\Data\Groundwater-Composition2' #os.listdir(inFolder) csvFolder = r'..\Data\Groundwater-Composition-csv' for file in os.listdir(inFolder): current_file = inFolder + '\\' + file outFile = csvFolder + '\\' + file with open(current_file, 'r') as in_file: lines = in_file.read...
10,841
Given the following text description, write Python code to implement the functionality described below step by step Description: Convergence of Green function calculation We check the convergence with $N_\text{kpt}$ for the calculation of the vacancy Green function for FCC and HCP structures. In particular, we will lo...
Python Code: import sys sys.path.extend(['../']) import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') %matplotlib inline import onsager.crystal as crystal import onsager.GFcalc as GFcalc Explanation: Convergence of Green function calculation We check the convergence with $N_\text{kpt}$ ...
10,842
Given the following text description, write Python code to implement the functionality described below step by step Description: Pythonic APIs Step1: Sizing with len() Step2: Arithmetic Step3: A simple but full-featured Pythonic class String formatting mini-language
Python Code: s = 'Fluent' L = [10, 20, 30, 40, 50] print(list(s)) # list constructor iterates over its argument a, b, *middle, c = L # tuple unpacking iterates over right side print((a, b, c)) for i in L: print(i, end=' ') Explanation: Pythonic APIs: the workshop notebook Tutorial overview Introduction A simple b...
10,843
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas cheat sheet <img src="https Step1: Thus Series can have different datatypes. Operations on series You can add, multiply and other numerical opertions on Series just like on numpy arr...
Python Code: import pandas as pd import numpy as np #from a list l1 = [1,2,3,4,5] ser1 = pd.Series(data = l1) #when you dont specify labels for index, it is autogenerated ser1 #from a numpy array arr1 = np.array(l1) l2 = ['a', 'b', 'c','e', 'd'] ser2 = pd.Series(data=arr1, index=l2) #indices can of any data type, here...
10,844
Given the following text description, write Python code to implement the functionality described below step by step Description: Tidy Data Thsis notebbok is designed to explore Hadley Wickman article about tidy data using pandas The datasets are available on github Step1: Original TB dataset. Corresponding to each ‘...
Python Code: import pandas as pd import numpy as np # tuberculosis (TB) dataset path_tb = '/Users/ericfourrier/Documents/ProjetR/tidy-data/data/tb.csv' df_tb = pd.read_csv(path_tb) df_tb.head(20) Explanation: Tidy Data Thsis notebbok is designed to explore Hadley Wickman article about tidy data using pandas The dataset...
10,845
Given the following text description, write Python code to implement the functionality described below step by step Description: The role of dipole orientations in distributed source localization When performing source localization in a distributed manner (MNE/dSPM/sLORETA/eLORETA), the source space is defined as a gr...
Python Code: from mayavi import mlab import mne from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse data_path = sample.data_path() evokeds = mne.read_evokeds(data_path + '/MEG/sample/sample_audvis-ave.fif') left_auditory = evokeds[0].apply_baseline() fwd = mne.read_forward_...
10,846
Given the following text description, write Python code to implement the functionality described below step by step Description: Assignment 9 Lorenzo Biasi, Julius Vernie Step1: 1.1 We can see in the plot the fixed points. In the central point the function has a slope bigger than one, so it is not a stable point. For...
Python Code: import numpy as np import matplotlib.pyplot as plt from scipy.optimize import fsolve %matplotlib inline def sigmoid(x): return 1. / (1 + np.exp(-x)) def df(x, w=0, theta=0): return w * sigmoid(x) * (1 - sigmoid(x)) def f(x, w=0, theta=0): return w * sigmoid(x) + theta def g(x, w, theta): re...
10,847
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: TFRecord 和 tf.Example <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step5: tf.Example tf.Example 的数据类...
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...
10,848
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting house prices Step1: As you can see, we have 404 training samples and 102 test samples. The data comprises 13 features. The 13 features in the input data are as follow Step2: Th...
Python Code: from keras.datasets import boston_housing (train_data, train_targets), (test_data, test_targets) = boston_housing.load_data() train_data.shape test_data.shape Explanation: Predicting house prices: a regression example This notebook contains the code samples found in Chapter 3, Section 6 of Deep Learning w...
10,849
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Load Image As Greyscale Step2: Enhance Image Step3: View Image
Python Code: # Load image import cv2 import numpy as np from matplotlib import pyplot as plt Explanation: Title: Enhance Contrast Of Greyscale Image Slug: enhance_contrast_of_greyscale_image Summary: How to enhance the contrast of images using OpenCV in Python. Date: 2017-09-11 12:00 Category: Machine Learning Tags:...
10,850
Given the following text description, write Python code to implement the functionality described below step by step Description: A Simple Symbolic Calculator This file shows how a simple symbolic calculator can be implemented using Ply. The grammar for the language implemented by this parser is as follows Step1: The...
Python Code: import ply.lex as lex Explanation: A Simple Symbolic Calculator This file shows how a simple symbolic calculator can be implemented using Ply. The grammar for the language implemented by this parser is as follows: $$ \begin{array}{lcl} \texttt{stmnt} & \rightarrow & \;\texttt{IDENTIFIER} \;\texttt{':=...
10,851
Given the following text description, write Python code to implement the functionality described below step by step Description: Neural Network Example with Keras (C) 2018-2019 by Damir Cavar Version Step1: We will use numpy as well Step2: In his tutorial, as linked above, Jason Brownlee suggests that we initialize ...
Python Code: from keras.models import Sequential from keras.layers import Dense Explanation: Neural Network Example with Keras (C) 2018-2019 by Damir Cavar Version: 1.1, January 2019 License: Creative Commons Attribution-ShareAlike 4.0 International License (CA BY-SA 4.0) This is a tutorial related to the L665 course o...
10,852
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 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 about embedding words for use in natural lang...
10,853
Given the following text description, write Python code to implement the functionality described below step by step Description: LAB 5b Step1: Lab Task #1 Step2: Check our trained model files Let's check the directory structure of our outputs of our trained model in folder we exported the model to in our last lab. W...
Python Code: import os Explanation: LAB 5b: Deploy and predict with Keras model on Cloud AI Platform. Learning Objectives Setup up the environment Deploy trained Keras model to Cloud AI Platform Online predict from model on Cloud AI Platform Batch predict from model on Cloud AI Platform Introduction In this notebook, ...
10,854
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 gc from sklearn.preprocessing import StandardScaler from sklearn.model_selection import StratifiedKFold from sklearn.metrics import * from keras import backend as K from keras.models import Model, Sequential from keras.layers import * from keras.optimizers import * from keras.c...
10,855
Given the following text description, write Python code to implement the functionality described below step by step Description: dftdecompose - Illustrate the decomposition of the image in primitive 2-D waves This demonstration illustrates the decomposition of a step function image into cossenoidal waves of increasin...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from numpy.fft import fft2 from numpy.fft import ifft2 import sys,os ia898path = os.path.abspath('/etc/jupyterhub/ia898_1s2017/') if ia898path not in sys.path: sys.path.append(ia898path) import ia898.src as ia f = 50 * np.ones((128,1...
10,856
Given the following text description, write Python code to implement the functionality described below step by step Description: GeometryPlot Step1: First of all, we will create a geometry to work with Step2: GeometryPlot allows you to quickly visualize a geometry. You can create a GeometryPlot out of a geometry ver...
Python Code: import sisl import sisl.viz import numpy as np Explanation: GeometryPlot End of explanation geom = sisl.geom.graphene_nanoribbon(9) Explanation: First of all, we will create a geometry to work with End of explanation # GeometryPlot is the default plot of a geometry, so one can just do plot = geom.plot() Ex...
10,857
Given the following text description, write Python code to implement the functionality described below step by step Description: Network Biology Coding Assignment 3 Submitted By Step1: Question 1 Step2: Final Coexpression network (images exported from Cytoscape) Step3: Degree Distribution for cases <br> i. Gene Dup...
Python Code: import networkx as nx import numpy as np import matplotlib.pyplot as plt import random import copy from Bio.PDB import * from IPython.display import HTML, display import tabulate from __future__ import division from IPython.display import Image Explanation: Network Biology Coding Assignment 3 Submitted By:...
10,858
Given the following text description, write Python code to implement the functionality described below step by step Description: 텐서플로우 라이브러리를 임포트 하세요. 텐서플로우에는 MNIST 데이터를 자동으로 로딩해 주는 헬퍼 함수가 있습니다. "MNIST_data" 폴더에 데이터를 다운로드하고 훈련, 검증, 테스트 데이터를 자동으로 읽어 들입니다. one_hot 옵션을 설정하면 정답 레이블을 원핫벡터로 바꾸어 줍니다. Step1: minist.train.ima...
Python Code: from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) Explanation: 텐서플로우 라이브러리를 임포트 하세요. 텐서플로우에는 MNIST 데이터를 자동으로 로딩해 주는 헬퍼 함수가 있습니다. "MNIST_data" 폴더에 데이터를 다운로드하고 훈련, 검증, 테스트 데이터를 자동으로 읽어 들입니다. one_hot 옵션을 설정하면 정답 레이블을 원핫벡터로 바꾸어 줍니다. End of...
10,859
Given the following text description, write Python code to implement the functionality described below step by step Description: 모형 결합 모형 결합(model combining) 방법은 앙상블 방법론(ensemble methods)이라고도 한다. 이는 특정한 하나의 예측 방법이 아니라 복수의 예측 모형을 결합하여 더 나은 성능의 예측을 하려는 시도이다. 모형 결합 방법을 사용하면 일반적으로 계산량은 증가하지만 다음과 같은 효과가 있다. 단일 모형을 사용할 때 보...
Python Code: X = np.array([[-1.0, -1.0], [-1.2, -1.4], [1, -0.5], [-3.4, -2.2], [1.1, 1.2], [-2.1, -0.2]]) y = np.array([1, 1, 1, 2, 2, 2]) x_new = [0, 0] plt.scatter(X[y==1,0], X[y==1,1], s=100, c='r') plt.scatter(X[y==2,0], X[y==2,1], s=100, c='b') plt.scatter(x_new[0], x_new[1], s=100, c='g') from sklearn.linear_mod...
10,860
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: MNIST on TPU (Tensor Processing Unit)<br>or GPU using tf.Keras and tf.data.Dataset <table><tr><td><img valign="middle" src="https Step2: (you can double-ckick on collapsed cells to v...
Python Code: import os, re, time, json import PIL.Image, PIL.ImageFont, PIL.ImageDraw import numpy as np import tensorflow as tf from matplotlib import pyplot as plt print("Tensorflow version " + tf.__version__) #@title visualization utilities [RUN ME] This cell contains helper functions used for visualization and down...
10,861
Given the following text description, write Python code to implement the functionality described below step by step Description: Sequence alignment Genetic material such as DNA and proteins comes in sequences made up of different blocks. The study of these sequences and their correlation is invaluable to the field of ...
Python Code: a1 = AminoAcid("A") print(a1) a2 = AminoAcid(a1) print(a1 == a2) a3 = AminoAcid("K") print(a3.getName("long")) Explanation: Sequence alignment Genetic material such as DNA and proteins comes in sequences made up of different blocks. The study of these sequences and their correlation is invaluable to the fi...
10,862
Given the following text description, write Python code to implement the functionality described below step by step Description: Experiment Step1: Load and check data Step2: ## Analysis Experiment Details Step3: Results
Python Code: %load_ext autoreload %autoreload 2 from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import glob import tabulate import pprint import click import numpy as np import pandas as pd from ray.tune.commands import * from nupic.research.framewo...
10,863
Given the following text description, write Python code to implement the functionality described below step by step Description: ABC calibration of $I_\text{Na}$ in Nygren model using original dataset. Step1: Initial set-up Load experiments used by Nygren $I_\text{Na}$ model in the publication Step2: Load the myokit...
Python Code: import os, tempfile import logging import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns import numpy as np from ionchannelABC import theoretical_population_size from ionchannelABC import IonChannelDistance, EfficientMultivariateNormalTransition, IonChannelAcceptor from ionchannelA...
10,864
Given the following text description, write Python code to implement the functionality described below step by step Description: IPython Notebook for turning in solutions to the problems in the Essentials of Paleomagnetism Textbook by L. Tauxe Problems in Chapter 1 Problem 1 Step1: Problem 2a Step2: Problem 2b Step3...
Python Code: # code to calculate H_r and H_theta import numpy as np deg2rad=np.pi/180. # converts degrees to radians # write code here to calculate H_r and H_theta and convert to B_r, B_theta # This is how you print out nice formatted numbers # floating point variables have the syntax: # '%X.Yf'%(FP_variable) where...
10,865
Given the following text description, write Python code to implement the functionality described below step by step Description: 你的第一个神经网络 在此项目中,你将构建你的第一个神经网络,并用该网络预测每日自行车租客人数。我们提供了一些代码,但是需要你来实现神经网络(大部分内容)。提交此项目后,欢迎进一步探索该数据和模型。 Step1: 加载和准备数据 构建神经网络的关键一步是正确地准备数据。不同尺度级别的变量使网络难以高效地掌握正确的权重。我们在下方已经提供了加载和准备数据的代码。你很快将进一步学习...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: 你的第一个神经网络 在此项目中,你将构建你的第一个神经网络,并用该网络预测每日自行车租客人数。我们提供了一些代码,但是需要你来实现神经网络(大部分内容)。提交此项目后,欢迎进一步探索该数据和模型。 End of explanation data_path = 'Bike-Sharing-Dataset/hour....
10,866
Given the following text description, write Python code to implement the functionality described below step by step Description: Catedra 01 Primera tarea sera anunciada hoy. Entrega el segundo miercoles, despues de haber tenido 2 auxiliares. La primera parte del curso Derivadas e Integrales numericas. Manejo de errore...
Python Code: import matplotlib.pyplot as plt import matplotlib as mp import numpy as np import math # Esta linea hace que los graficos aparezcan en el notebook en vez de una ventana nueva. %matplotlib inline Explanation: Catedra 01 Primera tarea sera anunciada hoy. Entrega el segundo miercoles, despues de haber tenido ...
10,867
Given the following text description, write Python code to implement the functionality described below step by step Description: 정규화 선형 회귀 정규화(regularized) 선형 회귀 방법은 선형 회귀 계수(weight)에 대한 제약 조건을 추가함으로써 모형이 과도하게 최적화되는 현상, 즉 과최적화를 막는 방법이다. Regularized Method, Penalized Method, Contrained Least Squares 이라고도 불리운다. 모형이 과도하게...
Python Code: np.random.seed(0) n_samples = 30 X = np.sort(np.random.rand(n_samples)) y = np.cos(1.5 * np.pi * X) + np.random.randn(n_samples) * 0.1 dfX = pd.DataFrame(X, columns=["x"]) dfX = sm.add_constant(dfX) dfy = pd.DataFrame(y, columns=["y"]) df = pd.concat([dfX, dfy], axis=1) model = sm.OLS.from_formula("y ~ x +...
10,868
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: TensorFlowアドオンオプティマイザ:ConditionalGradient <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: モデルの構築...
Python Code: #@title Licensed under the Apache License, Version 2.0 # 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 # distributed under the...
10,869
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">Balance Scale Classification - UCI</h1> Analysis of the <a href="http Step1: Check for Class Imbalance Step2: Feature Importances Now we check for feature importances. H...
Python Code: import pandas as pd import numpy as np %pylab inline pylab.style.use('ggplot') url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/balance-scale/balance-scale.data' balance_df = pd.read_csv(url, header=None) balance_df.columns = ['class_name', 'left_weight', 'left_distance', 'right_weight', 'r...
10,870
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Tutorial Step1: Hello World! Step2: # starts a comment line. f(x,y) is a function call. f is the function name, x and y are the arguments. Values, Types, Variables Step3: RHS of =...
Python Code: from __future__ import print_function Explanation: Python Tutorial End of explanation # Output "Hello World!" print("Hello, World!") print("Hello World!", 10.0) Explanation: Hello World! End of explanation # define a variable s = "Hello World!" x = 10.0 i = 42 # define 2 variables at once a,b = 1,1 # outpu...
10,871
Given the following text description, write Python code to implement the functionality described below step by step Description: Index file visualization This notebook shows an easy way to represent the In Situ data positions using the index files.<br> For this visualization of a sample <i>index_latest.txt</i> dataset...
Python Code: indexfile = "datafiles/index_latest.txt" Explanation: Index file visualization This notebook shows an easy way to represent the In Situ data positions using the index files.<br> For this visualization of a sample <i>index_latest.txt</i> dataset of the Copernicus Marine Environment Monitoring Service. End o...
10,872
Given the following text description, write Python code to implement the functionality described below step by step Description: Load data Step1: Semantic transformations http Step2: TI-IDF + LSI Step3: Save corpora Step4: Transform "unseen" documents What is the best way to get LDA scores on a corpus used for tra...
Python Code: # Load pre-saved BoW # Save BoW user_dir = os.path.expanduser('~/cltk_data/user_data/') try: os.makedirs(user_dir) except FileExistsError: pass bow_path = os.path.join(user_dir, 'bow_lda_gensim.mm') mm_corpus = gensim.corpora.MmCorpus(bow_path) print(mm_corpus) print(next(iter(mm_corpus))) Explanat...
10,873
Given the following text description, write Python code to implement the functionality described below step by step Description: 1.1 The Weiner Process A Weiner process, $W(t)\,$, is a continuos-time stocastic process. By definition, the value of the process at time $t$ is Step1: Or expressing $D$ in $\textrm{nm}^2 /...
Python Code: import numpy as np d = 5e-9 # particle radius in meters eta = 1.0e-3 # viscosity of water in SI units (Pascal-seconds) at 293 K kB = 1.38e-23 # Boltzmann constant T = 293 # Temperature in degrees Kelvin D = kB*T/(3*np.pi*eta*d) # [m^2 / s] D Explanation: 1.1 The Weiner Process A Weiner ...
10,874
Given the following text description, write Python code to implement the functionality described below step by step Description: The role of dipole orientations in distributed source localization When performing source localization in a distributed manner (MNE/dSPM/sLORETA/eLORETA), the source space is defined as a gr...
Python Code: import mne import numpy as np from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse data_path = sample.data_path() evokeds = mne.read_evokeds(data_path + '/MEG/sample/sample_audvis-ave.fif') left_auditory = evokeds[0].apply_baseline() fwd = mne.read_forward_solut...
10,875
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Load Iris Flower Data Step2: Standardize Features Step3: Train Support Vector Classifier Step4: Create Previously Unseen Observation Step5: View Predicted Probabilities
Python Code: # Load libraries from sklearn.svm import SVC from sklearn import datasets from sklearn.preprocessing import StandardScaler import numpy as np Explanation: Title: Calibrate Predicted Probabilities In SVC Slug: calibrate_predicted_probabilities_in_svc Summary: How to calibrate predicted probabilities in s...
10,876
Given the following text description, write Python code to implement the functionality described below step by step Description: Yellowbrick Text Examples This notebook is a sample of the text visualizations that yellowbrick provides Step2: Load Text Corpus for Example Code Yellowbrick has provided a text corpus wran...
Python Code: import os import sys # Modify the path sys.path.append("..") import yellowbrick as yb import matplotlib.pyplot as plt Explanation: Yellowbrick Text Examples This notebook is a sample of the text visualizations that yellowbrick provides End of explanation from download import download_all from sklearn....
10,877
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc" style="margin-top Step1: Importing data Step2: Data preparing and cleaning
Python Code: from skdata.data import ( SkDataFrame as DataFrame, SkDataSeries as Series ) import pandas as pd Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc" style="margin-top: 1em;"><ul class="toc-item"><li><span><a href="#SkData---Data-Specification" data-toc-modified-id=...
10,878
Given the following text description, write Python code to implement the functionality described below step by step Description: In data science, it's common to have lots of nearly duplicate data. For instance, you'll find lots of nearly duplicate web pages in crawling the internet; you'll find lots of pictures of the...
Python Code: import itertools import string import functools letters = string.ascii_lowercase vocab = list(map(''.join, itertools.product(letters, repeat=2))) from random import choices def zipf_pdf(k): return 1/k**1.07 def exponential_pdf(k, base): return base**k def new_document(n_words, pdf): return set(...
10,879
Given the following text description, write Python code to implement the functionality described below step by step Description: Resolving Conflicts Using Precedence Declarations This file shows how shift/reduce and reduce/reduce conflicts can be resolved using operator precedence declarations. The following grammar i...
Python Code: import ply.lex as lex tokens = [ 'NUMBER' ] def t_NUMBER(t): r'0|[1-9][0-9]*' t.value = int(t.value) return t literals = ['+', '-', '*', '/', '^', '(', ')'] t_ignore = ' \t' def t_newline(t): r'\n+' t.lexer.lineno += t.value.count('\n') def t_error(t): print(f"Illegal character '{t...
10,880
Given the following text description, write Python code to implement the functionality described below step by step Description: Interlab from iGEM 2015 Step1: Configuring and reading your data You first need to map each column in your plate to a colony or a control. Step2: Then, we an instance of PlateMate Step3: ...
Python Code: %matplotlib inline import pylab as pl from math import sqrt import sys # importing platemate sys.path.insert(0, '../src') import platemate Explanation: Interlab from iGEM 2015 End of explanation ColumnNames = { 'C' : "Dev1", 'D' : "Dev2", 'E' : "Dev3" } controlNames = { 'A' : "LB", ...
10,881
Given the following text description, write Python code to implement the functionality described below step by step Description: Part 6 Step1: Each "letter" of a string again belongs to the string type. A string of length one is called a character. Step2: Since computers store data in binary, the designers of early...
Python Code: W = "Hello" print W for j in range(len(W)): # len(W) is the length of the string W. print W[j] # Access the jth character of the string. Explanation: Part 6: Ciphers and Key exchange In this notebook, we introduce cryptography -- how to communicate securely over insecure channels. We begin with a s...
10,882
Given the following text description, write Python code to implement the functionality described below step by step Description: Theory and Practice of Visualization Exercise 1 Imports Step1: Graphical excellence and integrity Find a data-focused visualization on one of the following websites that is a positive examp...
Python Code: from IPython.display import Image Explanation: Theory and Practice of Visualization Exercise 1 Imports End of explanation # Add your filename and uncomment the following line: Image(filename='graphie.JPG') Explanation: Graphical excellence and integrity Find a data-focused visualization on one of the follo...
10,883
Given the following text description, write Python code to implement the functionality described below step by step Description: Code Testing and CI The notebook contains problems about code testing and continuous integration with Travis CI. Original by E Tollerud 2017 for LSSTC DSFP Session3 and AstroHackWeek, modifi...
Python Code: !conda install pytest pytest-cov Explanation: Code Testing and CI The notebook contains problems about code testing and continuous integration with Travis CI. Original by E Tollerud 2017 for LSSTC DSFP Session3 and AstroHackWeek, modified by B Sipocz Problem 1: Set up py.test in you repo In this problem we...
10,884
Given the following text description, write Python code to implement the functionality described below step by step Description: Make me an Image Analyst already! In the last lesson you learnt the basics of Python. You learnt what variables are, how loops function and how to get a list of our filenames. In this lesson...
Python Code: import os import glob root_root = '/home/aneesh/Images/Source/' dir_of_root = os.listdir(root_root) file_paths = [glob.glob(os.path.join(root_root,dor, '*.tif')) for dor in dir_of_root] print(file_paths[0][0]) Explanation: Make me an Image Analyst already! In the last lesson you learnt the basics of Python...
10,885
Given the following text description, write Python code to implement the functionality described below step by step Description: $f_{2}(c,p) = \dfrac{1}{2}r_{c}c^{2}+\dfrac{1}{4}u_{c}c^{4}+\dfrac{1}{6}v_{c}c^{6}+\dfrac{1}{2}r_{p}p^{2}+\dfrac{1}{4}u_{p}p^{4}-\gamma cp-\dfrac{1}{2}ec^{2}p^{2}-Ep$ Step1: Rescaling
Python Code: f2 = ((1/2)*r_c*c**2+(1/4)*u_c*c**4+(1/6)*v_c*c**6+(1/2)*r_p*p**2+(1/4)*u_p*p**4-E*p-gamma*c*p-e*c**2*p**2/2) nsimplify(f2) Explanation: $f_{2}(c,p) = \dfrac{1}{2}r_{c}c^{2}+\dfrac{1}{4}u_{c}c^{4}+\dfrac{1}{6}v_{c}c^{6}+\dfrac{1}{2}r_{p}p^{2}+\dfrac{1}{4}u_{p}p^{4}-\gamma cp-\dfrac{1}{2}ec^{2}p^{2}-Ep$ End...
10,886
Given the following text description, write Python code to implement the functionality described below step by step Description: The NEST noise_generator Hans Ekkehard Plesser, 2015-06-25 This notebook describes how the NEST noise_generator model works and what effect it has on model neurons. NEST needs to be in your ...
Python Code: import sympy sympy.init_printing() x = sympy.Symbol('x') sympy.series((1-sympy.exp(-x))/(1+sympy.exp(-x)), x) Explanation: The NEST noise_generator Hans Ekkehard Plesser, 2015-06-25 This notebook describes how the NEST noise_generator model works and what effect it has on model neurons. NEST needs to be in...
10,887
Given the following text description, write Python code to implement the functionality described below step by step Description: Iterative vs fragment-based mapping Iterative mapping first proposed by <a name="ref-1"/>(Imakaev et al., 2012), allows to map usually a high number of reads. However other methodologies, le...
Python Code: from pytadbit.mapping.full_mapper import full_mapping Explanation: Iterative vs fragment-based mapping Iterative mapping first proposed by <a name="ref-1"/>(Imakaev et al., 2012), allows to map usually a high number of reads. However other methodologies, less "brute-force" can be used to take into account ...
10,888
Given the following text description, write Python code to implement the functionality described below step by step Description: Code printers The most basic form of code generation are the code printers. The convert SymPy expressions into the target language. The most common languages are C, C++, Fortran, and Python...
Python Code: from sympy import * init_printing() Explanation: Code printers The most basic form of code generation are the code printers. The convert SymPy expressions into the target language. The most common languages are C, C++, Fortran, and Python, but over a dozen languages are supported. Here, we will quickly go...
10,889
Given the following text description, write Python code to implement the functionality described below step by step Description: Federal Reserve Series Data Download federal reserve series. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file exce...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: Federal Reserve Series Data Download federal reserve series. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain...
10,890
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', 'bnu', 'sandbox-1', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: BNU Source ID: SANDBOX-1 Sub-Topics: Radiative Forcings. Properties: 85...
10,891
Given the following text description, write Python code to implement the functionality described below step by step Description: Traveling Salesman Problem In this assignment you will implement one or more algorithms for the traveling salesman problem, such as the dynamic programming algorithm covered in the video lec...
Python Code: import numpy as np file = "tsp.txt" # file = "test2.txt" data = open(file, 'r').readlines() n = int(data[0]) graph = {} for i,v in enumerate(data[1:]): graph[i] = tuple(map(float, v.strip().split(" "))) dist_val = np.zeros([n,n]) for i in range(n): for k in range(n): dist_val[i,k] = di...
10,892
Given the following text description, write Python code to implement the functionality described below step by step Description: cxMate Service DEMO By Ayato Shimada, Mitsuhiro Eto This DEMO shows 1. detect communities using an igraph's community detection algorithm 2. paint communities (nodes and edges) in different ...
Python Code: # Tested on: !python --version Explanation: cxMate Service DEMO By Ayato Shimada, Mitsuhiro Eto This DEMO shows 1. detect communities using an igraph's community detection algorithm 2. paint communities (nodes and edges) in different colors 3. perform layout using graph-tool's sfdp algorithm End of explana...
10,893
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mohc', 'ukesm1-0-ll', 'atmoschem') Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: MOHC Source ID: UKESM1-0-LL Topic: Atmoschem Sub-Topics: Transport,...
10,894
Given the following text description, write Python code to implement the functionality described below step by step Description: DAT210x - Programming with Python for DS Module3 - Lab3 Step1: Load up the wheat seeds dataset into a dataframe. We've stored a copy in the Datasets directory. Step2: Create a new 3D subpl...
Python Code: import pandas as pd import matplotlib.pyplot as plt import matplotlib # Look pretty... # matplotlib.style.use('ggplot') plt.style.use('ggplot') Explanation: DAT210x - Programming with Python for DS Module3 - Lab3 End of explanation # .. your code here .. Explanation: Load up the wheat seeds dataset into a ...
10,895
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Tensorboard in DeepChem DeepChem Neural Networks models are built on top of tensorflow. Tensorboard is a powerful visualization tool in tensorflow for viewing your model architecture ...
Python Code: from IPython.display import Image, display import deepchem as dc from deepchem.molnet import load_tox21 from deepchem.models.tensorgraph.models.graph_models import GraphConvModel # Load Tox21 dataset tox21_tasks, tox21_datasets, transformers = load_tox21(featurizer='GraphConv') train_dataset, valid_dataset...
10,896
Given the following text description, write Python code to implement the functionality described below step by step Description: Lambda Expressions Lambda expressions allow us to create "anonymous" functions i.e functions without a name. This basically means we can quickly make ad-hoc functions without needing to prop...
Python Code: # Normal function def square(num): result = num**2 return result square(2) # Simplified Version #1 def square(num): return num**2 square(3) # Simplified Version #1 def square(num):return num**2 square(4) Explanation: Lambda Expressions Lambda expressions allow us to create "anonymous" functions...
10,897
Given the following text description, write Python code to implement the functionality described below step by step Description: Problem Statement Step1: IMDB comments dataset has been stored in the following location Step2: There are 50000 lines in the file. Let's the first line Step3: Total size of the file is 66...
Python Code: spark.sparkContext.uiWebUrl Explanation: Problem Statement: IMDB Comment Sentiment Classifier Dataset: For this exercise we will use a dataset hosted at http://ai.stanford.edu/~amaas/data/sentiment/ Problem Statement: This is a dataset for binary sentiment classification containing substantially more data...
10,898
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Data Analysis, 3rd ed Chapter 10, demo 3 Normal approximaton for Bioassay model. Step1: Find the mode by minimising negative log posterior. Compute gradients and Hessian analytical...
Python Code: import numpy as np from scipy import optimize, stats %matplotlib inline import matplotlib.pyplot as plt import arviz as az import os, sys # add utilities directory to path util_path = os.path.abspath(os.path.join(os.path.pardir, 'utilities_and_data')) if util_path not in sys.path and os.path.exists(util_pa...
10,899
Given the following text description, write Python code to implement the functionality described below step by step Description: Короче функция, которая домнажать вектор на случайную матрица! $$X_{1\times n}R_{n\times k}=C_{1\times k}$$, где Step1: Вытаскивание даных из файла! Ссылки
Python Code: def mm(x, k): if x.shape[0] > 1: x=x.T r = np.random.rand(x.shape[1],k) print(r) #print(x.dot(r)) return(x.dot(r)) mm(np.array([[1,2, 1,132, 1,2]]), 5) Explanation: Короче функция, которая домнажать вектор на случайную матрица! $$X_{1\times n}R_{n\times k}=C_{1\times k}$$, ...