Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
9,400 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="images/csdms_logo.jpg">
Example 1
Read and explore the output from Example 1 -- a vector parameter study that evaluates an objective function over the Rosenbrock function.
Use pyla... | Python Code:
%pylab inline
Explanation: <img src="images/csdms_logo.jpg">
Example 1
Read and explore the output from Example 1 -- a vector parameter study that evaluates an objective function over the Rosenbrock function.
Use pylab magic:
End of explanation
dat_file = '../examples/1-rosenbrock/dakota.dat'
data = numpy.... |
9,401 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
pyschedule - resource-constrained scheduling in python
pyschedule is the easiest way to match tasks with resources. Do you need to plan a conference or schedule your employees and there are ... | Python Code:
pip install pyschedule
Explanation: pyschedule - resource-constrained scheduling in python
pyschedule is the easiest way to match tasks with resources. Do you need to plan a conference or schedule your employees and there are a lot of requirements to satisfy, like availability of rooms or maximal allowed w... |
9,402 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
APIs and Scraping
Overview of today's topic
Step1: An API is an application programming interface. It provides a structured way to send commands or requests to a piece of software. "API" of... | Python Code:
import geopandas as gpd
import folium
import osmnx as ox
import pandas as pd
import re
import requests
import time
from bs4 import BeautifulSoup
from geopy.geocoders import GoogleV3
from keys import google_api_key
# define a pause duration between API requests
pause = 0.1
Explanation: APIs and Scraping
Ove... |
9,403 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using custom containers with AI Platform Training
Learning Objectives
Step1: Run the command in the cell below to install gcsfs package.
Step2: Prepare lab dataset
Set environment variable... | Python Code:
import json
import os
import numpy as np
import pandas as pd
import pickle
import uuid
import time
import tempfile
from googleapiclient import discovery
from googleapiclient import errors
from google.cloud import bigquery
from jinja2 import Template
from kfp.components import func_to_container_op
from typi... |
9,404 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mass Spec Data Analysis
Step1: Relative intensity
Every MS run has a characteristic intensity scale depending on the quantity of sample, concentration of cells / protein and probably other ... | Python Code:
# First, we must perform the incantations.
%pylab inline
import pandas as pd
# Parse data file.
proteins = pd.read_table('data/pubs2015/proteinGroups.txt', low_memory=False)
# Find mass spec intensity columns.
intensity_cols = [c for c in proteins.columns if 'intensity '
in c.lower() and 'lfq' ... |
9,405 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bayesian Statistics Made Simple
Code and exercises from my workshop on Bayesian statistics in Python.
Copyright 2016 Allen Downey
MIT License
Step1: Working with Pmfs
Create a Pmf object to... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
from thinkbayes2 import Pmf, Suite
import thinkplot
Explanation: Bayesian Statistics Made Simple
Code and exercises from my workshop on Bayesian statistics in Python.
Copyright 2016 Allen Do... |
9,406 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification
Consider a binary classification problem. The data and target files are available online. The domain of the problem is chemoinformatics. Data is about toxicity of 4K small mol... | Python Code:
from eden.util import load_target
y = load_target( 'http://www.bioinf.uni-freiburg.de/~costa/bursi.target' )
Explanation: Classification
Consider a binary classification problem. The data and target files are available online. The domain of the problem is chemoinformatics. Data is about toxicity of 4K smal... |
9,407 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Permanent Income Model
Chase Coleman and Thomas Sargent
This notebook maps instances of the linear-quadratic-Gaussian permanent income model
with $\beta R = 1$ into a linear state space syst... | Python Code:
import quantecon as qe
import numpy as np
import scipy.linalg as la
import matplotlib.pyplot as plt
%matplotlib inline
np.set_printoptions(suppress=True, precision=4)
Explanation: Permanent Income Model
Chase Coleman and Thomas Sargent
This notebook maps instances of the linear-quadratic-Gaussian permanent... |
9,408 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Let´s reproject to Alberts or something with distance
Step1: Uncomment to reproject
proj string taken from
Step2: Model Fitting Using a GLM
The general model will have the form
Step3: Fit... | Python Code:
new_data.crs = {'init':'epsg:4326'}
Explanation: Let´s reproject to Alberts or something with distance
End of explanation
#new_data = new_data.to_crs("+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=37.5 +lon_0=-96 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs ")
Explanation: Uncomment to reproject
p... |
9,409 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Train Station Data Cleaner
Data source
https
Step1: Step 1
Step2: Comparison with bus and tram reports.
Station entries v Boardings and alightings
The train station entry data does not pro... | Python Code:
rawtrain = './raw/Train Station Entries 2008-09 to 2011-12 - data.XLS'
Explanation: Train Station Data Cleaner
Data source
https://www.data.vic.gov.au/data/dataset/train-station-entries-2008-09-to-2011-12-new
Data Temporal Coverage: 01/07/2008 to 30/06/2012
Comparable data with buses and trams [Weekeday by... |
9,410 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
9,411 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p>1. Load the `"virgo_novisc.0054.gdf"` dataset from the `"data"` directory.</p>
Step1: <p>2. Create a `SlicePlot` of temperature along the y-axis, with a width of 0.4 Mpc. Change the colo... | Python Code:
ds = yt.load("../data/virgo_novisc.0054.gdf")
Explanation: <p>1. Load the `"virgo_novisc.0054.gdf"` dataset from the `"data"` directory.</p>
End of explanation
slc = yt.SlicePlot(ds, "y", ["temperature"], width=(0.4, "Mpc"))
slc.set_cmap("temperature", "algae")
slc.annotate_magnetic_field()
Explanation: <p... |
9,412 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Writing on files
This is a Python notebook in which you will practice the concepts learned during the lectures.
Startup ROOT
Import the ROOT module
Step1: Writing histograms
Create a TFile ... | Python Code:
import ROOT
Explanation: Writing on files
This is a Python notebook in which you will practice the concepts learned during the lectures.
Startup ROOT
Import the ROOT module: this will activate the integration layer with the notebook automatically
End of explanation
rndm = ROOT.TRandom3(1)
filename = "histo... |
9,413 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Map the acoustic environment
This notebook creates a map of biophony and anthrophony, predicted from a multilevel regression model.
The model takes land cover areas (within a specified radiu... | Python Code:
# datawaves database
from landscape.models import LandCoverMergedMapArea
from database.models import Site
from geo.models import Boundary
from django.contrib.gis.geos import Point, Polygon
from django.contrib.gis.db.models.functions import Intersection, Envelope
from django.contrib.gis.db.models import Col... |
9,414 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2022 The TensorFlow Authors.
Step1: Text Searcher with TensorFlow Lite Model Maker
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step... | 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... |
9,415 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: CSE 6040, Fall 2015
Step2: Task 1(a). [5 points] From the Yelp! Academic Dataset, create an SQLite database called, yelp-rest.db, which contains the subset of the data pertaining to ... | Python Code:
# As you complete Part 1, place any additional imports you
# need in this code cell.
import json
import sqlite3 as db
import pandas
from IPython.display import display
import string
# A little helper function you can use to quickly inspect tables:
def peek_table (db, name):
Given a database connec... |
9,416 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Milestone Project 1
Step1: Step 1
Step2: Step 2
Step3: Step 3
Step4: Step 4
Step5: Step 5
Step6: Step 6
Step7: Step 7
Step8: Step 8
Step9: Step 9
Step10: Step 10 | Python Code:
# For using the same code in either Python 2 or 3
from __future__ import print_function
## Note: Python 2 users, use raw_input() to get player input. Python 3 users, use input()
Explanation: Milestone Project 1: Full Walkthrough Code Solution
Below is the filled in code that goes along with the complete w... |
9,417 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
extract features from each photo in the directory using a function extract_features
| Python Code::
def extract_features(filename):
# load the model
model = VGG16()
# re-structure the model
model = Model(inputs=model.inputs, outputs=model.layers[-2].output)
# load the photo
image = load_img(filename, target_size=(224, 224))
# convert the image pixels to a numpy array
image = img_to_array(image)
... |
9,418 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Leitura 14 - Arrays Multidimensionais (Matrize3)
By Hans. Original
Step1: Uma das maiores vantagens da vetorizaçao eh a possibilidade da aplicacao de inumeras operaçoes diretamente a cada u... | Python Code:
import sys
import numpy as np
print(sys.version) # Versao do python - Opcional
print(np.__version__) # VErsao do modulo numpy - Opcional
# Criando um vetor padrao com 25 valores
npa = np.arange(25)
npa
# Transformando o vetor npa em um vetor multidimensional usando o metodo reshape
npa.reshape(5,5)
# Podem... |
9,419 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Waymo Open Dataset Tutorial (using local Jupyter kernel)
Website
Step1: Load waymo_open_dataset package
Step2: Read one frame
Each file in the dataset is a sequence of frames ordered by fr... | Python Code:
# copybara removed file resource import
import os
if os.path.exists('tutorial_local.ipynb'):
# in case it is executed as a Jupyter notebook from the tutorial folder.
os.chdir('../')
fake_predictions_path = '{pyglib_resource}waymo_open_dataset/metrics/tools/fake_predictions.bin'.format(pyglib_resour... |
9,420 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Data Explanation Benchmarking
Step1: Load Data and Model
Step2: Class Label Mapping
Step3: Define Score Function
Step4: Define Image Masker
Step5: Create Explainer Object
Step6: ... | Python Code:
import json
import numpy as np
import shap
import shap.benchmark as benchmark
import tensorflow as tf
import scipy as sp
from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input
Explanation: Image Data Explanation Benchmarking: Image Multiclass Classification
This notebook demonstrates... |
9,421 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This code will load the model information, generate the model definition, and run the model estimation using FSL
Step1: Load the scan and model info, and generate the event files for FSL fr... | Python Code:
import nipype.algorithms.modelgen as model # model generation
import nipype.interfaces.fsl as fsl # fsl
from nipype.interfaces.base import Bunch
import os,json,glob
import numpy
import nibabel
import nilearn.plotting
from make_event_files_from_json import MakeEventFilesFromJSON
%matplotlib inlin... |
9,422 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulating with FBA
Simulations using flux balance analysis can be solved using Model.optimize(). This will maximize or minimize (maximizing is the default) flux through the objective reacti... | Python Code:
import pandas
pandas.options.display.max_rows = 100
import cobra.test
model = cobra.test.create_test_model("textbook")
Explanation: Simulating with FBA
Simulations using flux balance analysis can be solved using Model.optimize(). This will maximize or minimize (maximizing is the default) flux through the o... |
9,423 | Given the following text description, write Python code to implement the functionality described.
Description:
Count of K
To store the frequency array ; Function to check palindromic of of any substring using frequency array ; Initialise the odd count ; Traversing frequency array to compute the count of characters havi... | Python Code:
freq =[0 ] * 26
def checkPalindrome() :
oddCnt = 0
for x in freq :
if(x % 2 == 1 ) :
oddCnt += 1
return oddCnt <= 1
def countPalindromePermutation(s , k ) :
for i in range(k ) :
freq[ord(s[i ] ) - 97 ] += 1
ans = 0
if(checkPalindrome() ) :
ans += 1
i = 0
j = k
... |
9,424 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Document retrieval from wikipedia data
Fire up GraphLab Create
Step1: Load some text data - from wikipedia, pages on people
Step2: Data contains
Step3: Explore the dataset and checkout th... | Python Code:
import graphlab
Explanation: Document retrieval from wikipedia data
Fire up GraphLab Create
End of explanation
people = graphlab.SFrame('people_wiki.gl/')
Explanation: Load some text data - from wikipedia, pages on people
End of explanation
people.head()
len(people)
Explanation: Data contains: link to wik... |
9,425 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Join two sheets, groupby and sum on the joined data
Step1: Change the index to be the showname
Step2: Do the same for views
DANGER note that battle-star has a hyphen!
Step3: Join on shows... | Python Code:
import pandas as pd
# load both sheets as new dataframes
shows_df = pd.read_csv("show_category.csv")
views_df = pd.read_excel("views.xls")
Explanation: Join two sheets, groupby and sum on the joined data
End of explanation
shows_df.head()
shows_df = shows_df.set_index('showname')
shows_df.head()
Explanatio... |
9,426 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The pickle module implements an algorithm for turning an arbitrary Python object into a series of bytes. This process is also called serializing the object. The byte stream representing the ... | Python Code:
import pickle
import pprint
data = [{'a': 'A', 'b': 2, 'c': 3.0}]
print('DATA:', end=' ')
pprint.pprint(data)
data_string = pickle.dumps(data)
print('PICKLE: {!r}'.format(data_string))
import pickle
import pprint
data1 = [{'a': 'A', 'b': 2, 'c': 3.0}]
print('BEFORE: ', end=' ')
pprint.pprint(data1)
data1_s... |
9,427 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Installation
Just pip install
Step1: From a dictionary
Step2: From a list
Step3: From a yaml file
Step5: From a yaml string
Step6: From a dot-list
Step7: From command line arguments
To... | Python Code:
from omegaconf import OmegaConf
conf = OmegaConf.create()
print(conf)
Explanation: Installation
Just pip install:
pip install omegaconf
If you want to try this notebook after checking out the repository be sure to run
python setup.py develop at the repository root before running this code.
Creating OmegaC... |
9,428 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<span style="color
Step1: A genome file
You will need a genome file in fasta format (optionally it can be gzip compressed).
Step2: Initialize the tool
You can generate single or paired-end... | Python Code:
# conda install ipyrad -c bioconda
import ipyrad.analysis as ipa
Explanation: <span style="color:gray">ipyrad-analysis toolkit: </span> digest genomes
The purpose of this tool is to digest a genome file in silico using the same restriction enzymes that were used for an empirical data set to attempt to extr... |
9,429 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stock Trading Strategy Backtesting
Author
Step1: Download data
This project will use the historical daily closing quotes data for S&P 500 index from January 3,2000 to December 9,2016, which... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from plotly.offline import init_notebook_mode,iplot
import plotly.graph_objs as go
%matplotlib inline
init_notebook_mode(connected=True)
Explanation: Stock Trading Strategy Backtesting
Author: Long Shangshang (Cheryl)
Date: December 15... |
9,430 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have a Series that looks like: | Problem:
import pandas as pd
s = pd.Series([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0.98,0.93],
index=['146tf150p','havent','home','okie','thanx','er','anything','lei','nite','yup','thank','ok','where','beerage','anytime','too','done','645','tick','blank'])
import numpy as np
def g(s):
return s.iloc[np.lexsor... |
9,431 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Week 1 - Getting Started
Step1: Python Summary
Further information
More information is usually available with the help function. Using ? brings up the same information in ipython.
Using th... | Python Code:
import numpy as np
print("Numpy:", np.__version__)
Explanation: Week 1 - Getting Started
End of explanation
location = 'Bethesda'
zip_code = 20892
elevation = 71.9
print("We're in", location, "zip code", zip_code, ", ", elevation, "m above sea level")
print("We're in " + location + " zip code " + str(zip_c... |
9,432 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 9
Python Basic, Lesson 4, v1.0.1, 2016.12 by David.Yi
Python Basic, Lesson 4, v1.0.2, 2017.03 modified by Yimeng.Zhang
v1.1,2020.4 5, edit by David Yi
本次内容要点
日期函数库 datetime 用法介绍... | Python Code:
# 显示今天日期
# 可以比较一下三种结果的差异
from datetime import datetime, date
import time
print(datetime.now())
print(date.today())
print(time.time())
# 各种日期时间类型的数据类型
print(type(datetime.now()))
print(type(date.today()))
print(type(time.time()))
# 连续运行显示时间戳,看看时间戳差了多少毫秒
# 因为电脑运行速度太快,没有意外的话,可能看到的时间是一样的
for i in range(10):
... |
9,433 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sistema binario
Step1: Primero definimos los símbolos de las variables a usar
Step2: Momento de inercia
Step3: Ahora ingresamos la forma de la órbita Kepleriana, en términos de $a, e, \va... | Python Code:
from sympy import *
init_printing(use_unicode=True)
Explanation: Sistema binario: Energía y Momentum angular radiado
End of explanation
a = Symbol('a', positive=True)
e = Symbol('e', positive=True)
mu = Symbol('mu', positive=True)
L = Symbol('L',positive=True)
omega0 = Symbol('omega0',positive=True)
phi = ... |
9,434 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>The BurnMan Tutorial</h1>
Part 5
Step1: Each equality constraint can be a list of constraints, in which case equilibrate will loop over them. In the next code block we change the equali... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import burnman
from burnman import equilibrate
from burnman.minerals import SLB_2011
# Set the pressure, temperature and composition
pressure = 3.e9
temperature = 1500.
composition = {'Na': 0.02, 'Fe': 0.2, 'Mg': 2.0, 'Si': 1.9,
'Ca': 0.2, '... |
9,435 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id="Shallow_Water_Bathymetry_top"></a>
Shallow Water Bathymetry
Visualizing Differences in Depth With Spectral Analysis
<hr>
Notebook Summary
Import data from LANDSAT 8
A bathymetry index... | Python Code:
import sys
import os
sys.path.append(os.environ.get('NOTEBOOK_ROOT'))
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def bathymetry_index(df, m0 = 1, m1 = 0):
return m0*(np.log(df.blue)/np.log(df.green))+m1
Explanation: <a id="Shallow_Water_Bathymetry_top">... |
9,436 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Natural language processing (NLP) is a field of computer science, artificial intelligence and computational linguistics concerned with the interactions between computers and human (natural) ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
with open('data/reviews.txt','r') as file_handler:
reviews = np.array(list(map(lambda x:x[:-1], file_handler.readlines())))
with open('data/labels.txt','r') as file_handler:
labels = np.array(list(map(lambda x:x[:-1].upper(), fil... |
9,437 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
lab
Laboratory tests that have have been mapped to a standard set of measurements. Unmapped measurements are recorded in the customLab table. The lab table is fairly well populated by hospit... | Python Code:
# Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import psycopg2
import getpass
import pdvega
# for configuring connection
from configobj import ConfigObj
import os
%matplotlib inline
# Create a database connection using settings from config file
config='../db/conf... |
9,438 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Probability Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step3: 前処理行列を用いた確率的勾配ランジュバン動力学法を使用してディリクレ過程混合モデルを適合する
<table class="tfo-no... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# 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... |
9,439 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: gdsfactory in 5 minutes
Component -> Circuit -> Mask
gdsfactory easily enables you to go from a Component, to a higher level Component (circuit), or even higher level Component (Mask)... | Python Code:
from typing import Optional
import gdsfactory as gf
from gdsfactory.component import Component
from gdsfactory.components.bend_euler import bend_euler
from gdsfactory.components.coupler90 import coupler90 as coupler90function
from gdsfactory.components.coupler_straight import (
coupler_straight as coup... |
9,440 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spatiotemporal permutation F-test on full sensor data
Tests for differential evoked responses in at least
one condition using a permutation clustering test.
The FieldTrip neighbor templates ... | Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
# Jona Sassenhagen <jona.sassenhagen@gmail.com>
# Alex Rockhill <aprockhill@mailbox.org>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD-3-Clause
import numpy as np
import matplotlib.pyplot as plt
from mpl_to... |
9,441 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demo caching
This notebook shows how caching of daily results is organised. First we show the low-level approach, then a high-level function is used.
Low-level approach
Step1: We demonstrat... | Python Code:
import pandas as pd
from opengrid.library import misc
from opengrid.library import houseprint
from opengrid.library import caching
import charts
hp = houseprint.Houseprint()
Explanation: Demo caching
This notebook shows how caching of daily results is organised. First we show the low-level approach, then a... |
9,442 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Instalation
Source
Step1: Import
Step2: Create samples
Step3: Visualize | Python Code:
! pip install numpy
! pip install scipy -U
! pip install -U scikit-learn
Explanation: Instalation
Source: ...
Scikit-learn requires:
Python (>= 2.6 or >= 3.3),
NumPy (>= 1.6.1),
SciPy (>= 0.9).
If you already have a working installation of numpy and scipy, the easiest way to install scikit-lear... |
9,443 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training
training3.py 파일에 아래에 예제들에서 설명되는 함수들을 정의하라.
예제 1
인자로 x 라디안(호도, radian)을 입력받아 각도(degree)로 계산하여 되돌려주는 함수 degree(x)를 정의하라.
`degree(x) = (x * 360) / (2 * pi)`
여기서 pi는 원주율을 나타내며, 라디안(호오)... | Python Code:
import math # math 모듈을 임포트해야 pi 값을 사용할 수 있다.
def degree(x):
return (x *360.0) / (2 * math.pi)
degree(math.pi)
Explanation: Training
training3.py 파일에 아래에 예제들에서 설명되는 함수들을 정의하라.
예제 1
인자로 x 라디안(호도, radian)을 입력받아 각도(degree)로 계산하여 되돌려주는 함수 degree(x)를 정의하라.
`degree(x) = (x * 360) / (2 * pi)`
여기서 pi는 원주율을 나타내... |
9,444 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implementation on the nWAM data
Our implementation based on the work of the authors. We use the same module as coded in the JobTraining ipt. Please Note that the current implementation is in... | Python Code:
from ols import ols
from logit import logit
from att import att
%pylab inline
import warnings
warnings.filterwarnings('ignore') # Remove pandas warnings
import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.nonparametric.kde import KDEUnivariate
import seaborn as sns
from __... |
9,445 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Diagrama TS
Vamos elaborar um diagrama TS com o auxílio do pacote gsw [https
Step1: Se você não conseguiu importar a biblioteca acima, precisa instalar o módulo gsw.
Em seguida, importamos... | Python Code:
import gsw
Explanation: Diagrama TS
Vamos elaborar um diagrama TS com o auxílio do pacote gsw [https://pypi.python.org/pypi/gsw/3.0.3], que é uma alternativa em python para a toolbox gsw do MATLAB:
End of explanation
import numpy as np
import matplotlib.pyplot as plt
sal = np.linspace(0, 42, 100)
temp = np... |
9,446 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Authenticate with the docker registry first
bash
gcloud auth configure-docker
If using TPUs please also authorize Cloud TPU to access your project as described here.
Set up your output bucke... | Python Code:
BUCKET = "gs://" # your bucket here
assert re.search(r'gs://.+', BUCKET), 'A GCS bucket is required to store your results.'
Explanation: Authenticate with the docker registry first
bash
gcloud auth configure-docker
If using TPUs please also authorize Cloud TPU to access your project as described here.
Set... |
9,447 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Scalable Kernel Interpolation for Product Kernels (SKIP)
Overview
In this notebook, we'll overview of how to use SKIP, a method that exploits product structure in some kernels to reduce the ... | Python Code:
import math
import torch
import gpytorch
from matplotlib import pyplot as plt
# Make plots inline
%matplotlib inline
Explanation: Scalable Kernel Interpolation for Product Kernels (SKIP)
Overview
In this notebook, we'll overview of how to use SKIP, a method that exploits product structure in some kernels t... |
9,448 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Text generation with an RNN
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Download the Sh... | 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... |
9,449 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Imports
Step1: Model preparation
Variables
Any model exported using the export_inference_graph.py tool can be loaded here simply by changing PATH_TO_CKPT to point to a new .pb file.
By de... | Python Code:
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
%matplotlib inline
# This is needed since the notebook is st... |
9,450 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data mining the hansard
Estimating contribution by party
Step2: Data gathering and parsing
Get data
mine hansard from theyworkforyou scrape for June 2015 onwards using lxml
Step4: Parse th... | Python Code:
%matplotlib inline
import sys
#sys.path.append('/home/fin/Documents/datamining_hansard/dh/lib/python3.4/site-packages/')
import nltk
import nltk.tokenize
import itertools
import glob
import lxml
import lxml.html
import requests
import os
import csv
import wordcloud
import matplotlib.pyplot as plt
from scip... |
9,451 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejercicios Graphs, Paths & Components
Ejercicios básicos de Grafos.
Ejercicio - Número de Nodos y Enlaces
(resuelva en código propio y usando la librería NerworkX o iGraph)
Cuente en número ... | Python Code:
edges = set([(1, 2), (3, 1), (3, 2), (2, 4)])
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import scipy as sc
import itertools
import random
Explanation: Ejercicios Graphs, Paths & Components
Ejercicios básicos de Grafos.
Ejercicio - Número de Nodos y Enlaces
(resuelva en código... |
9,452 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reinforcement learning based training of modulation scheme without a channel model
This code is provided as supplementary material of the lecture Machine Learning and Optimization in Communi... | Python Code:
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from ipywidgets import interactive
import ipywidgets as widgets
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print("We are using the following device for learning:"... |
9,453 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Eficiencia terminal y mujeres en ingeniería
Objetivo
Explorar la relación entre el porcentaje de eficiencia terminal por estado y ciclo escolar, con respecto al porcentaje de mujeres inscrit... | Python Code:
%matplotlib inline
import matplotlib
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
plt.rcParams['figure.figsize']=(20,7)
import sys
reload(sys)
sys.setdefaultencoding('utf8')
Mujeres=pd.read_csv('/Datos/Mujeres_ingeniería_y_tec... |
9,454 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Arterial line study
This notebook reproduces the arterial line study in MIMIC-III. The following is an outline of the notebook
Step1: 1 - Generate materialized views
Before generating the a... | Python Code:
# Install OS dependencies. This only needs to be run once for each new notebook instance.
!pip install PyAthena
from pyathena import connect
from pyathena.util import as_pandas
from __future__ import print_function
# Import libraries
import datetime
import numpy as np
import pandas as pd
import matplotlib... |
9,455 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Collaborative filtering on the MovieLense Dataset
Learning Objectives
Know how to build a BigQuery ML Matrix Factorization Model
Know how to use the model to make recommendations for a user
... | Python Code:
import os
PROJECT = "your-project-here" # REPLACE WITH YOUR PROJECT ID
# Do not change these
os.environ["PROJECT"] = PROJECT
%%bash
rm -r bqml_data
mkdir bqml_data
cd bqml_data
curl -O 'http://files.grouplens.org/datasets/movielens/ml-20m.zip'
unzip ml-20m.zip
yes | bq rm -r $PROJECT:movielens
bq --locatio... |
9,456 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
usALEX-5samples - Template
This notebook is executed through 8-spots paper analysis.
For a direct execution, uncomment the cell below.
Step1: Load software and filenames definitions
Step2: ... | Python Code:
# ph_sel_name = "all-ph"
# data_id = "7d"
Explanation: usALEX-5samples - Template
This notebook is executed through 8-spots paper analysis.
For a direct execution, uncomment the cell below.
End of explanation
from fretbursts import *
init_notebook()
from IPython.display import display
Explanation: Load sof... |
9,457 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
So I chose a min_score from the other jupyter notebook, but when I look at the max scores of investment rounds, the highest scores are always 1-1.5% below the score cutoff threshold. My theo... | Python Code:
import modeling_utils.data_prep as data_prep
from sklearn.externals import joblib
import time
platform = 'lendingclub'
store = pd.HDFStore(
'/Users/justinhsi/justin_tinkering/data_science/lendingclub/{0}_store.h5'.
format(platform),
append=True)
Explanation: So I chose a min_score from the othe... |
9,458 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Part of Speech Tags
In this notebook, we learn more about POS tags.
Tagsets and Examples
Universal tagset
Step1: Or this summary table (also c.f. https
Step2: Various algorithms can be us... | Python Code:
import nltk
nltk.help.upenn_tagset()
nltk.help.upenn_tagset('WP$')
nltk.help.upenn_tagset('PDT')
nltk.help.upenn_tagset('DT')
nltk.help.upenn_tagset('POS')
nltk.help.upenn_tagset('RBR')
nltk.help.upenn_tagset('RBS')
nltk.help.upenn_tagset('MD')
Explanation: Part of Speech Tags
In this notebook, we learn mo... |
9,459 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Text segmentation example
Step1: Training examples
Training examples are defined through the Imageset class of TRIOSlib. The class defines a list of tuples with pairs of input and desired o... | Python Code:
# Required modules
from trios.feature_extractors import RAWFeatureExtractor
import trios
import numpy as np
from TFClassifier import TFClassifier
from CNN_TFClassifier import CNN_TFClassifier
import scipy as sp
import scipy.ndimage
import trios.shortcuts.persistence as p
import matplotlib
import matplotlib... |
9,460 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Post Training Quantization
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step1: Train and export the model
Step2: For the example, we only tra... | Python Code:
! pip uninstall -y tensorflow
! pip install -U tf-nightly
import tensorflow as tf
tf.enable_eager_execution()
! git clone --depth 1 https://github.com/tensorflow/models
import sys
import os
if sys.version_info.major >= 3:
import pathlib
else:
import pathlib2 as pathlib
# Add `models` to the python ... |
9,461 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Sklearn Ridge - Training a Ridge Regression Model
| Python Code::
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error, mean_absolute_error
# initialise & fit a ridge regression model with alpha set to 1
# if the model is overfitting, increase the alpha value
model = Ridge(alpha=1)
model.fit(X_train, y_train)
# create dictionary that con... |
9,462 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
^ gor
Step2: Vidimo, da sta $f(0)$ in $f(1)$ različnega predznaka, kar pomeni, da je na intervalu $(0,1)$ ničla.
Step3: Predstavimo bisekcijo še grafično. | Python Code:
f = lambda x: x-2**(-x)
a,b=(0,1) # začetni interval
(f(a),f(b))
Explanation: ^ gor: Uvod
Reševanje enačb z bisekcijo
Vsako enačbo $l(x)=d(x)$ lahko prevedemo na iskanje ničle funkcije
$$f(x)=l(x)-d(x)=0.$$
Ničlo zvezne funkcije lahko zanesljivo poiščemo z bisekcijo. Ideja je preprosta. Če so vrednosti f... |
9,463 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Generative Adversarial Networks (GANs)
So far in CS231N, all the applications of neural networks that we have explored have been discriminative models that take an input and are train... | Python Code:
from __future__ import print_function, division
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.r... |
9,464 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: This notebook provides an introduction to some of the basic concepts of machine learning.
Let's start by generating some data to work with. Let's say that we have a dataset that has ... | Python Code:
import numpy,pandas
%matplotlib inline
import matplotlib.pyplot as plt
import scipy.stats
from sklearn.model_selection import LeaveOneOut,KFold
from sklearn.preprocessing import PolynomialFeatures,scale
from sklearn.linear_model import LinearRegression,LassoCV,Ridge
import seaborn as sns
import statsmodels... |
9,465 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I’m trying to solve a simple ODE to visualise the temporal response, which works well for constant input conditions using the new solve_ivp integration API in SciPy. For example: | Problem:
import scipy.integrate
import numpy as np
N0 = 10
time_span = [-0.1, 0.1]
def dN1_dt (t, N1):
return -100 * N1 + np.sin(t)
sol = scipy.integrate.solve_ivp(fun=dN1_dt, t_span=time_span, y0=[N0,]) |
9,466 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demonstration
Step2: Generate noisy samples
Draw real and imaginary part of each sample from independent normal distributions
Step3: Noise samples in complex plane
Step4: Can you see the ... | Python Code:
# import necessary libraries
import numpy as np # basic vector / matrix tools, numerical math
from matplotlib import pyplot as plt # Plotting
import seaborn # prettier plots
import math # General math functions
from scipy import signal, stats... |
9,467 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Define a few building blocks for generating our input data
Step1: And a method for plotting and evaluating target algorithms
Note that it supports two algorithms. One ref (reference) and on... | Python Code:
def constant(v, count = 100):
return [v] * count
def jitter(v, amplitude):
return [y + random.randint(0, amplitude) - amplitude * 0.5 for y in v]
def increasing(from_, to_, count = 100):
return list(np.arange(from_, to_, (to_ - from_) / count))
def sin(base, amplitude, count = 100):
return ... |
9,468 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Spectral Fits to Calculate Fluxes
3ML provides a module to calculate the integral flux from a spectral fit and additionally uses the covariance matrix or posteror to calculate the erro... | Python Code:
%pylab inline
from threeML import *
Explanation: Using Spectral Fits to Calculate Fluxes
3ML provides a module to calculate the integral flux from a spectral fit and additionally uses the covariance matrix or posteror to calculate the error in the flux value for the integration range selected
End of explan... |
9,469 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SimpleITK Image Basics <a href="https
Step1: Image Construction
There are a variety of ways to create an image. All images' initial value is well defined as zero.
Step2: Pixel Types
The pi... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import SimpleITK as sitk
Explanation: SimpleITK Image Basics <a href="https://mybinder.org/v2/gh/InsightSoftwareConsortium/SimpleITK-Notebooks/master?filepath=Python%2F01_Image_Basics.ipynb"><img style="float: right;" src="https://mybinder.org/badge_logo.s... |
9,470 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyGraphistry Tutorial
Step1: Load Protein Interactions
Select columns of interest and drop empty rows.
Step2: Let's have a quick peak at the data
Bind the columns storing the source/destin... | Python Code:
import pandas
import graphistry
# To specify Graphistry account & server, use:
# graphistry.register(api=3, username='...', password='...', protocol='https', server='hub.graphistry.com')
# For more options, see https://github.com/graphistry/pygraphistry#configure
Explanation: PyGraphistry Tutorial: Visuali... |
9,471 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gradient
Use metpy.calc.gradient.
This example demonstrates the various ways that MetPy's gradient function
can be utilized.
Step1: Create some test data to use for our example
Step2: Calc... | Python Code:
import numpy as np
import metpy.calc as mpcalc
from metpy.units import units
Explanation: Gradient
Use metpy.calc.gradient.
This example demonstrates the various ways that MetPy's gradient function
can be utilized.
End of explanation
data = np.array([[23, 24, 23],
[25, 26, 25],
... |
9,472 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Basics
Step1: Indentation and Code Blocks
Step2: Statements/Multiline statements
A new line signals the end of a statement
Step3: For multi-line statements, use the \ character at the... | Python Code:
# this is a correct variable name
variable_name = 10
# this is not a correct variable name - variable names can't start with a number
4tops = 5
# these variables are not the same
distance = 10
Distance = 20
disTance = 30
print "distance = ", distance
print "Distance = ", Distance
print "disTance = ", disTa... |
9,473 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Business Dataset
Step1: Open/Closed
Step2: City and State
Step3: Review
Step4: https
Step5: User
Step6: https
Step7: Checkin
Step8: Tip | Python Code:
{
"business_id":"encrypted business id",
"name":"business name",
"neighborhood":"hood name",
"address":"full address",
"city":"city",
"state":"state -- if applicable --",
"postal code":"postal code",
"latitude":latitude,
"longitude":longitude,
"stars":star rating, **... |
9,474 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinary Differential Equations Exercise 3
Imports
Step1: Damped, driven nonlinear pendulum
Basic setup
Here are the basic parameters we are going to use for this exercise
Step3: Write a f... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy.integrate import odeint
from IPython.html.widgets import interact, fixed
Explanation: Ordinary Differential Equations Exercise 3
Imports
End of explanation
g = 9.81 # m/s^2
l = 0.5 # length of pendul... |
9,475 | 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... |
9,476 | 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... |
9,477 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cortical Signal Suppression (CSS) for removal of cortical signals
This script shows an example of how to use CSS
Step1: Load sample subject data
Step2: Find patches (labels) to activate
St... | Python Code:
# Author: John G Samuelsson <johnsam@mit.edu>
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import sample
from mne.simulation import simulate_sparse_stc, simulate_evoked
Explanation: Cortical Signal Suppression (CSS) for removal of cortical signals
This script shows an exa... |
9,478 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
データセットをトレーニングデータセットとテストデータセットに分割する
Wineデータセットを用い、前処理を行った後次元数を減らすための特徴選択の手法を見ていく。
wineデータセットのクラスは1,2,3の3種類。これは3種類の葡萄を表している。
Step1: 特徴量の尺度を揃える
一般的な手法は__正規化(normalization)__と__標準化(standardizat... | Python Code:
import pandas as pd
import numpy as np
df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None)
df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'P... |
9,479 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Text mining - Clustering
Machine Learning types
Step1: Scraping
Step2: TF-IDF vectorization
Step3: K-Means clustering
Step4: Important terms according to K-Means
Step5: Hierarchical (Ag... | Python Code:
import time
import requests
import numpy as np
import pandas as pd
from itertools import chain
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
from textblob import TextBlob
from gensim.models import word2vec
from scipy.cluster.hierarchy import ward, dendrogram
from sklearn.metrics.pairwise im... |
9,480 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Locality Sensitive Hashing
Locality Sensitive Hashing (LSH) provides for a fast, efficient approximate nearest neighbor search. The algorithm scales well with respect to the number of data p... | Python Code:
import numpy as np
import graphlab
from scipy.sparse import csr_matrix
from scipy.sparse.linalg import norm
from sklearn.metrics.pairwise import pairwise_distances
import time
from copy import copy
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Locality Sensitive Hashing
Locality Sensitive... |
9,481 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
写程序,可由键盘读入用户姓名例如Mr. right,让用户输入出生的月份与日期,判断用户星座,假设用户是金牛座,则输出,Mr. right,你是非常有性格的金牛座!
Step1: 写程序,可由键盘读入两个整数m与n(n不等于0),询问用户意图,如果要求和则计算从m到n的和输出,如果要乘积则计算从m到n的积并输出,如果要求余数则计算m除以n的余数的值并输出,否则则计算m整除n的... | Python Code:
name=input('请输入你的名字')
print(name)
date=float(input('请输入你的生日'))
if 1.19<date<2.19:
print('你是水瓶座')
elif 2.18<date<3.21:
print('你是双鱼座')
elif 3.20<date<4.20:
print('你是白羊座')
elif 4.19<date<5.21:
print('你是金牛座')
elif 5.20<date<6.22:
print('你是双子座')
elif 6.21<date<7.23:
print('你是巨蟹座')
elif 7... |
9,482 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this notebook, the article's simulations of the default procedure is rerun and compared to the procedure using Scipy's optimization scipy.optimize.least_square function.
Relevant modules ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import time
import sys
import os
%matplotlib inline
# Change directory to the code folder
os.chdir('..//code')
# Functions to sample the diffusion-weighted gradient directions
from dipy.core.sphere import disperse_charges, HemiSphere
# F... |
9,483 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Two-layer neural network
In this notebook a two-layer neural network is implemented from scratch following the methodology of the course http
Step1: The initial variance is scaled by a fact... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# Data generation obtained ... |
9,484 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Note that you have to execute the command jupyter notebook in the parent directory of
this directory for otherwise jupyter won't be able to access the file style.css.
Step1: This example h... | Python Code:
from IPython.core.display import HTML
with open ("../style.css", "r") as file:
css = file.read()
HTML(css)
Explanation: Note that you have to execute the command jupyter notebook in the parent directory of
this directory for otherwise jupyter won't be able to access the file style.css.
End of explanat... |
9,485 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implementing a Neural Network from Scratch - An Introduction
In this post we will implement a simple 3-layer neural network from scratch. We won't derive all the math that's required, but I ... | Python Code:
# Package imports
import matplotlib.pyplot as plt
import numpy as np
import sklearn
import sklearn.datasets
import sklearn.linear_model
import matplotlib
# Display plots inline and change default figure size
%matplotlib inline
matplotlib.rcParams['figure.figsize'] = (10.0, 8.0)
Explanation: Implementing a ... |
9,486 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Utilities
The global variable gCache is used as a cache for the function evaluate defined later. Instead of just storing the values for a given State, the cache stores pairs of the form
* ... | Python Code:
gCache = {}
Explanation: Utilities
The global variable gCache is used as a cache for the function evaluate defined later. Instead of just storing the values for a given State, the cache stores pairs of the form
* ('=', v),
* ('≤', v), or
* ('≥', v).
The first component of these pairs is a flag that spec... |
9,487 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Model.fit の処理をカスタマイズする
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https
Step2: 最初の簡単な例
簡単な例から始めてみまし... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
9,488 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning Engineer Nanodegree
Capstone Project
Santiago Giraldo
July 29, 2017
Perhaps one of the trendiest topics in the world right now is machine learning and big data, which have b... | Python Code:
import numpy as np
import pandas as pd
import datetime
import scipy as sp
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
import psycopg2
import time
import itertools
from pandas.io.sql import read_sql
from sklearn.model_selection import train_test_split
from sklearn.model_selectio... |
9,489 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Esercizio 2
Considerare il file movies.csv ottenuto estraendo i primi 1000 record del dataset scaricabile all'indirizzo https
Step1: Importazione dei moduli pandas e ast e numpy.
Step2: 1)... | Python Code:
input_file_name = './movies.csv'
n_most_popular = 15 # Parametro N
Explanation: Esercizio 2
Considerare il file movies.csv ottenuto estraendo i primi 1000 record del dataset scaricabile all'indirizzo https://www.kaggle.com/rounakbanik/the-movies-dataset#movies_metadata.csv.
Tale dataset è in formato csv e... |
9,490 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
5. Funkcije
Do sada smo koristili funkcije, no samo one unaprijed definirane u Pythonu poput funkcije float(), len() i slično. U ovom ćemo poglavlju naučiti pisati vlastite funkcije i to iz ... | Python Code:
def uvecaj(broj):
return broj+1
Explanation: 5. Funkcije
Do sada smo koristili funkcije, no samo one unaprijed definirane u Pythonu poput funkcije float(), len() i slično. U ovom ćemo poglavlju naučiti pisati vlastite funkcije i to iz dva važna razloga:
1. organizacija koda koji rješava neki problem fu... |
9,491 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
In this exercise, you'll add dropout to the Spotify model from Exercise 4 and see how batch normalization can let you successfully train models on difficult datasets.
Run the ne... | Python Code:
# Setup plotting
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
# Set Matplotlib defaults
plt.rc('figure', autolayout=True)
plt.rc('axes', labelweight='bold', labelsize='large',
titleweight='bold', titlesize=18, titlepad=10)
plt.rc('animation', html='html5')
# Setup feedback syst... |
9,492 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Classifying The Habeerman Dataset
When complete, I will review your code, so please submit your code via pull-request to the Introduction to Machine Learning with Scikit-Learn reposit... | Python Code:
%matplotlib inline
import os
import json
import time
import pickle
import requests
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
URL = "http://archive.ics.uci.edu/ml/machine-learning-databases/haberman/haberman.data"
def fetch_data(fname='habeerman.data'):
Helper method to... |
9,493 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
HydroTrend
Link to this notebook
Step1: And load the HydroTrend plugin.
Step2: HydroTrend will now be activated in PyMT.
Exercise 1
Step3: Q1a
Step4: Q1b
Step5: Q1c | Python Code:
import matplotlib.pyplot as plt
import numpy as np
Explanation: HydroTrend
Link to this notebook: https://github.com/csdms/pymt/blob/master/docs/demos/hydrotrend.ipynb
Package installation command: $ conda install notebook pymt_hydrotrend
Command to download a local copy:
$ curl -O https://raw.githubuserco... |
9,494 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id="topcell"></a>
Tellurium Notebook Tutorial
The Tellurium notebook environment is a self-contained Jupyter-like environment based on the nteract project. Tellurium adds special cells fo... | Python Code:
model simple()
S1 -> S2; k1*S1
k1 = 0.1
S1 = 10
end
simple.simulate(0, 50, 100)
simple.plot()
Explanation: <a id="topcell"></a>
Tellurium Notebook Tutorial
The Tellurium notebook environment is a self-contained Jupyter-like environment based on the nteract project. Tellurium adds special cells for wo... |
9,495 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome to NumbaSOM
A fast Self-Organizing Map Python library implemented in Numba.
This is a fast and simple to use SOM library. It utilizes online training (one data point at the time) rat... | Python Code:
from numbasom import *
Explanation: Welcome to NumbaSOM
A fast Self-Organizing Map Python library implemented in Numba.
This is a fast and simple to use SOM library. It utilizes online training (one data point at the time) rather than batch training. The implemented topologies are a simple 2D lattice or a ... |
9,496 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2A.eco - Les expressions régulières
Step2: Lorsqu'on remplit un formulaire, on voit souvent le format "MM/JJ/AAAA" qui précise sous quelle forme on s'attend à ce qu’une date soit écrite. L... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: 2A.eco - Les expressions régulières : à quoi ça sert ? (correction)
Chercher un mot dans un texte est une tâche facile, c'est l'objectif de la méthode find attachée aux chaînes de caractères, elle suffit encore lorsqu'on cherche u... |
9,497 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistic Regression
Predicting a Category or Class
ACKNOWLEDGEMENT
Some of the code in this notebook is based on John D. Wittenauer's notebooks that cover the exercises in Andrew Ng's course... | Python Code:
# Import our usual libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import os
# OS-independent way to navigate the file system
# Data directory is one directory up in relation to directory of this notebook
data_dir_root = os.path.normpath(os.getcwd() + os.... |
9,498 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SQL practice session
To start off, re-write the code to extract the 5GB file to a database. You can look at my code if you get stuck, but dont copy paste. Look at the code, but type it in y... | Python Code:
# import sqlite3 here
#open connection to database
# 1st challenge: Write a sql query to search for the name: zoidberg
# Note: It will return 0
Explanation: SQL practice session
To start off, re-write the code to extract the 5GB file to a database. You can look at my code if you get stuck, but dont copy pa... |
9,499 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Double Multiple Stripe Analysis (2MSA) for Single Degree of Freedom (SDOF) Oscillators
<img src="../../../../figures/intact-damaged.jpg" width="500" align="middle">
Step1: Load capacity cur... | Python Code:
import numpy
from rmtk.vulnerability.common import utils
from rmtk.vulnerability.derivation_fragility.NLTHA_on_SDOF import MSA_utils
from rmtk.vulnerability.derivation_fragility.NLTHA_on_SDOF.read_pinching_parameters import read_parameters
from rmtk.vulnerability.derivation_fragility.NLTHA_on_SDOF import d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.