Connectivity
Python
Deep Learning with TensorFlowTM
FileTools
XMLTools
Additional Updates
Maple 2018 is now packaged with a Python 3.6 kernel.
The Python kernel is linked to Maple. This means you can execute Python scripts, and return results to Maple.
Everyone who installs Maple will also have access to a Python interpreter with a selection of useful Python libraries. In Maple, with(Python); loads a small set of tools to help execute commands, inspect variables, and interact with Python.
withPython;
EvalFunction,EvalMember,EvalString,GetVariable,ImportModule,None,SetVariable,Start,Stop
Arbitrary strings can be parsed and evaluated:
EvalString1+1;
2
EvalString7 ^ 15;
8
EvalString7 ** 15;
4747561509943
EvalString15 // 2 ;
7
Here's a slightly longer string to parse and evaluate after importing the "statistics" package:
ImportModulestatistics;
EvalString⁡statistics.median_grouped([1, 3, 3, 5, 7], interval=2)
3.50000000000000
Evaluating as a string is easy and flexible, but you can go even further and make Python functions look like native Maple functions:
mg ≔ EvalStringstatistics.median_grouped;
mg≔<Python object: <function median_grouped at 0x000000000AC490D0>>
mg1,3,3,5,7, interval=2;
ImportModulemath;
pysin ≔ EvalStringmath.sin;
pysin≔<Python object: <built-in function sin>>
pysin1.0;
0.841470984807897
Module :- member notation can be used to class methods:
pymath ≔ EvalStringmath;
pymath≔<Python object: <module 'math' (built-in)>>
pymath:-cos1.0;
0.540302305868140
pymath:-acos1.0;
0.
pymath:-sqrt2;
1.41421356237310
Here is a more involved example that uses a Python package for HTML parsing and manipulation.
ImportModule⁡from bs4 import BeautifulSoup
htmldoc≔<html><body><h1>Great Novels</h1><ul><li><a href=\"http://MiguelDeCervantes.com\">Don Quixote</a><li><a href=\"http://FyodorDostoevsky.com\">Crime and Punishment</a><li><a href=\"http://AlexandreDumas.com\">The Count of Monte Cristo</a></ul></body></html>:
soup≔EvalFunctionBeautifulSoup,htmldoc,html.parser:
soup:-h1:-string
Great Novels
seq⁡link:-text,link in soup:-find_alla
Don Quixote,Crime and Punishment,The Count of Monte Cristo
New procedures can be defined from Maple:
EvalString⁡def mysum(a,b): return a+b,output=none
pysum ≔ GetVariablemysum;
pysum≔<Python object: <function mysum at 0x000000000A683E18>>
pysum1,1;
Options are available to control how results come back to Maple. Above we see 'output'='none' to prevent any result from coming back. Next, we'll use 'output' = 'python' to avoid converting back to a Maple object; and instead capture an object reference, in this case to an empty string. This allows us access to Python string methods in the result.
emptystring≔EvalString⁡'',output=python
emptystring≔<Python object: >
emptystring:-join⁡a,b,c
abc
The Python process is in a separate memory space than Maple, and can be stopped and restarted at any time.
EvalStringa=1\nb=2\nc=3:
GetVariablea, GetVariableb, GetVariablec;
1,2,3
Stop;
true
Error, (in Python:-GetVariable) name 'a' is not defined
EvalString2+2;
4
For more, see Python.
Maple 2018 includes a new package, DeepLearning, which offers an limited API to the TensorFlow toolset for machine learning using neural networks.
Example: Fitting a Curve
Here we perform least-squares regression to fit a Fourier series to a set of sample data given by:
restart: Points ≔ 0.2.11.−1.52.−3.13.6.34.8.25.11.56.12.77.8.4:
The general formula for a Fourier series with 2 N+1 terms and coefficients c,a__1,...,a__N,b__1,...,b__N is given by:
F≔x,a,b,c,N→c + addan cosn x + bn sinn x,n=1..N
x,a,b,c,N↦c+add⁡an⁢cos⁡n⁢x+bn⁢sin⁡n⁢x,n=1..N
For this example we take N=4:N ≔ 4
We first declare a sequence of variables in the deep learning graph corresponding to each an and bn:
withDeepLearning:
SetEagerExecutionfalse
a ≔ Array1..N,i→Variable0.5, datatype=float4:
b ≔ Array1..N,i→Variable0.5, datatype=float4:
c ≔ Variable0.5, datatype=float4:
We can now define placeholders to hold the sample x- and y-values against which we want to fit Fx,a,b,N:
x ≔ Placeholder float4
DeepLearning TensorName: Placeholder:0Shape: undefinedData Type: float[4]
y ≔ Placeholder float4
y≔DeepLearning TensorName: Placeholder_1:0Shape: undefinedData Type: float[4]
We can now define a least-squares distance function which we aim to minimize:
loss ≔ReduceSumFx,a,b,c,N− y2
loss≔DeepLearning TensorName: Sum:0Shape: undefinedData Type: float[4]
optimizer ≔ OptimizerGradientDescent0.01;
optimizer≔DeepLearning Optimizer<tensorflow.python.training.gradient_descent.GradientDescentOptimizer object at 0x000000001D427E80>
train ≔ optimizer:-Minimizeloss;
train≔DeepLearning TensorName: GradientDescentShape: undefinedData Type: undefined
With the structure of our deep learning graph defined, we can proceed to train it on sample data. After initializing the session, we run 1000 training cycles using the training data.
x__training ≔ convertPoints..,1,list
0.,1.,2.,3.,4.,5.,6.,7.
y__training ≔ convertPoints..,2,list
2.1,−1.5,−3.1,6.3,8.2,11.5,12.7,8.4
init ≔VariablesInitializer:
sess ≔ Session
sess≔DeepLearning Session<tensorflow.python.client.session.Session object at 0x000000001D427A90>
sess:-Runinit:
for i to 1000 do sess:-Run train, x in x__training, y in y__training :end do:
We can now query the state of the trained model for the present value of the loss function:
sess:-Runloss,x in x__training, y in y__training
0.000535954604856670
As this is a small value, we have a close fit for the data. We can then obtain the final value of the parameters from the trained model.
result≔ sess:-RunConcatenatea,0,Concatenateb,0,c,x in x__training, y in y__training
2.085738658905038.18983650207520−2.98846912384033−10.7947034835815,−8.44673156738281−8.051170349121091.606977939605710.845224976539612,5.61942768096924
A,B,C ≔ result1,result2,result3
A,B,C≔2.085738658905038.18983650207520−2.98846912384033−10.7947034835815,−8.44673156738281−8.051170349121091.606977939605710.845224976539612,5.61942768096924
Finally, we can visualize the result: withplots:
Example: Classification
Here we use a deep neural network to classify the famous Iris flower data set collected by Edgar Anderson and made famous by Ronald Fisher. This data set includes 150 distinct observations of iris flowers, each of which consists of four empirical observations (sepal length, sepal width, petal length, and petal width) along with a classification into one of three known species (I. setosa, I. versicolor, and I. virginica).
We will repeat here the classical task for which this data set is used: attempting prediction of the species based on the four measured quantities
Training and Test Data We have divided the data in into training and test data: the former is used to build the model, the latter is used to test its predictive accuracy.
training_data ≔ Importexample/iris_training.csv,base=datadir;test_data ≔ Importexample/iris_test.csv, base=datadir;
test_data≔SepalLengthSepalWidthPetalLengthPetalWidthSpecies16.43.24.51.5versicolor27.135.92.1virginica35.24.11.50.1setosa47.736.12.3virginica57.73.86.72.2virginica66.12.65.61.4virginica753.51.30.3setosa85.62.74.21.3versicolor………………
We see that this data set has 150 samples (120 for training and 30 for testing) and that the Species column has three distinct species: NumRowstest_data, NumRowstraining_data
30,120
converttest_dataSpecies,set union converttraining_dataSpecies,set
setosa,versicolor,virginica
To simplify things we will replace the strings designating the species classification with the numbers 0,1,2 (corresponding to setosa, versicolor, and virginica, respectively):
training_set ≔ mapeval,training_data,setosa=0,versicolor=1,virginica=2;
training_set≔SepalLengthSepalWidthPetalLengthPetalWidthSpecies162.241125.43.91.30.4035.634.11.3146.43.15.51.8254.431.30.2064.83.41.60.2075.43.91.70.40853.21.20.20………………
test_set ≔ mapeval,test_data,setosa=0,versicolor=1,virginica=2;
test_set≔SepalLengthSepalWidthPetalLengthPetalWidthSpecies16.43.24.51.5127.135.92.1235.24.11.50.1047.736.12.3257.73.86.72.2266.12.65.61.42753.51.30.3085.62.74.21.31………………
Training the Deep Neural Network Model
With our data prepared, we can now actually define and train the model.
Our first step is to define a feature for each of the four observed quantities in the test data minus the final one (species) which we aim to predict:
cols ≔ ColumnLabelstest_set
cols≔SepalLength,SepalWidth,PetalLength,PetalWidth,Species
fc ≔ map NumericColumn, cols1..4, shape=1
fc≔Feature Column_NumericColumn(key='SepalLength', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None),Feature Column_NumericColumn(key='SepalWidth', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None),Feature Column_NumericColumn(key='PetalLength', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None),Feature Column_NumericColumn(key='PetalWidth', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None)
We can now define a deep neural network classifier with these features. It has 3 classes because there are 3 species of iris in the dataset.
classifier ≔ DNNClassifierfc, hidden_units = 10,20,10, num_classes = 3;
classifier≔DeepLearning Estimator<tensorflow.python.estimator.canned.dnn.DNNClassifier object at 0x000000005536D2B0>
We are now ready to train the model.
classifier:-Train training_set1..4, training_set5, steps=2000, num_epochs=none, shuffle=true
DeepLearning TensorName: noneShape: undefinedData Type: undefined
Now trained, we can evaluate the classifier on the test set, and we see that we have achieved 96.7% predictive accuracy:
results ≔ classifier:-Evaluate test_set1..4, test_set5, shuffle=false, num_epochs=1
We can now build a predictor function that takes an arbitrary set of measurements as a DataSeries and returns a prediction:
predictor ≔ procds classifier:-PredictTransposeDataFrameds, num_epochs=1, shuffle=false1 end proc:
Using a Trained Model
With this we can take an arbitrary new point, and generate a prediction from the trained model:
ds ≔ DataSeries5.8, 3.1, 5.0, 1.7,labels=cols1..4
ds≔SepalLength5.8SepalWidth3.1PetalLength5.0PetalWidth1.7
predictords
logits−8.940464973449710.8610070347785954.63907480239868probabilities1.23782979244424⁢10−60.02235560119152070.977643132209778class_ids2classes<Python object: b'2'>
The probabilities field in the above result records the estimated probabilities for each class.
In this case, the model predicts with high probability that this particular sample is class 2, and therefore I. virginica.
The CanonicalPath command resolves any relative directories and symbolic links present in a given file path to construct a canonical version of this path.
with⁡FileTools:
CanonicalPath⁡C:\\Users\\MapleUser\\..
C:\Users
The IsLink command tests whether a given file path corresponds to a symbolic link.
IsLink⁡/usr/local/bin/perl
ToRecord formats an XML tree as a nested record
with⁡XMLTools:
This example shows how repeated elements are put into a list, and the order they occurred can be deduced from the _order export.
xml≔ParseString⁡<doc><a>1</a><b>2</b><a>3</a></doc>:
r≔ToRecord⁡xml:
Print⁡r
<doc> <a>1</a> <b>2</b> <a>3</a></doc>
r:-doc:-a1
1
r:-doc:-b
r:-doc:-a2
3
r:-doc:-_order
a,b,a
The new MapleTA:-QTI command converts IMS Question & Test Interoperability (QTI) files into Maple T.A./Möbius course module.
OpenMaple enhances Java connectivity with several new commands, including toBigDecimal, toBigInteger, Relation, evalBoolean, lhs and set.
Download Help Document