2020.04.21.机器学习-tensorflow2.0
当做一个日记 每天记录自己在学习上的成长
import tensorflow as tf
import keras
from keras.models import Sequential
import numpy as np
#拟合xy
#model=Sequential([keras.layers.Dense(units=1,input_shape=[1])])
#model.compile(optimizer='sgd',loss='mean_squared_error')
#
#xs=np.array([-1,0,1,2,3,4],dtype=float)
#ys=np.array([-3,-1,1,3,5,7],dtype=float)
#
#model.fit(xs,ys,epochs=500)
#
#print(model.predict([10]))
#fashion
fashion_mnist=keras.datasets.fashion_mnist
(train_images,train_labels),(test_images,test_labels)=fashion_mnist.load_data()
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self,epoch,logs={}):
if(logs.get('loss')<0.1):
print("\nLoss is low")
self.model.stop_training=True
callback=myCallback()
import matplotlib.pyplot as plt
plt.imshow(train_images[0])
print(train_images.shape)
train_images=train_images.reshape(60000,28,28,1)
train_images=train_images/255
test_images=test_images.reshape(10000,28,28,1)
test_images=test_images/255
model=tf.keras.models.Sequential([tf.keras.layers.Conv2D(64,(3,3),activation='relu',input_shape=(28,28,1)),\
tf.keras.layers.MaxPooling2D(2,2),\
tf.keras.layers.Conv2D(64,(3,3),activation='relu'),\
tf.keras.layers.MaxPooling2D(2,2),\
tf.keras.layers.Flatten(),\
tf.keras.layers.Dense(128,activation=tf.nn.relu),\
tf.keras.layers.Dense(10,activation=tf.nn.softmax)])
model.compile(optimizer=tf.optimizers.Adam(),loss='sparse_categorical_crossentropy')
model.fit(train_images,train_labels,epochs=5,callbacks=[callback])
model.summary()
test_loss=model.evaluate(test_images,test_labels)
##每层可视化
print(test_labels[0:40])
f,axarr=plt.subplots(3,4)
FIRST_PICTURE=0
SECOND_PICTURE=23
THIRD_PICTURE=2
CV_N=1 #第l层的第CV_N个卷积滤波器
from tensorflow.keras import models
layer_outputs=[layer.output for layer in model.layers]
activation_model=tf.keras.models.Model(inputs=model.input,outputs=layer_outputs)#输入都是原来那个图片 layer的参数已经训练好了,所以每个layer的输出是这样的
for x in range(0,4):
f1=activation_model.predict(test_images[FIRST_PICTURE].reshape(1,28,28,1))[x]
axarr[0,x].imshow(f1[0,:,:,CV_N],cmap='inferno')
axarr[0,x].grid(False)
f2=activation_model.predict(test_images[SECOND_PICTURE].reshape(1,28,28,1))[x]
axarr[1,x].imshow(f1[0,:,:,CV_N],cmap='inferno')
axarr[1,x].grid(False)
f3=activation_model.predict(test_images[THIRD_PICTURE].reshape(1,28,28,1))[x]
axarr[2,x].imshow(f1[0,:,:,CV_N],cmap='inferno')
axarr[2,x].grid(False)
用fashion数据集进行CNN的训练,数据集的类型是numpy,Conv2D需要有4dimension,(nums of train_data,size,size,channel)
遇到的问题:tensorflow版本不同 有的语法不同
碰到Adam优化器用不了,下列链接可以解决:
解决方法
感觉csdn这个还蛮好用的诶。
可以很开心的写日记了 哈哈
keras卷积核的维度:
https://blog.csdn.net/WepLeo/article/details/76615857