【问题标题】:Is there a way I can get the coefs_ attribute before fitting sklearn MLPRegressor?有没有办法在拟合 sklearn MLPRegressor 之前获得 coefs_ 属性?
【发布时间】:2018-12-05 06:51:29
【问题描述】:

我是机器学习的新手,我正在练习制作一个近似函数的神经网络。出于学习和查看神经网络状态的目的,我想知道神经网络的初始系数。这是一个可重现的示例:

import sklearn.neural_network as sknn
import numpy as np

LIMIT = 10.0

# Function I want to approximate
def funcion(x):
    if x<3:
        return 0
    if x>7:
        return 12
    return 3*(x-3)

X = np.array([])    
Y = np.array([])    

# Data training set
for x in np.arange(0.0, LIMIT, 1.5):
    X = np.append(X, x)
    Y = np.append(Y, funcion(x))

X = np.append(X,10)
Y = np.append(Y, funcion(10))

X = np.reshape(X, (-1,1))

nn = sknn.MLPRegressor(
    learning_rate_init=0.01, 
    learning_rate = 'constant',
    activation='logistic',  
    hidden_layer_sizes=(2,1),
    max_iter=1,
    random_state=None)


print('coefficients: ', nn.coefs_)  # THIS GIVES THE ERROR

nn.fit(X, Y)

输出:

Traceback (most recent call last):
  File "aproxFun2.py", line 41, in <module>
    print('coefficients: ', nn.coefs_)
AttributeError: 'MLPRegressor' object has no attribute 'coefs_'

每当我调用nn.coefs_ 时它都会打印数据之后我调用nn.fit(X, Y) 函数,但我想知道拟合前的值。

【问题讨论】:

  • 对不起老兄,正如你所见,我是使用这个平台的新手。感谢您的建议。
  • 酷 - 只记得使用一些常识:)

标签: python scikit-learn neural-network


【解决方案1】:

coefs_ 在调用 _initialize(self, y, layer_units) 之前没有被初始化(在 fit() 中),所以我猜你不能。

【讨论】:

    【解决方案2】:

    阅读源代码(link),初始化在所有层上迭代执行,方法如下:

    def _init_coef(self, fan_in, fan_out):
        if self.activation == 'logistic':
            # Use the initialization method recommended by
            # Glorot et al.
            init_bound = np.sqrt(2. / (fan_in + fan_out))
        elif self.activation in ('identity', 'tanh', 'relu'):
            init_bound = np.sqrt(6. / (fan_in + fan_out))
        else:
            # this was caught earlier, just to make sure
            raise ValueError("Unknown activation function %s" %
                             self.activation)
    
        coef_init = self._random_state.uniform(-init_bound, init_bound,
                                               (fan_in, fan_out))
        intercept_init = self._random_state.uniform(-init_bound, init_bound,
                                                    fan_out)
        return coef_init, intercept_init
    

    其中fan_infan_out 分别代表输入的大小。输出层。

    所以你实际上可以通过运行上面的代码来计算出固定随机状态的初始化。

    关于初始化本身,权重是从以 0 为中心的均匀分布中采样的。分布的支持是输出和输入层大小的函数。有关详细信息,请参阅参考论文 Understanding the difficulty of training deep feedforward neural networks

    【讨论】:

      猜你喜欢
      • 2019-07-05
      • 2022-07-21
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      • 1970-01-01
      • 2019-10-29
      • 2010-11-23
      • 1970-01-01
      相关资源
      最近更新 更多