markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Connect to Db2The db2_doConnect routine is called when a connection needs to be established to a Db2 database. The command does not require any parameters since it relies on the settings variable which contains all of the information it needs to connect to a Db2 database.```db2_doConnect()```There are 4 additional var... | def db2_doConnect():
global _hdbc, _hdbi, _connected, _runtime
global _settings
if _connected == False:
if len(_settings["database"]) == 0:
return False
dsn = (
"DRIVER={{IBM DB2 ODBC DRIVER}};"
"DATABASE={0};"
"HOSTNAME={1};"
... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Load/Save SettingsThere are two routines that load and save settings between Jupyter notebooks. These routines are called without any parameters.```load_settings() save_settings()```There is a global structure called settings which contains the following fields:```_settings = { "maxrows" : 10, "maxgrid" :... | def load_settings():
# This routine will load the settings from the previous session if they exist
global _settings
fname = "db2connect.pickle"
try:
with open(fname,'rb') as f:
_settings = pickle.load(f)
# Reset runtime to 1 since it would be un... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Error and Message FunctionsThere are three types of messages that are thrown by the %db2 magic command. The first routine will print out a success message with no special formatting:```success(message)```The second message is used for displaying an error message that is not associated with a SQL error. This type of er... | def db2_error(quiet,connect=False):
global sqlerror, sqlcode, sqlstate, _environment
try:
if (connect == False):
errmsg = ibm_db.stmt_errormsg().replace('\r',' ')
errmsg = errmsg[errmsg.rfind("]")+1:].strip()
else:
errmsg = ibm_db.conn_errormsg(... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Macro ProcessorA macro is used to generate SQL to be executed by overriding or creating a new keyword. For instance, the base `%sql` command does not understand the `LIST TABLES` command which is usually used in conjunction with the `CLP` processor. Rather than specifically code this in the base `db2.ipynb` file, we c... | def setMacro(inSQL,parms):
global _macros
names = parms.split()
if (len(names) < 2):
errormsg("No command name supplied.")
return None
macroName = names[1].upper()
_macros[macroName] = inSQL
return | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Check MacroThis code will check to see if there is a macro command in the SQL. It will take the SQL that is supplied and strip out three values: the first and second keywords, and the remainder of the parameters.For instance, consider the following statement:```CREATE DATABASE GEORGE options....```The name of the macr... | def checkMacro(in_sql):
global _macros
if (len(in_sql) == 0): return(in_sql) # Nothing to do
tokens = parseArgs(in_sql,None) # Take the string and reduce into tokens
macro_name = tokens[0].upper() # Uppercase the name of the token
if ... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Split AssignmentThis routine will return the name of a variable and it's value when the format is x=y. If y is enclosed in quotes, the quotes are removed. | def splitassign(arg):
var_name = "null"
var_value = "null"
arg = arg.strip()
eq = arg.find("=")
if (eq != -1):
var_name = arg[:eq].strip()
temp_value = arg[eq+1:].strip()
if (temp_value != ""):
ch = temp_value[0]
if (ch in ["'",'"']):
... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Parse Args The commands that are used in the macros need to be parsed into their separate tokens. The tokens are separated by blanks and strings that enclosed in quotes are kept together. | def parseArgs(argin,_vars):
quoteChar = ""
inQuote = False
inArg = True
args = []
arg = ''
for ch in argin.lstrip():
if (inQuote == True):
if (ch == quoteChar):
inQuote = False
arg = arg + ch #z
else:
arg = ... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Run MacroThis code will execute the body of the macro and return the results for that macro call. | def runMacro(script,in_sql,tokens):
result = ""
runIT = True
code = script.split("\n")
level = 0
runlevel = [True,False,False,False,False,False,False,False,False,False]
ifcount = 0
_vars = {}
for i in range(0,len(tokens)):
vstr = str(i)
_vars[vstr] = tokens[i]
... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Substitute VarsThis routine is used by the runMacro program to track variables that are used within Macros. These are kept separate from the rest of the code. | def subvars(script,_vars):
if (_vars == None): return script
remainder = script
result = ""
done = False
while done == False:
bv = remainder.find("{")
if (bv == -1):
done = True
continue
ev = remainder.find("}")
if (ev == -1):
... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
SQL TimerThe calling format of this routine is:```count = sqlTimer(hdbc, runtime, inSQL)```This code runs the SQL string multiple times for one second (by default). The accuracy of the clock is not that great when you are running just one statement, so instead this routine will run the code multiple times for a second... | def sqlTimer(hdbc, runtime, inSQL):
count = 0
t_end = time.time() + runtime
while time.time() < t_end:
try:
stmt = ibm_db.exec_immediate(hdbc,inSQL)
if (stmt == False):
db2_error(flag(["-q","-quiet"]))
return(-1)
... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Split ArgsThis routine takes as an argument a string and then splits the arguments according to the following logic:* If the string starts with a `(` character, it will check the last character in the string and see if it is a `)` and then remove those characters* Every parameter is separated by a comma `,` and commas... | def splitargs(arguments):
import types
# String the string and remove the ( and ) characters if they at the beginning and end of the string
results = []
step1 = arguments.strip()
if (len(step1) == 0): return(results) # Not much to do here - no args found
if (step1[... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
DataFrame Table CreationWhen using dataframes, it is sometimes useful to use the definition of the dataframe to create a Db2 table. The format of the command is:```%sql using create table [with data | columns asis]```The value is the name of the dataframe, not the contents (`:df`). The definition of the data types ... | def createDF(hdbc,sqlin,local_ns):
import datetime
import ibm_db
global sqlcode
# Strip apart the command into tokens based on spaces
tokens = sqlin.split()
token_count = len(tokens)
if (token_count < 5): # Not enough parameters
errormsg("Insufficient... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
SQL ParserThe calling format of this routine is:```sql_cmd, encoded_sql = sqlParser(sql_input)```This code will look at the SQL string that has been passed to it and parse it into two values:- sql_cmd: First command in the list (so this may not be the actual SQL command)- encoded_sql: SQL with the parameters removed i... | def sqlParser(sqlin,local_ns):
sql_cmd = ""
encoded_sql = sqlin
firstCommand = "(?:^\s*)([a-zA-Z]+)(?:\s+.*|$)"
findFirst = re.match(firstCommand,sqlin)
if (findFirst == None): # We did not find a match so we just return the empty string
return sql_cmd, encoded_sql
... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Variable Contents FunctionThe calling format of this routine is:```value = getContents(varName,quote,name_space)```This code will take the name of a variable as input and return the contents of that variable. If the variable is not found then the program will return None which is the equivalent to empty or null. Note ... | def getContents(varName,flag_quotes,local_ns):
#
# Get the contents of the variable name that is passed to the routine. Only simple
# variables are checked, i.e. arrays and lists are not parsed
#
STRING = 0
NUMBER = 1
LIST = 2
RAW = 3
DICT = 4
PANDAS = 5
try:
... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Add QuotesQuotes are a challenge when dealing with dictionaries and Db2. Db2 wants strings delimited with single quotes, while Dictionaries use double quotes. That wouldn't be a problems except imbedded single quotes within these dictionaries will cause things to fail. This routine attempts to double-quote the single ... | def addquotes(inString,flag_quotes):
if (isinstance(inString,dict) == True): # Check to see if this is JSON dictionary
serialized = json.dumps(inString)
else:
serialized = inString
# Replace single quotes with '' (two quotes) and wrap everything in single quotes
if (flag_... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Create the SAMPLE Database TablesThe calling format of this routine is:```db2_create_sample(quiet)```There are a lot of examples that depend on the data within the SAMPLE database. If you are running these examples and the connection is not to the SAMPLE database, then this code will create the two (EMPLOYEE, DEPARTME... | def db2_create_sample(quiet):
create_department = """
BEGIN
DECLARE FOUND INTEGER;
SET FOUND = (SELECT COUNT(*) FROM SYSIBM.SYSTABLES WHERE NAME='DEPARTMENT' AND CREATOR=CURRENT USER);
IF FOUND = 0 THEN
EXECUTE IMMEDIATE('CREATE TABLE DEPARTMENT(DEPTNO CHAR(3) NOT NU... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Check optionThis function will return the original string with the option removed, and a flag or true or false of the value is found.```args, flag = checkOption(option_string, option, false_value, true_value)```Options are specified with a -x where x is the character that we are searching for. It may actually be more ... | def checkOption(args_in, option, vFalse=False, vTrue=True):
args_out = args_in.strip()
found = vFalse
if (args_out != ""):
if (args_out.find(option) >= 0):
args_out = args_out.replace(option," ")
args_out = args_out.strip()
found = vTrue
return args... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Plot DataThis function will plot the data that is returned from the answer set. The plot value determines how we display the data. 1=Bar, 2=Pie, 3=Line, 4=Interactive.```plotData(flag_plot, hdbi, sql, parms)```The hdbi is the ibm_db_sa handle that is used by pandas dataframes to run the sql. The parms contains any of ... | def plotData(hdbi, sql):
try:
df = pandas.read_sql(sql,hdbi)
except Exception as err:
db2_error(False)
return
if df.empty:
errormsg("No results returned")
return
col_count = len(df.columns)
if flag(["-pb","-bar"]... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Find a ProcedureThis routine will check to see if a procedure exists with the SCHEMA/NAME (or just NAME if no schema is supplied) and returns the number of answer sets returned. Possible values are 0, 1 (or greater) or None. If None is returned then we can't find the procedure anywhere. | def findProc(procname):
global _hdbc, _hdbi, _connected, _runtime
# Split the procedure name into schema.procname if appropriate
upper_procname = procname.upper()
schema, proc = split_string(upper_procname,".") # Expect schema.procname
if (proc == None):
proc = schema
# Call i... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Parse Call ArgumentsThis code will parse a SQL call name(parm1,...) and return the name and the parameters in the call. | def parseCallArgs(macro):
quoteChar = ""
inQuote = False
inParm = False
ignore = False
name = ""
parms = []
parm = ''
sqlin = macro.replace("\n","")
sqlin.lstrip()
for ch in sqlin:
if (inParm == False):
# We hit a blank in the name, so ignore ev... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Get ColumnsGiven a statement handle, determine what the column names are or the data types. | def getColumns(stmt):
columns = []
types = []
colcount = 0
try:
colname = ibm_db.field_name(stmt,colcount)
coltype = ibm_db.field_type(stmt,colcount)
while (colname != False):
columns.append(colname)
types.append(coltype)
colcount += 1
... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Call a ProcedureThe CALL statement is used for execution of a stored procedure. The format of the CALL statement is:```CALL PROC_NAME(x,y,z,...)```Procedures allow for the return of answer sets (cursors) as well as changing the contents of the parameters being passed to the procedure. In this implementation, the CALL ... | def parseCall(hdbc, inSQL, local_ns):
global _hdbc, _hdbi, _connected, _runtime, _environment
# Check to see if we are connected first
if (_connected == False): # Check if you are connected
db2_doConnect()
if _connected == False: return None
... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Parse Prepare/ExecuteThe PREPARE statement is used for repeated execution of a SQL statement. The PREPARE statement has the format:```stmt = PREPARE SELECT EMPNO FROM EMPLOYEE WHERE WORKDEPT=? AND SALARY<?```The SQL statement that you want executed is placed after the PREPARE statement with the location of variables m... | def parsePExec(hdbc, inSQL):
import ibm_db
global _stmt, _stmtID, _stmtSQL, sqlcode
cParms = inSQL.split()
parmCount = len(cParms)
if (parmCount == 0): return(None) # Nothing to do but this shouldn't happen
keyword = cParms[0].upper() ... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Fetch Result SetThis code will take the stmt handle and then produce a result set of rows as either an array (`-r`,`-array`) or as an array of json records (`-json`). | def fetchResults(stmt):
global sqlcode
rows = []
columns, types = getColumns(stmt)
# By default we assume that the data will be an array
is_array = True
# Check what type of data we want returned - array or json
if (flag(["-r","-array"]) == False):
# See if we wa... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Parse CommitThere are three possible COMMIT verbs that can bs used:- COMMIT [WORK] - Commit the work in progress - The WORK keyword is not checked for- ROLLBACK - Roll back the unit of work- AUTOCOMMIT ON/OFF - Are statements committed on or off?The statement is passed to this routine and then checked. | def parseCommit(sql):
global _hdbc, _hdbi, _connected, _runtime, _stmt, _stmtID, _stmtSQL
if (_connected == False): return # Nothing to do if we are not connected
cParms = sql.split()
if (len(cParms) == 0): return # Nothing to do but this shoul... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Set FlagsThis code will take the input SQL block and update the global flag list. The global flag list is just a list of options that are set at the beginning of a code block. The absence of a flag means it is false. If it exists it is true. | def setFlags(inSQL):
global _flags
_flags = [] # Delete all of the current flag settings
pos = 0
end = len(inSQL)-1
inFlag = False
ignore = False
outSQL = ""
flag = ""
while (pos <= end):
ch = inSQL[pos]
if (ignore == True):
outSQL =... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Check to see if flag ExistsThis function determines whether or not a flag exists in the global flag array. Absence of a value means it is false. The parameter can be a single value, or an array of values. | def flag(inflag):
global _flags
if isinstance(inflag,list):
for x in inflag:
if (x in _flags):
return True
return False
else:
if (inflag in _flags):
return True
else:
return False | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Generate a list of SQL lines based on a delimiterNote that this function will make sure that quotes are properly maintained so that delimiters inside of quoted strings do not cause errors. | def splitSQL(inputString, delimiter):
pos = 0
arg = ""
results = []
quoteCH = ""
inSQL = inputString.strip()
if (len(inSQL) == 0): return(results) # Not much to do here - no args found
while pos < len(inSQL):
ch = inSQL[pos]
pos += 1
if (... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Main %sql Magic DefinitionThe main %sql Magic logic is found in this section of code. This code will register the Magic command and allow Jupyter notebooks to interact with Db2 by using this extension. | @magics_class
class DB2(Magics):
@needs_local_scope
@line_cell_magic
def sql(self, line, cell=None, local_ns=None):
# Before we event get started, check to see if you have connected yet. Without a connection we
# can't do anything. You may have a connection request in t... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Pre-defined MacrosThese macros are used to simulate the LIST TABLES and DESCRIBE commands that are available from within the Db2 command line. | %%sql define LIST
#
# The LIST macro is used to list all of the tables in the current schema or for all schemas
#
var syntax Syntax: LIST TABLES [FOR ALL | FOR SCHEMA name]
#
# Only LIST TABLES is supported by this macro
#
if {^1} <> 'TABLES'
exit {syntax}
endif
#
# This SQL is a temporary table that contains the... | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Set the table formatting to left align a table in a cell. By default, tables are centered in a cell. Remove this cell if you don't want to change Jupyter notebook formatting for tables. In addition, we skip this code if you are running in a shell environment rather than a Jupyter notebook | #%%html
#<style>
# table {margin-left: 0 !important; text-align: left;}
#</style> | _____no_output_____ | Apache-2.0 | db2.ipynb | Db2-DTE-POC/Db2-Openshift-11.5.4 |
Profiling TensorFlow Multi GPU Multi Node Training Job with Amazon SageMaker DebuggerThis notebook will walk you through creating a TensorFlow training job with the SageMaker Debugger profiling feature enabled. It will create a multi GPU multi node training using Horovod. (Optional) Install SageMaker and SMDebug Py... | import sys
import IPython
install_needed = False # should only be True once
if install_needed:
print("installing deps and restarting kernel")
!{sys.executable} -m pip install -U sagemaker smdebug
IPython.Application.instance().kernel.do_shutdown(True) | _____no_output_____ | Apache-2.0 | sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node.ipynb | Amirosimani/amazon-sagemaker-examples |
1. Create a Training Job with Profiling EnabledYou will use the standard [SageMaker Estimator API for Tensorflow](https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/sagemaker.tensorflow.htmltensorflow-estimator) to create training jobs. To enable profiling, create a `ProfilerConfig` object and pass it to... | distributions = {
"mpi": {
"enabled": True,
"processes_per_host": 4,
"custom_mpi_options": "-verbose -x HOROVOD_TIMELINE=./hvd_timeline.json -x NCCL_DEBUG=INFO -x OMPI_MCA_btl_vader_single_copy_mechanism=none",
}
} | _____no_output_____ | Apache-2.0 | sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node.ipynb | Amirosimani/amazon-sagemaker-examples |
Configure rulesWe specify the following rules:- loss_not_decreasing: checks if loss is decreasing and triggers if the loss has not decreased by a certain persentage in the last few iterations- LowGPUUtilization: checks if GPU is under-utilizated - ProfilerReport: runs the entire set of performance rules and create a f... | from sagemaker.debugger import Rule, ProfilerRule, rule_configs
rules = [
Rule.sagemaker(rule_configs.loss_not_decreasing()),
ProfilerRule.sagemaker(rule_configs.LowGPUUtilization()),
ProfilerRule.sagemaker(rule_configs.ProfilerReport()),
] | _____no_output_____ | Apache-2.0 | sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node.ipynb | Amirosimani/amazon-sagemaker-examples |
Specify a profiler configurationThe following configuration will capture system metrics at 500 milliseconds. The system metrics include utilization per CPU, GPU, memory utilization per CPU, GPU as well I/O and network.Debugger will capture detailed profiling information from step 5 to step 15. This information include... | from sagemaker.debugger import ProfilerConfig, FrameworkProfile
profiler_config = ProfilerConfig(
system_monitor_interval_millis=500,
framework_profile_params=FrameworkProfile(
local_path="/opt/ml/output/profiler/", start_step=5, num_steps=10
),
) | _____no_output_____ | Apache-2.0 | sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node.ipynb | Amirosimani/amazon-sagemaker-examples |
Get the image URIThe image that we will is dependent on the region that you are running this notebook in. | import boto3
session = boto3.session.Session()
region = session.region_name
image_uri = f"763104351884.dkr.ecr.{region}.amazonaws.com/tensorflow-training:2.3.1-gpu-py37-cu110-ubuntu18.04" | _____no_output_____ | Apache-2.0 | sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node.ipynb | Amirosimani/amazon-sagemaker-examples |
Define estimatorTo enable profiling, you need to pass the Debugger profiling configuration (`profiler_config`), a list of Debugger rules (`rules`), and the image URI (`image_uri`) to the estimator. Debugger enables monitoring and profiling while the SageMaker estimator requests a training job. | import sagemaker
from sagemaker.tensorflow import TensorFlow
estimator = TensorFlow(
role=sagemaker.get_execution_role(),
image_uri=image_uri,
instance_count=2,
instance_type="ml.p3.8xlarge",
entry_point="tf-hvd-train.py",
source_dir="entry_point",
profiler_config=profiler_config,
distr... | _____no_output_____ | Apache-2.0 | sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node.ipynb | Amirosimani/amazon-sagemaker-examples |
Start training jobThe following `estimator.fit()` with `wait=False` argument initiates the training job in the background. You can proceed to run the dashboard or analysis notebooks. | estimator.fit(wait=False) | _____no_output_____ | Apache-2.0 | sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node.ipynb | Amirosimani/amazon-sagemaker-examples |
2. Analyze Profiling DataCopy outputs of the following cell (`training_job_name` and `region`) to run the analysis notebooks `profiling_generic_dashboard.ipynb`, `analyze_performance_bottlenecks.ipynb`, and `profiling_interactive_analysis.ipynb`. | training_job_name = estimator.latest_training_job.name
print(f"Training jobname: {training_job_name}")
print(f"Region: {region}") | _____no_output_____ | Apache-2.0 | sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node.ipynb | Amirosimani/amazon-sagemaker-examples |
While the training is still in progress you can visualize the performance data in SageMaker Studio or in the notebook.Debugger provides utilities to plot system metrics in form of timeline charts or heatmaps. Checkout out the notebook [profiling_interactive_analysis.ipynb](analysis_tools/profiling_interactive_analysis.... | import pip
def import_or_install(package):
try:
__import__(package)
except ImportError:
pip.main(["install", package])
import_or_install("smdebug") | _____no_output_____ | Apache-2.0 | sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node.ipynb | Amirosimani/amazon-sagemaker-examples |
Access the profiling data using the SMDebug `TrainingJob` utility class | from smdebug.profiler.analysis.notebook_utils.training_job import TrainingJob
tj = TrainingJob(training_job_name, region)
tj.wait_for_sys_profiling_data_to_be_available() | _____no_output_____ | Apache-2.0 | sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node.ipynb | Amirosimani/amazon-sagemaker-examples |
Plot time line chartsThe following code shows how to use the SMDebug `TrainingJob` object, refresh the object if new event files are available, and plot time line charts of CPU and GPU usage. | from smdebug.profiler.analysis.notebook_utils.timeline_charts import TimelineCharts
system_metrics_reader = tj.get_systems_metrics_reader()
system_metrics_reader.refresh_event_file_list()
view_timeline_charts = TimelineCharts(
system_metrics_reader,
framework_metrics_reader=None,
select_dimensions=["CPU",... | _____no_output_____ | Apache-2.0 | sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node.ipynb | Amirosimani/amazon-sagemaker-examples |
3. Download Debugger Profiling Report The `ProfilerReport()` rule creates an html report `profiler-report.html` with a summary of builtin rules and recommenades of next steps. You can find this report in your S3 bucket. | rule_output_path = estimator.output_path + estimator.latest_training_job.job_name + "/rule-output"
print(f"You will find the profiler report in {rule_output_path}") | _____no_output_____ | Apache-2.0 | sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node.ipynb | Amirosimani/amazon-sagemaker-examples |
Лабораторная работа 2 - Линейная и полиномиальная регрессия. Одна из множества задач, которой занимается современная физика это поиск материала для изготовления сверхпроводника, работающего при комнатной температуре. Кроме теоретических методов есть и подход со стороны статистики, который подразумевает анализ базы дан... | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd | _____no_output_____ | MIT | lab2/Lab 2.ipynb | KHYehor/MachineLearning |
В файле **data.csv** содержится весь датасет. | data = pd.read_csv('data.csv')
data | _____no_output_____ | MIT | lab2/Lab 2.ipynb | KHYehor/MachineLearning |
Итого имеем 21 тысячу строк и 169 колонок, из которых первые 167 - признаки, колонка **critical_temp** содержит величину, которую надо предсказать. Колонка **material** - содержит химическую формулу материала, ее можно отбросить.Выполним предобработку данных и разобъем на тренировочную и тестовую выборки: | # X - last two columns cut.
# Y - pre last column.
x, y = data.values[:, :-2].astype(np.float32), data.values[:, -2:-1].astype(np.float32)
np.random.seed(1337)
is_train = np.random.uniform(size=(x.shape[0],)) < 0.95
x_train, y_train = x[is_train], y[is_train]
x_test, y_test = x[~is_train], y[~is_train]
print(f'Train... | Train samples: 20210
Test samples: 1053
| MIT | lab2/Lab 2.ipynb | KHYehor/MachineLearning |
Реализуйте методы с пометкой `TODO` класса PolynomialRegression:Метод `preprocess` должен выполнять следующее преобразование:$$\begin{array}{l}X=\begin{bmatrix}x_{i,j}\end{bmatrix}_{m\times n}\\preprocess( X) =\begin{bmatrix}1 & x_{1,1} & \dotsc & x_{1,1} & x^{2}_{1,1} & \dotsc & x^{2}_{1,1} & \dotsc & x^{p}_{1,1} &... | class PolynomialRegression:
def __init__(
self,
alpha1,
alpha2,
poly_deg,
learning_rate,
batch_size,
train_steps
):
self.alpha1 = alpha1
self.alpha2 = alpha2
self.poly_deg = poly_deg
self.learning_rate = learning_rate
... | Test MAE: 12.593122309572655
| MIT | lab2/Lab 2.ipynb | KHYehor/MachineLearning |
Полученный MAE на тестовой выборке должен быть приблизительно равен $12.5$. Выполните поиск оптимальных параметров регуляризации $\alpha_1,\alpha_2$ по отдельности (то есть устанавливаете один параметр равным нулю и ищете второй, потом наоборот) и старшей степени полиномиальной регрессии (`poly_deg`). Обратите внимание... | a1 = 10 ** np.linspace(-9, -1, 9)
a2 = 10 ** np.linspace(-9, -1, 9)
fig, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(20, 10))
fig.suptitle('Poly deg. = 5')
ax1.set_xlabel('Alpha 1')
ax1.set_ylabel('Score')
ax1.set_xscale('log')
ax1.plot([a1i for a1i in a1], [PolynomialRegression(a1i, 0, 1, 1e-3, 1024, 1000).fi... | _____no_output_____ | MIT | lab2/Lab 2.ipynb | KHYehor/MachineLearning |
Визуализируйте зависимость предсказанной критической температуры от истинной для лучшей модели: | reg = PolynomialRegression(1e-5, 1e-5, 5, 1e-3, 1024, 1000).fit(x_train, y_train)
y_test_pred = reg.predict(x_test)
print(f'Test MAE: {reg.score(x_test, y_test)}')
plt.figure(figsize=(10, 10))
plt.scatter(y_test[:, 0], y_test_pred[:, 0], marker='.', c='r')
plt.xlabel('True Y')
plt.ylabel('Predicted Y')
plt.show() | Test MAE: 11.26531342526687
| MIT | lab2/Lab 2.ipynb | KHYehor/MachineLearning |
Define paths for the model and data of interest | model_type = "profile"
# Shared paths/constants
reference_fasta = "/users/amtseng/genomes/hg38.fasta"
chrom_sizes = "/users/amtseng/genomes/hg38.canon.chrom.sizes"
data_base_path = "/users/amtseng/att_priors/data/processed/"
model_base_path = "/users/amtseng/att_priors/models/trained_models/%s/" % model_type
chrom_set ... | _____no_output_____ | MIT | notebooks/consistency_of_importance_over_different_initializations.ipynb | atseng95/fourier_attribution_priors |
Get all runs/epochs with random initializations | def import_metrics_json(model_base_path, run_num):
"""
Looks in {model_base_path}/{run_num}/metrics.json and returns the contents as a
Python dictionary. Returns None if the path does not exist.
"""
path = os.path.join(model_base_path, str(run_num), "metrics.json")
if not os.path.exists(path):
... | _____no_output_____ | MIT | notebooks/consistency_of_importance_over_different_initializations.ipynb | atseng95/fourier_attribution_priors |
Data preparationCreate an input data loader, that maps coordinates or bin indices to data needed for the model | if model_type == "profile":
input_func = data_loading.get_profile_input_func(
files_spec_path, input_length, profile_length, reference_fasta
)
pos_examples = data_loading.get_positive_profile_coords(
files_spec_path, chrom_set=chrom_set
)
else:
input_func = data_loading.get_binary_in... | _____no_output_____ | MIT | notebooks/consistency_of_importance_over_different_initializations.ipynb | atseng95/fourier_attribution_priors |
Compute importances | # Pick a sample of 100 random coordinates/bins
num_samples = 100
rng = np.random.RandomState(20200318)
sample = pos_examples[rng.choice(len(pos_examples), size=num_samples, replace=False)]
# For profile models, add a random jitter to avoid center-bias
if model_type == "profile":
jitters = np.random.randint(-128, 12... | _____no_output_____ | MIT | notebooks/consistency_of_importance_over_different_initializations.ipynb | atseng95/fourier_attribution_priors |
Compute similarity | def cont_jaccard(seq_1, seq_2):
"""
Takes two gradient sequences (I x 4 arrays) and computes a similarity between
them, using a continuous Jaccard metric.
"""
# L1-normalize
norm_1 = np.sum(np.abs(seq_1), axis=1, keepdims=True)
norm_2 = np.sum(np.abs(seq_2), axis=1, keepdims=True)
norm_1... | _____no_output_____ | MIT | notebooks/consistency_of_importance_over_different_initializations.ipynb | atseng95/fourier_attribution_priors |
Table of Contents1 init2 モデリング2.1 べースモデル2.2 グリッドサーチ3 本番モデル4 ランダムフォレスト5 work init | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
pwd
cd ../
cd data
cd raw
pdf_train = pd.read_csv("train.tsv", sep="\t")
pdf_train.T
pdf_test = pd.read_csv("test.tsv", sep="\t")
pdf_test.T
pdf_test.describe()
for str_col in ["C%s"%i for i in range(1,7)]:
print("# "+str_col)
v_cnt = pdf_... | _____no_output_____ | MIT | notebooks/lightGBM_v01-Copy1.ipynb | mnm-signate/analysys_titanic |
モデリング | from sklearn.metrics import roc_auc_score
from sklearn.model_selection import ParameterGrid, KFold, train_test_split
import lightgbm as lgb
| _____no_output_____ | MIT | notebooks/lightGBM_v01-Copy1.ipynb | mnm-signate/analysys_titanic |
べースモデル | def cross_valid_lgb(X,y,param,n_splits,random_state=1234, num_boost_round=1000,early_stopping_rounds=5):
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, train_test_split
import lightgbm as lgb
kf = StratifiedKFold(n_splits=n_splits, shuffle=True,random_sta... | _____no_output_____ | MIT | notebooks/lightGBM_v01-Copy1.ipynb | mnm-signate/analysys_titanic |
グリッドサーチ | grid = {
'boosting_type': ['goss'],
'objective': ['binary'],
'metric': ['auc'],
# 'num_leaves':[31 + i for i in range(-10, 11)],
# 'min_data_in_leaf':[20 + i for i in range(-10, 11)],
'num_leaves':[31],
'min_data_in_leaf':[20],
'max_depth':[-1]
}
X = pdf_clns_train.drop("click",1)
... | 0.8083715191616564 {'boosting_type': 'goss', 'max_depth': -1, 'metric': 'auc', 'min_data_in_leaf': 20, 'num_leaves': 31, 'objective': 'binary'}
| MIT | notebooks/lightGBM_v01-Copy1.ipynb | mnm-signate/analysys_titanic |
本番モデル | lst_model = cross_lgb(X,y,param=best_param,n_splits=5,random_state=1234, num_boost_round=1000,early_stopping_rounds=5)
lst_model
lst_pred = []
for mdl in lst_model:
pred = mdl.predict(pdf_clns_test)
lst_pred.append(pred)
nparr_preds = np.array(lst_pred)
mean_pred = nparr_preds.mean(0)
mean_pred
pdf_submit = pd... | _____no_output_____ | MIT | notebooks/lightGBM_v01-Copy1.ipynb | mnm-signate/analysys_titanic |
ランダムフォレスト | from sklearn.ensemble import RandomForestClassifier
X = X.fillna(0)
clf = RandomForestClassifier()
clf.fit(X,y)
pdf_clns_test = pdf_clns_test.fillna(0)
pred = clf.predict_proba(pdf_clns_test)
pred
pdf_submit_rf = pd.DataFrame({
"id":pdf_test.id,
"score":pred[:,1]
})
pdf_submit_rf.T
pdf_submit_rf.to_csv("su... | _____no_output_____ | MIT | notebooks/lightGBM_v01-Copy1.ipynb | mnm-signate/analysys_titanic |
work | params = {
'boosting_type': 'goss',
'objective': 'binary',
'metric': 'auc',
'learning_rate': 0.1,
'num_leaves': 23,
'min_data_in_leaf': 1,
}
gbm = lgb.train(
params,
lds_train,
num_boost_round=1000,
valid_sets=lds_test,
early_stopping_rounds=5,
)
dc... | [1] valid_0's auc: 0.720192
Training until validation scores don't improve for 5 rounds.
[2] valid_0's auc: 0.726811
[3] valid_0's auc: 0.731667
[4] valid_0's auc: 0.737238
[5] valid_0's auc: 0.739277
[6] valid_0's auc: 0.740883
[7] valid_0's auc: 0.742216
[8] valid_0's auc: 0.743704
[9] valid_0's auc: 0.744488
[10] va... | MIT | notebooks/lightGBM_v01-Copy1.ipynb | mnm-signate/analysys_titanic |
import tensorflow as tf
print(tf.__version__) | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST | |
The Fashion MNIST data is available directly in the tf.keras datasets API. You load it like this: | mnist = tf.keras.datasets.fashion_mnist | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
Calling load_data on this object will give you two sets of two lists, these will be the training and testing values for the graphics that contain the clothing items and their labels. | (training_images, training_labels), (test_images, test_labels) = mnist.load_data() | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
What does these values look like? Let's print a training image, and a training label to see...Experiment with different indices in the array. For example, also take a look at index 42...that's a a different boot than the one at index 0 | import numpy as np
np.set_printoptions(linewidth=200)
import matplotlib.pyplot as plt
plt.imshow(training_images[0])
print(training_labels[0])
print(training_images[0]) | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
You'll notice that all of the values in the number are between 0 and 255. If we are training a neural network, for various reasons it's easier if we treat all values as between 0 and 1, a process called '**normalizing**'...and fortunately in Python it's easy to normalize a list like this without looping. You do it like... | training_images = training_images / 255.0
test_images = test_images / 255.0 | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
Now you might be wondering why there are 2 sets...training and testing -- remember we spoke about this in the intro? The idea is to have 1 set of data for training, and then another set of data...that the model hasn't yet seen...to see how good it would be at classifying values. After all, when you're done, you're goin... | model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)]) | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
**Sequential**: That defines a SEQUENCE of layers in the neural network**Flatten**: Remember earlier where our images were a square, when you printed them out? Flatten just takes that square and turns it into a 1 dimensional set.**Dense**: Adds a layer of neuronsEach layer of neurons need an **activation function** to ... | model.compile(optimizer = tf.optimizers.Adam(),
loss = 'sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(training_images, training_labels, epochs=5) | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
Once it's done training -- you should see an accuracy value at the end of the final epoch. It might look something like 0.9098. This tells you that your neural network is about 91% accurate in classifying the training data. I.E., it figured out a pattern match between the image and the labels that worked 91% of the tim... | model.evaluate(test_images, test_labels) | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
For me, that returned a accuracy of about .8838, which means it was about 88% accurate. As expected it probably would not do as well with *unseen* data as it did with data it was trained on! As you go through this course, you'll look at ways to improve this. To explore further, try the below exercises: Exercise 1:For ... | classifications = model.predict(test_images)
print(classifications[0]) | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
Hint: try running print(test_labels[0]) -- and you'll get a 9. Does that help you understand why this list looks the way it does? | print(test_labels[0]) | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
Exercise 2: Let's now look at the layers in your model. Experiment with different values for the dense layer with 512 neurons. What different results do you get for loss, training time etc? Why do you think that's the case? | import tensorflow as tf
print(tf.__version__)
mnist = tf.keras.datasets.mnist
(training_images, training_labels) , (test_images, test_labels) = mnist.load_data()
training_images = training_images/255.0
test_images = test_images/255.0
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
... | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
Exercise 3: What would happen if you remove the Flatten() layer. Why do you think that's the case? You get an error about the shape of the data. It may seem vague right now, but it reinforces the rule of thumb that the first layer in your network should be the same shape as your data. Right now our data is 28x28 images... | import tensorflow as tf
print(tf.__version__)
mnist = tf.keras.datasets.mnist
(training_images, training_labels) , (test_images, test_labels) = mnist.load_data()
training_images = training_images/255.0
test_images = test_images/255.0
model = tf.keras.models.Sequential([#tf.keras.layers.Flatten(),
... | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
Exercise 4: Consider the final (output) layers. Why are there 10 of them? What would happen if you had a different amount than 10? For example, try training the network with 5You get an error as soon as it finds an unexpected value. Another rule of thumb -- the number of neurons in the last layer should match the numbe... | import tensorflow as tf
print(tf.__version__)
mnist = tf.keras.datasets.mnist
(training_images, training_labels) , (test_images, test_labels) = mnist.load_data()
training_images = training_images/255.0
test_images = test_images/255.0
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
... | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
Exercise 5: Consider the effects of additional layers in the network. What will happen if you add another layer between the one with 512 and the final layer with 10. Ans: There isn't a significant impact -- because this is relatively simple data. For far more complex data (including color images to be classified as flo... | import tensorflow as tf
print(tf.__version__)
mnist = tf.keras.datasets.mnist
(training_images, training_labels) , (test_images, test_labels) = mnist.load_data()
training_images = training_images/255.0
test_images = test_images/255.0
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
... | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
Exercise 6: Consider the impact of training for more or less epochs. Why do you think that would be the case? Try 15 epochs -- you'll probably get a model with a much better loss than the one with 5Try 30 epochs -- you might see the loss value stops decreasing, and sometimes increases. This is a side effect of somethin... | import tensorflow as tf
print(tf.__version__)
mnist = tf.keras.datasets.mnist
(training_images, training_labels) , (test_images, test_labels) = mnist.load_data()
training_images = training_images/255.0
test_images = test_images/255.0
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
... | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
Exercise 7: Before you trained, you normalized the data, going from values that were 0-255 to values that were 0-1. What would be the impact of removing that? Here's the complete code to give it a try. Why do you think you get different results? | import tensorflow as tf
print(tf.__version__)
mnist = tf.keras.datasets.mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images=training_images/255.0
test_images=test_images/255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(5... | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
Exercise 8: Earlier when you trained for extra epochs you had an issue where your loss might change. It might have taken a bit of time for you to wait for the training to do that, and you might have thought 'wouldn't it be nice if I could stop the training when I reach a desired value?' -- i.e. 95% accuracy might be en... | import tensorflow as tf
print(tf.__version__)
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if(logs.get('loss')<0.4):
print("\nReached 60% accuracy so cancelling training!")
self.model.stop_training = True
callbacks = myCallback()
mnist = tf.keras.datasets.fa... | _____no_output_____ | MIT | Course_1_Part_4_Lesson_2_Notebook.ipynb | poojan-dalal/fashion-MNIST |
Configure through code.Restart the kernel here. | import logging
import sys
root_logger = logging.getLogger()
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter("%(levelname)s: %(message)s")
handler.setFormatter(formatter)
root_logger.addHandler(handler)
root_logger.setLevel("INFO")
logging.info("Hello logging world") | INFO: Hello logging world
| MIT | 01_Workshop-master/Chapter06/Exercise94/Exercise94.ipynb | Anna-MarieTomm/Learn_Python_with_Anna-Marie |
Configure with dictConfig.Restart the kernel here. | import logging
from logging.config import dictConfig
dictConfig({
"version": 1,
"formatters": {
"short":{
"format": "%(levelname)s: %(message)s",
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "short",
... | INFO: Hello logging world
| MIT | 01_Workshop-master/Chapter06/Exercise94/Exercise94.ipynb | Anna-MarieTomm/Learn_Python_with_Anna-Marie |
Configure with basicConfig.Restart the kernel here. | import sys
import logging
logging.basicConfig(
level="INFO",
format="%(levelname)s: %(message)s",
stream=sys.stdout
)
logging.info("Hello there!") | INFO: Hello there!
| MIT | 01_Workshop-master/Chapter06/Exercise94/Exercise94.ipynb | Anna-MarieTomm/Learn_Python_with_Anna-Marie |
Configure with fileconfig.Restart the kernel here. | import logging
from logging.config import fileConfig
fileConfig("logging-config.ini")
logging.info("Hello there!") | INFO: Hello there!
| MIT | 01_Workshop-master/Chapter06/Exercise94/Exercise94.ipynb | Anna-MarieTomm/Learn_Python_with_Anna-Marie |
[Advent of Code 2020: Day 10](https://adventofcode.com/2020/day/10) \-\-\- Day 10: Adapter Array \-\-\-Patched into the aircraft's data port, you discover weather forecasts of a massive tropical storm. Before you can figure out whether it will impact your vacation plans, however, your device suddenly turns off!Its ba... | import unittest
from IPython.display import Markdown, display
from aoc_puzzle import AocPuzzle
class AdapterArray(AocPuzzle):
def parse_data(self, raw_data):
self.adapter_list = list(map(int, raw_data.split('\n')))
self.adapter_list.sort()
self.adapter_list.insert(0,0)
self.ad... | _____no_output_____ | MIT | AoC 2020/AoC 2020 - Day 10.ipynb | RubenFixit/AoC |
--- Part Two ---To completely determine whether you have enough adapters, you'll need to figure out how many different ways they can be arranged. Every arrangement needs to connect the charging outlet to your device. The previous rules about when adapters can successfully connect still apply.The first example above (t... | class AdapterArray2(AdapterArray):
def count_all_arrangements(self, output=False):
arrangements_list = [1]
for a_index in range(1,len(self.adapter_list)):
adapter = self.adapter_list[a_index]
arrangements = 0
for pa_index in range(a_index):
... | _____no_output_____ | MIT | AoC 2020/AoC 2020 - Day 10.ipynb | RubenFixit/AoC |
An Jupyter notebook for running PCSE/WOFOST on a CGMS8 databaseThis Jupyter notebook will demonstrate how to connect and read data from a CGMS8 database for a single grid. Next the data will be used to run a PCSE/WOFOST simulation for potential and water-limited conditions, the latter is done for all soil types prese... | %matplotlib inline
import os, sys
data_dir = os.path.join(os.getcwd(), "data")
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import sqlalchemy as sa
import pandas as pd
import pcse
from pcse.db.cgms8 import GridWeatherDataProvider, AgroManagementDataProvider, SoilDataIterator, \
... | This notebook was built with:
python version: 3.6.7 |Anaconda, Inc.| (default, Oct 24 2018, 09:45:24) [MSC v.1912 64 bit (AMD64)]
PCSE version: 5.4.1
| MIT | 05 Using PCSE WOFOST with a CGMS8 database.ipynb | CHNEWUAF/pcse_notebooks |
Building the connection to a CGMS8 databaseThe connection to the database will be made using SQLAlchemy. This requires a database URL to be provided, the format of this URL depends on the database of choice. See the SQLAlchemy documentation on [database URLs](http://docs.sqlalchemy.org/en/latest/core/engines.htmldatab... | cgms8_db = "d:/nobackup/CGMS8_Anhui/CGMS_Anhui_complete.db"
dbURL = "sqlite:///%s" % cgms8_db
engine = sa.create_engine(dbURL) | _____no_output_____ | MIT | 05 Using PCSE WOFOST with a CGMS8 database.ipynb | CHNEWUAF/pcse_notebooks |
Defining what should be simulatedFor the simulation to run, some IDs must be provided that refer to the location (`grid_no`), crop type (`crop_no`) and year (`campaign_year`) for which the simulation should be carried out. These IDs refer to columns in the CGMS database that are used to define the relationships. | grid_no = 81159
crop_no = 1 # Winter-wheat
campaign_year = 2008
# if input/output should be printed set show_results=True
show_results = True | _____no_output_____ | MIT | 05 Using PCSE WOFOST with a CGMS8 database.ipynb | CHNEWUAF/pcse_notebooks |
Retrieving data for the simulation from the database Weather dataWeather data will be derived from the GRID_WEATHER table in the database. By default, the entire time-series of weather data available for this grid cell will be fetched from the database. | weatherdata = GridWeatherDataProvider(engine, grid_no)
print(weatherdata) | Weather data provided by: GridWeatherDataProvider
--------Description---------
Weather data derived for grid_no: 81159
----Site characteristics----
Elevation: 29.0
Latitude: 33.170
Longitude: 116.334
Data available for 1990-01-01 - 2013-11-03
Number of missing days: 0
| MIT | 05 Using PCSE WOFOST with a CGMS8 database.ipynb | CHNEWUAF/pcse_notebooks |
Agromanagement informationAgromanagement in CGMS mainly refers to the cropping calendar for the given crop and location. | agromanagement = AgroManagementDataProvider(engine, grid_no, crop_no, campaign_year)
agromanagement | _____no_output_____ | MIT | 05 Using PCSE WOFOST with a CGMS8 database.ipynb | CHNEWUAF/pcse_notebooks |
Soil informationA CGMS grid cell can contain multiple soils which may or may not be suitable for a particular crop. Moreover, a complicating factor is the arrangement of soils in many soil maps which consist of *Soil Mapping Units* `(SMUs)` which are soil associations whose location on the map is known. Within an SMU,... | soil_iterator = SoilDataIterator(engine, grid_no)
soil_iterator
suitable_stu = STU_Suitability(engine, crop_no) | _____no_output_____ | MIT | 05 Using PCSE WOFOST with a CGMS8 database.ipynb | CHNEWUAF/pcse_notebooks |
Crop parametersCrop parameters are needed for parameterizing the crop simulation model. The `CropDataProvider` will retrieve them from the database for the given crop_no, grid_no and campaign_year. | cropd = CropDataProvider(engine, grid_no, crop_no, campaign_year)
if show_results:
print(cropd) | Crop parameter values for grid_no=81159, crop_no=1 (winter wheat), variety_no=55, campaign_year=2008 derived from sqlite:///d:/nobackup/CGMS8_Anhui/CGMS_Anhui_complete.db
{'CFET': 1.0, 'CVL': 0.685, 'CVO': 0.709, 'CVR': 0.694, 'CVS': 0.662, 'DEPNR': 4.5, 'DLC': 10.0, 'DLO': 13.5, 'DVSEND': 2.0, 'EFFTB': [0.0, 0.45, 40.... | MIT | 05 Using PCSE WOFOST with a CGMS8 database.ipynb | CHNEWUAF/pcse_notebooks |
Site parametersSite parameters are an ancillary class of parameters that are related to a given site. For example, an important parameter is the initial amount of moisture in the soil profile (WAV) and the Atmospheric CO$_2$ concentration (CO2). Site parameters will be fetched for each soil type within the soil iterat... | daily_results = {}
summary_results = {} | _____no_output_____ | MIT | 05 Using PCSE WOFOST with a CGMS8 database.ipynb | CHNEWUAF/pcse_notebooks |
Potential production | # For potential production we can provide site data directly
sited = WOFOST71SiteDataProvider(CO2=360, WAV=25)
# We do not need soildata for potential production so we provide some dummy values here
soild = DummySoilDataProvider()
# Start WOFOST, run the simulation
parameters = ParameterProvider(sitedata=sited, soilda... | _____no_output_____ | MIT | 05 Using PCSE WOFOST with a CGMS8 database.ipynb | CHNEWUAF/pcse_notebooks |
Water-limited productionWater-limited simulations will be carried out for each soil type. First we will check that the soil type is suitable. Next we will retrieve the site data and run the simulation. Finally, we will collect the output and store the results. | for smu_no, area, stu_no, percentage, soild in soil_iterator:
# Check if this is a suitable STU
if stu_no not in suitable_stu:
continue
# retrieve the site data for this soil type
sited = SiteDataProvider(engine, grid_no, crop_no, campaign_year, stu_no)
# Start WOFOST, run the simulation
... | _____no_output_____ | MIT | 05 Using PCSE WOFOST with a CGMS8 database.ipynb | CHNEWUAF/pcse_notebooks |
Visualizing and exporting simulation results We can visualize the simulation results using pandas and matplotlib | # Generate a figure with 10 subplots
fig, axes = plt.subplots(nrows=5, ncols=2, figsize=(12, 30))
# Plot results
for runid, results in daily_results.items():
for var, ax in zip(results, axes.flatten()):
results[var].plot(ax=ax, title=var, label=runid)
ax.set_title(var)
fig.autofmt_xdate()
axes[0][0]... | _____no_output_____ | MIT | 05 Using PCSE WOFOST with a CGMS8 database.ipynb | CHNEWUAF/pcse_notebooks |
Exporting the simulation resultsA pandas DataFrame or panel can be easily export to a [variety of formats](http://pandas.pydata.org/pandas-docs/stable/io.html) including CSV, Excel or HDF5. First we convert the results to a Panel, next we will export to an Excel file. | excel_fname = os.path.join(data_dir, "output", "cgms8_wofost_results.xls")
panel = pd.Panel(daily_results)
panel.to_excel(excel_fname) | _____no_output_____ | MIT | 05 Using PCSE WOFOST with a CGMS8 database.ipynb | CHNEWUAF/pcse_notebooks |
Simulating with a different start date waterbalanceBy default CGMS starts the simulation when the crop is planted. Particularly in dry climates this can be problematic because the results become very sensitive to the initial value of the soil water balance. In such scenarios, it is more realistic to start the water ba... | for smu_no, area, stu_no, percentage, soild in soil_iterator:
# Check if this is a suitable STU
if stu_no not in suitable_stu:
continue
# retrieve the site data for this soil type
sited = SiteDataProvider(engine, grid_no, crop_no, campaign_year, stu_no)
# update the campaign start date in th... | _____no_output_____ | MIT | 05 Using PCSE WOFOST with a CGMS8 database.ipynb | CHNEWUAF/pcse_notebooks |
Let's show the results As you can see, the results from the simulation are slightly different because of a different start date of the water balance.NOTE: the dates on the x-axis are the same except for the soil moisture chart 'SM' where the water-limited simulation results start before potential results. This is a ma... | # Generate a figure with 10 subplots
fig, axes = plt.subplots(nrows=5, ncols=2, figsize=(12, 30))
# Plot results
for runid, results in daily_results.items():
for var, ax in zip(results, axes.flatten()):
results[var].plot(ax=ax, title=var, label=runid)
fig.autofmt_xdate()
axes[0][0].legend(loc='upper left') | _____no_output_____ | MIT | 05 Using PCSE WOFOST with a CGMS8 database.ipynb | CHNEWUAF/pcse_notebooks |
7.6 Transformerモデル(分類タスク用)の実装- 本ファイルでは、クラス分類のTransformerモデルを実装します。 ※ 本章のファイルはすべてUbuntuでの動作を前提としています。Windowsなど文字コードが違う環境での動作にはご注意下さい。 7.6 学習目標1. Transformerのモジュール構成を理解する2. LSTMやRNNを使用せずCNNベースのTransformerで自然言語処理が可能な理由を理解する3. Transformerを実装できるようになる 事前準備書籍の指示に従い、本章で使用するデータを用意します | import math
import numpy as np
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchtext
# Setup seeds
torch.manual_seed(1234)
np.random.seed(1234)
random.seed(1234)
class Embedder(nn.Module):
'''idで示されている単語をベクトルに変換します'''
def __init__(self, text_embedding_vectors):
... | 出力のテンソルサイズ: torch.Size([24, 2])
出力テンソルのsigmoid: tensor([[0.6980, 0.3020],
[0.7318, 0.2682],
[0.7244, 0.2756],
[0.7135, 0.2865],
[0.7022, 0.2978],
[0.6974, 0.3026],
[0.6831, 0.3169],
[0.6487, 0.3513],
[0.7096, 0.2904],
[0.7221, 0.2779],
[0.7... | MIT | 7_nlp_sentiment_transformer/7-6_Transformer.ipynb | Jinx-git/pytorch_advanced |
Run model module locally | import os
# Import os environment variables for file hyperparameters.
os.environ["TRAIN_FILE_PATTERN"] = "gs://machine-learning-1234-bucket/gan/data/cifar10/train*.tfrecord"
os.environ["EVAL_FILE_PATTERN"] = "gs://machine-learning-1234-bucket/gan/data/cifar10/test*.tfrecord"
os.environ["OUTPUT_DIR"] = "gs://machine-le... | _____no_output_____ | Apache-2.0 | machine_learning/gan/cdcgan/tf_cdcgan/tf_cdcgan_run_module_local.ipynb | ryangillard/artificial_intelligence |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.