python - sknn - 第二次拟合时输入尺寸不匹配

标签 python scikit-learn reinforcement-learning

我试图创建一个利用强化学习的神经网络。我选择 scikit-neuralnetwork 作为库(因为它很简单)。不过,似乎拟合两次使 Theano 崩溃。

这是导致崩溃的最简单代码(注意,有哪些层并不重要,学习率或 n_iter 也不重要):

import numpy as np
from sknn.mlp import Classifier, Layer

clf = Classifier(
    layers=[
        Layer("Softmax")
        ],
    learning_rate=0.001,
    n_iter=1)

clf.fit(np.array([[0.]]), np.array([[0.]])) # Initialize the network for learning

X = np.array([[-1.], [1.]])
Y = np.array([[1.], [0.]])

clf.fit(X, Y) # crash

这是我得到的错误:

ValueError: Input dimension mis-match. (input[0].shape[1] = 2, input[1].shape[1] = 1)
Apply node that caused the error: Elemwise{Mul}[(0, 1)](y, LogSoftmax.0)
Toposort index: 12
Inputs types: [TensorType(float64, matrix), TensorType(float64, matrix)]
Inputs shapes: [(1L, 2L), (1L, 1L)]
Inputs strides: [(16L, 8L), (8L, 8L)]
Inputs values: [array([[ 1.,  0.]]), array([[ 0.]])]
Outputs clients: [[Sum{axis=[1], acc_dtype=float64}(Elemwise{Mul}[(0, 1)].0)]]

在 Python 2.7.11 中测试

sknn 不支持多次拟合,还是我犯了一些愚蠢的错误?如果没有,您应该如何实现强化学习?

最佳答案

我不经常使用 sknn,但它与 sklearn 非常相似,所以我也许可以提供帮助!

首先,当使用 fit 方法时,您将重新初始化权重,如果您想根据新数据更新权重,您应该使用 partial_fit 方法。

关于崩溃,这是因为您的 X 数组在第一维而非第二维中的形状不同。

import numpy as np
from sknn.mlp import Classifier, Layer

clf = Classifier(
    layers=[
        Layer("Softmax")
        ],
    learning_rate=0.001,
    n_iter=1)

# Original training data
X = np.array([[0.]])
Y = np.array([[0.]])
print X.shape, Y.shape

# Data used for second fitting
X = np.array([[-1.], [1.]])
Y = np.array([[1.], [0.]])
print X.shape, Y.shape


# Use the partial fit method to update weights
clf.partial_fit(X, Y) # Initialize the network for learning
clf.partial_fit(X, Y) # Update the weights


# Multiple training examples by stacking two on top of each other
X = np.concatenate((X, X))
Y = np.concatenate((Y, Y))
print X.shape, Y.shape

clf.partial_fit(X, Y)

输出:

(1, 1) (1, 1)
(2, 1) (2, 1)
(4, 1) (4, 1)

关于python - sknn - 第二次拟合时输入尺寸不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38009309/

相关文章:

machine-learning - 决策树 split 策略

machine-learning - Q-Learning:你能倒退吗?

machine-learning - 带有规划的 Dyna-Q 与 n 步 Q 学习

tensorflow - tf-agent 的 `policy` 和 `collect_policy` 有什么区别?

python - python优化的程序化控制?

python - Django中如何处理数据库异常

python - 为 Amazon CloudFront 创建签名 Cookie

python - 在 Python 字典列表上实现 "select distinct ... from ..."

python - SGD分类器对不同维度输入数据的部分拟合学习

python - LogisticRegression.predict_proba 的 scikit-learn 返回值