Coursera-Deep Learning専門コース(4):畳み込みニューラルネットワーク:-weak4プログラミングの割り当て

顔認識

幸せな家のための顔認識

from keras.models import Sequential
from keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate
from keras.models import Model
from keras.layers.normalization import BatchNormalization
from keras.layers.pooling import MaxPooling2D, AveragePooling2D
from keras.layers.merge import Concatenate
from keras.layers.core import Lambda, Flatten, Dense
from keras.initializers import glorot_uniform
from keras.engine.topology import Layer
from keras import backend as K
K.set_image_data_format('channels_first')
import cv2
import os
import numpy as np
from numpy import genfromtxt
import pandas as pd
import tensorflow as tf
from fr_utils import *
from inception_blocks_v2 import *

%matplotlib inline
%load_ext autoreload
%autoreload 2

np.set_printoptions(threshold=np.nan)

0-素朴な顔の検証

顔認証では、2つの画像が与えられ、それらが同じ人物であるかどうかを通知する必要があります。これを行う最も簡単な方法は、2つの画像をピクセルごとに比較することです。生の画像間の距離が選択したしきい値よりも小さい場合、同じ人物である可能性があります。
ここに写真の説明を書きます

1-顔画像を128次元ベクトルにエンコードする

1.1-ConvNetを使用してエンコーディングを計算する

FaceNetモデルのトレーニングには、大量のデータと長い時間がかかります。したがって、適用されるディープラーニング設定の一般的なプラクティスに従って、他の誰かがすでにトレーニングしたウェイトをロードしてみましょう。ネットワークアーキテクチャは、SzegedyらのInceptionモデルに従います。Inceptionネットワークの実装を提供しました。ファイルinception_blocks.pyを見て、それがどのように実装されているかを確認できます(Jupyterノートブックの上部にある[File-> Open…]に移動してください)。

FRmodel = faceRecoModel(input_shape=(3, 96, 96))
print("Total Params:", FRmodel.count_params())

合計パラメーター:3743280
128ニューロンの完全に接続されたレイヤーを最後のレイヤーとして使用することにより、モデルは出力がサイズ128のエンコーディングベクトルであることを保証します。次に、次のように2つの顔画像を比較するエンコーディングを使用します。
ここに写真の説明を書きます
つまり、エンコーディングは良いものであれば:
同じ人の2枚の画像のエンコーディングお互いに非常に似ている
別の人物の2枚の画像のエンコードは非常に異なっている
トリプレット損失関数はこれを定式化し、「プッシュ」しようとするの2枚の画像のエンコーディング同じ人物(アンカーとポジティブ)を互いに近づける一方で、異なる人物(アンカー、ネガティブ)の2つの画像のエンコーディングをさらに引き離します。
ここに写真の説明を書きます

1.2-トリプレットの損失

# GRADED FUNCTION: triplet_loss

def triplet_loss(y_true, y_pred, alpha = 0.2):
    """
    Implementation of the triplet loss as defined by formula (3)

    Arguments:
    y_true -- true labels, required when you define a loss in Keras, you don't need it in this function.
    y_pred -- python list containing three objects:
            anchor -- the encodings for the anchor images, of shape (None, 128)
            positive -- the encodings for the positive images, of shape (None, 128)
            negative -- the encodings for the negative images, of shape (None, 128)

    Returns:
    loss -- real number, value of the loss
    """

    anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]

    ### START CODE HERE ### (≈ 4 lines)
    # Step 1: Compute the (encoding) distance between the anchor and the positive
    pos_dist = tf.reduce_sum(tf.square(tf.subtract(y_pred[0],y_pred[1])))
    # Step 2: Compute the (encoding) distance between the anchor and the negative
    neg_dist = tf.reduce_sum(tf.square(tf.subtract(y_pred[0],y_pred[2])))
    # Step 3: subtract the two previous distances and add alpha.
    basic_loss = tf.add(tf.subtract(pos_dist,neg_dist),alpha)
    # Step 4: Take the maximum of basic_loss and 0.0. Sum over the training examples.
    loss = tf.reduce_sum(tf.maximum(basic_loss,0.0))
    ### END CODE HERE ###

    return loss
