# 导入必要的库
import numpy as np
import os
from PIL import Image
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# 加载图像数据
def load_image_data(image_dir):
X = []
y = []
class_labels = os.listdir(image_dir)
for label in class_labels:
class_dir = os.path.join(image_dir, label)
if os.path.isdir(class_dir):
for file_name in os.listdir(class_dir):
file_path = os.path.join(class_dir, file_name)
if file_path.endswith(('.png', '.jpg', '.jpeg')):
image = Image.open(file_path)
image = np.array(image)
X.append(image)
y.append(int(label))
return np.array(X), np.array(y)
# 加载数据
image_dir = 'path/to/your/image/directory' # 替换为你的图像数据路径
X, y = load_image_data(image_dir)
# 确保所有图像大小一致
assert all(img.shape == X[0].shape for img in X), "所有图像大小必须一致"
# 数据预处理:将图像数据展开为一维向量,并标准化数据
X = X.reshape((X.shape[0], -1))
scaler = StandardScaler()
X = scaler.fit_transform(X)
# 定义SVM模型
model = SVC(kernel='linear', C=1.0)
# 定义五折交叉验证
kf = KFold(n_splits=5, shuffle=True, random_state=42)
accuracy_list = []
for train_index, test_index in kf.split(X
# 导入必要的库
import numpy as np
import os
from PIL import Image
from sklearn.model_selection import train_test_split, KFold
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# 加载图像数据
def load_image_data(image_dir, target_size=(64, 64)):
X = []
y = []
class_labels = os.listdir(image_dir)
for label in class_labels:
class_dir = os.path.join(image_dir, label)
if os.path.isdir(class_dir):
for file_name in os.listdir(class_dir):
file_path = os.path.join(class_dir, file_name)
if file_path.endswith(('.png', '.jpg', '.jpeg')):
image = Image.open(file_path)
image = image.resize(target_size)
image = np.array(image)
if image.shape == (64, 64, 3): # 只保留形状为(64, 64, 3)的图像
X.append(image)
y.append(int(label))
return np.array(X), np.array(y)
# 加载数据
image_dir = 'path/to/your/image/directory' # 替换为你的图像数据路径
X, y = load_image_data(image_dir)
# 数据预处理:将图像数据展开为一维向量,并标准化数据
X = X.reshape((X.shape[0], -1))
scaler = StandardScaler()
X = scaler.fit_transform(X)
# 定义SVM模型
model = SVC(kernel='linear', C=1.0)
# 定义五折交叉验证
kf = KFold(n_splits=5, shuffle=True, random_state=42)
accuracy_list = []
for train_index, test_index in kf.split(X):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
# 训练SVM模型
model.fit(X_train, y_train)
# 评估模型
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
accuracy_list.append(accuracy)
# 输出平均准确率
print(f'平均准确率: {np.mean(accuracy_list):.4f}')