ARB Security Solutions, LLC.

Pytorch To Train An ML Model, Upload to SPO

This script trains a simple PyTorch model (in this case, a linear regression model) and saves it to a file using torch.save(). It then uses the Office365 and Site classes from the shareplum library to authenticate and connect to SharePoint Online. The upload_to_sharepoint() function uploads the model file to the specified target folder in the SharePoint Online document library.

import os
import torch
from shareplum import Site
from shareplum import Office365
import requests

# SharePoint Online credentials and site information
username = 'your_username'
password = 'your_password'
site_url = 'https://your_sharepoint_site_url'
document_library = 'Documents'

# Training a PyTorch model
def train_model():
# Define your model and training code here
# For simplicity, let's assume we have a basic model and training loop
model = torch.nn.Linear(10, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
criterion = torch.nn.MSELoss()

for epoch in range(10):
# Training code goes here
pass

return model

# Save the trained model
def save_model(model, filename):
torch.save(model.state_dict(), filename)

# Upload the model file to SharePoint Online
def upload_to_sharepoint(filename, target_folder):
with Office365(site_url, username=username, password=password) as auth:
site = Site(site_url, auth=auth)
folder = site.Folder(f'{document_library}/{target_folder}')

with open(filename, 'rb') as file:
folder.upload_file(file, os.path.basename(filename))

print(f"Model '{os.path.basename(filename)}' uploaded to SharePoint Online.")

# Main script
if __name__ == '__main__':
# Train the model
trained_model = train_model()

# Save the model to a file
model_filename = 'trained_model.pt'
save_model(trained_model, model_filename)

# Upload the model file to SharePoint Online
target_folder = 'ML_Models'
upload_to_sharepoint(model_filename, target_folder)

Comments are closed.