一、图片基础和keras介绍
1、图片三要素
2、keras常用api
3、keras读取图片
使用image前需安装pillow
pip install Pillow
from tensorflow.python.keras.preprocessing.image import load_img, img_to_array def main(): img = load_img("./images/img01.jpg", target_size=[300,300]) img = img_to_array(img) print(img) if __name__ == "__main__": main()
4、NHWC和NCHW
二、神经网络基础
1、神经网络
2、创建神经网络模型
#创建神经网络模型 model = Sequential([ Flatten(input_shape=(28,28)), Dense(128,activation=tf.nn.relu), Dense(10,activation=tf.nn.softmax) ])
model的一些属性
3、模型的训练和评估
1)compile
loss:
2)fit
3)evaluate
4、案例:实现多层神经网络进行时装分类
import tensorflow as tf from tensorflow.python import keras from tensorflow.python.keras import Sequential from tensorflow.python.keras.layers import Flatten, Dense import os import numpy as np class SingleNN(object): #神经网络模型 model = Sequential([ Flatten(input_shape=(28,28)), Dense(128,activation=tf.nn.relu), Dense(10,activation=tf.nn.softmax) ]) #初始化获取数据集 def __init__(self): (self.x_train, self.y_train), (self.x_test, self.y_test) = keras.datasets.fashion_mnist.load_data() #进行数据归一化 self.x_train = self.x_train / 255.0 self.x_test = self.x_test / 255.0 #编译模型优化器 def singlenn_compile(self): SingleNN.model.compile( optimizer=keras.optimizers.SGD(lr=0.01), #优化器 loss= keras.losses.sparse_categorical_crossentropy, #损失函数 数据非one-hot编码 metrics=['accuracy'] ) return None #训练模型 def singlenn_fit(self): #fit当中添加回调函数,记录训练模型过程 modelcheck = keras.callbacks.ModelCheckpoint( filepath="./ckpt/singlenn_{epoch:02d}-{val_acc:.2f}.h5", monitor='val_acc', #保存损失率还是准确率 save_weights_only=True, mode='auto', period=1 ) #添加tensorboard观察 tensorboard = keras.callbacks.TensorBoard( log_dir="./graph", histogram_freq=1, write_grads=True, write_images=True ) SingleNN.model.fit(self.x_train, self.y_train, epochs=1, batch_size=128, callbacks=[modelcheck, tensorboard]) #epochs迭代次数,batch_size每次迭代选择的样本 return None #评估模型 def single_evalute(self): test_loss, test_acc = SingleNN.model.evaluate(self.x_test, self.y_test) #返回损失率和精确率 print(test_loss,test_acc) return None #用保存的模型预测 def single_predict(self): if os.path.exists("./tmp/ckpt/checkpoint"): SingleNN.model.load_weights("./tmp/ckpt/SingleNN.h5") return SingleNN.model.predict(self.x_test) if __name__ == '__main__': singlenn = SingleNN() # singlenn.singlenn_compile() # singlenn.singlenn_fit() # singlenn.single_evalute() # #保存模型 # SingleNN.model.save_weights("./tmp/ckpt/SingleNN.h5") #使用模型预测 predictions = singlenn.single_predict() print(predictions) print(np.argmax(predictions,axis=1))