首页 > 编程语言 >SVM多分类--PYTHON

SVM多分类--PYTHON

时间:2022-11-08 11:26:23浏览次数:44  
标签:SVM -- PYTHON train import print new sklearn svm

import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.model_selection import cross_val_score
import warnings
warnings.filterwarnings("ignore")
from sklearn import svm, datasets, feature_selection
from sklearn.feature_selection import SelectPercentile, f_classif


#data = pd.read_excel('XGboost补充.xlsx')
data = pd.read_excel('样本内.xlsx')

X = data.iloc[:, 1:].values
y = data.iloc[:, 0].values


#from sklearn.feature_selection import VarianceThreshold
#vt = VarianceThreshold()
#vt.fit_transform(X)
#var_thd = pd.DataFrame(vt.variances_, columns = ["Variance"])
#var_thd = var_thd.reset_index()
#sorts = var_thd.sort_values('Variance',ascending=0)
#print(sorts)
#sorts_DF = pd.DataFrame(sorts)
#sorts_DF.to_csv(path_or_buf="SVM特征选择.csv",index=False)






X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)
#归一化处理
from sklearn.preprocessing import StandardScaler
StandardScaler = StandardScaler()
StandardScaler.fit(X_train)
X_train = StandardScaler.transform(X_train)
X_test = StandardScaler.transform(X_test)


#调参
from sklearn.model_selection import GridSearchCV
grid = GridSearchCV(SVC(), param_grid={"C": [0.1, 1, 10], "gamma": [1, 0.1, 0.01]}, cv=4) # 总共有9种参数组合的搜索空间
grid.fit(X, y)
print("The best parameters are %s with a score of %0.2f"
% (grid.best_params_, grid.best_score_))


clf_svm = svm.SVC(C=10, gamma=0.01,max_iter=200, class_weight='balanced')
clf_svm.fit(X_train, y_train)
y_svm_pred = clf_svm.predict(X_test)
print("支持向量机预测测试集准确率为:",accuracy_score(y_test,y_svm_pred))
print("支持向量机预测测试集结果与实际结果的混淆矩阵为:\n",confusion_matrix(y_test,y_svm_pred))
print("支持向量机预测结果评估报告为:\n",classification_report(y_test,y_svm_pred))
print("交叉验证的结果为:",cross_val_score(clf_svm,X,y,cv=5))



#Test on Training data
train_result = clf_svm.predict(X_train)
precision = sum(train_result == y_train)/y_train.shape[0]
print('Training precision: ', precision)
#Test on test data
test_result = clf_svm.predict(X_train)
precision = sum(test_result == y_train)/y_train.shape[0]
print('Test precision: ', precision)



#data_new = pd.read_excel('样本外-随机森林.xlsx')
#data_new = pd.read_excel('样本外.xlsx')
data_new = pd.read_excel('样本外--隐含评级.xlsx')
x_new_train = data_new.iloc[:, 1:].values
y_new_train = data_new.iloc[:, 0].values
x_new_train = StandardScaler.transform(x_new_train)
y_new_pred = clf_svm.predict(x_new_train)
print(y_new_pred,y_new_train)
result_new_1 = accuracy_score(y_new_train, y_new_pred)
print("Accuracy:", result_new_1)
result_new_2 = confusion_matrix(y_new_train, y_new_pred)
print("Confusion Matrix:")
print(result_new_2)
result_new_3= classification_report(y_new_train, y_new_pred)
print("Classification Report:", )
print(result_new_3)

标签:SVM,--,PYTHON,train,import,print,new,sklearn,svm
From: https://www.cnblogs.com/maxzz/p/16869030.html

相关文章

  • markdown基础语法,windows快捷键和常用的Dos命令
    Markdown学习标题:#号加空格,回车生成一级标题需要几号标题就在前面加几个#号,最多是六个#二级标题三级标题四级标题五级标题六级标题字体Helloworld!(粗体是前后两......
  • centos确认防火墙
    https://blog.csdn.net/lemon_lrj/article/details/124131221 1、命令行界面输入命令“systemctlstatusfirewalld.service”并按下回车键。2、然后在下方可度以查看......
  • Day05:Java运算时的类型转换
    Java运算时的类型转换在Java运算时,不同的数据类型之间可以进行加减乘除的预算;但是,不同类型的数据需要先转换为同一类型才能够运算强制类型转换从字节大小排序数据类型......
  • python总结
    #字符串的合并s1="abc"s2="def"s=s1+s2print(s)#"abcdef"s="".join([s1,s2])#前提:序列里面的元素必须是字符串print(s)#"abcdef"fromfunctoolsimportreduce......
  • golang批量处理M个Task设置消费者只有N个然后逐个消费
    1、消费逻辑封装:packageutilsimport("context""errors""fmt")//ConsumerFuncparamsecondislist.itemtypeConsumerFuncfunc(context.Conte......
  • iOS15.6以后UITableview设置UITableViewStyleGrouped底部会多出一段空白
    在适配iPhone14的过程中,发现之前没问题的UITableview底部会多出一截,查看低版本系统手机正常显示,iOS15.6的iPhone11也有同样的问题。继iOS11以后UITableview多出空白又有新......
  • C# MVC 权限过滤器
    实现需求:验证Token是否有效,重写状态码和返回内容///<summary>///权限过滤器,验证Token是否有效///</summary>///<paramname="filterCo......
  • git代码管理 之 文件夹/文件修改大小写问题
    问题复现1、创建一个TEST文件夹,TEST文件夹下有一个test.js文件。2、将这个修改推送到gitee仓库上3、修改本地文件夹的名字大小写,从TEST,修改为Test。这个时候就出现......
  • github 设置代理
    1.直接修改.git/config文件注意:仅对当前仓库有效,推荐这种,因为不是所有的仓库都需要走代理[http"https://github.com"] proxy=http://127.0.0.1:10802.命......
  • 怎么选工作流表单设计器?
    随着业务量的扩大,很多企业都想选择一款优良的工作流表单设计器来提升工作效率和质量。在大数据时代,操作简单、维护便利的工作流表单设计器确实能为企业的发展带来更大的帮......