TensorFlow入门官方demo

这个demo是TensorFlow官方提供的新手入门教程,训练了一个结构非常简单的神经网络,对于小白而言可以快速入手TensorFlow。以下代码的执行默认配置好TensorFlow环境并导入keras。

官方教程地址

程序需要导入以下模块

import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
import mnist_reader

注意:mnist_reader不是系统自带,而需要手动添加至文件夹Lib\site-packages,其作用是用于读取数据集(文件点此获取)

接下来导入数据,

train_images = np.ones((60000,28,28))
test_images = np.ones((10000,28,28))
train_images_pre,train_labels = mnist_reader.load_mnist('/深度学习/fashion-minist数据集',kind='train')
test_images_pre,test_labels = mnist_reader.load_mnist('/深度学习/fashion-minist数据集',kind='t10k')
for i in range(60000):
    image_array = train_images_pre[i, :]
    image_array = image_array.reshape(28, 28)
    train_images[i, :] = image_array

for i in range(10000):
    image_array = test_images_pre[i, :]
    image_array = image_array.reshape(28, 28)
    test_images[i, :] = image_array

由于官方给的程序读取出来的是二维数组,但我们需要的是三维数组,所以这里做了一些转换(数据集在这里获取)

在这里可使用如下程序观测数据集中某个的图片

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

在这里插入图片描述

定义标签名称,并将图片灰度归一化

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

#图片归一化
train_images = train_images / 255.0
test_images = test_images / 255.0

创建模型

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

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

接下来训练,训练次数十次

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

通过softmax算法将结果变为概率

probability_model = tf.keras.Sequential([model,tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)

通过调用以下程序可以看出,图片对应标签出现的概率最大,符合预期。

print(predictions[0])
print(np.argmax(predictions[0]))
print(test_labels[0])

在这里插入图片描述
调用以下程序可以将训练结果可视化

def plot_image(i, predictions_array, true_label, img):
  predictions_array, true_label, img = predictions_array, 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, true_label[i]
  plt.grid(False)
  plt.xticks(range(10))
  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')

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[i], test_labels, test_images)
  plt.subplot(num_rows, 2*num_cols, 2*i+2)
  plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show()

训练结果
训练结果
完整代码点这里

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
TensorFlow是谷歌开发的一个开源机器学习框架,Python是一种广泛使用的编程语言,两者结合起来可以实现深度学习,自然语言处理,计算机视觉等多个领域的应用。本文将提供一个TensorFlow Python3 Demo实例,介绍如何使用TensorFlow实现MNIST数字识别任务。 首先,我们需要安装TensorFlow和其他必要的依赖项。可以使用pip命令直接进行安装,示例代码如下: ``` pip install tensorflow matplotlib numpy ``` 接下来,我们需要导入必要的库和模块: ``` import tensorflow as tf import matplotlib.pyplot as plt import numpy as np ``` 现在,我们可以开始构建模型。这里我们采用经典的卷积神经网络(CNN)架构,包括卷积层,池化层,全连接层和dropout操作。其中,卷积和池化层用于提取图片的特征,全连接层用于分类,dropout层用于防止过拟合。 ``` model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(pool_size=(2, 2)), tf.keras.layers.Conv2D(64, (3, 3), activation='relu'), tf.keras.layers.MaxPooling2D(pool_size=(2, 2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ]) ``` 在构建模型后,我们需要对其进行编译,即选择损失函数,优化器和评估标准。这里我们选择交叉熵作为损失函数,Adam优化器和准确率作为评估标准。 ``` model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) ``` 接下来,我们需要加载数据。MNIST是一个手写数字数据集,包含0-9十个数字的灰度图像,每张图片的大小为28x28。我们可以使用TensorFlow提供的API方便地加载数据。 ``` mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 x_train = x_train.reshape(x_train.shape[0], 28, 28, 1) x_test = x_test.reshape(x_test.shape[0], 28, 28, 1) ``` 在加载数据后,我们可以开始训练模型。这里我们使用fit方法进行训练,指定训练数据,验证数据,训练轮数和批次大小。 ``` history = model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test), batch_size=32) ``` 最后,我们可以使用matplotlib库绘制损失函数和准确率的变化趋势。 ``` plt.plot(history.history['loss'], label='Training Loss') plt.plot(history.history['val_loss'], label='Validation Loss') plt.legend() plt.show() plt.plot(history.history['accuracy'], label='Training Accuracy') plt.plot(history.history['val_accuracy'], label='Validation Accuracy') plt.legend() plt.show() ``` 完整的TensorFlow Python3 Demo代码如下: ``` import tensorflow as tf import matplotlib.pyplot as plt import numpy as np model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(pool_size=(2, 2)), tf.keras.layers.Conv2D(64, (3, 3), activation='relu'), tf.keras.layers.MaxPooling2D(pool_size=(2, 2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 x_train = x_train.reshape(x_train.shape[0], 28, 28, 1) x_test = x_test.reshape(x_test.shape[0], 28, 28, 1) history = model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test), batch_size=32) plt.plot(history.history['loss'], label='Training Loss') plt.plot(history.history['val_loss'], label='Validation Loss') plt.legend() plt.show() plt.plot(history.history['accuracy'], label='Training Accuracy') plt.plot(history.history['val_accuracy'], label='Validation Accuracy') plt.legend() plt.show() ``` 通过以上示例,可以很好地了解如何使用TensorFlow实现一个数字识别任务。当然,TensorFlow还有很多其他功能和API,需要更深入的学习和掌握。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值