Skip to content

Instantly share code, notes, and snippets.

import Fritz
// Fetch all of the models matching the tag
// we chose based on the machine identifier
let tagManager = ModelTagManager(tags: [tag])
// Loop through all of the models returned and download each model.
// In this case, we should only have a single model for each tag.
var allModels: [FritzMLModel] = []
tagManager.fetchManagedModelsForTags { managedModels, error in
private var machineIdentifier: String {
// Returns a machine identifier string. E.g. iPhone10,3 or iPhone7,1
// A full list of machine identifiers can be found here:
// https://gist.github.com/adamawolf/3048717
if let simulatorModelIdentifier = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] { return simulatorModelIdentifier }
var systemInfo = utsname()
uname(&systemInfo)
return withUnsafeMutablePointer(to: &systemInfo.machine) {
ptr in String(cString: UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self))
}
@jamesonthecrow
jamesonthecrow / fast_style_transfer_small.py
Last active November 27, 2018 23:38
A smaller style transfer network.
@classmethod
def build(
cls,
image_size,
alpha=1.0,
input_tensor=None,
checkpoint_file=None):
"""Build a Small Transfer Network Model using keras' functional API.
This architecture removes some blocks of layers and reduces the size
of convolutions to save on computation.
@jamesonthecrow
jamesonthecrow / fast_style_transfer_width_multiplier.py
Last active November 27, 2018 23:31
An illustration of fast artistic style transfer with a width multiplier included.
@classmethod
def build(
cls,
image_size,
alpha=1.0,
input_tensor=None,
checkpoint_file=None):
"""Build a Transfer Network Model using keras' functional API.
Args:
image_size - the size of the input and output image (H, W)
@jamesonthecrow
jamesonthecrow / trainSubredditSuggester.swift
Created November 11, 2018 03:37
Train a text classification model with CreateML to suggest subreddits based on a proposed title.
import CreateML
import Foundation
// Load our data into an MLDataTable object.
let dataFilename = "PATH/TO/data.json"
let data = try MLDataTable(contentsOf: URL(fileURLWithPath: dataFilename))
print(data.description)
/*
Columns:
label string
@jamesonthecrow
jamesonthecrow / subreddit_suggester_test_new.py
Created November 11, 2018 03:36
Test the subreddit suggester on the newest 100 posts in each subreddit.
import coremltools
# Scrape the 100 newest posts from each subreddit
max_posts = 100
posts = []
for subreddit in subreddits:
posts.extend(get_n_posts(max_posts, subreddit, sort='new'))
# Apply the same preprocessing to the data
new_df = pandas.DataFrame(posts, columns=['subreddit', 'title'])
@jamesonthecrow
jamesonthecrow / subreddit_suggester_test_custom.py
Last active November 11, 2018 03:35
Test the subreddit suggester on some custom titles.
# Test the model on some titles I wrote with specific subreddits in mind.
sample_titles = [
'Saw this good boy at the park today.',
'Latest NIPS submission from OpenAI',
'TIL you can use Core ML to suggest subreddits to users',
'I made a tutorial using CreateML AMA',
'Westworld and Game of Thrones coming to netflix',
'We park in driveways, but drive on parkways',
'From the top of Mt. Fuji, Japan',
"What's the first thing you do every morning?",
@jamesonthecrow
jamesonthecrow / subreddit_suggester_reddit_scraper.py
Created November 11, 2018 03:34
Scrape data for the subreddit suggester.
import requests
import json
def get_listing(subreddit, sort='top', after=None, limit=25):
# Set the user agent on the request so we don't get rate limited
headers = {'User-agent': 'Subreddit Title Bot'}
url_fmt = 'https://www.reddit.com/r/{subreddit}/{sort}.json'
url = url_fmt.format(subreddit=subreddit, sort=sort)
params = {'after': after, 'limit': limit, 't': 'year'}
response = requests.get(url, params=params, headers=headers)
@jamesonthecrow
jamesonthecrow / subreddit_suggester_preprocess_data.py
Created November 11, 2018 03:34
Preprocess data for the subreddit suggester.
import pandas
import re
import json
# Use pandas and regex to clean up the post titles.
df = pandas.DataFrame(posts, columns=['subreddit', 'title'])
# Remove any [tag] markers in a post title
df.title = df.title.apply(lambda x: re.sub(r'\[.*\]', '', x))
# Remove all other punctuation except spaces
df.title = df.title.apply(lambda x: re.sub(r'\W(?<![ ])', '', x))
@jamesonthecrow
jamesonthecrow / inference_subreddit_suggester.swift
Last active November 11, 2018 03:37
Incorporate the subreddit suggester into your iOS app.
// Drag your subredditClassifier.mlmodel to the Xcode project navigator.
// Use the model with the following code.
import NaturalLanguage
let subredditPredictor = try NLModel(mlModel: subredditClassifier().model)
subredditPredictor.predictedLabel(for: "TIL you can use Core ML to suggest subreddits to users.")