Skip to content

Instantly share code, notes, and snippets.

View ksivaman's full-sized avatar

Kirthi Shankar Sivamani ksivaman

View GitHub Profile
@ksivaman
ksivaman / modify.py
Created August 9, 2019 23:53
Loop for modifying target image for neural style transfer
for ii in range(1, steps+1):
# get the features from your target image
target_features = get_features(target, vgg)
# the content loss
content_loss = torch.mean((target_features['conv4_2'] - content_features['conv4_2'])**2)
# the style loss
# initialize the style loss to 0
@ksivaman
ksivaman / hyperparams.py
Created August 9, 2019 23:47
Set features and hyperparams for neural style transfer.
# get content and style features only once before training
content_features = get_features(content, vgg)
style_features = get_features(style, vgg)
# calculate the gram matrices for each layer of our style representation
style_grams = {layer: gram_matrix(style_features[layer]) for layer in style_features}
#initialize the target image as the content image
target = content.clone().requires_grad_(True).to(device)
@ksivaman
ksivaman / gram.py
Last active August 9, 2019 23:44
Gram matrix calculator for neural style transfer
def gram_matrix(tensor):
# get the batch_size, depth, height, and width of the Tensor
_, d, h, w = tensor.size()
# reshape so we're multiplying the features for each channel
tensor = tensor.view(d, h * w)
# calculate the gram matrix
gram = torch.mm(tensor, tensor.t())
@ksivaman
ksivaman / gram.py
Created August 9, 2019 23:42
Gram matrix calculator for neural style transfer
def gram_matrix(tensor):
# get the batch_size, depth, height, and width of the Tensor
_, d, h, w = tensor.size()
# reshape so we're multiplying the features for each channel
tensor = tensor.view(d, h * w)
# calculate the gram matrix
gram = torch.mm(tensor, tensor.t())
@ksivaman
ksivaman / get_features.py
Created August 9, 2019 23:36
extract features from the vgg19 network
def get_features(image, model, layers=None):
""" Run an image forward through a model and get the features for
a set of layers. Default layers are for VGGNet matching Gatys et al (2016)
"""
## Need the layers for the content and style representations of an image
if layers is None:
layers = {'0': 'conv1_1',
'5': 'conv2_1',
'10': 'conv3_1',
@ksivaman
ksivaman / pretrained_model.py
Created August 9, 2019 23:31
initialize pretrained model for neural style transfer
vgg = models.vgg19(pretrained=True).features
# freeze VGG params to avoid chanhe
for param in vgg.parameters():
param.requires_grad_(False)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
vgg.to(device)
@ksivaman
ksivaman / imports.py
Created August 9, 2019 23:29
imports for neural style transfer
from PIL import Image
from io import BytesIO
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import time
import torch
import torch.optim as optim
import requests
@ksivaman
ksivaman / train.py
Created July 14, 2019 00:17
Training loop for a simple feed forward neural network.
def train(train_X, train_Y, epochs, lr, layers=[4, 5, 1], activate=['R', 'S']):
# initiation of neural netowrk parameters
params_w, params_b = init(layers)
losses = []
accuracies = []
# performing calculations for subsequent iterations
for i in range(epochs):
# step forward
@ksivaman
ksivaman / update_params.py
Created July 13, 2019 23:57
A function to update weights and biases for a feed forward neural network.
def param_updates(params_w, params_b, gradients, lr, layers=[4, 5, 1]):
for index in range(len(layers) - 1):
#gradient descent
params_w["weight" + str(index + 1)] -= lr * gradients["d_weight" + str(index + 1)]
params_b["bias" + str(index + 1)] -= lr * gradients["d_bias" + str(index + 1)]
return params_w, params_b
@ksivaman
ksivaman / loss_and_accuracy.py
Created July 13, 2019 23:47
Utils for binary classification in a feed forward neural net.
#binary cross entropy loss
def cross_entropy_loss(y_pred, train_Y):
num_samples = y_pred.shape[1]
cost = -1 / num_samples * (np.dot(train_Y, np.log(y_pred).T) + np.dot(1 - train_Y, np.log(1 - y_pred).T))
return np.squeeze(cost)
#convert probabilities to class prediction with threshold 0.5
def get_class_from_probs(probabilities):
class_ = np.copy(probabilities)
class_[class_ > 0.5] = 1