基于PCA的字体分类代码


使用pca和机器学习算法,完成不同字体的分类模型,详细代码请私信,包含数据集,完整的jupyter代码,英文报告。

1 数据集介绍

数据集来源于:https://www.kaggle.com/datasets/nikbearbrown/tmnist-alphabet-94-characters?datasetId=1564532&sortBy=voteCount ,这是两种不同的字体,我们需要对其进行分类。
在这里插入图片描述
在这里插入图片描述

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import OneHotEncoder
x1 = df[df["names"] == "Teko-Light"]
x2 = df[df["names"] == "SpectralSC-Medium"]
#我们选择x1和x2数据集中的ABCD分别展示出来
def get_alpha_image(x, label):
    alpha = x[x["labels"] == label]
    alpha_image = alpha.iloc[0, 2:].values.reshape((28, 28))
    return np.asarray(alpha_image, dtype=int)
A = get_alpha_image(x1, "A")
B = get_alpha_image(x1, "B")
C = get_alpha_image(x1, "C")
D = get_alpha_image(x1, "D")

fig = plt.figure()
ax = fig.subplots(1, 4)
plt.title("Teko-Light", x=-1.5, y=1.5)
ax[0].imshow(A)
ax[1].imshow(B)
ax[2].imshow(C)
ax[3].imshow(D)
plt.show()

A = get_alpha_image(x2, "A")
B = get_alpha_image(x2, "B")
C = get_alpha_image(x2, "C")
D = get_alpha_image(x2, "D")

fig = plt.figure()
ax = fig.subplots(1, 4)
plt.title("SpectralSC-Medium", x=-1.5, y=1.5)
ax[0].imshow(A)
ax[1].imshow(B)
ax[2].imshow(C)
ax[3].imshow(D)
plt.show()

2 PCA

from sklearn.decomposition import PCA
pca = PCA(100)
pca.fit(x_train)
new_x_train = pca.transform(x_train)
new_x_test = pca.transform(x_test)

3 SVM

from sklearn.svm import  SVC
model  = SVC()
model.fit(new_x_train, y_train)
train_y_pred = model.predict(new_x_train)
test_y_pred = model.predict(new_x_test)

from sklearn.metrics import accuracy_score, confusion_matrix

print("train acc {}".format(round(accuracy_score(y_train, train_y_pred),4 )))
print("test acc {}".format(round(accuracy_score(y_test, test_y_pred),4 )))

print("train confusion_matrix: ")
print(confusion_matrix(y_train, train_y_pred))
print("test confusion_matrix: ")
print(confusion_matrix(y_test, test_y_pred))

在这里插入图片描述

4 参数调优

pca_n = [25, 50, 100,150]
svm_c = [0.1, 1, 10,100,200]
acc_result = []
for n in pca_n:
    acc_one = []
    for c in svm_c:
        pca = PCA(n)
        pca.fit(x_train)
        new_x_train = pca.transform(x_train)
        new_x_test = pca.transform(x_test)
        model  = SVC(C = c)
        model.fit(new_x_train, y_train)
        test_y_pred = model.predict(new_x_test)
        test_acc = round(accuracy_score(y_test, test_y_pred),4 )
        print("pca-N: {:<5} svm-C: {:<5} test-acc: {:<5}".format(n, c, test_acc))
        acc_one.append(test_acc)
    acc_result.append(acc_one)

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王小葱鸭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值