59427


Kerasでcifar10のデータセットを転移学習を用いて分類するという目的のコードなのですが、エラーが出てきてこれはどういうことなのでしょうか？

* * *

**ソースコード**

[code]

    from keras import optimizers
    from keras.applications.vgg16 import VGG16
    from keras.datasets import cifar10
    from keras.layers import Dense, Dropout, Flatten, Input
    from keras.models import Model, Sequential
    from keras.utils.np_utils import to_categorical
    import matplotlib.pyplot as plt
    import numpy as np
    
    (X_train, y_train), (X_test, y_test) = cifar10.load_data()
    X_train = X_train[:300]
    X_test = X_test[:100]
    y_train = to_categorical(y_train)[:300]
    y_test = to_categorical(y_test)[:100]
    
    #input_tensorを定義
    input_tensor = Input(shape=(32, 32, 3))
    
    vgg16 = VGG16(include_top=False, weights='imagenet', input_tensor=input_tensor)
    
    top_model = Sequential()
    top_model.add(Flatten(input_shape=vgg16.output_shape[1:]))
    top_model.add(Dense(256, activation='sigmoid'))
    top_model.add(Dropout(0.5))
    top_model.add(Dense(10, activation='softmax'))
    
    # vgg16とtop_modelを連結
    model = Model(inputs=vgg16.input, outputs=top_model(vgg16.output))
    
    # 19層目までの重みをfor文を用いて固定
    for layer in model.layers[:19]:
        layer.trainable = False
    
    model.compile(loss='categorical_crossentropy',
                  optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),
                  metrics=['accuracy'])
    
    
    model.load_weights('param_vgg.hdf5')
    
    model.fit(X_train, y_train, validation_data=(X_test, y_test), batch_size=32, epochs=1)
    
    # 以下でモデルの重みを保存する
    # model.save_weights('param_vgg.hdf5')
    
    # 精度の評価
    scores = model.evaluate(X_test, y_test, verbose=1)
    print('Test loss:', scores[0])
    print('Test accuracy:', scores[1])
    
    # データの可視化（テストデータの先頭の10枚）
    for i in range(10):
        plt.subplot(2, 5, i+1)
        plt.imshow(X_test[i])
    plt.suptitle("テストデータの先頭の10枚",fontsize=16)
    plt.show()
    
    # 予測（テストデータの先頭の10枚）
    pred = np.argmax(model.predict(X_test[0:10]), axis=1)
    print(pred)
    
    model.summary()
    
[/code]

**エラーメッセージ**

[code]

    ----------------------------------------
    Using TensorFlow backend.
    WARNING:tensorflow:From /Users/ipodtao/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
    Instructions for updating:
    Colocations handled automatically by placer.
    WARNING:tensorflow:From /Users/ipodtao/anaconda3/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.
    Instructions for updating:
    Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.
    ---------------------------------------------------------------------------
    OSError                                   Traceback (most recent call last)
    <ipython-input-1-da6afae9ece9> in <module>
         37 
         38 
    ---> 39 model.load_weights('param_vgg.hdf5')
         40 
         41 model.fit(X_train, y_train, validation_data=(X_test, y_test), batch_size=32, epochs=1)
    
    ~/anaconda3/lib/python3.7/site-packages/keras/engine/network.py in load_weights(self, filepath, by_name, skip_mismatch, reshape)
       1155         if h5py is None:
       1156             raise ImportError('`load_weights` requires h5py.')
    -> 1157         with h5py.File(filepath, mode='r') as f:
       1158             if 'layer_names' not in f.attrs and 'model_weights' in f:
       1159                 f = f['model_weights']
    
    ~/anaconda3/lib/python3.7/site-packages/h5py/_hl/files.py in __init__(self, name, mode, driver, libver, userblock_size, swmr, rdcc_nslots, rdcc_nbytes, rdcc_w0, track_order, **kwds)
        392                 fid = make_fid(name, mode, userblock_size,
        393                                fapl, fcpl=make_fcpl(track_order=track_order),
    --> 394                                swmr=swmr)
        395 
        396             if swmr_support:
    
    ~/anaconda3/lib/python3.7/site-packages/h5py/_hl/files.py in make_fid(name, mode, userblock_size, fapl, fcpl, swmr)
        168         if swmr and swmr_support:
        169             flags |= h5f.ACC_SWMR_READ
    --> 170         fid = h5f.open(name, flags, fapl=fapl)
        171     elif mode == 'r+':
        172         fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl)
    
    h5py/_objects.pyx in h5py._objects.with_phil.wrapper()
    
    h5py/_objects.pyx in h5py._objects.with_phil.wrapper()
    
    h5py/h5f.pyx in h5py.h5f.open()
    
    OSError: Unable to open file (unable to open file: name = 'param_vgg.hdf5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0)
    
[/code]


CC BY-SA 4.0
2019-10-03T00:39:49.873
59426
2019-10-03T05:23:51.327
2019-10-03T05:23:51.327
3060
35156
question
python keras
Kerasによる転移学習プログラムの実行時、"OSError: Unable to open file" エラーになってしまう


`param_vgg.hdf5`というファイルを開こうとして、`No such file or
directory`（そんなファイルは無い）というエラーが出ています。なので、`param_vgg.hdf5`というファイルが存在するかを確認して下さい。

事前に学習したパラメーター（モデルの重み）を`param_vgg.hdf5`というファイルに保存しておくことが前提で動作するプログラムを実行している、ということではないですかね？


CC BY-SA 4.0
2019-10-03T01:18:30.630
59427
2019-10-03T01:18:30.630
21092
59426
answer