with tf.Session() as test:
    tf.set_random_seed(1)
    y_true = (None, None, None)
    y_pred = (tf.random_normal([3, 128], mean=6, stddev=0.1, seed = 1),
              tf.random_normal([3, 128], mean=1, stddev=1, seed = 1),
              tf.random_normal([3, 128], mean=3, stddev=4, seed = 1))
    loss = triplet_loss(y_true, y_pred)

    print("loss = " + str(loss.eval()))

損失= 350.026

2-トレーニング済みモデルのロード

FRmodel.compile(optimizer = 'adam', loss = triplet_loss, metrics = ['accuracy'])
load_weights_from_FaceNet(FRmodel)

ここに写真の説明を書きます

3-モデルの適用

ハッピーハウスに戻る!以前の課題で家の幸福認識を実装したため、居住者は幸福に暮らしています。
しかし、いくつかの問題が浮上しています。ハッピーハウスはとても幸せになり、近所の幸せな人は皆あなたのリビングルームにたむろしに来ています。それは本当に混雑し始めており、それは家の居住者に悪影響を及ぼしています。これらすべてのランダムな幸せな人々もあなたの食べ物をすべて食べています。
したがって、ドアの入り口のポリシーを変更することを決定し、たとえ幸せであるとしても、ランダムな幸せな人々がもう入るのを許可するだけではありません!代わりに、指定されたリストの人だけが入るように顔認証システムを構築したいと思います。入場するには、各人がIDカード(IDカード)をスワイプしてドアで自分を識別する必要があります。次に、顔認識システムは、彼らが本人であると主張している人物であることを確認します。

3.1-顔認証

database = {}
database["danielle"] = img_to_encoding("images/danielle.png", FRmodel)
database["younes"] = img_to_encoding("images/younes.jpg", FRmodel)
database["tian"] = img_to_encoding("images/tian.jpg", FRmodel)
database["andrew"] = img_to_encoding("images/andrew.jpg", FRmodel)
database["kian"] = img_to_encoding("images/kian.jpg", FRmodel)
database["dan"] = img_to_encoding("images/dan.jpg", FRmodel)
database["sebastiano"] = img_to_encoding("images/sebastiano.jpg", FRmodel)
database["bertrand"] = img_to_encoding("images/bertrand.jpg", FRmodel)
database["kevin"] = img_to_encoding("images/kevin.jpg", FRmodel)
database["felix"] = img_to_encoding("images/felix.jpg", FRmodel)
database["benoit"] = img_to_encoding("images/benoit.jpg", FRmodel)
database["arnaud"] = img_to_encoding("images/arnaud.jpg", FRmodel)
# GRADED FUNCTION: verify

def verify(image_path, identity, database, model):
    """
    Function that verifies if the person on the "image_path" image is "identity".

    Arguments:
    image_path -- path to an image
    identity -- string, name of the person you'd like to verify the identity. Has to be a resident of the Happy house.
    database -- python dictionary mapping names of allowed people's names (strings) to their encodings (vectors).
    model -- your Inception model instance in Keras

    Returns:
    dist -- distance between the image_path and the image of "identity" in the database.
    door_open -- True, if the door should open. False otherwise.
    """

    ### START CODE HERE ###

    # Step 1: Compute the encoding for the image. Use img_to_encoding() see example above. (≈ 1 line)
    encoding = img_to_encoding(image_path,model)

    # Step 2: Compute distance with identity's image (≈ 1 line)
    dist = np.linalg.norm(encoding-database[identity])

    # Step 3: Open the door if dist < 0.7, else don't open (≈ 3 lines)
    if dist<0.7:
        print("It's " + str(identity) + ", welcome home!")
        door_open = True
    else:
        print("It's not " + str(identity) + ", please go away")
        door_open = False

    ### END CODE HERE ###

    return dist, door_open
verify("images/camera_0.jpg", "younes", database, FRmodel)

3.2-顔認識

