import os
import numpy as np
from PIL import Image
from sklearn import svm
from sklearn.model_selection import train_test_split
# 定义函数读取图像数据
def load_images_from_folder(folder):
images=[]
for filenames in os.listdir(folder):
img = Image.open(os.path.join(folder,filenames))
img = img.resize((64,64))
if img is not None:
images.append(np.array(img).flatten())
return images
X = [] #储存图像数据
y = [] #储存图像标签
root_folder = r"C:\Users\33711\Desktop\Images" #指定根文件夹路径
for i, foldername in enumerate(os.listdir(root_folder)): #enumerate 函数获取每个子文件夹的索引 i 和文件夹名 foldername
images = load_images_from_folder(os.path.join(root_folder, foldername)) #调用 load_images_from_folder 函数加载指定文件夹中的图像数据
X.extend(images)
y.extend([i] * len(images)) #得到一个长度与当前文件夹图像数量相同的标签列表
# 将数据转换为NumPy数
X = np.array(X)
y = np.array(y)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练SVM模型
clf = svm.SVC(C = 3.0,max_iter=200)
clf.fit(X_train,y_train,sample_weight=None)
# 在测试集上进行预测
predictions = clf.predict(X_test)
for i, prediction in enumerate(predictions): #调用 enumerate函数
print(f"样本 {i+1}: 预测类别为 {prediction}, 实际类别为 {y_test[i]}")
# 计算准确率
accuracy = clf.score(X_test, y_test)
print("准确率:", accuracy)
import os
import numpy as np
from PIL import Image
from sklearn import svm
from sklearn.model_selection import train_test_split
# 定义函数读取图像数据
def load_images_from_folder(folder):
images=[]
for filenames in os.listdir(folder):
img = Image.open(os.path.join(folder,filenames))
img = img.resize((64,64))
if img is not None:
images.append(np.array(img).flatten())
return images
X = [] #储存图像数据
y = [] #储存图像标签
root_folder = r"D:\机器学习第三次作业\UCMerced_LandUse\Images" #指定根文件夹路径
for i, foldername in enumerate(os.listdir(root_folder)): #enumerate 函数获取每个子文件夹的索引 i 和文件夹名 foldername
images = load_images_from_folder(os.path.join(root_folder, foldername)) #调用 load_images_from_folder 函数加载指定文件夹中的图像数据