TensorFlow入门(一)

TensorFlow环境搭建

mac os环境:

macOS 10.12.6(Sierra)或更高版本(不支持GPU)
需要 Xcode 8.3 或更高版本

  • 使用Python的pip软件包管理器安装TensorFlow

//首次安装
pip install tensorflow

//升级
pip install --user --upgrade tensorflow


//验证是否安装成功
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"

如果出现像我一样的报错

《TensorFlow入门(一)》 err

更新库:

pip install --upgrade numpy
  • docker 容器运行tensorflow

首先在mac os安装docker,使用docker 命令在终端运行容器

推荐使用这种方式,部署简单随心所欲


//在容器中run tensorflow 映射本地端口 
docker run  --name=tensorflow  -it --rm -v $(realpath ~/notebooks):/tf/notebooks -p 8888:8888 tensorflow/tensorflow:latest-py3-jupyter

docker 容器运行后会看到token

《TensorFlow入门(一)》 tensorflow容器运行成功

保持容器后台运行并推出 : control + p , control +q

使用Jupyter notebook server进行操作,使用浏览器打开
http://localhost:8888

copy token值点击login,写下造物主语句hello wold


//测试代码

import tensorflow as tf
from tensorflow.keras import layers

print(tf.VERSION)
print(tf.keras.__version__)

tf.enable_eager_execution(); 
print(tf.reduce_sum(tf.random_normal([1000, 1000])));

《TensorFlow入门(一)》 tensorflow容器运行成功

TensorFlow Keras指南

TensorFlow是一个用于研究和生产的开源机器学习库。TensorFlow为初学者和专家提供API,以便为桌面,移动,Web和云开发

高级Keras API提供构建块来创建和训练深度学习模型

  • 训练第一个神经网络-基础分类

案例是Google出的学习Demo

使用的是 tf.keras,它是一种用于在 TensorFlow 中构建和训练模型的高阶 API

copy一下code至juputer 运行,可以自己调试

# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)

# Fashion MNIST 数据集导入
# 将使用 60000 张图像训练网络,并使用 10000 张图像评估经过学习的网络分类图像的准确率
# 加载数据集会返回 4 个 NumPy 数组
fashion_mnist = keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()


# 标签是整数数组,介于 0 到 9 之间。这些标签对应于图像代表的服饰所属的类别

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# 检查数据格式
# 60000 张图像,每张图像都表示为 28x28 像素
# 输出为(60000, 28, 28)
train_images.shape
# 数据长度
len(train_labels)
print("数据长度:",len(train_labels))

train_labels
print("标签:",train_labels)

# 测试集1000张 28*28像素的图片
test_images.shape

print("数据预处理,检查第一张图 应该 0 到 255 之间")

#训练的时候注释掉,但必须运行一次
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)

# 将这些值缩小到 0 到 1 之间,然后将其馈送到神经网络模型,将图像组件的数据类型从整数转换为浮点数,然后除以 255
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]])
    
 

print("构建神经网络需要先配置模型的层,然后再编译模型")

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

# 编译模型
print("start 编译模型")

model.compile(optimizer=tf.train.AdamOptimizer(),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# 训练模型 epochs值自己修改
print("start 训练模型")

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


print ("评估准确率:比较一下模型在测试数据集上的表现")
test_loss, test_acc = model.evaluate(test_images, test_labels)

print('测试数据的准确率:', test_acc)


print ("做出预测")
predictions = model.predict(test_images)

#看看第一个预测  ,数组的10个数字代表了每个标签的可信度预测
predictions[0]

print("获取可信度最大值:",np.argmax(predictions[0]))

# 检查测试标签以查看该预测是否正确
test_labels[0]

# 将该预测绘制成图来查看全部 10 个通道
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')


print("看看第 0 张图像、预测和预测数组")

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)

# 看看第 12 张图像、预测和预测数组

i = 12
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)



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)
    
   
# 最后,使用经过训练的模型对单个图像进行预测
print("最后,使用经过训练的模型对单个图像进行预测")

img = test_images[0]

print(img.shape)


#tf.keras 模型已经过优化,可以一次性对样本批次或样本集进行预测

img = (np.expand_dims(img,0))

print(img.shape)


# 预测这张图像
predictions_single = model.predict(img)

print(predictions_single)

plot_value_array(0, predictions_single, test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)


np.argmax(predictions_single[0])
    
    



可以看到训练的次数增加,模型准确度也变高,是不是越多越好呢?当然不是

《TensorFlow入门(一)》 模型训练

识别结果:mode对测试集进行识别

《TensorFlow入门(一)》 mode对测试集进行识别

    原文作者:youseewhat
    原文地址: https://www.jianshu.com/p/36b0263ea2d2
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