TensorFlow2.0入门教程

一. TensorFlow是什么

TensorFlow是由Google Brain 团队为深度神经网络(DNN)开发的功能强大的开源软件库,于2015年11月首次发布,在Apache 2.x协议许可下可用。截至今天,短短的两年内,其 GitHub库大约845个贡献者共提交超过17000次,这本身就是衡量TensorFlow流行度和性能的一个指标。
Alt
开源深度学习库TensorFlow允许将深度神经网络的计算部署到任意数量的CPU或 GPU的服务器. PC或移动设备上,且只利用一个TensorFlow API。你可能会问,还有很多其他的深度学习库,如Torch. Theano. Caffe和MxNet,那TensorFlow与其他深度学习库的区别在哪里呢?包括 TensorFlow 在内的大多数深度学习库能够自动求导. 开源. 支持多种 CPU/GPU. 拥有预训练模型,并支持常用的NN架构,如递归神经网络(RNN). 卷积神经网络(CNN)和深度置信网络(DBN)。
TensorFlow 则还有更多的特点,如下:
a. 支持所有流行语言,如Python. C++. Java. R和Go。
b. 可以在多种平台上工作,甚至是移动平台和分布式平台。
c. 它受到所有云服务(AWS. Google和Azure)的支持。
d. Keras–高级神经网络API,已经与TensorFlow 整合。
e. 与 Torch/Theano比较,TensorFlow拥有更好的计算图表可视化。
f. 允许模型部署到工业生产中,并且容易使用。
g. 有非常好的社区支持。
h. TensorFlow不仅仅是一个软件库,它是一套包括TensorFlow, TensorBoard和TensorServing的软件。

二、hello world

在任何计算机语言中学习的第一个程序是都是 Hello world,从程序 Hello world 开始。
TensorFlow 安装验证的代码:

import tensorflow as tf 
message = tf .constant ( 'Welcome to the exciting world of Deep Neural Networks! ')
with tf .Session () as sess :
print (sess. run (message) .decode() )

Alt
报错
Could not load dynamic library ‘cudart64_101.dll’; dlerror: cudart64_101.dll not found. Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Alt
GPU不能运行时退回到CPU版本。
Attempting to fetch value instead of handling error internal:could not retrieve CUDA device attribute <81: UNKNOWN ERROR<1>
Alt
显卡内存太次了。。
Alt
随即安装TensorFlow CPU版本:pip3 install tensorflow-cpu -i https://pypi.douban.com/simple
Alt
测试TensorFlow是否安装成功

import tensorflow as tf
version = tf.__version__
gpu_ok = tf.test.is_gpu_available()
print("tf version:",version,"\nif use GPU",gpu_ok)

结果显示如下:
Alt
再次运行,出现问题
Alt
解决方案
在报错的逻辑代码的前面加个空格就一切ok了,一个缩进就解决了这个异常,解决这个bug不是主要目的,了解python的语法结构和特点才是我们该做的事情。
python里面方法体并不使用{}来区分,python的是用缩进来识别语法逻辑块的(i.e. if, while, for, def 等)。在python中,所有的逻辑代码块也就是一个方法中的代码,都必须使用相同的缩进来标识区分是同一个方法,否则编译会报错。所谓缩进,就是每一行开头的空白。这个空白可以由多个空格或者制表符组成。python下面你怎么缩进都可以,比如3个空格,2个tab,这样都是合法的。但是同一个逻辑块下面必须用一样的。

三、一个简单的TensorFlow程序

  1. 新建一个线性拟合的python文件,内容如下:
import tensorflow as tf
X = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
y = tf.constant([[10.0], [20.0]])
class Linear(tf.keras.Model):
    def __init__(self):
        super().__init__()
        self.dense = tf.keras.layers.Dense(
            units=1,
            activation=None,
            kernel_initializer=tf.zeros_initializer(),
            bias_initializer=tf.zeros_initializer()
        )
    def call(self, input):
        output = self.dense(input)
        return output
model = Linear()
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)
for i in range(100):
    with tf.GradientTape() as tape:
        y_pred = model(X)      # 调用模型 y_pred = model(X) 而不是显式写出 y_pred = a * X + b
        loss = tf.reduce_mean(tf.square(y_pred - y))
    grads = tape.gradient(loss, model.variables)    # 使用 model.variables 这一属性直接获得模型中的所有变量
    optimizer.apply_gradients(grads_and_vars=zip(grads, model.variables))
    if i % 10 == 0:
        print(i, loss.numpy())
print(model.variables)
  1. 然后运行,结果如下Alt

四、图像分类

我们将构建一个简单的图像分类器

from __future__ import absolute_import, division, print_function
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
import numpy as np
print(tf.__version__)

1. 获取Fashion MNIST数据集

使用Fashion MNIST数据集,该数据集包含10个类别中的70,000个灰度图像。

mnist=keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = keras.datasets.fashion_mnist.load_data()

Alt

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

2.探索数据

在训练模型之前探索数据集的格式。 以下显示训练集中有60,000个图像,每个图像表示为28 x 28像素:

print(train_images.shape)
print(train_labels.shape)
print(test_images.shape)
print(test_labels.shape)

3.处理数据

plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()

Alt

train_images = train_images / 255.0
test_images = test_images / 255.0
plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    plt.xlabel(class_names[train_labels[i]])
    plt.show()

Alt

4.构造网络

model = keras.Sequential(
[
    layers.Flatten(input_shape=[28, 28]),
    layers.Dense(128, activation='relu'),
    layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
             loss='sparse_categorical_crossentropy',
             metrics=['accuracy'])

5.训练与验证

model.fit(train_images, train_labels, epochs=5)

Alt

model.evaluate(test_images, test_labels)

Alt

6.预测

predictions = model.predict(test_images)
print(predictions[0])
print(np.argmax(predictions[0]))
print(test_labels[0])

Alt

def plot_image(i, predictions_array, true_label, img):
  predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
  plt.grid(False)
  plt.xticks([])
  plt.yticks([])
  plt.imshow(img, cmap=plt.cm.binary)

  predicted_label = np.argmax(predictions_array)
  if predicted_label == true_label:
    color = 'blue'
  else:
    color = 'red'
  
  plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
                                100*np.max(predictions_array),
                                class_names[true_label]),
                                color=color)

def plot_value_array(i, predictions_array, true_label):
  predictions_array, true_label = predictions_array[i], true_label[i]
  plt.grid(False)
  plt.xticks([])
  plt.yticks([])
  thisplot = plt.bar(range(10), predictions_array, color="#777777")
  plt.ylim([0, 1]) 
  predicted_label = np.argmax(predictions_array)
 
  thisplot[predicted_label].set_color('red')
  thisplot[true_label].set_color('blue')
i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions,  test_labels)
plt.show()

Alt

# Plot the first X test images, their predicted label, and the true label
# Color correct predictions in blue, incorrect predictions in red
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
  plt.subplot(num_rows, 2*num_cols, 2*i+1)
  plot_image(i, predictions, test_labels, test_images)
  plt.subplot(num_rows, 2*num_cols, 2*i+2)
  plot_value_array(i, predictions, test_labels)
  plt.show()

Alt
[1]: https://blog.csdn.net/qq_31456593/article/details/88605746
[2]: http://c.biancheng.net/view/1882.html

发布了3 篇原创文章 · 获赞 0 · 访问量 145

猜你喜欢

转载自blog.csdn.net/qq_22326895/article/details/104678887