This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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', |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
NewerOlder