我在研究支持向量机,使用gridsearchcv提取了多项式、线性和RBF的最佳参数。我希望分离出C和degree值,以便在fit函数中调用数据集的最佳参数,从而计算调整后的参数的准确性。
包含元组的字典是
({‘C’: 1, ‘degree’: 1}, {‘C’: 0.1, ‘degree’: 1}, {‘C’: 1, ‘degree’: 1})
我尝试使用
for i in c.items(): value=i print(value)
但得到了错误:AttributeError: ‘tuple’ object has no attribute ‘items’
我的代码进展如下:
def svc_param_selection(self, X, y, nfolds): #我们使用svc_param_selection调整两个超参数C和d #松弛惩罚超参数 Cs = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100] #svc多项式核的度数 degrees = [1, 2, 3, 4, 5] #初始化参数网格为字典 param_grid = {'C': Cs, 'degree' : degrees} #使用输入的nfold交叉验证初始化最佳参数搜索 search = grid_search.GridSearchCV(svm.SVC(kernel='poly'), param_grid, cv=nfolds) search1 = grid_search.GridSearchCV(svm.SVC(kernel='linear'), param_grid, cv=nfolds) search2 = grid_search.GridSearchCV(svm.SVC(kernel='rbf'), param_grid, cv=nfolds) #将搜索对象拟合到输入的训练数据上 search.fit(X, y) search1.fit(X, y) search2.fit(X, y) #返回最佳参数 search.best_params_ search1.best_params_ search2.best_params_ print("[*] 正在搜索最适合数据拟合的最佳参数.......") print("参数为:") #print(search.best_params_) #print(search1.best_params_) #print(search2.best_params_) return search.best_params_,search1.best_params_,search2.best_params_def param_sel(self): X_train,y_train,X_test,y_test=self.norm() #self.svc_param_selection(X_train, y_train, 10) degree=np.array([]) c= self.svc_param_selection(X_train, y_train, 10) print(c) for i in c.items(): value=i print(value)def fit(self): X_train,y_train,X_test,y_test=self.norm() final_svc_poly1 = svm.SVC(C=1, degree=1, kernel='poly') final_svc_poly2 = svm.SVC(C=1, degree=1, kernel='linear') final_svc_poly3 = svm.SVC(C=1, degree=1, kernel='rbf') final_svc_poly1.fit(X_train, y_train) final_svc_poly2.fit(X_train, y_train) final_svc_poly3.fit(X_train, y_train) print("[*] 正在计算测试数据集的准确性") print("多项式核的准确性",final_svc_poly1.score(X_test, y_test)) print("线性核的准确性",final_svc_poly2.score(X_test, y_test)) print("RBF核的准确性",final_svc_poly3.score(X_test, y_test))
输出:
[*] 正在搜索最适合数据拟合的最佳参数.......参数为:({'C': 1, 'degree': 1}, {'C': 0.1, 'degree': 1}, {'C': 1, 'degree': 1})---------------------------------------------------------------------------AttributeError Traceback (most recent call last)<ipython-input-106-4be4dd58a851> in <module> 1 if __name__=='__main__':----> 2 main()<ipython-input-105-7b466d716ef5> in main() 7 #X_train,y_train=first.split_data() 8 #print(X_train)----> 9 param=second.param_sel() 10 second.fit()<ipython-input-104-57f0d958ed41> in param_sel(self) 69 c= self.svc_param_selection(X_train, y_train, 10) 70 print(c)---> 71 for i in c.items(): 72 value=i 73 print(value)
AttributeError: ‘tuple’ object has no attribute ‘items’
回答:
你的值 – C=({'C': 1, 'degree': 1}, {'C': 0.1, 'degree': 1}, {'C': 1, 'degree': 1})
是一个字典的元组,因此它没有items
属性。
你可以这样遍历元组 –
for item in C: print(item)
因此,根据澄清进行修复 –
c_values = []degrees = []for item in C: c_values.append(item['C']) degrees.append(item['degree'])
顺便说一下 – 在你的循环中,你在每次迭代中覆盖了value,并且在循环外打印它。