Hyperopt错误TypeError: 'generator' object is not subscriptable

最近在使用学习机器学习算法时,使用下python的调参库 Hyperopt, 发现程序一直出现问题,结果发现不是程序问题,而是在安装 Hyperopt时出现问题。

在安装Hyperopt时 会自动安装依赖库 networkx-2.1, 结果发现其并不支持 Hyperopt-0.1

解决方法:

卸载 networkx : pip uninstall networkx 


下载 networkx-1.11 版本



或者直接安装: pip install networkx==1.11

Hyperopt

分布式异步超参数优化,用于在搜索空间上进行串行和并行优化,其中可能包括实值,离散和条件维度。

Hyperopt的工作是通过一组可能的参数找到标量值,可能随机函数的最佳值。虽然许多优化软件包会假设这些输入来自向量空间,但Hyperopt的不同之处在于它鼓励您更详细地描述搜索空间。通过提供有关定义函数的位置以及您认为最佳值在哪里的更多信息,可以让hyperopt中的算法更有效地进行搜索。


使用hyperopt的方式是描述:

  • 目标函数最小化
  • 搜索的空间
  • 在其中存储搜索的所有点评估的数据库
  • 要使用的搜索算法

这个(最基本的)教程将介绍如何编写函数和搜索空间,使用默认Trials数据库和伪random搜索算法。

(1)节介绍了目标函数和hyperopt之间通信的不同调用约定。

hyperopt的优化算法与您的目标函数之间进行通信的最简单协议是您的目标函数从搜索空间接收到有效点,并返回与该点关联的浮点损失(又称负效用)

from hyperopt import fmin, tpe, hp
best = fmin(fn=lambda x: x ** 2,
    space=hp.uniform('x', -10, 10),
    algo=tpe.suggest,
    max_evals=100)
print best

(2)部分是关于描述搜索空间的。

搜索空间由嵌套的函数表达式组成,包括随机表达式。随机表达式是超参数。从这个嵌套的随机程序中抽样定义了随机搜索算法。超参数优化算法的工作原理是将正常的“采样”逻辑替换为自适应探索策略,它们不会尝试从搜索空间中指定的分布中进行实际采样。
from hyperopt import hp
space = hp.choice('a',
    [
        ('case 1', 1 + hp.lognormal('c1', 0, 1)),
        ('case 2', hp.uniform('c2', -10, 10))
    ])

实例:

感知器判别鸢尾花数据的代码,使用的学习率是0.1, 迭代50次得到了一个测试集上正确率为82%的结果。使用hyperopt优化参数,将正确率提升到了93%,可见参数优化对于提高模型精度,至关重要。

# -*- coding:utf-8 -*-
# author: charlesyy time:2018/05/14
import numpy
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
iris = datasets.load_iris() # multi-class classification,
#  Classes                          3
# Samples per class               50
# Samples total                  150
# Dimensionality                   4
# Features            real, positive
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
sc.fit(X_train)
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)

from sklearn.linear_model import Perceptron
ppn = Perceptron(n_iter=50, eta0=0.1, random_state=0)
ppn.fit(X_train_std, y_train)

y_pred = ppn.predict(X_test_std)
print('未使用参数优化', accuracy_score(y_test, y_pred))

# 使用Hyperopt
def percept(args):
    global X_train_std, y_train, y_test
    ppn = Perceptron(n_iter=int(args["n_iter"]), eta0=args["eta"]*0.01, random_state=0)
    ppn.fit(X_train_std, y_train)
    y_pred = ppn.predict(X_test_std)
    return -accuracy_score(y_test, y_pred)

from hyperopt import fmin, tpe, hp, partial
space = {"n_iter": hp.choice("n_iter", range(30, 50)),
         "eta": hp.uniform("eta", 0.05, 0.5)}
algo = partial(tpe.suggest, n_startup_jobs=10)
best = fmin(fn=percept, space=space, algo=algo, max_evals=100)
print(best)
print('使用参数优化:', percept(best))



TypeError: 'NoneType' object is not subscriptable python3写的代码

10-09

