質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

2回答

1230閲覧

Python3 Error when checking model input: the list of Numpy arrays that you are passing to your model

SuzuAya

総合スコア71

Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2019/07/07 07:15

前提・実現したいこと

kerasの分類問題コードで以下のエラーが発生しています。
これまでのこちらでのご質問とご回答を確認しましたが、解決方法が分からず相談をさせていただきました。
yのラベル形式の変換がうまくいっていないような気がするのですが、解決方法についてアドバイスをいただけないでしょうか。
お手数をおかけしますがどうぞよろしくお願い致します。

発生している問題・エラーメッセージ

ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 2 array(s), but instead got the following list of 1 arrays: [array([[[[1. ], [1. ], [1. ], ..., [1. ], [1. ], [1. ]], [[1. ], [1. ],...

該当のソースコード

Python

1from __future__ import absolute_import 2from __future__ import division 3from __future__ import print_function 4 5from keras.layers import Lambda, Input, Dense 6from keras.models import Model 7from keras.models import Sequential, model_from_json 8from keras.losses import mse, binary_crossentropy 9from keras.layers import Conv2D, Flatten 10from keras.applications.mobilenet import MobileNet 11from keras.layers.pooling import MaxPool2D 12from keras.utils import plot_model, np_utils 13from keras.applications.mobilenetv2 import MobileNetV2 14from keras.callbacks import Callback, EarlyStopping, TensorBoard, ModelCheckpoint, LearningRateScheduler, CSVLogger 15from keras import optimizers 16from keras import backend as K 17from keras.layers import Layer 18from keras import regularizers 19from keras.preprocessing.image import array_to_img, img_to_array,load_img 20from keras.preprocessing.image import ImageDataGenerator 21from keras.layers import Activation, BatchNormalization, Dropout, GlobalAveragePooling2D 22 23from sklearn.model_selection import train_test_split 24 25import numpy as np 26import matplotlib.pyplot as plt 27import argparse 28import os 29import re 30import glob 31import random as rn 32import tensorflow as tf 33import cv2 34from PIL import Image 35 36import warnings 37warnings.filterwarnings('ignore') 38 39%matplotlib inline 40 41class Arcfacelayer(Layer): 42 # s:softmaxの温度パラメータ, m:margin 43 def __init__(self, output_dim, s=30, m=0.50, easy_margin=False): 44 self.output_dim = output_dim 45 self.s = s 46 self.m = m 47 self.easy_margin = easy_margin 48 super(Arcfacelayer, self).__init__() 49 50 # 重みの作成 51 def build(self, input_shape): 52 # Create a trainable weight variable for this layer. 53 self.kernel = self.add_weight(name='kernel', 54 shape=(input_shape[0][1], self.output_dim), 55 initializer='uniform', 56 trainable=True) 57 super(Arcfacelayer, self).build(input_shape) 58 59 60 # mainの処理 61 def call(self, x): 62 y = x[1] 63 x_normalize = tf.math.l2_normalize(x[0]) # x = x'/ ||x'||2 64 k_normalize = tf.math.l2_normalize(self.kernel) # Wj = Wj' / ||Wj'||2 65 66 cos_m = K.cos(self.m) 67 sin_m = K.sin(self.m) 68 th = K.cos(np.pi - self.m) 69 mm = K.sin(np.pi - self.m) * self.m 70 71 cosine = K.dot(x_normalize, k_normalize) # W.Txの内積 72 sine = K.sqrt(1.0 - K.square(cosine)) 73 74 phi = cosine * cos_m - sine * sin_m #cos(θ+m)の加法定理 75 76 if self.easy_margin: 77 phi = tf.where(cosine > 0, phi, cosine) 78 79 else: 80 phi = tf.where(cosine > th, phi, cosine - mm) 81 82 # 正解クラス:cos(θ+m) 他のクラス:cosθ 83 output = (y * phi) + ((1.0 - y) * cosine) 84 output *= self.s 85 86 return output 87 88 def compute_output_shape(self, input_shape): 89 90 return (input_shape[0][0], self.output_dim) #入力[x,y]のためx[0]はinput_shape[0][0] 91 92# network parameters 93image_size_width, image_size_height = (512, 496) 94input_shape = (image_size_width,image_size_height,1) 95batch_size = 16 96kernel_size = 3 97filters = 16 98epochs = 100 99num_classes = 4 100weight_decay = 1e-4 101 102folder = ["A","B","C","D"] 103 104X = [] 105Y = [] 106for index, name in enumerate(folder): 107 dir = "./" + name 108 files = glob.glob(dir + "/*.jpeg") 109 for i, file in enumerate(files): 110 image = Image.open(file) 111 image = image.convert("L")#("RGB") 112 image = image.resize((image_size_width, image_size_height)) 113 data = np.asarray(image) 114 X.append(data) 115 Y.append(index) 116 117X = np.array(X) 118Y = np.array(Y) 119 120X = np.reshape(X, [-1, image_size_width,image_size_height,1]) 121X = X.astype('float32') / 255 122 123print(X.shape) 124 125# 正解ラベルの形式を変換 126Y = np_utils.to_categorical(Y, num_classes) 127 128# 学習用データとテストデータ 129X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.20) 130print(X_train.shape, X_test.shape, y_train.shape, y_test.shape) 131 132#学習に使用するmodelを作成する関数 133def create_mobilenet_with_arcface(n_categories, file_path=None): 134 input=Input(shape=(512,496,1)) 135 print(input.shape) 136 yinput = Input(shape=(4,))#n_categories, 137 print(yinput.shape) 138 139 x = Conv2D(32, kernel_size=(3, 3), activation='relu')(input) 140 print("after conv2D:", x.shape)# after conv2D: (?, 510, 494, 32) 141 x = MaxPool2D(pool_size=(2, 2))(x) 142 print("after MaxPooling:", x.shape)# after MaxPooling: (?, 255, 247, 32) 143 x = Conv2D(64, kernel_size=(3, 3), activation='relu')(x) 144 print("after conv2D:", x.shape)# after conv2D: (?, 253, 245, 64) 145 x = MaxPool2D(pool_size=(2, 2))(x) 146 print("after MaxPooling:", x.shape)# after MaxPooling: (?, 126, 122, 64) 147 # stock hidden model 148 hidden = GlobalAveragePooling2D()(x)# hidden: (?, 64) 149 print("hidden:",hidden.shape) 150 # stock Feature extraction 151 #x = Dropout(0.5)(hidden) 152 x = Arcfacelayer(4, 30, 0.05)([hidden, yinput])#([hidden,yinput]) # (?, 4) 153 print(x.shape) 154 #x = Dense(1024,activation='relu')(x) 155 prediction = Activation('softmax')(x) 156 print(prediction.shape)# (?, 4) 157 model = Model(inputs=[input, yinput],outputs=prediction) 158 159 if file_path: 160 model.load_weights(file_path) 161 print('weightは{}'.format(file_path)) 162 163 return model 164 165 166Adam = optimizers.Adam(lr=1e-4, decay=1e-4,beta_1=0.9, beta_2=0.999, epsilon=1e-8) 167model = create_mobilenet_with_arcface(4, file_path=None) 168model.compile(optimizer=Adam, loss='categorical_crossentropy', metrics=["accuracy"]) 169 170callbacks = [] 171callbacks.append(ModelCheckpoint(filepath="model.ep{epoch:02d}.h5", save_best_only=True)) 172callbacks.append(EarlyStopping(monitor='val_loss', patience=5, verbose=1)) 173callbacks.append(CSVLogger("history.csv")) 174 175history = model.fit(X_train, y_train, 176 batch_size=batch_size, 177 epochs=epochs, 178 verbose=1, 179 validation_data=(X_test, y_test), 180 callbacks=callbacks) 181 182score = model.evaluate(X_test, y_test, verbose=0) 183print('Test loss:', score[0]) 184print('Test accuracy:', score[1]) 185 186

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

多分、
model = Model(inputs=[input, yinput],outputs=prediction)
のinputs=[input, yinput]の部分が、
model.fit(X_train, y_train, ...)
とあっていないということだと思います。

inputs=... を一つにするか、
model.fit([X_train,..],)
とする必要があると思います。

参考
https://keras.io/ja/getting-started/functional-api-guide/

投稿2019/07/07 23:57

daesaka

総合スコア136

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

SuzuAya

2019/07/08 23:33

>0kcalさん たくさん時間を割いていただき本当にありがとうございました! >daesakaさん ご回答ありがとうございました。お手数をお掛けしました。
guest

0

実行すると、同じエラーになります。
直す方法、いまだ、不明です。

追記:
list()をつけるとか、逆に、np.arrayをつけるような対応の回答が散見されます。
これに該当するか不明ですが。
そもそも、なぜ、動かなくなっているのかが、わからないですが。。。

いま、動作確認できない環境なので、あしからず。
(回答になっておらず、恐縮です。)

⇒ 思考錯誤しましたが、ダメでした。断念します。

投稿2019/07/07 22:08

編集2019/07/08 19:28
0kcal

総合スコア275

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問