あなたの顔認証システムはほとんど正常に機能しています。しかし、キアンはIDカードを盗まれたため、その夜家に戻ったときは入店できませんでした。
このような不快感を減らすには、顔認証システムを顔認識システムに変更します。これにより、IDカードを携帯する必要がなくなりました。許可された人は家まで歩くことができ、正面玄関がロック解除されます!
入力として画像を受け取り、それが許可された人物の1人であるかどうか(そうであれば、誰であるか)を判別する顔認識システムを実装します。以前の顔認証システムとは異なり、別の入力として人物の名前を取得することはありません。
演習:who_is_it()を実装してください。次の手順を実行する必要があります。
image_pathから画像のターゲットエンコーディングを計算し
ます。ターゲットエンコーディングとの距離が最も短いデータベースからエンコーディングを見つけます。
min_dist変数を十分に大きな数(100)に初期化します。入力のエンコーディングに最も近いエンコーディングを追跡するのに役立ちます。
データベース辞書の名前とエンコーディングをループします。database.items()でfor(name、db_enc)をループ使用します。
ターゲットの「エンコーディング」とデータベースから現在の「エンコーディング」の間のL2距離を計算します。
この距離がmin_distより小さい場合は、min_distをdistに、identityをnameに設定します。

# GRADED FUNCTION: who_is_it

def who_is_it(image_path, database, model):
    """
    Implements face recognition for the happy house by finding who is the person on the image_path image.

    Arguments:
    image_path -- path to an image
    database -- database containing image encodings along with the name of the person on the image
    model -- your Inception model instance in Keras

    Returns:
    min_dist -- the minimum distance between image_path encoding and the encodings from the database
    identity -- string, the name prediction for the person on image_path
    """

    ### START CODE HERE ### 

    ## Step 1: Compute the target "encoding" for the image. Use img_to_encoding() see example above. ## (≈ 1 line)
    encoding = img_to_encoding(image_path,model)

    ## Step 2: Find the closest encoding ##

    # Initialize "min_dist" to a large value, say 100 (≈1 line)
    min_dist = 100

    # Loop over the database dictionary's names and encodings.
    for (name, db_enc) in database.items():

        # Compute L2 distance between the target "encoding" and the current "emb" from the database. (≈ 1 line)
        dist = np.linalg.norm(encoding-db_enc)

        # If this distance is less than the min_dist, then set min_dist to dist, and identity to name. (≈ 3 lines)
        if dist<min_dist:
            min_dist = dist
            identity = name

    ### END CODE HERE ###

    if min_dist > 0.7:
        print("Not in the database.")
    else:
        print ("it's " + str(identity) + ", the distance is " + str(min_dist))

    return min_dist, identity
who_is_it("images/camera_0.jpg", database, FRmodel)

深層学習とアート:ニューラルスタイルの転送

