无法使用numpy数组加载keras中初始化层的最后一个偏置项

时间:2019-02-21 21:25:38

标签: python numpy tensorflow keras

我有一个用以下代码生成的2层神经网络:

def getModel():
model=Sequential()
model.add(Dense(4, activation='sigmoid', input_shape=(4,)))
model.add(Dense(1, activation='sigmoid'))
model.summary()
model.compile(loss='binary_crossentropy',optimizer='adam'  ,metrics=['accuracy'])
return model

每层都有一个权重向量和一个偏差向量,其形状/值如下例所示:

type,length= <class 'numpy.ndarray'> (4, 4)
type,length= <class 'numpy.ndarray'> (4,)
[array([[-1.7419001 ,  1.2651203 ,  0.7003008 ,  1.416193  ],
   [ 0.44382066,  0.69123524,  1.5097519 , -0.8737072 ],
   [-0.554937  , -1.2773337 , -2.2347293 , -1.7490497 ],
   [-0.16615662, -2.6573877 , -1.0334445 , -0.30910656]],
  dtype=float32), array([ 4.2480081e-02, -2.1411135e+00, -1.1447016e+00,   4.8992259e-04],
  dtype=float32)]
<class 'list'>
<class 'list'>
type,length= <class 'numpy.ndarray'> (4, 1)
type,length= <class 'numpy.ndarray'> (1,)
[array([[ 1.5777158],
   [-1.3019325],
   [ 0.5813155],
   [ 1.4168079]], dtype=float32), array([-0.49027315], dtype=float32)]

我尝试像这样在镜像神经网络中初始化权重:

test=np.load('WeightTest.npy')
LON1=[]
LON2=[]

k=0
for i in range(4):
    for j in range(4):
        L1[i,j]=test[k]
        k=k+1
for i in range(4):
   L2[i]=test[k]
    k=k+1
for i in range(4):
    L3[i,0]=test[k]
    k=k+1
L4=test[k]

LON1.append(L1)
LON1.append(L2)
LON2.append(L3)
LON2.append(L4)

testNN2=getModel()

testNN2.layers[0].set_weights(LON1)
testNN2.layers[1].set_weights(LON2)

第一层似乎设置正确,但是随后出现此错误:

Traceback (most recent call last):
  File "weightLoadTester.py", line 65, in <module>
    testNN2.layers[1].set_weights(LON2)
  File "/home/chase/venv/lib/python3.6/site-packages/keras/engine    /base_layer.py", line 1057, in set_weights
'provided weight shape ' + str(w.shape))

ValueError:图层权重形状(1,)与提供的权重形状()不兼容

任何想法在这里可能出什么问题吗?谢谢!

0 个答案:

没有答案