banner
RustyNail

RustyNail

coder. 【blog】https://rustynail.me 【nostr】wss://ts.relays.world/ wss://relays.world/nostr

【調包俠的機器學習】圖片分類

%matplotlib inline
导入tensorflow as tf
!pip install d2l
从d2l导入tensorflow as d2l
(x_train,y_train),(x_test,y_test)= tf.keras.datasets.fashion_mnist.load_data()
#y_train
#d2l.show_images(tf.constant(x_train [:10]),1,10
x_train.shape,y_train.shape
((60000,28,28),(60000,))
#一个热y,10个类
y_train_hot = tf.one_hot(y_train [:],10
y_train_hot.shape
TensorShape([60000,10])
x_train_shaped = tf.reshape(x_train,[60000-1])/ 255
x_train_shaped.shape,x_train_shaped [:1]
(TensorShape([60000,784]),
 <tf.Tensor:形状=(1,784),dtype = float32,numpy =
数组([[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]],dtype = float32)>)
net = tf.keras.Sequential([
    tf.keras.layers.Dense(units = 10,input_dim = 784,activation = tf.keras.activations.softmax)
])
sgd = tf.keras.optimizers.SGD(learning_rate = 0.01
net.compile(optimizer = sgd,loss ='mse',metrics = ['accuracy'])
history = net.fit(x_train_shaped,y_train_hot,batch_size = 1000,epochs = 500,validation_split = 0.2
net.summary()
Epoch 1/500
48/48 [==============================] - 0s 4ms/step - loss: 0.0957 - accuracy: 0.0224 - val_loss: 0.0950 - val_accuracy: 0.0231
Epoch 500/500
48/48 [==============================] - 0s 2ms/step - loss: 0.0347 - accuracy: 0.7809 - val_loss: 0.0346 - val_accuracy: 0.7787
Model: "sequential_2"
_________________________________________________________________
 Layer(type)                Output Shape              Param #   
=================================================================
 dense_3(Dense)             (None,10)                7850      
                                                                 
=================================================================
Total params: 7,850
Trainable params: 7,850
Non-trainable params: 0
_________________________________________________________________
print(x_test.shape)
x_test_shaped = tf.reshape(x_test,[10000-1])/ 255
y_test_hot = tf.one_hot(y_test,10
x_test_shaped.shape,y_test_hot.shape
(10000,28,28)
(TensorShape([10000,784]),TensorShape([10000,10]))
net.evaluate(x_test_shaped,y_test_hot)
313/313 [==============================] - 1s 2ms/step - loss: 0.0357 - accuracy: 0.7704
[0.03569139540195465,0.7703999876976013]
#!pip install matplotlib
导入matplotlib.pyplot as plt
print(“keys:”,history.history.keys())
plt.plot(history.history [“loss”],label =“loss”)
plt.plot(history.history [“accuracy”],label =“accuracy”)
plt.plot(history.history [“val_loss”],label =“val_loss”)
plt.plot(history.history [“val_accuracy”],label =“val_accuracy”)
plt.legend()
plt.show()
keys:dict_keys(['loss','accuracy','val_loss','val_accuracy'])

![png](https://oss.rustynail.me/someone/api/files/get?filePath=files/output_9_1.png)

py = net.predict(x_test_shaped)
py.argmax(axis = 1).shape
313/313 [==============================] - 0s 866us/step
(10000,)
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。