今週の第2課題へようこそ。この課題では、ニューラルスタイルの転送について学習します。このアルゴリズムは、Gatysらによって作成されました。(2015)(https://arxiv.org/abs/1508.06576)。
この割り当てでは、次のことを行います。
ニューラルスタイルの転送アルゴリズム
実装するアルゴリズムを使用して新しい芸術的な画像を生成
するこれまでに研究したアルゴリズムのほとんどは、コスト関数を最適化してパラメーター値のセットを取得します。ニューラルスタイル転送では、コスト関数を最適化してピクセル値を取得します。

import os
import sys
import scipy.io
import scipy.misc
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
from PIL import Image
from nst_utils import *
import numpy as np
import tensorflow as tf

%matplotlib inline

1-問題の説明

ニューラルスタイル転送(NST)は、ディープラーニングで最も楽しいテクニックの1つです。以下に示すように、「コンテンツ」画像(C)と「スタイル」画像(S)の2つの画像をマージして、「生成」画像(G)を作成します。生成された画像Gは、画像Cの「コンテンツ」と画像Sの「スタイル」を組み合わせたものです。
この例では、パリのルーブル美術館の画像(コンテンツ画像C)を生成し、印象派運動のリーダー、クロード・モネ(スタイル画像S)。
ここに写真の説明を書きます

2-転移学習

ニューラルスタイル転送(NST)は、以前にトレーニングされたたたみ込みネットワークを使用し、その上に構築されます。別のタスクでトレーニングされたネットワークを使用し、それを新しいタスクに適用するアイデアは、転移学習と呼ばれます。
元のNSTペーパー(https://arxiv.org/abs/1508.06576)に従って、VGGネットワ​​ークを使用します。具体的には、VGGネットワ​​ークの19レイヤーバージョンであるVGG-19を使用します。このモデルはすでに非常に大規模なImageNetデータベースでトレーニングされており、さまざまな低レベル機能(初期のレイヤー)と高レベル機能(より深いレイヤー)を認識することを学びました。
次のコードを実行して、VGGモデルからパラメーターを読み込みます。これには数秒かかる場合があります。

3-ニューラルスタイルの転送

3.1-コンテンツコストの計算

content_image = scipy.misc.imread("images/louvre.jpg")
imshow(content_image)

ここに写真の説明を書きます

ここに写真の説明を書きます


# GRADED FUNCTION: compute_content_cost

def compute_content_cost(a_C, a_G):
    """
    Computes the content cost

    Arguments:
    a_C -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image C 
    a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image G

    Returns: 
    J_content -- scalar that you compute using equation 1 above.
    """

    ### START CODE HERE ###
    # Retrieve dimensions from a_G (≈1 line)
    m, n_H, n_W, n_C = a_G.get_shape().as_list()

    # Reshape a_C and a_G (≈2 lines)
    a_C_unrolled = tf.reshape(a_C,shape=(n_H* n_W,n_C))
    a_G_unrolled = tf.reshape(a_G,shape=(n_H* n_W,n_C))

    # compute the cost with tensorflow (≈1 line)
    J_content = tf.reduce_sum(tf.square(tf.subtract(a_C_unrolled,a_G_unrolled)))/(4*n_H*n_W*n_C)
    ### END CODE HERE ###

    return J_content
tf.reset_default_graph()

with tf.Session() as test:
    tf.set_random_seed(1)
    a_C = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4)
    a_G = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4)
    J_content = compute_content_cost(a_C, a_G)
    print("J_content = " + str(J_content.eval()))

J_content = 6.76559

3.2-スタイルコストの計算

3.2.1-スタイルマトリックス

ここに写真の説明を書きます

# GRADED FUNCTION: gram_matrix

def gram_matrix(A):
    """
    Argument:
    A -- matrix of shape (n_C, n_H*n_W)

    Returns:
    GA -- Gram matrix of A, of shape (n_C, n_C)
    """

    ### START CODE HERE ### (≈1 line)
    GA = tf.matmul(A,tf.transpose(A))
    ### END CODE HERE ###

    return GA
tf.reset_default_graph()

with tf.Session() as test:
    tf.set_random_seed(1)
    A = tf.random_normal([3, 2*1], mean=1, stddev=4)
    GA = gram_matrix(A)

    print("GA = " + str(GA.eval()))

GA = [[ 6.42230511 -4.42912197 -2.09668207]
[ -4.42912197 19.46583748 19.56387138]
[ -2.09668207 19.56387138 20.6864624 ]]

3.2.2-スタイルコスト

# GRADED FUNCTION: compute_layer_style_cost

def compute_layer_style_cost(a_S, a_G):
    """
    Arguments:
    a_S -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image S 
    a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image G

    Returns: 
    J_style_layer -- tensor representing a scalar value, style cost defined above by equation (2)
    """

    ### START CODE HERE ###
    # Retrieve dimensions from a_G (≈1 line)
    m, n_H, n_W, n_C =  a_G.get_shape().as_list()

    # Reshape the images to have them of shape (n_C, n_H*n_W) (≈2 lines)
    a_S = tf.reshape(a_S,shape=(n_H*n_W,n_C))
    a_G = tf.reshape(a_G,shape=(n_H*n_W,n_C))

    # Computing gram_matrices for both images S and G (≈2 lines)
    GS = gram_matrix(tf.transpose(a_S))
    GG = gram_matrix(tf.transpose(a_G))

    # Computing the loss (≈1 line)
    J_style_layer = tf.reduce_sum(tf.square(tf.subtract(GS,GG)))/(4*(n_C*n_C)*(n_W * n_H) * (n_W * n_H))

    ### END CODE HERE ###

    return J_style_layer
tf.reset_default_graph()

