0% found this document useful (0 votes)
11 views7 pages

Flower CNN

Uploaded by

jj Kim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views7 pages

Flower CNN

Uploaded by

jj Kim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

from google.

colab import drive


drive.mount('/content/drive')
import cv2
import matplotlib.pyplot as plt
path="/content/drive/MyDrive/NUUME/人工智慧/Flower/training"
dirs = {"4_tulip": 4, "3_sunflower": 3, "2_rose": 2, "1_dandelion": 1, "0_daisy": 0}
img = cv2.imread("/content/drive/MyDrive/NUUME/人工智
慧/Flower/training/0_daisy/10140303196_b88d3d6cec.jpg")#
#img = cv2.imread("/content/drive/MyDrive/Colab
Notebooks/data/Mid_EX/train/flower_data/test/1128626197_3f52424215_n.jpg")
plt.imshow(img, cmap="gray")
resized_img = cv2.resize(img, (144,144), interpolation = cv2.INTER_AREA)
plt.imshow(resized_img, cmap="gray")
#-----------------------------------------------------------------------------------------------------------
import glob
from tqdm import tqdm
import os
y_ = []
data_x = []
classN = next(os.walk(path))
dim = (128, 128)
#-----------------------------------------------------------------------------------------------------------
for i in range(len(classN[1])):
class_path = path + '/' + classN[1][i] + '/*.*'
print(class_path)
img_path = glob.glob(class_path)
print(img_path)

for j in tqdm(range(len(img_path))):
y_.append(dirs[classN[1][i]])
img = cv2.imread(img_path[j], 1)
resized_img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
data_x.append(resized_img)
#-----------------------------------------------------------------------------------------------------------
import pandas as pd
import numpy as np
data_DF = pd.get_dummies(y_)
y_one_hot=np.array(data_DF, dtype='float32')
data_x = np.array(data_x, dtype='float32')
x_= data_x/255
print(x_.shape)
print(y_one_hot.shape)
# 使用 sklearn 的 train_test_split 之前,先洗牌圖像和標籤
from sklearn.utils import shuffle
data_x, y_one_hot = shuffle(data_x, y_one_hot, random_state=42)
from sklearn.model_selection import train_test_split
#-------------- training set, testing set 分割-----------------------------
x_train, x_test, y_train, y_test = train_test_split(data_x, y_one_hot, test_size=0.10,
random_state=42)
#---------------------check data----------------------------------
print("training set data dimension")
print(x_train.shape)
print(y_train.shape)
print("-----------")
print("training set: %i" % len(x_train))
print("testing set: %i" % len(x_test))
print(x_test.shape)
print(y_test.shape)
#-----------------------------------------------------------------------------------------------------------
import cv2
from google.colab.patches import cv2_imshow
no_pitc=3100

#gray cv2. evtColor (x train[no_pitc. 1.


imgg=x_train[no_pitc, :, :, :]
cv2_imshow(imgg)
print(y_train[no_pitc])
#-----------------------------------------------------------------------------------------------------------
import cv2
import matplotlib.pyplot as plt
import glob
from tqdm import tqdm
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
#-----------------------------------------------------------------------------------------------------------
# 定義超參數
batch_size = 64
learning_rate = 0.0001
epochs = 40

# 正規化像素值
x_train_normalized = x_train / 255.0
x_test_normalized = x_test / 255.0

# 定義模型
model = Sequential([
Conv2D(256, (3, 3), activation='relu', input_shape=(128, 128, 3)),
MaxPooling2D((2, 2)),
Conv2D(128, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Conv2D(32, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Flatten(),
Dense(32, activation='relu'),
Dense(5, activation='softmax') # 5 classes for 5 types of flowers
])
# 編譯模型
model.compile(optimizer=Adam(learning_rate=learning_rate),
loss='categorical_crossentropy',
metrics=['accuracy'])

# 訓練模型
history = model.fit(x_train_normalized, y_train,
epochs=epochs,
batch_size=batch_size,
validation_data=(x_test_normalized, y_test))
model.save('model_CNN_0607T1.keras')
# 繪製訓練和驗證的損失及準確率曲線
plt.figure(figsize=(12, 4))

plt.subplot(1, 2, 1)
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()

plt.subplot(1, 2, 2)
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()

plt.show()
#-----------------------------------------------------------------------------------------------------------
# Plot training and validation accuracy and loss
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(25)
# Predict on the test set
predictions = model.predict(x_test)
predicted_classes = np.argmax(predictions, axis=1)
true_classes = np.argmax(y_test, axis=1)
#-----------------------------------------------------------------------------------------------------------
# Save the predictions to a CSV file
results_df = pd.DataFrame({
'True Class': true_classes,
'Predicted Class': predicted_classes
})
results_df.to_csv('/content/drive/MyDrive/NUUME/人工智慧/Flower/results_0607-
1.csv', index=False)

print("Predictions saved to results.csv")


#-----------------------------------------------------------------------------------------------------------
from tensorflow.keras.models import load_model
import os
import cv2
import numpy as np
import pandas as pd

# 載入訓練好的模型
model = load_model('model_CNN_0607T1.keras')

# 讀取測試資料
csv_path = '/content/drive/MyDrive/NUUME/人工智
慧/Flower/submission_answer.csv'
if not os.path.exists(csv_path):
raise FileNotFoundError(f"CSV file not found: {csv_path}")

test_data = pd.read_csv(csv_path)

# 確認資料格式
if 'id' not in test_data.columns:
raise ValueError("CSV file must contain 'id' column")

test_images = test_data['id'].astype(str)
path = "/content/drive/MyDrive/NUUME/人工智慧/Flower/test"

# 初始化列表以存儲預測結果
predictions = []

# 迭代每個圖像路徑
for image_name in test_images:
image_name_with_extension = image_name + ".jpg"
# 構建完整圖像路徑
image_path = os.path.join(path, image_name_with_extension)
# 檢查圖像是否存在
if not os.path.exists(image_path):
print(f"Image not found: {image_path}")
continue
# 讀取圖像
image = cv2.imread(image_path)
# 如果圖像讀取成功
if image is not None:
print(f"Reading image: {image_path}")
# 對圖像進行大小調整
resized_img = cv2.resize(image, (128, 128), interpolation=cv2.INTER_AREA)
# 正規化圖像像素值
normalized_img = resized_img / 255.0
# 將圖像轉換為模型所需的格式:(1, height, width, channels)
input_image = np.expand_dims(normalized_img, axis=0)
# 使用模型進行預測
prediction = model.predict(input_image)
# 取得預測結果中概率最高的類別索引
predicted_class_index = np.argmax(prediction)
# 將預測結果添加到列表中
predictions.append(predicted_class_index)
print(f"Prediction for image {image_name}: {predicted_class_index}")
else:
print(f"Failed to read image: {image_path}")

# 將預測結果列表轉換為 NumPy 陣列
predictions = np.array(predictions)

print("Predictions:", predictions)
#-----------------------------------------------------------------------------------------------------------
true_name = test_data.iloc[:, 1].astype(float)
#print(true_name)
k=0
for i in range(len(true_name)):
if true_name[i] == predictions[i]:
k=k+1
#print("correct")
#else:
#print("wrong")
acc = (k/len(true_name))*100
print("Accuracy: {}%".format(acc))

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy