要回答为什么使用变量 net 和 net1 获得相同的系数和预测的问题,是因为它们都是对同一个对象的引用。
要检查这一点,您可以运行以下命令:
print(net is net1)
您将收到True。原因是您已经为 MLPRegressor 对象创建了引用。因此,当您 fit 具有 X 和 y 值的模型时,net 的模型将尝试适应提供的值,然后将相同的对象分配给 net1。
接下来,我认为您必须降低学习率(例如 0.01)才能更好地学习,或者至少让您的神经网络适应所提供的数据。
最后,正如您可能已经检查过的,您的模型可能不会在测试数据之外的值上表现得更好,因为您的数据是随机数据。
编辑:
根据在每轮 epoch 后打印学习权重(系数)的请求,我添加了额外的细节。与MLPRegressor 一样,您将无法在每次迭代/批次等之后打印学习权重的详细信息。为此,您将不得不使用sknn.mlp 模块。他们有各种callbacks,可用于打印/评估您的学习时间。
请考虑以下代码以帮助您入门:
def print_coeff_callback(**variables):
print('End of epoch: {}'.format(variables['i']))
print('Layer 0: Weights:')
print(variables['best_params'][0][0])
print('Layer 0: Biases:')
print(variables['best_params'][0][1])
print('Layer 1: Weights:')
print(variables['best_params'][1][0])
print('Layer 1: Biases:')
print(variables['best_params'][1][1])
print()
import numpy as np
temp_data_x = np.random.randn(200,3)
temp_data_y = temp_data_x[:,0] + temp_data_x[:,1] + temp_data_x[:,2]\
+ np.random.randn(200,1).reshape(200,)
from sknn.mlp import Regressor, Layer
net = Regressor(layers = [Layer('Tanh', units = 3), Layer('Linear', units = 1)],
learning_rate = 0.01, n_iter = 10,
verbose = True, random_state = 3,
callback = {'on_epoch_finish': print_coeff_callback})
net.fit(temp_data_x[0:150,],temp_data_y[0:150])
当您运行此代码时,在每个 epoch 结束时,您将获得如下额外详细信息:
End of epoch: 1
Layer 0: Weights:
[[-0.50751932 -0.72378025 -0.37128063]
[-0.53206593 -0.33147215 0.83072845]
[-0.66474313 -0.76372327 -0.85991181]]
Layer 0: Biases:
[-0.03277463 -0.10826231 0.01669442]
Layer 1: Weights:
[[-0.88015991]
[-1.13531142]
[ 0.06633887]]
Layer 1: Biases:
[ 0.16668694]
End of epoch: 2
Layer 0: Weights:
[[-0.49187796 -0.70438651 -0.36641678]
[-0.66897643 -0.51718653 0.83213911]
[-0.68042139 -0.72434914 -0.85017705]]
Layer 0: Biases:
[ 0.09687692 0.04577672 0.00219902]
Layer 1: Weights:
[[-1.11614207]
[-1.31741563]
[-0.02267721]]
Layer 1: Biases:
[ 0.02075817]
如您所见,学习到的权重/偏差的详细信息是存在的,并且它们会不时发生变化。