张政的技术专栏 A Coder

交叉调参

2017-11-10

阅读:


写了一个交叉调参的mod,主要是使用sklearn框架里的各个函数实现的。

(python3)

	from sklearn import datasets
	from sklearn.model_selection import train_test_split
	from sklearn.model_selection import GridSearchCV
	from sklearn.metrics import classification_report
	from sklearn.svm import SVC

	digits = datasets.load_digits()

	n_samples = len(digits.images)
	X = digits.images.reshape((n_samples, -1))
	y = digits.target

	X_train, X_test, y_train, y_test = train_test_split(
		X, y, test_size=0.5, random_state=0)
	tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],
						 'C': [1, 10, 100, 1000]},
						{'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]
	scores = ['precision', 'r2']
	for score in scores:
		print("# Tuning hyper-parameters for %s" % score)
		print()

		 # 调用 GridSearchCV,将 SVC(), tuned_parameters, cv=5, 还有 scoring 传递进去,
		clf = GridSearchCV(SVC(), tuned_parameters, cv=5,
						   scoring='%s_macro' % score)
		# 用训练集训练这个学习器 clf
		clf.fit(X_train, y_train)

		print("Best parameters set found on development set:")
		print()

		# 再调用 clf.best_params_ 就能直接得到最好的参数搭配结果
		print(clf.best_params_)

		print()
		print("Grid scores on development set:")
		print()
		means = clf.cv_results_['mean_test_score']
		stds = clf.cv_results_['std_test_score']

		# 看一下具体的参数间不同数值的组合后得到的分数是多少
		for mean, std, params in zip(means, stds, clf.cv_results_['params']):
			print("%0.3f (+/-%0.03f) for %r"
				  % (mean, std * 2, params))

		print()

		print("Detailed classification report:")
		print()
		print("The model is trained on the full development set.")
		print("The scores are computed on the full evaluation set.")
		print()
		y_true, y_pred = y_test, clf.predict(X_test)

		# 打印在测试集上的预测结果与真实值的分数
		print(classification_report(y_true, y_pred))

		print()

调参确实实现了,不过作用在我们的数据集上,用了好几种机器学习方法结果都不好,只能试试深度学习的神经网络了(烦~~)。


Similar Posts

下一篇 NAN问题

Comments