报错在图片里面,不清楚具体怎么改。[img=http://img.bbs.csdn.net/upload/201710/09/1507512052_96666.png][/img]rn[code=python]rn# -*- coding: utf-8 -*-rn"""rnCreated on Sun Oct 8 20:20:44 2017rnrn@author: llrn"""rnrnimport numpy as nprnrndef findMax1(array):rn if len(array)<1:#len(array)得到列表长度rn return [-1,-1]rn index = 1rn unit = array[index]rn for j in range(1,len(array)):rn if array[j] > array[index+1] and array[j] > array[index-1]:#if的含多条件语句的写法rn unit = array[j]rn return [unit,j]#返回的是一个列表类型,最大值和它的坐标1rnrndef getMax1(matrix, column_Num):rn array = [col[column_Num] for col in matrix]#将找到的列循环遍历后放到列表中rn return findMax1(array)rn rndef getPeak(matrix, leftCol, rightCol):rn if rightCol <= leftCol:rn r = getMax1(matrix,leftCol)rn r.append(leftCol)rn mid = int((leftCol + rightCol) / 2)rn unit = getMax1(matrix, mid)#返回的变量名要和接收传参的名字一样rnrn rightElem = getMax1(matrix, mid+1)rn if leftCol == rightCol - 1:rn leftElem = unitrn if leftElem[0] > rightElem[0]:rn r = leftElemrn r.append(mid)rn else:rn r = rightElemrn r.append(mid+1)rn return rrnrn leftElem = getMax1(matrix, mid-1)rn if unit[0] >= leftElem[0] and unit[0] >= rightElem[0]:rn unit.append(mid)rn return unitrn if unit[0] < leftElem[0]:rn return getPeak(matrix,leftCol,mid-1)rn return getPeak(matrix,mid+1,rightCol)rnrnrnrnprint("please input row:")rnn = int(input())rnprint("please input column:")rnm = int(input())rnmatrix = np.random.randint(100,999,size=[n,m])rnprint(matrix)rnrnresult = getPeak(matrix,0,len(matrix[0])-1)rnrnprint(result)rnrn[/code]

pyqt问题:TypeError: 'sip.methoddescriptor' object is not callable

09-21

用pyqt4的qt设计师做了个主窗口,然后放了个按钮,弄了个槽:点按钮后,窗口退出rnrn然后:pyuic4 -o test.py test.uirnrn写了个测试脚本:rnfrom PyQt4.QtGui import * rnfrom PyQt4.QtCore import * rnimport sys rnimport test2 rn rnclass TestDlg(QDialog, test2.Ui_MainWindow): rn def __init__(self, parent=None): rn super(TestDlg, self).__init__(parent) rn self.setupUi(self) rnapp = QApplication(sys.argv) rndialog = TestDlg() rndialog.show() rnrnrn执行报错:rnTraceback (most recent call last):rn File "F:\Python26\Lib\site-packages\PyQt4\test919.py", line 11, in rn dialog = TestDlg()rn File "F:\Python26\Lib\site-packages\PyQt4\test919.py", line 9, in __init__rn self.setupUi(self)rn File "F:\Python26\Lib\site-packages\PyQt4\test2.py", line 26, in setupUirn MainWindow.setCentralWidget(self.centralwidget)rnTypeError: 'sip.methoddescriptor' object is not callablernrntest.py 的内容是:rn# -*- coding: utf-8 -*-rnrn# Form implementation generated from reading ui file 'test2.ui'rn#rn# Created: Fri Sep 21 12:52:53 2012rn# by: PyQt4 UI code generator 4.9.4rn#rn# WARNING! All changes made in this file will be lost!rnrnfrom PyQt4 import QtCore, QtGuirnrntry:rn _fromUtf8 = QtCore.QString.fromUtf8rnexcept AttributeError:rn _fromUtf8 = lambda s: srnrnclass Ui_MainWindow(object):rn def setupUi(self, MainWindow):rn MainWindow.setObjectName(_fromUtf8("MainWindow"))rn MainWindow.resize(195, 69)rn self.centralwidget = QtGui.QWidget(MainWindow)rn self.centralwidget.setObjectName(_fromUtf8("centralwidget"))rn self.pushButton = QtGui.QPushButton(self.centralwidget)rn self.pushButton.setGeometry(QtCore.QRect(50, 10, 75, 23))rn self.pushButton.setObjectName(_fromUtf8("pushButton"))rn MainWindow.setCentralWidget(self.centralwidget)rn self.menubar = QtGui.QMenuBar(MainWindow)rn self.menubar.setGeometry(QtCore.QRect(0, 0, 195, 17))rn self.menubar.setObjectName(_fromUtf8("menubar"))rn MainWindow.setMenuBar(self.menubar)rn self.statusbar = QtGui.QStatusBar(MainWindow)rn self.statusbar.setObjectName(_fromUtf8("statusbar"))rn MainWindow.setStatusBar(self.statusbar)rnrn self.retranslateUi(MainWindow)rn QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.deleteLater)rn QtCore.QMetaObject.connectSlotsByName(MainWindow)rnrn def retranslateUi(self, MainWindow):rn MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))rn self.pushButton.setText(QtGui.QApplication.translate("MainWindow", "PushButton", None, QtGui.QApplication.UnicodeUTF8))rnrnrn【注明】老是提示:TypeError: 'sip.methoddescriptor' object is not callable,这是个什么东东?rn

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试