Code Monkey home page Code Monkey logo

machinelearningclass's Introduction


目录


准备工作

  • 开机选择第一个操作系统:LINUX

  • LINUX系统管理员密码:123456

  • 系统启动后打开左边栏FireFox火狐浏览器

  • 在上方地址编辑栏输入FTP网址:

    地址:ftp://10.105.240.91

    用户名:student

    密码:asdf1234

  • 进入编程之美目录

  • 下载实验视频资料以及相应文档


实验一、Python机器学习入门:有监督学习

实验目标

  • 了解机器学习的基本概念,了解机器学习的应用方法。

  • 通过实验掌握机器学习预测任务的基本流程。

实验器材及准备

实验器材

  • 硬件:电脑PC一台

  • 软件:Ubuntu、Anaconda3 5.0.1、Scikit-learn 0.19及其依赖包

实验准备

实验内容与步骤

Jupyter Notebook 简介

Jupyter Notebook,以前又称为IPython notebook,是一个交互式笔记本,支持运行40+种编程语言,详见介绍

打开编译环境

  1. 进入Ubuntu系统后,同时按下Ctrl+Alt+T打开终端Terminal窗口。

  2. 在终端窗口中输入以下1条命令打开Jupyter Notebook编译环境:

    jupyter notebook
  3. 键入Enter回车键后等待,浏览器会自动打开如下地址:

  4. 点击页面右上方区域按钮New->Python3

  5. exper1.txt文件中代码复制入In[]:后光标中,键入Shift+Enter运行。

  6. 代码文件exper1.txt中实现了以下步骤:

    1. 导入实验依赖模块

      #导入matplotlib绘图工具包
      import matplotlib.pyplot as plt
      # Import datasets, classifiers and performance metrics
      from sklearn import datasets, svm, metrics
    2. 载入示例数据集。载入Scikit-learn自带数据集手写数字识别集(Handwritten Digits Data Set)

      # The digits dataset
      # 加载数据集
      digits = datasets.load_digits()
    3. 查看数据集。使用matplotlib显示数据集图片。

      # The data that we are interested in is made of 8x8 images of digits, let's
      # have a look at the first 4 images, stored in the `images` attribute of the
      # dataset.  If we were working from image files, we could load them using
      # matplotlib.pyplot.imread.  Note that each image must have the same size. For these
      # images, we know which digit they represent: it is given in the 'target' of
      # the dataset.
      # 查看数据集前4张图片
      images_and_labels = list(zip(digits.images, digits.target))
      for index, (image, label) in enumerate(images_and_labels[:4]):
          plt.subplot(2, 4, index + 1)
          plt.axis('off')
          plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
          plt.title('Training: %i' % label)
    4. 数据预处理。使用numpy将图片展开成向量。

      # To apply a classifier on this data, we need to flatten the image, to
      # turn the data in a (samples, feature) matrix:
      # 数据预处理:将数据集展开成向量
      n_samples = len(digits.images)
      data = digits.images.reshape((n_samples, -1))
    5. 构建分类器模型。使用Scikit-learn中的分类器SVM

      # Create a classifier: a support vector classifier
      # 构建分类器SVM
      classifier = svm.SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
        degree=3, gamma=0.001, kernel='rbf',
        max_iter=-1, probability=False, random_state=None, shrinking=True,
        tol=0.001, verbose=False)
    6. 训练分类器模型。使用一半数据集进行模型的训练。

      # We learn the digits on the first half of the digits
      # 训练分类器
      classifier.fit(data[:n_samples // 2], digits.target[:n_samples // 2])
    7. 使用训练好的分类器模型预测另一半数据集。

      # Now predict the value of the digit on the second half:
      # 测试分类效果
      expected = digits.target[n_samples // 2:]
      predicted = classifier.predict(data[n_samples // 2:])
    8. 检查分类器的预测效果。使用Scikit-learn自带metrics检查预测准确率、召回率及混淆矩阵(Confusion Matrix)等。

      print("Classification report for classifier %s:\n%s\n"
            % (classifier, metrics.classification_report(expected, predicted)))
      print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted))
      
      images_and_predictions = list(zip(digits.images[n_samples // 2:], predicted))
      for index, (image, prediction) in enumerate(images_and_predictions[:4]):
          plt.subplot(2, 4, index + 5)
          plt.axis('off')
          plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
          plt.title('Prediction: %i' % prediction)
      plt.show()

实验结果

  • 分类器说明和每个分类的准确率precision,召回率recall,F1分数f1-score和各类别参与训练的样本数。

  • 混淆矩阵:可看到测试数据集被分类的情况。

  • 训练和测试情况。

课后习题

  • 参考SVM参数表修改SVM参数,如惩罚因子C、rbf核函数的系数gamma等,观察预测结果的变化情况。修改代码后键入Shift+Enter可再次运行。


expert1.txt文件内容如下:

print(__doc__)

# Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org>
# License: BSD 3 clause

# Standard scientific Python imports
import matplotlib.pyplot as plt

# Import datasets, classifiers and performance metrics
from sklearn import datasets, svm, metrics

# The digits dataset
# 加载数据集
digits = datasets.load_digits()

# The data that we are interested in is made of 8x8 images of digits, let's
# have a look at the first 4 images, stored in the `images` attribute of the
# dataset.  If we were working from image files, we could load them using
# matplotlib.pyplot.imread.  Note that each image must have the same size. For these
# images, we know which digit they represent: it is given in the 'target' of
# the dataset.
# 查看前4张图片
images_and_labels = list(zip(digits.images, digits.target))
for index, (image, label) in enumerate(images_and_labels[:4]):
    plt.subplot(2, 4, index + 1)
    plt.axis('off')
    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title('Training: %i' % label)

# To apply a classifier on this data, we need to flatten the image, to
# turn the data in a (samples, feature) matrix:
# 数据预处理:展开成向量
n_samples = len(digits.images)
data = digits.images.reshape((n_samples, -1))

# Create a classifier: a support vector classifier
# 构建分类器SVM
classifier = svm.SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
  degree=3, gamma=0.001, kernel='rbf',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False)

# We learn the digits on the first half of the digits
# 训练分类器
classifier.fit(data[:n_samples // 2], digits.target[:n_samples // 2])

# Now predict the value of the digit on the second half:
# 测试分类效果
expected = digits.target[n_samples // 2:]
predicted = classifier.predict(data[n_samples // 2:])

print("Classification report for classifier %s:\n%s\n"
      % (classifier, metrics.classification_report(expected, predicted)))
print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted))

images_and_predictions = list(zip(digits.images[n_samples // 2:], predicted))
for index, (image, prediction) in enumerate(images_and_predictions[:4]):
    plt.subplot(2, 4, index + 5)
    plt.axis('off')
    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title('Prediction: %i' % prediction)

plt.show()

实验二、Python机器学习入门:无监督学习

实验目标

  • 了解机器学习有监督和无监督的区别。

  • 通过实验掌握简单无监督算法使用方式。

实验器材及准备

实验器材

  • 硬件:电脑PC一台

  • 软件:Ubuntu、Anaconda3 5.0.1、Scikit-learn 0.19及其依赖包

实验准备

实验内容与步骤

  1. 打开编译环境。如实验一打开Jupyter Notebook,新建New->Python3交互窗口。

  2. 代码文件exper2.txt中实现了以下步骤:

    1. 导入实验依赖模块

      from time import time
      import numpy as np
      import matplotlib.pyplot as plt
      from sklearn import metrics
      from sklearn.cluster import KMeans
      from sklearn.datasets import load_digits
      from sklearn.decomposition import PCA
      from sklearn.preprocessing import scale
    2. 载入示例数据集。载入Scikit-learn自带数据集手写数字识别集(Handwritten Digits Data Set)。

      # 设定随机数种子
      np.random.seed(42)
      # 加载数据集
      digits = load_digits()
    3. 数据预处理。标准化数据,并获取数据集相关信息。

      data = scale(digits.data)
      # 解析数据集
      # 数据集包含10个分类(手写数字1-10),1797个样本,特征维度为64维;
      # 样本数,特征维度
      n_samples, n_features = data.shape
      # 类别数
      n_digits = len(np.unique(digits.target))
      labels = digits.target
      sample_size = 300
      print("n_digits: %d, \t n_samples %d, \t n_features %d"
            % (n_digits, n_samples, n_features))
    4. 定义bench_k_means函数用以完成模型的训练及打印模型的聚类评估指标。

      # 函数:训练并测试分类效果
      def bench_k_means(estimator, name, data):
          t0 = time()
          estimator.fit(data)
          print('%-9s\t%.2fs\t%i\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f'
                % (name, (time() - t0), estimator.inertia_,
                   metrics.homogeneity_score(labels, estimator.labels_),
                   metrics.completeness_score(labels, estimator.labels_),
                   metrics.v_measure_score(labels, estimator.labels_),
                   metrics.adjusted_rand_score(labels, estimator.labels_),
                   metrics.adjusted_mutual_info_score(labels,  estimator.labels_),
                   metrics.silhouette_score(data, estimator.labels_,
                                            metric='euclidean',
                                            sample_size=sample_size)))
    5. 分别构建三种不同的K-means聚类器

      print(82 * '_')
      print('init\t\ttime\tinertia\thomo\tcompl\tv-meas\tARI\tAMI\tsilhouette')
      # 构建K-means分类器1: 初始化中心点为k-means++,传入以上函数				 
      
      bench_k_means(KMeans(init='k-means++', n_clusters=n_digits, n_init=10),
                    name="k-means++", data=data)
      			  
      # 构建K-means分类器2:初始化中心点为random,传入以上函数
      bench_k_means(KMeans(init='random', n_clusters=n_digits, n_init=10),
                    name="random", data=data)
      
      # in this case the seeding of the centers is deterministic, hence we run the
      # kmeans algorithm only once with n_init=1
      # 构建K-means分类器3,利用PCA找到数据主轴,将其作为kmeans初始化中心点的方法,传入以上函数	
      # 进行PCA降维
      pca = PCA(n_components=n_digits).fit(data)
      bench_k_means(KMeans(init=pca.components_, n_clusters=n_digits, n_init=1),
                    name="PCA-based",
                    data=data)
      print(82 * '_')
    6. 聚类可视化。使用matplotlib可视化聚类结果(PCA降维到2维以便平面显示)。

      reduced_data = PCA(n_components=2).fit_transform(data)
      # 习题:修改此处参数
      kmeans = KMeans(init='k-means++', n_clusters=n_digits, n_init=10)
      kmeans.fit(reduced_data)
      
      # Step size of the mesh. Decrease to increase the quality of the VQ.
      h = .02     # point in the mesh [x_min, x_max]x[y_min, y_max].
      
      # Plot the decision boundary. For that, we will assign a color to each
      x_min, x_max = reduced_data[:, 0].min() - 1, reduced_data[:, 0].max() + 1
      y_min, y_max = reduced_data[:, 1].min() - 1, reduced_data[:, 1].max() + 1
      xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
      
      # Obtain labels for each point in mesh. Use last trained model.
      Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()])
      
      # Put the result into a color plot
      Z = Z.reshape(xx.shape)
      plt.figure(1)
      plt.clf()
      plt.imshow(Z, interpolation='nearest',
      	   extent=(xx.min(), xx.max(), yy.min(), yy.max()),
      	   cmap=plt.cm.Paired,
      	   aspect='auto', origin='lower')
      
      plt.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2)
      # Plot the centroids as a white X
      centroids = kmeans.cluster_centers_
      plt.scatter(centroids[:, 0], centroids[:, 1],
      	    marker='x', s=169, linewidths=3,
      	    color='w', zorder=10)
      plt.title('K-means clustering on the digits dataset (PCA-reduced data)\n'
      	  'Centroids are marked with white cross')
      plt.xlim(x_min, x_max)
      plt.ylim(y_min, y_max)
      plt.xticks(())
      plt.yticks(())
      plt.show()

实验结果

  • 数据集包含10个分类(手写数字1-10),1797个样本,特征维度为64维。

  • 可以看到3个不同kmeans初始化中心点方法的聚类器的效果,注意使用PCA-based方法初始化中心点速度极快,因为中心点更新次数少。

  • 最后在图中可以看到PCA降维到2维的数据聚类情况。

课后习题

  • 参考K-Means参数表修改K-Means参数,如聚类器初始化类型(k-means++randomPCA-based)、类别数n_clusters等,观察聚类结果变化情况。


expert2.txt文件内容如下:

print(__doc__)

from time import time
import numpy as np
import matplotlib.pyplot as plt

from sklearn import metrics
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale

# 设定随机数种子
np.random.seed(42)

# 加载数据集
digits = load_digits()
data = scale(digits.data)

# 解析数据集
n_samples, n_features = data.shape
n_digits = len(np.unique(digits.target))
labels = digits.target

sample_size = 300

print("n_digits: %d, \t n_samples %d, \t n_features %d"
      % (n_digits, n_samples, n_features))


print(82 * '_')
print('init\t\ttime\tinertia\thomo\tcompl\tv-meas\tARI\tAMI\tsilhouette')

# 函数:训练并测试分类效果
def bench_k_means(estimator, name, data):
    t0 = time()
    estimator.fit(data)
    print('%-9s\t%.2fs\t%i\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f'
	  % (name, (time() - t0), estimator.inertia_,
	     metrics.homogeneity_score(labels, estimator.labels_),
	     metrics.completeness_score(labels, estimator.labels_),
	     metrics.v_measure_score(labels, estimator.labels_),
	     metrics.adjusted_rand_score(labels, estimator.labels_),
	     metrics.adjusted_mutual_info_score(labels,  estimator.labels_),
	     metrics.silhouette_score(data, estimator.labels_,
				      metric='euclidean',
				      sample_size=sample_size)))

# 构建K-means分类器1,传入以上函数
bench_k_means(KMeans(init='k-means++', n_clusters=n_digits, n_init=10),
	      name="k-means++", data=data)

# 构建K-means分类器2,传入以上函数
bench_k_means(KMeans(init='random', n_clusters=n_digits, n_init=10),
	      name="random", data=data)

# in this case the seeding of the centers is deterministic, hence we run the
# kmeans algorithm only once with n_init=1
# 构建K-means分类器3,添加PCA降维,传入以上函数
pca = PCA(n_components=n_digits).fit(data)
bench_k_means(KMeans(init=pca.components_, n_clusters=n_digits, n_init=1),
	      name="PCA-based",
	      data=data)
print(82 * '_')

# #############################################################################
# 聚类可视化。使用matplotlib可视化聚类结果(PCA降维到2维以便平面显示)
# Visualize the results on PCA-reduced data

reduced_data = PCA(n_components=2).fit_transform(data)
# 习题:修改此处参数
kmeans = KMeans(init='k-means++', n_clusters=n_digits, n_init=10)
kmeans.fit(reduced_data)

# Step size of the mesh. Decrease to increase the quality of the VQ.
h = .02     # point in the mesh [x_min, x_max]x[y_min, y_max].

# Plot the decision boundary. For that, we will assign a color to each
x_min, x_max = reduced_data[:, 0].min() - 1, reduced_data[:, 0].max() + 1
y_min, y_max = reduced_data[:, 1].min() - 1, reduced_data[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

# Obtain labels for each point in mesh. Use last trained model.
Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(1)
plt.clf()
plt.imshow(Z, interpolation='nearest',
	   extent=(xx.min(), xx.max(), yy.min(), yy.max()),
	   cmap=plt.cm.Paired,
	   aspect='auto', origin='lower')

plt.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2)
# Plot the centroids as a white X
centroids = kmeans.cluster_centers_
plt.scatter(centroids[:, 0], centroids[:, 1],
	    marker='x', s=169, linewidths=3,
	    color='w', zorder=10)
plt.title('K-means clustering on the digits dataset (PCA-reduced data)\n'
	  'Centroids are marked with white cross')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
plt.show()

实验三、Python深度学习入门:单层神经网络

实验目标

  • 了解深度学习的基本概念。

  • 通过实验学会使用框架实现简单神经网络。

实验器材及准备

实验器材

  • 硬件:电脑PC一台

  • 软件:Ubuntu、Anaconda3 5.0.1、TensorFlow 1.3.0及其依赖包

实验准备

实验内容与步骤

  1. 打开编译环境。如实验一打开Jupyter Notebook,新建New->Python3交互窗口。

  2. 代码文件exper3.txt中实现了以下步骤:

    1. 导入实验所需模块

      from __future__ import absolute_import
      from __future__ import division
      from __future__ import print_function
      
      import argparse
      import sys
      
      from tensorflow.examples.tutorials.mnist import input_data
      import matplotlib.pyplot as plt
      import tensorflow as tf
    2. 载入示例数据集。载入Tensorflow自带数据集手写数字识别集(MNIST Data)。

      # 载入数据
      mnist = input_data.read_data_sets("/tmp/tensorflow/mnist/input_data", one_hot=True)
    3. 构建神经网络。利用Tensorflow构建简单神经网络。

      # 构建单层神经网络
      x = tf.placeholder(tf.float32, [None, 784])
      W = tf.Variable(tf.zeros([784, 10]))
      b = tf.Variable(tf.zeros([10]))
      y = tf.matmul(x, W) + b
      y_ = tf.placeholder(tf.float32, [None, 10])
    4. 构建损失函数和优化器

      # The raw formulation of cross-entropy,
      #
      #   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),
      #                                 reduction_indices=[1]))
      #
      # can be numerically unstable.
      #
      # So here we use tf.nn.softmax_cross_entropy_with_logits on the raw
      # outputs of 'y', and then average across the batch.
      # 构建损失函数
      cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
      # 构建优化器,注意learning_rate
      train_step = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cross_entropy)
    5. 构建TensorFlow会话并初始化变量。

      sess = tf.InteractiveSession()
      tf.global_variables_initializer().run()
    6. 进行模型的训练,在给定的训练样本上运行以上神经网络,每隔100轮打印一次训练情况,观察交叉熵(Cross Entropy)误差error值的变化。

      # 训练模型:range内迭代次数
      for i in range(1000):
          batch_xs, batch_ys = mnist.train.next_batch(100)
          sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
          if i%100==0:
              print("cross_entropy error:",sess.run(cross_entropy, feed_dict={x: batch_xs, y_: batch_ys}))
    7. 检查模型预测效果。定义准确率accuracy计算方式,检查模型预测准确率。

      # 测试训练好的模型
      correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
      accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
      print("test accuracy: ",sess.run(accuracy, feed_dict={x: mnist.test.images,
      				  y_: mnist.test.labels}))
    8. 选择图片进行测试,选择一张图片,用训练好的模型对新的图片进行预测。

      # part2 :选择图片测试
      # 第几张图片
      p = 0
      s = sess.run(y,feed_dict={x: mnist.test.images[p].reshape(1,784)})
    9. 打印模型预测结果,并可视化测试图片。

      print("Prediction : ",sess.run(tf.argmax(s, 1)))
      
      #显示图片
      plt.imshow(mnist.test.images[p].reshape(28,28), cmap=plt.cm.gray_r, interpolation='nearest')
      plt.show()

实验结果

  • 随着迭代的进行,神经网络在数据集上的交叉熵(Cross Entropy)误差error值越来越小,代表正在慢慢拟合训练数据,最后在测试集上的测试准确率accuracy91.02%

  • 选取测试集图片,进行预测:

课后习题

  • 修改学习迭代次数range、学习率learning_rate等,观察结果的变化。


expert3.txt文件内容如下:

part1:

"""A very simple MNIST classifier.
See extensive documentation at
https://www.tensorflow.org/get_started/mnist/beginners
"""
# part1
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys

from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
import tensorflow as tf

# 载入数据
mnist = input_data.read_data_sets("/tmp/tensorflow/mnist/input_data", one_hot=True)

# 构建单层神经网络
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b

# 定义损失函数和优化器
y_ = tf.placeholder(tf.float32, [None, 10])

# The raw formulation of cross-entropy,
#
#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),
#                                 reduction_indices=[1]))
#
# can be numerically unstable.
#
# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw
# outputs of 'y', and then average across the batch.
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
# 注意learning_rate
train_step = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cross_entropy)

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
# 训练模型:range内迭代次数
for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
    if i%100==0:
        print("cross_entropy error:",sess.run(cross_entropy, feed_dict={x: batch_xs, y_: batch_ys}))

# 测试训练好的模型
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("test accuracy: ",sess.run(accuracy, feed_dict={x: mnist.test.images,
				  y_: mnist.test.labels}))

part2:

# part2 :选择图片测试
# 第几张图片?
p = 0

s = sess.run(y,feed_dict={x: mnist.test.images[p].reshape(1,784)})
print("Prediction : ",sess.run(tf.argmax(s, 1)))

#显示图片
plt.imshow(mnist.test.images[p].reshape(28,28), cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()

实验四、Python深度学习入门:人脸识别实验

实验目标

  • 了解人脸识别的基本原理

  • 通过实验熟悉人脸识别的四个过程

实验器材及准备

实验器材

  • 硬件:电脑PC一台

  • 软件:Ubuntu、Docker、openface项目Docker容器镜像及其相关依赖包

实验准备

实验内容与步骤

实验环境及数据准备

Linux相关基础知识

  1. 本实验说明中所有命令语句均可使用 复制Copy / 粘贴Paste 操作在实验机的Terminal命令窗口中直接运行,调取命令窗口 快捷键Ctrl+Alt+T

  2. 复制Copy 命令语句时,请用鼠标选定本手册中每条命令语句的 第一个非空格字符 直至 最后一个非空格字符,注意命令语句中不要遗漏 斜杠/ 或者 空格Space

  3. Terminal命令窗口中的 复制Copy 操作可以使用 鼠标右键菜单->复制Copy 或者使用 快捷键Ctrl+Shift+C

  4. Terminal命令窗口中的 粘贴Paste 操作可以使用 鼠标右键菜单->粘贴Paste 或者使用 快捷键Ctrl+Shift+V

  5. Terminal命令窗口中可以使用 方向键 / 查看之前自己输入过的命令语句。

  6. Terminal命令窗口中输入命令或路径时,可以使用 快捷键Tab 对命令或路径进行快速补全操作。

Docker简介

Docker是一个开源的引擎,可以轻松的为任何应用创建一个轻量级的、可移植的、自给自足的容器。开发者在笔记本上编译测试通过的容器可以批量地在生产环境中部署,包括VMs(虚拟机)、bare metal、OpenStack集群和其他的基础应用平台。

  1. 本实验利用基于openface开源项目所提供的Docker容器镜像bamos/openface环境进行人脸识别实验。

  2. 注意事项!!!重要!!!】:

    Terminal命令窗口中进入Docker容器内运行的所有实验代码的工作目录均为/root/openface,请把命令语句中所有的 your_test_image_fullpath.jpg替换为你自己的完整图片路径,例如:/home/bupt/my_pic.jpg

运行Docker实验环境

  1. 使用快捷键Ctrl+Alt+T打开Terminal命令行窗口

  2. Terminal命令行窗口中依次运行以下2条命令进入Docker容器openface环境内:

    sudo xhost +local:root
    sudo docker run -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix:rw -v /home/$USER:/home/$USER:rw -t -i openface/allset /bin/bash
  3. 运行以上第1条命令后会被要求输入管理员密码,密码为123456,在输入密码时Terminal命令行窗口中不会显示密码输入,在确认输入无误后单击回车Enter按钮即可,若显示如下信息则表示第1条命令运行成功,可以继续输入第2条命令:

  4. 运行完以上2条命令进入Docker容器后,运行以下1条命令转至 openface工作目录/root/openface!!!重要!!!】:

    cd /root/openface
  5. 运行以下4条命令清除示例样本文件(若提示文件不存在则可忽略):

    rm /root/openface/aligned_face_0.jpg
    rm -r /home/bupt/training-images
    rm -r /home/bupt/aligned-images
    rm -r /home/bupt/generated-embeddings

建立人脸样本库

  1. 运行以下1条命令(或者使用鼠标左键单击左边栏图标手动进入bupt用户主目录/home/bupt内,再使用鼠标右键菜单新建文件夹New Folder选项)创建training-images文件夹(若提示目录已存在则可忽略):

    mkdir -vm 777 /home/bupt/training-images
  2. 运行类似以下命令语句(或者使用鼠标左键双击文件夹图标进入/home/bupt/training-images/目录内,再使用鼠标右键菜单新建文件夹New Folder选项)创建各个(必须2个以上)不同人的样本库文件夹,把以下命令中的person1person2person3等各自改为你自定义的名称后再运行,例如你自己的名字、你朋友的名字、你喜欢的明星的名字等:

    mkdir -vm 777 /home/bupt/training-images/person1
    mkdir -vm 777 /home/bupt/training-images/person2
    mkdir -vm 777 /home/bupt/training-images/person3

  3. 拷贝需要作为训练集的人脸照片样本至相应目录:

    通过网络下载或者U盘等移动存储设备把照片样本复制Copy至bupt用户主目录/home/bupt下的training-images文件夹中对应的各文件目录person1person2person3下(此时文件夹名应该已经替换为你自定义的名称了,并且每一个文件夹都必须要拷入图片文件使其不为空,如果不小心多建了不用的文件夹请务必Delete删除)。

  4. 注意事项!!!重要!!!】:

    • 把各个人的照片样本拷贝至与其相应的样本库文件夹,并保证每个照片样本中只有一张人脸,并清晰可见(眉/眼/鼻/嘴/脸廓完整,最好不要佩戴眼镜)。

    • 必须确保每个已建立的人脸库文件夹中均包含照片样本而不为空

    • 必须至少建立2个以上的人脸库文件夹,推荐3个以上。

    • 推荐每个人都有10张以上的照片样本,最好包含不同角度、侧面等,但是必须保证眉/眼/鼻/嘴/脸廓完整。

    • 并不需要提供经过align裁剪后的照片样本,普通的日常照片就行,openface会根据命令对照片样本进行align裁剪。


从照片中获取人脸

运行step-1_find-faces.py获取人脸位置

  1. 把以下1条命令中的your_test_image_fullpath.jpg替换为你自己准备的待测图片包含文件名及全路径完整路径,例如:/home/bupt/my_pic.jpg,再运行命令:

    python /root/openface/step-1_find-faces.py your_test_image_fullpath.jpg
  2. 运行以上命令之后会显示如下类似图片结果:

  3. 在Terminal命令行窗口中键入Enter回车按钮继续。


获取脸部特征并进行仿射变换

运行step-2a_finding-face-landmarks.py获取脸部特征

  1. 把以下1条命令中的your_test_image_fullpath.jpg替换为你自己准备的待测图片包含文件名及全路径完整图片路径,例如:/home/bupt/my_pic.jpg,再运行命令:

    python /root/openface/step-2a_finding-face-landmarks.py your_test_image_fullpath.jpg
  2. 运行以上命令之后会显示如下类似图片结果:

  3. 在Terminal命令行窗口中键入Enter回车按钮继续。

运行step-2b_projecting-faces.py获取仿射变换后的照片

  1. 把以下1条命令中的your_test_image_fullpath.jpg替换为你自己准备的待测图片包含文件名及全路径完整图片路径,例如:/home/bupt/my_pic.jpg,再运行命令:

    python /root/openface/step-2b_projecting-faces.py your_test_image_fullpath.jpg
  2. 运行以上命令之后会在工作目录/root/openface下生成如下相应的裁剪图片文件aligned_face_0.jpg

  3. 可运行以下1条命令把裁剪后的图片文件aligned_face_0.jpg拷贝至bupt用户主目录/home/bupt

    cp /root/openface/aligned_face_0.jpg /home/bupt/

    然后在主目录双击打开查看:


获取面部特征编码文件

运行main.lua对仿射变换后的人脸图片提取特征编码

  1. 依次运行以下3条命令:

    mkdir -p /home/bupt/my_aligned_face/my_face
    cp /root/openface/aligned_face_0.jpg /home/bupt/my_aligned_face/my_face/
    /root/openface/batch-represent/main.lua -outDir /home/bupt/my_reps/ -data /home/bupt/my_aligned_face/
  2. 运行以上命令之后可在/home/bupt/my_reps目录下找到如下相应的128维面部特征编码文件reps.csv

    双击打开查看文件内容:


进行完整的人脸识别实验

运行align-dlib.py进行仿射变换

  1. 运行以下1条命令:

    /root/openface/util/align-dlib.py /home/bupt/training-images/ align outerEyesAndNose /home/bupt/aligned-images/ --size 96
  2. 运行以上命令之后可在/home/bupt/aligned-images目录下找到仿射变换后的图片文件:

运行main.lua获取128维面部特征向量表示文件

  1. 运行以下1条命令:

    /root/openface/batch-represent/main.lua -outDir /home/bupt/generated-embeddings/ -data /home/bupt/aligned-images/
  2. 运行以上命令之后可在/home/bupt/generated-embaddings目录下找到labels.csv特征向量标识文件及reps.csv特征向量表示文件:

运行classifier.py train训练样本集并生成分类器

  1. 运行以下1条命令:

    /root/openface/demos/classifier.py train /home/bupt/generated-embeddings/
  2. 运行以上命令之后可在/home/bupt/generated-embaddings目录下找到如下classifier.pkl分类器文件:

运行classifier.py infer识别被测照片

  1. 把以下1条命令中的your_test_image_fullpath.jpg替换为你自己准备的待测图片包含文件名及全路径完整图片路径,例如:/home/bupt/my_pic.jpg,再运行命令:

    /root/openface/demos/classifier.py infer /home/bupt/generated-embeddings/classifier.pkl your_test_image_fullpath.jpg
  2. 运行以上命令之后会在Terminal命令窗口中显示类似如下识别结果:


machinelearningclass's People

Contributors

liuhuijiayou avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

machinelearningclass's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.