导入
识别更多对象——多类分类
学习如何将输出类别扩展到二分类之外,并了解为解决多分类问题需要进行哪些修改。
...
二分类与多分类
...
4096个输入及标签系统的三个星系类别
...
三种类型的星系
1# 导入所需库 2import numpy as np 3from PIL import Image 4from sklearn.model_selection import train_test_split 5from sklearn.svm import SVC 6from sklearn.metrics import accuracy_score 7 8def prepare_data(): 9 # 使用Pillow读取图像文件 10 img_list = [] 11 for i in range(1, 301): 12 img = Image.open('./gray_g'+str(i)+'.png').convert('L') 13 img_list.append(img) 14 15 # 将图像数据重塑为一维数组 16 img_data = np.array([np.array(img).flatten() for img in img_list]) 17 18 # 前100张图像标签为0,接下来的100张标签为1,最后100张标签为2 19 tag = np.concatenate((np.zeros(100), np.ones(100), np.ones(100)*2)) 20 21 return img_data, tag 22 23def get_model(): 24 # 返回选定的模型 25 return SVC() 26 27def train_model(model, data, tags): 28 29 # 训练支持向量机分类器 30 model.fit(data, tags) 31 32 return model 33 34def get_predictions(model, test_img): 35 36 # 获取预测结果 37 predictions = model.predict(test_img) 38 39 return predictions 40 41def evaluate_predictions(predicted_tags, actual_tags): 42 43 # 计算预测准确率 44 accuracy = accuracy_score(actual_tags, predicted_tags) 45 46 print("预测准确率:", accuracy) 47 48 49def main(): 50 51 # 数据准备 52 img_data, tags = prepare_data() 53 54 # 将数据划分为训练集和测试集 55 train_img, test_img, train_tags, test_tags = train_test_split(img_data, tags, test_size=0.2) 56 57 # 模型初始化 58 model = get_model() 59 60 # 模型训练 61 trained_model = train_model(model, train_img, train_tags) 62 63 # 预测阶段 64 predictions = get_predictions(trained_model, test_img) 65 66 # 评估预测结果 67 evaluate_predictions(predictions, test_tags) 68 69main()