import time
import random
import xlsxwriter
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
def file2matrix(filename):
fr = open(filename)
lines = fr.readlines()
numberOfLines = len(lines)
returnMat = []
returnLabel = []
for line in lines:
line = line.strip()
listFromLine = line.split('\t')
if len(listFromLine) == 51: # 假设每行包含50个特征值和1个标签值
returnMat.append(listFromLine[0:50]) # 将前50个元素添加到returnMat中
returnLabel.append(listFromLine[-1]) # 将最后一个元素作为标签添加到returnLabel中
returnMat = np.array(returnMat, dtype=float) # 将returnMat转换为浮点类型的NumPy数组
returnLabel = np.array(returnLabel, dtype=float) # 将returnLabel转换为浮点类型的NumPy数组
return returnMat, returnLabel
def autoNorm(dataSet):
minVals = dataSet.min(0)
maxVals = dataSet.max(0)
normDataSet = (dataSet - minVals) / (maxVals - minVals)
return normDataSet
# 从文件中加载数据
datingDataMat, datingLabels = file2matrix(r'D:\Project\50数据.txt')
# 对数据进行归一化
dataSet = autoNorm(datingDataMat)
# 使用PCA进行降维
pca = PCA(n_components=3)
dataSet = pca.fit_transform(dataSet)
start = time.perf_counter()
testsize = 0.25
# 将数据集拆分为训练集和测试集
xtrain, xtest, ytrain, ytest = train_test_split(dataSet, datingLabels, test_size=testsize)
# 创建并训练SVM模型
model = svm.SVC()
model.fit(xtrain, ytrain)
error = 0
for i in range(len(xtest)):
# 预测每个测试实例的标签
result = model.predict(xtest[i, :].reshape(1, -1))
if result != ytest[i]:
error += 1
accuracy = (1 - error / len(xtest)) * 100
print('准确率:', accuracy, '%')
end = time.perf_counter()
duration = end - start
print('耗时', duration, '秒')
Oak
This code is an example of a Support Vector Machine (SVM) classifier in machine learning.
The main functions are as follows:
- Read the dataset from the given file (filepath
filename
). - Normalize the dataset to scale the eigenvalues to the same range.
- The dimensionality reduction of the data set was performed using principal component analysis (PCA), and the data was reduced from the original 50 dimensions to 3 dimensions.
- Split the dataset into training and testing sets.
- Create an SVM classifier model and train the model using the training set.
- A prediction is made for each instance in the test set and the accuracy is calculated.
- Output accuracy and execution time of the code.
Overall, the code implements an SVM-based classifier for classifying a dataset and evaluates the accuracy of the classifier.