with tf.Session() as test:
    tf.set_random_seed(1)
    a_S = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4)
    a_G = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4)
    J_style_layer = compute_layer_style_cost(a_S, a_G)

    print("J_style_layer = " + str(J_style_layer.eval()))

J_style_layer = 9.19028

3.2.3スタイルの重み

def compute_style_cost(model, STYLE_LAYERS):
    """
    Computes the overall style cost from several chosen layers

    Arguments:
    model -- our tensorflow model
    STYLE_LAYERS -- A python list containing:
                        - the names of the layers we would like to extract style from
                        - a coefficient for each of them

    Returns: 
    J_style -- tensor representing a scalar value, style cost defined above by equation (2)
    """

    # initialize the overall style cost
    J_style = 0

    for layer_name, coeff in STYLE_LAYERS:

        # Select the output tensor of the currently selected layer
        out = model[layer_name]

        # Set a_S to be the hidden layer activation from the layer we have selected, by running the session on out
        a_S = sess.run(out)

        # Set a_G to be the hidden layer activation from same layer. Here, a_G references model[layer_name] 
        # and isn't evaluated yet. Later in the code, we'll assign the image G as the model input, so that
        # when we run the session, this will be the activations drawn from the appropriate layer, with G as input.
        a_G = out

        # Compute style_cost for the current layer
        J_style_layer = compute_layer_style_cost(a_S, a_G)

        # Add coeff * J_style_layer of this layer to overall style cost
        J_style += coeff * J_style_layer

    return J_style

3.3-最適化するための総コストの定義

# GRADED FUNCTION: total_cost

def total_cost(J_content, J_style, alpha = 10, beta = 40):
    """
    Computes the total cost function

    Arguments:
    J_content -- content cost coded above
    J_style -- style cost coded above
    alpha -- hyperparameter weighting the importance of the content cost
    beta -- hyperparameter weighting the importance of the style cost

    Returns:
    J -- total cost as defined by the formula above.
    """

    ### START CODE HERE ### (≈1 line)
    J = alpha*J_content+beta*J_style
    ### END CODE HERE ###

    return J
tf.reset_default_graph()

with tf.Session() as test:
    np.random.seed(3)
    J_content = np.random.randn()    
    J_style = np.random.randn()
    J = total_cost(J_content, J_style)
    print("J = " + str(J))

4-最適化問題の解決

J = total_cost(J_content,J_style,10,40)
# define optimizer (1 line)
optimizer = tf.train.AdamOptimizer(2.0)

# define train_step (1 line)
train_step = optimizer.minimize(J)
def model_nn(sess, input_image, num_iterations = 200):

    # Initialize global variables (you need to run the session on the initializer)
    ### START CODE HERE ### (1 line)
    sess.run(tf.global_variables_initializer())
    ### END CODE HERE ###

    # Run the noisy input image (initial generated image) through the model. Use assign().
    ### START CODE HERE ### (1 line)
    generated_image=sess.run(model['input'].assign(input_image))
    ### END CODE HERE ###

    for i in range(num_iterations):

        # Run the session on the train_step to minimize the total cost
        ### START CODE HERE ### (1 line)
        sess.run(train_step)
        ### END CODE HERE ###

        # Compute the generated image by running the session on the current model['input']
        ### START CODE HERE ### (1 line)
        generated_image=sess.run(model['input'])
        ### END CODE HERE ###

        # Print every 20 iteration.
        if i%20 == 0:
            Jt, Jc, Js = sess.run([J, J_content, J_style])
            print("Iteration " + str(i) + " :")
            print("total cost = " + str(Jt))
            print("content cost = " + str(Jc))
            print("style cost = " + str(Js))

            # save current generated image in the "/output" directory
            save_image("output/" + str(i) + ".png", generated_image)

    # save last generated image
    save_image('output/generated_image.jpg', generated_image)

    return generated_image

20反復後の画像:
ここに写真の説明を書きます
180反復後の画像
ここに写真の説明を書きます
:200反復後の画像
ここに写真の説明を書きます
ここに写真の説明を書きます

元の記事を34件公開 賞賛された4件 30,000回以上の閲覧

おすすめ

転載: blog.csdn.net/leaeason/article/details/78535946