`
daojin
  • 浏览: 677351 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

Tensorflow初学-1(运行minist分类器)

阅读更多


#from google.colab import drive
#drive.mount('/content/drive')

from __future__ import absolute_import, division, print_function, unicode_literals
import matplotlib.pyplot as plt;
import matplotlib.cm as cm
import numpy as np
# 安装 TensorFlow
try:
  # Colab only
  %tensorflow_version 2.x
except Exception:
    pass

import tensorflow as tf
mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()

print(y_train[0])
plt.figure(1) #图像显示
plt.imshow(x_train[0],cmap=cm.gray)
plt.show()

x_train, x_test = x_train / 255.0, x_test / 255.0
print(x_train.shape)

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  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'])

//模型训练
model.fit(x_train, y_train, epochs=5)

//模型估计
model.evaluate(x_test,  y_test, verbose=2)

//模型预测
image_raw = tf.io.read_file('../1.png','rb')
print(image_raw.shape)
img_data_png = tf.io.decode_png(image_raw)
print(img_data_png.shape)
print(type(img_data_png))
img_data_png_gray = tf.image.rgb_to_grayscale(
    img_data_png, name=None
)
imageScaled= tf.image.resize(img_data_png_gray, (28,28))
imageScaled = tf.image.adjust_contrast(imageScaled, 10)
imageScaled = 255.0 - imageScaled
print(imageScaled.shape)
squeezed  = np.squeeze(imageScaled)
print(squeezed.shape)
#squeezed_float = np.array(squeezed)/255.0f
squeezed = squeezed/255.0
print(squeezed.shape)
result = model.predict(np.array([squeezed]))
print(result)
print(type(squeezed))
print(squeezed.shape)
plt.figure(1) #图像显示
plt.imshow(squeezed,cmap=cm.gray)
plt.show()




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics