- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当我尝试在 python 中运行代码时遇到了这个问题,我该如何解决?
---> 95 验证(sm_classifier,x_test_normal_s,y_n2_test,y_test,classes_names,'NSLKDD SAE-SAE(测试)')
96 #if 姓名 == " main ":main() ## with if
97
<ipython-input-23-95022ce9a680> in validation(classifier, data, y_data, y_target, class_names, title)
52 print ("No accuracy to be computed")
53 else:
---> 54 accuracy = model_selection.cross_val_score(classifier,x, y_target, scoring='accuracy')
55 print("Accuracy: "+ str(accuracy))
56 precision = model_selection.cross_val_score(self.classifier, x, target, scoring='precision')
C:\ProgramData\Anaconda3\lib\site-packages\sklearn\model_selection\_validation.py in cross_val_score(estimator, X, y, groups, scoring, cv, n_jobs, verbose, fit_params, pre_dispatch)
130 cv = check_cv(cv, y, classifier=is_classifier(estimator))
131 cv_iter = list(cv.split(X, y, groups))
--> 132 scorer = check_scoring(estimator, scoring=scoring)
133 # We clone the estimator to make sure that all the folds are
134 # independent, and that it is pickle-able.
C:\ProgramData\Anaconda3\lib\site-packages\sklearn\metrics\scorer.py in check_scoring(estimator, scoring, allow_none)
248 if not hasattr(estimator, 'fit'):
249 raise TypeError("estimator should be an estimator implementing "
--> 250 "'fit' method, %r was passed" % estimator)
251 if isinstance(scoring, six.string_types):
252 return get_scorer(scoring)
TypeError: estimator should be an estimator implementing 'fit' method, <__main__.Softmax object at 0x00000000048D1F98> was passed
def __init__(self, batch_size=50, epochs=1000, learning_rate=1e-2, reg_strength=1e-5, weight_update='adam'):
self.W = None
self.batch_size = batch_size
self.epochs = epochs
self.learning_rate = learning_rate
self.reg_strength = reg_strength
self.weight_update = weight_update
def train(self, X, y):
n_features = X.shape[1]
n_classes = y.max() + 1
self.W = np.random.randn(n_features, n_classes) / np.sqrt(n_features/2)
config = {'reg_strength': self.reg_strength, 'batch_size': self.batch_size,
'learning_rate': self.learning_rate, 'eps': 1e-8, 'decay_rate': 0.99,
'momentum': 0.9, 'cache': None, 'beta_1': 0.9, 'beta_2':0.999,
'velocity': np.zeros(self.W.shape)}
c = globals()['Softmax']
for epoch in range(self.epochs):
loss, config = getattr(c, self.weight_update)(self, X, y, config)
print ("Epoch:" +str(epoch)+", Loss: "+str(loss))
def predict(self, X):
return np.argmax(X.dot(self.W), 1)
def loss(self, X, y, W, b, reg_strength):
sample_size = X.shape[0]
predictions = X.dot(W) + b
# Fix numerical instability
predictions -= predictions.max(axis=1).reshape([-1, 1])
# Run predictions through softmax
softmax = math.e**predictions
softmax /= softmax.sum(axis=1).reshape([-1, 1])
# Cross entropy loss
loss = -np.log(softmax[np.arange(len(softmax)), y]).sum()
loss /= sample_size
loss += 0.5 * reg_strength * (W**2).sum()
softmax[np.arange(len(softmax)), y] -= 1
dW = (X.T.dot(softmax) / sample_size) + (reg_strength * W)
return loss, dW
def sgd(self, X, y, config):
items = itemgetter('learning_rate', 'batch_size', 'reg_strength')(config)
learning_rate, batch_size, reg_strength = items
loss, dW = self.sample_and_calculate_gradient(X, y, batch_size, self.W, 0, reg_strength)
self.W -= learning_rate * dW
return loss, config
def sgd_with_momentum(self, X, y, config):
items = itemgetter('learning_rate', 'batch_size', 'reg_strength', 'momentum')(config)
learning_rate, batch_size, reg_strength, momentum = items
loss, dW = self.sample_and_calculate_gradient(X, y, batch_size, self.W, 0, reg_strength)
config['velocity'] = momentum*config['velocity'] - learning_rate*dW
self.W += config['velocity']
return loss, config
def rms_prop(self, X, y, config):
items = itemgetter('learning_rate', 'batch_size', 'reg_strength', 'decay_rate', 'eps', 'cache')(config)
learning_rate, batch_size, reg_strength, decay_rate, eps, cache = items
loss, dW = self.sample_and_calculate_gradient(X, y, batch_size, self.W, 0, reg_strength)
cache = np.zeros(dW.shape) if cache == None else cache
cache = decay_rate * cache + (1-decay_rate) * dW**2
config['cache'] = cache
self.W -= learning_rate * dW / (np.sqrt(cache) + eps)
return loss, config
def adam(self, X, y, config):
items = itemgetter('learning_rate', 'batch_size', 'reg_strength', 'eps', 'beta_1', 'beta_2')(config)
learning_rate, batch_size, reg_strength, eps, beta_1, beta_2 = items
config.setdefault('t', 0)
config.setdefault('m', np.zeros(self.W.shape))
config.setdefault('v', np.zeros(self.W.shape))
loss, dW = self.sample_and_calculate_gradient(X, y, batch_size, self.W, 0, reg_strength)
config['t'] += 1
config['m'] = config['m']*beta_1 + (1-beta_1)*dW
config['v'] = config['v']*beta_2 + (1-beta_2)*dW**2
m = config['m']/(1-beta_1**config['t'])
v = config['v']/(1-beta_2**config['t'])
self.W -= learning_rate*m/(np.sqrt(v)+eps)
return loss, config
def sample_and_calculate_gradient(self, X, y, batch_size, w, b, reg_strength):
random_indices = random.sample(range(X.shape[0]), batch_size)
X_batch = X[random_indices]
y_batch = y[random_indices]
return self.loss(X_batch, y_batch, w, b, reg_strength)
最佳答案
如果您更改,它应该可以工作(或至少,它可以修复当前错误)
def train(self, X, y):
def fit(self, X, y):
fit
和
predict
方法。
class Softmax:
from sklearn.base import BaseEstimator, ClassifierMixin
class Softmax(BaseEstimator, ClassifierMixin):
关于python - estimator 应该是一个实现 'fit' 方法的估计器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50656471/
几个月前,我使用了tf.contrib.learn.DNNRegressor来自 TensorFlow 的 API,我发现它使用起来非常方便。最近几个月我没有跟上TensorFlow的发展。现在我有一
我们正在尝试将旧的训练代码转换为更符合 tf.estimator.Estimator 的代码。在初始代码中,我们针对目标数据集微调原始模型。在使用 variables_to_restore 和 ini
我目前运行的是 TensorFlow 1.9.0。我的自定义估算器是使用 tf.estimator.Estimator 创建的,并且运行时没有出现任何故障。但是,我在 model_dir 下没有找到任
我刚刚用 tensorflow 训练了一个 CNN 来识别太阳黑子。我的模型与 this 几乎相同.问题是我无法在任何地方找到关于如何使用训练阶段生成的检查点进行预测的明确解释。 尝试使用标准恢复方法
我正在尝试使用我自己的数据集和类对在 imagenet 上预训练的 Inception-resnet v2 模型进行迁移学习。我的原始代码库是对 tf.slim 的修改我再也找不到的示例,现在我正在尝
在 train(...) 完成后,如何从 tf.estimator.Estimator 获取最后一个 global_step ?例如,典型的基于估算器的训练例程可能如下设置: n_epochs = 1
一年多来我一直在使用自己的 Estimator/Experiment 之类的代码,但我最终想加入 Dataset+Estimator 的行列。 我想做如下的事情: for _ in range(N):
我正在考虑将我的代码库移动到 tf.estimator.Estimator ,但我找不到如何将它与张量板摘要结合使用的示例。 MWE: import numpy as np import tensor
我的印象是在 tf.estimator.Estimator 实例上调用 evaluate() 不会在多个 GPU 上运行模型,即使分配策略是 MirroredStrategy,配置为至少使用 2 个
我遇到了一些小问题,但我不知道如何处理。 当我使用 tf.estimator.Estimator 时,它会在每个步骤中记录两行,例如: INFO:tensorflow:global_step/sec:
在此tutorial ,他们通过为 tf.nn.softmax 节点命名成功地记录了 softmax 函数。 tf.nn.softmax(logits, name="softmax_tensor")
我发现 tensorflow train_and_evaluate 的工作方式与传统的 tf.estimator train 和 evaluate 相比有点不同。train_and_evaluate
我正在使用 tensorflow 版本 2.0.0-beta1。打电话时 tf.estimator.inputs.pandas_input_fn 它给了我一个错误。 module 'tensorflo
有没有办法在另一个模型 B 中使用经过 tf.estimator 训练的模型 A? 这是情况,假设我有一个训练有素的“模型 A”和 model_a_fn()。“模型 A”获取图像作为输入,并输出一些类
我正在尝试在本地运行对象检测 API。 我相信我已经按照 TensorFlow Object Detection API 中的描述设置了所有内容。但是,当我尝试运行 model_main.py 时,会
请原谅我的编码经验。我正在尝试使用 GridSearch 进行一系列回归。我正在尝试循环整个过程以使过程更快,但我的代码不够好并且不介意提高效率。这是我的代码: classifiers=[Lasso(
我在将纯 Keras 模型转换为不平衡数据集上的 TensorFlow Estimator API 时遇到了一些麻烦。 使用纯 Keras API 时,class_weight 参数在 model.f
当发生上述错误时,我经常使用有关估计器的tensorflow官方教程,而它在google.colab中正常运行。 我使用的环境是win10-64bit&tensorflow-gpu==1.12.0&p
Closed. This question is opinion-based。它当前不接受答案。 想要改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。 已关闭6年。
Closed. This question is opinion-based。它当前不接受答案。 想要改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。 1年前关闭。
我是一名优秀的程序员,十分优秀!