Skip to content

Instantly share code, notes, and snippets.

View JacopoMangiavacchi's full-sized avatar

Jacopo Mangiavacchi JacopoMangiavacchi

View GitHub Profile
@JacopoMangiavacchi
JacopoMangiavacchi / SwiftUIDragPinchView.swift
Created July 31, 2022 22:49
SwiftUI DragGesture & MagnificationGesture
struct DragPinchView: View {
@State var currentOffset = CGSize.zero
@State var currentScale: CGFloat = 1.0
@State var gestureOffset = CGSize.zero
@State var gestureScale: CGFloat = 1.0
var body: some View {
let dragGesture = DragGesture()
.onChanged { value in gestureOffset = value.translation }
.onEnded { _ in
@JacopoMangiavacchi
JacopoMangiavacchi / vgg_perceptual_loss.py
Last active January 17, 2022 17:14 — forked from alper111/vgg_perceptual_loss.py
PyTorch implementation of VGG perceptual loss
import torch
import torchvision
class VGGPerceptualLoss(torch.nn.Module):
def __init__(self, resize=True):
super(VGGPerceptualLoss, self).__init__()
blocks = []
blocks.append(torchvision.models.vgg16(pretrained=True).features[:4].eval())
blocks.append(torchvision.models.vgg16(pretrained=True).features[4:9].eval())
blocks.append(torchvision.models.vgg16(pretrained=True).features[9:16].eval())
import Foundation
public extension String {
/**
Enables passing in negative indices to access characters
starting from the end and going backwards.
if num is negative, then it is added to the
length of the string to retrieve the true index.
*/
private func evaluateGraph(log: (String) -> Void) {
let testingSample = testDataX!.count / imageSize
let testingBatches = testingSample / batchSize
inferenceGraph = MLCInferenceGraph(graphObjects: [graph])
inferenceGraph.addInputs(["image" : inputTensor])
inferenceGraph.compile(options: [], device: device)
// TESTING LOOP FOR A FULL EPOCH ON TESTING DATA
private func execTrainingLoop(log: (String) -> Void) {
let trainingSample = trainingDataX!.count / imageSize
let trainingBatches = trainingSample / batchSize
for epoch in 0..<epochs {
var epochMatch = 0
for batch in 0..<trainingBatches {
let xData = trainingDataX!.withUnsafeBufferPointer { pointer in
MLCTensorData(immutableBytesNoCopy: pointer.baseAddress!.advanced(by: batch * imageSize * batchSize),
private func buildTrainingGraph() {
trainingGraph = MLCTrainingGraph(graphObjects: [graph],
lossLayer: MLCLossLayer(descriptor: MLCLossDescriptor(type: .softmaxCrossEntropy,
reductionType: .mean)),
optimizer: MLCAdamOptimizer(descriptor: MLCOptimizerDescriptor(learningRate: 0.001,
gradientRescale: 1.0,
regularizationType: .none,
regularizationScale: 0.0),
beta1: 0.9,
beta2: 0.999,
private func initializeTensors() {
device = MLCDevice(type: .cpu)!
inputTensor = MLCTensor(descriptor: MLCTensorDescriptor(shape: [batchSize, imageSize, 1, 1], dataType: .float32)!)
dense1WeightsTensor = MLCTensor(descriptor: MLCTensorDescriptor(shape: [1, imageSize*dense1LayerOutputSize, 1, 1], dataType: .float32)!,
randomInitializerType: .glorotUniform)
dense1BiasesTensor = MLCTensor(descriptor: MLCTensorDescriptor(shape: [1, dense1LayerOutputSize, 1, 1], dataType: .float32)!,
randomInitializerType: .glorotUniform)
dense2WeightsTensor = MLCTensor(descriptor: MLCTensorDescriptor(shape: [1, dense1LayerOutputSize*numberOfClasses, 1, 1], dataType: .float32)!,
// Load in memory and split is not performant
private func getFileLine(filePath: String, process: (String) -> Void) {
guard let filePointer:UnsafeMutablePointer<FILE> = fopen(filePath,"r") else {
preconditionFailure("Could not open file at \(filePath)")
}
defer {
fclose(filePointer)
}
private func readDataSet(fileName: String, updateStatus: @escaping (Int) -> Void) -> ([Float], [Float]) { //}(MLCTensor, MLCTensor) {
guard let filePath = Bundle.main.path(forResource: fileName, ofType: "csv") else {
fatalError("CSV file not found")
}
let serialQueue = DispatchQueue(label: "MNIST.serial.queue.\(fileName)")
var count = 0
var X = [Float]()
var Y = [Float]()
@JacopoMangiavacchi
JacopoMangiavacchi / MLCompute.swift
Last active January 15, 2021 07:14
MLCompute Playground
import Foundation
import MLCompute
import PlaygroundSupport
let page = PlaygroundPage.current
page.needsIndefiniteExecution = true
let tensor1 = MLCTensor(descriptor: MLCTensorDescriptor(shape: [6, 1], dataType: .float32)!)
let tensor2 = MLCTensor(descriptor: MLCTensorDescriptor(shape: [6, 1], dataType: .float32)!)
let tensor3 = MLCTensor(descriptor: MLCTensorDescriptor(shape: [6, 1], dataType: .float32)!)