到數第三天! 今天來一樣來學機器學習吧~
圖像分類的程式碼
# 匯入必要的函式庫
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from keras.utils import to_categorical
# 載入CIFAR-10資料集
(train_images, train_labels), (test_images, test_labels) = cifar10.load_data()
# 將圖像數據縮放到[0, 1]範圍
train_images = train_images.astype('float32') / 255
test_images = test_images.astype('float32') / 255
# 將標籤數據進行獨熱編碼
num_classes = 10
train_labels = to_categorical(train_labels, num_classes)
test_labels = to_categorical(test_labels, num_classes)
# 創建卷積神經網絡模型
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
# 編譯模型
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 訓練模型
model.fit(train_images, train_labels, epochs=10, batch_size=64, validation_data=(test_images, test_labels))
# 評估模型性能
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f'測試集準確率: {test_acc}')
# 使用模型進行預測
predictions = model.predict(test_images)
# 隨機選擇一個測試圖像並視覺化預測結果
index = np.random.randint(0, len(test_images))
plt.imshow(test_images[index])
predicted_label = np.argmax(predictions[index])
print(f'模型預測的標籤: {predicted_label}')
plt.show()
模型預測
目前進度:28/30!!