10月1日 tensorflow2.0终于发布了正式版。
一 安装
#升级pip
pip install --upgrade pip
#windows下有可能提示与user相关的升级失败信息 下面这句就能解决
#pip install --user --upgrade pip
#然后正式安装
#cup 版本
tensorflow 2
pip install tensorflow==2.0.0
#GPU 版本
pip install tensorflow-gpu==2.0.0
#安装gpu版本还要必须安装两个软件,一个是cuda,一个cudnn,cuda是显卡开发工具,cudann是加速器。安装时注意版本,如果是tensorflow2,就用最新版的即可。
#cuda 下载地址(无需注册):https://developer.nvidia.com/cuda-zone
#cudnn 下载地址(需要注册) :https://developer.nvidia.com/cudnn
#图像处理库,非常重要东西。
pip install scikit-image
二 训练mnist
from __future__ import absolute_import, division, print_function
import tensorflow as tf
# 导入数据集
mnist = tf.keras.datasets.mnist
# 载入 训练数据集 和测试数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 整形转浮点,除255 是归一化
x_train, x_test = x_train / 255.0, x_test / 255.0
#
model = tf.keras.models.Sequential([ #建立序列模型
#flaten是将图像转为张量 input_shape 是输入28*28的图像, 展平所有像素 28*28 = 784
tf.keras.layers.Flatten(input_shape=(28, 28)),
#dense层为全连接层,输出128个神经元,计划函数是relu relu是大于0则保留原值,小于0则使用0
tf.keras.layers.Dense(256, activation='relu'),
# tf.keras.layers.Dense(128, activation='sigmoid'),
#使用0.2的失活率 失火驴
tf.keras.layers.Dropout(0.2),
#再接一个全连接层,激活函数使用 softmax,得到对各个类别预测的概率。 softmax是多酚类 sigmoid取值0,1,tanh取值-1,1, relu过滤掉小于0的值
tf.keras.layers.Dense(10, activation='softmax')
])
#选择 Adam 优化器。与随机梯度 类似。但效果更好。 compile 是训练
model.compile(optimizer='adam',
#损失函数使用 sparse_categorical_crossentropy,输入的是整形的标签,例如 [1, 2, 3, 4]
#还有一个损失函数是 categorical_crossentropy,输入的是 one-hot 编码的标签。
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
#查看第一个数据
# print(x_train[0])
#查看第一个这正确结果
# print(y_train[1])
#fit 用于训练模型,对训练数据遍历一次为一个 epoch,这里遍历 5 次。
model.fit(x_train, y_train, epochs=300)
# xx = model.predict(x_train[1])
# print(xx)
#evaluate 用于评估模型,返回的数值分别是损失和指标。
# model.evaluate(x_test, y_test)
#将模型保存成h5文件
model.save('mnist_cnn_1.h5')
三 读取已有h5模型
from __future__ import absolute_import, division, print_function
import tensorflow as tf
from tensorflow import keras
import os
# 导入数据集
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
# 读取已有模型
new_model = tf.keras.models.load_model('mnist_cnn_1.h5')
# 运行模型
new_model.evaluate(x_test, y_test)
预测模型
from __future__ import absolute_import, division, print_function
import tensorflow as tf
from tensorflow import keras
import os
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from tensorflow.keras.preprocessing import image
# 导入数据集
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
# # 读取已有模型
new_model = tf.keras.models.load_model('mnist_cnn_1.h5')
# 测试模型
# new_model.evaluate(x_test, y_test)
# 正式预测一组数据(取得概率)
#manic = new_model.predict(x_test)
# 正式预测一组数据(取得样本训练时的 分类)
# print(type(x_train))
#正式预测一个样品,预测接受的时numpy的数组数据,所以如果使用单样品,就需要组一个数组
# simple1 = np.array([x_test[3]])
# classe = new_model.predict_classes(simple1)
# # # #打印 预测分类
# print(classe)
# # # # 打印正确答案
# print(y_test[3])
#使用自己的图片 目录下的 子目录中放置图片,子文件夹名就是分类名
train_data_dir = r"D://myproject//tensorflow2"
#val_data_dir = r"D://Learning//tensorflow_2.0//smile//data//val"
train_datagen = ImageDataGenerator(
rescale=1./255,
# shear_range=0.2,
# horizontal_flip=True
)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(28, 28),#将图像调整为28*28
class_mode="sparse",
# color_mode: 颜色模式,grayscale","rgb"
color_mode="grayscale",
)
for data_batch, labels_batch in train_generator:
# print('data_batch:', type(data_batch))
# print('labels_batch:', type(labels_batch))
# print('data batch shape:', data_batch.shape)
# print('labels batch shape:', labels_batch.shape)
# 打印正确答案
# print('labels_batch:', labels_batch)
#将3维 转为2维,为了图像显示
#显示图像
plt.subplots(len(data_batch), 1)
##打印 预测分类
for i in range(0,len(data_batch-1)):
#显示凸显
img = np.reshape(data_batch[i],(28,28))
plt.imshow(img)
# 转格式 #预测
ii = np.reshape(data_batch[i], (1,28,28))
classe = new_model.predict_classes(ii)
print(classe)
break
plt.show()
# 直接输入图片
# # 读取一个图片,重置图片尺寸,设置颜色类别为黑白 "grayscale", "rgb", or "rgba
# i = load_img('D:\\myproject\\tensorflow2\\smile\\4.png', target_size = (28, 28), color_mode="grayscale")
# #弹出窗口查看图像
# print(i)
# plt.figure(1)
# plt.imshow(i)
# plt.show()
# #重置尺寸
# #i = i.resize((28, 28))
# # image.flags.writeable = True #如果报错就加这个
# # image = np.asarray(image,'f') # 转换
# # 图片转数组
# x = img_to_array(i)
# # 归一化
# x = x / 255.0
# #将图像加入一个大数组中 数据结构需要
# image_list = np.array([x])
# # 图形适配
# image_list = np.reshape(image_list, (1,28,28))
# #预测
# # print(image_list)
# classe = new_model.predict_classes(image_list)
# ##打印 预测分类
# print(classe)