I'm developing a FastAPI application which uses sci-kit learn to generate some SVG files which are saved locally before being uploaded to AWS-S3 for permanent storage. However, once deployed on Heroku I realised it doesn't allow for writing to local storage.
An example of how these files are generated:
from sklearn.tree import DecisionTreeClassifier, plot_tree
import matplotlib.pyplot as plt
fig = plt.figure()
decision_tree = plot_tree(
pruned_clf_dt, # a decision tree made by sklearn
filled=True,
rounded=True,
class_names= classNames,
feature_names=X.columns)
fig.savefig("example.svg", bbox_inches='tight')
Is it possible to do fig.savefig
(into a variable) to save the SVG in memory or somehow save the plotted tree as an SVG into AWS-S3?
Answer is yes it's possible by using StringIO, though S3 requires the object to be in a string(?) like format eg:
import io
from sklearn.tree import DecisionTreeClassifier, plot_tree
import matplotlib.pyplot as plt
fig = plt.figure()
decision_tree = plot_tree(
pruned_clf_dt,
filled=True,
rounded=True,
class_names= classNames,
feature_names=X.columns)
s = io.StringIO()
fig.savefig(s, format = 'svg', bbox_inches='tight')
svg = s.getvalue()
name = "filename.svg"
s3bucket.put_object(
Key=name,
Body=svg,
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.