python - 函数不断选择第一个 clf 作为最佳模型
问题描述
我按照本教程为 midi 文件制作流派分类器,我终于到了可以尝试隐藏网络大小等的部分,但是我发现我的函数一直选择第一个模型作为最佳模型,无论其准确性如何。代码看起来应该对我有用,但我觉得我错过了一些非常简单的东西。
def train_model(t_features, t_labels, v_features, v_labels):
"""
this func trains a nn using a few dif configs
INPUT: training features(nparray flt), training labels(nparray int), validation features(nparray float), validation labels(nparay int)
OUTPUT: the classifier which achieved the best validation accuracy (sklearn neural multilayer perceptron)
"""
#NN and SVM Configs
clf1 = MLPClassifier(solver='adam', alpha=1e-4, hidden_layer_sizes=(100, 100), random_state= 1)
clf2 = MLPClassifier(solver='adam', alpha=1e-4, hidden_layer_sizes=( 40, 20, 10, 5, 1), random_state= 1)
clf3 = MLPClassifier(solver='adam', alpha=1e-4, hidden_layer_sizes=(240, 120, 80, 40, 20, 10, 1), random_state= 1)
clf4 = MLPClassifier(solver='sgd', alpha=1e-4, hidden_layer_sizes=(12, 10), random_state= 1)
clf_svm = SVC()
#keep track of best model
best_clf = None
best_accurracy = 0
#test accuracies of models and get the best one
for clf in [clf1, clf2, clf3, clf4, clf_svm]:
t_labels_hot = one_hot(t_labels)
v_labels_hot = one_hot(v_labels)
if (type(clf) == SVC):
clf = clf.fit(t_features, t_labels)
else:
clf = clf.fit(t_features, t_labels_hot)
predictions = clf.predict(v_features)
count = 0
for i in range(len(v_labels)):
if (type(clf) != SVC):
if np.array_equal(v_labels_hot[i], predictions[i]):
count += 1
else:
if (v_labels[i] == predictions[i]):
count += 1
accuracy = count / len(v_labels_hot)
if accuracy > best_accurracy:
best_accurracy= accuracy
best_clf = clf
print(best_clf)
print("best accuracy:", best_accurracy)
return best_clf
解决方案
推荐阅读
- java - java:使用 Optional 优化 Java 中的 if 语句
- python - 如何将整数列表转换并保存为位图图像?
- angularjs - Yarn + Lerna + Angular Libs = 出版失败?
- c++ - 递归函数的 Matlab 代码生成
- javascript - Javascript 只能访问 Ajax 之后的一些新 DOM 有什么原因吗?
- asp.net-core - 在 ASP.NET Core Startup.cs 中访问当前用户
- visual-studio-code - Vscode 没有在面板中显示问题选项卡
- java - 将两个 Double 相除并将 Double 商乘以 Int 时如何将 Double 转换为 Int?
- jsonschema - JSON Schema - 在引用的 Json 中使用条件逻辑
- python - 评论没有在我的 Django Python 网站上打印出来