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

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

新規登録して質問してみよう
ただいま回答率
85.50%
Python 3.x

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

Q&A

解決済

1回答

795閲覧

kaggleでforkしたkernelを実行した後、結果をcsvに出力する方法について

SuzuAya

総合スコア71

Python 3.x

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

0グッド

0クリップ

投稿2019/04/24 03:52

前提・実現したいこと

Python勉強歴約半年の初心者です。
コードに慣れるため、kaggleを始めてみましたが、他の方のkernelをforkして実行したところ、実行まではうまくいったのですが、実行結果をkaggleへの提出用csvファイルへ出力するコマンドは記載されておらず、やり方について教えていただければ幸いです。
提出用csvファイルには、patentIDと、その患者の眼病のラベル番号を記載する必要があります。

該当のソースコード

規定文字数に収まらなかったため、データの前処理部分を割愛しています。

#Training Set #These are augmented and a real mess t_x, t_y = next(train_gen) fig, m_axs = plt.subplots(2, 4, figsize = (16, 8)) for (c_x, c_y, c_ax) in zip(t_x, t_y, m_axs.flatten()): c_ax.imshow(np.clip(c_x*127+127, 0, 255).astype(np.uint8)) c_ax.set_title('Severity {}'.format(np.argmax(c_y, -1))) c_ax.axis('off') WARNING: The TensorFlow contrib module will not be included in TensorFlow 2.0. For more information, please see: * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md * https://github.com/tensorflow/addons If you depend on functionality not listed there, please file an issue. #Attention Model from keras.applications.vgg16 import VGG16 as PTModel from keras.applications.inception_resnet_v2 import InceptionResNetV2 as PTModel from keras.applications.inception_v3 import InceptionV3 as PTModel from keras.layers import GlobalAveragePooling2D, Dense, Dropout, Flatten, Input, Conv2D, multiply, LocallyConnected2D, Lambda from keras.models import Model in_lay = Input(t_x.shape[1:]) base_pretrained_model = PTModel(input_shape = t_x.shape[1:], include_top = False, weights = 'imagenet') base_pretrained_model.trainable = False pt_depth = base_pretrained_model.get_output_shape_at(0)[-1] pt_features = base_pretrained_model(in_lay) from keras.layers import BatchNormalization bn_features = BatchNormalization()(pt_features) # here we do an attention mechanism to turn pixels in the GAP on an off attn_layer = Conv2D(64, kernel_size = (1,1), padding = 'same', activation = 'relu')(Dropout(0.5)(bn_features)) attn_layer = Conv2D(16, kernel_size = (1,1), padding = 'same', activation = 'relu')(attn_layer) attn_layer = Conv2D(8, kernel_size = (1,1), padding = 'same', activation = 'relu')(attn_layer) attn_layer = Conv2D(1, kernel_size = (1,1), padding = 'valid', activation = 'sigmoid')(attn_layer) # fan it out to all of the channels up_c2_w = np.ones((1, 1, 1, pt_depth)) up_c2 = Conv2D(pt_depth, kernel_size = (1,1), padding = 'same', activation = 'linear', use_bias = False, weights = [up_c2_w]) up_c2.trainable = False attn_layer = up_c2(attn_layer) mask_features = multiply([attn_layer, bn_features]) gap_features = GlobalAveragePooling2D()(mask_features) gap_mask = GlobalAveragePooling2D()(attn_layer) # to account for missing values from the attention model gap = Lambda(lambda x: x[0]/x[1], name = 'RescaleGAP')([gap_features, gap_mask]) gap_dr = Dropout(0.25)(gap) dr_steps = Dropout(0.25)(Dense(128, activation = 'relu')(gap_dr)) out_layer = Dense(t_y.shape[-1], activation = 'softmax')(dr_steps) retina_model = Model(inputs = [in_lay], outputs = [out_layer]) from keras.metrics import top_k_categorical_accuracy def top_2_accuracy(in_gt, in_pred): return top_k_categorical_accuracy(in_gt, in_pred, k=2) retina_model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['categorical_accuracy', top_2_accuracy]) retina_model.summary() from keras.callbacks import ModelCheckpoint, LearningRateScheduler, EarlyStopping, ReduceLROnPlateau weight_path="{}_weights.best.hdf5".format('retina') checkpoint = ModelCheckpoint(weight_path, monitor='val_loss', verbose=1, save_best_only=True, mode='min', save_weights_only = True) reduceLROnPlat = ReduceLROnPlateau(monitor='val_loss', factor=0.8, patience=3, verbose=1, mode='auto', min_delta=0.0001, cooldown=5, min_lr=0.0001) early = EarlyStopping(monitor="val_loss", mode="min", patience=6) # probably needs to be more patient, but kaggle time is limited callbacks_list = [checkpoint, early, reduceLROnPlat] !rm -rf ~/.keras # clean up before starting training retina_model.fit_generator(train_gen, steps_per_epoch = train_df.shape[0]//batch_size, validation_data = valid_gen, validation_steps = valid_df.shape[0]//batch_size, epochs = 25, callbacks = callbacks_list, workers = 0, # tf-generators are not thread-safe use_multiprocessing=False, max_queue_size = 0 ) # fresh valid gen valid_gen = flow_from_dataframe(valid_idg, valid_df, path_col = 'path', y_col = 'level_cat') vbatch_count = (valid_df.shape[0]//batch_size-1) out_size = vbatch_count*batch_size test_X = np.zeros((out_size,)+t_x.shape[1:], dtype = np.float32) test_Y = np.zeros((out_size,)+t_y.shape[1:], dtype = np.float32) for i, (c_x, c_y) in zip(tqdm_notebook(range(vbatch_count)), valid_gen): j = i*batch_size test_X[j:(j+c_x.shape[0])] = c_x test_Y[j:(j+c_x.shape[0])] = c_y Show Attention Did our attention model learn anything useful? # get the attention layer since it is the only one with a single output dim for attn_layer in retina_model.layers: c_shape = attn_layer.get_output_shape_at(0) if len(c_shape)==4: if c_shape[-1]==1: print(attn_layer) break <keras.layers.convolutional.Conv2D object at 0x7f2df6081dd8> import keras.backend as K rand_idx = np.random.choice(range(len(test_X)), size = 6) attn_func = K.function(inputs = [retina_model.get_input_at(0), K.learning_phase()], outputs = [attn_layer.get_output_at(0)] ) fig, m_axs = plt.subplots(len(rand_idx), 2, figsize = (8, 4*len(rand_idx))) [c_ax.axis('off') for c_ax in m_axs.flatten()] for c_idx, (img_ax, attn_ax) in zip(rand_idx, m_axs): cur_img = test_X[c_idx:(c_idx+1)] attn_img = attn_func([cur_img, 0])[0] img_ax.imshow(np.clip(cur_img[0,:,:,:]*127+127, 0, 255).astype(np.uint8)) attn_ax.imshow(attn_img[0, :, :, 0]/attn_img[0, :, :, 0].max(), cmap = 'viridis', vmin = 0, vmax = 1, interpolation = 'lanczos') real_cat = np.argmax(test_Y[c_idx, :]) img_ax.set_title('Eye Image\nCat:%2d' % (real_cat)) pred_cat = retina_model.predict(cur_img) attn_ax.set_title('Attention Map\nPred:%2.2f%%' % (100*pred_cat[0,real_cat])) fig.savefig('attention_map.png', dpi = 300) #Evaluate the results from sklearn.metrics import accuracy_score, classification_report pred_Y = retina_model.predict(test_X, batch_size = 32, verbose = True) pred_Y_cat = np.argmax(pred_Y, -1) test_Y_cat = np.argmax(test_Y, -1) print('Accuracy on Test Data: %2.2f%%' % (accuracy_score(test_Y_cat, pred_Y_cat))) print(classification_report(test_Y_cat, pred_Y_cat)) import seaborn as sns from sklearn.metrics import confusion_matrix sns.heatmap(confusion_matrix(test_Y_cat, pred_Y_cat), annot=True, fmt="d", cbar = False, cmap = plt.cm.Blues, vmax = test_X.shape[0]//16) <matplotlib.axes._subplots.AxesSubplot at 0x7f2d9e1d6e80> #ROC Curve for healthy vs sick from sklearn.metrics import roc_curve, roc_auc_score sick_vec = test_Y_cat>0 sick_score = np.sum(pred_Y[:,1:],1) fpr, tpr, _ = roc_curve(sick_vec, sick_score) fig, ax1 = plt.subplots(1,1, figsize = (6, 6), dpi = 150) ax1.plot(fpr, tpr, 'b.-', label = 'Model Prediction (AUC: %2.2f)' % roc_auc_score(sick_vec, sick_score)) ax1.plot(fpr, fpr, 'g-', label = 'Random Guessing') ax1.legend() ax1.set_xlabel('False Positive Rate') ax1.set_ylabel('True Positive Rate'); fig,m_axs = plt.subplots(2, 4, figsize = (32, 20)) for (idx, c_ax) in enumerate(m_axs.flatten()): c_ax.imshow(np.clip(test_X[idx]*127+127,0 , 255).astype(np.uint8), cmap = 'bone') c_ax.set_title('Actual Severity: {}\n{}'.format(test_Y_cat[idx], '\n'.join(['Predicted %02d (%04.1f%%): %s' % (k, 100*v, '*'*int(10*v)) for k, v in sorted(enumerate(pred_Y[idx]), key = lambda x: -1*x[1])])), loc='left') c_ax.axis('off')

試したこと

以下を参考に、notebookの一番下にセルを追加し、sub.to_csv( 'sub.csv' )を実行しましたが、「sub is not defined」というエラーが出てしまいました。
https://kaeru-nantoka.hatenablog.com/entry/2018/09/08/184733

やり方が分からず、本当に困っています…。皆様お忙しいことかと存じますが、ご回答の程よろしくお願いいたします。

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

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

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

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

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

guest

回答1

0

自己解決

forkの内容によって、提出ファイルへの出力まで書いてくれているもの、そうでないものがあるようでした。
今後は、色々な方のコードを見たり実行したりして、kernelに頼らずゼロからコードを書けるように勉強したいと思います。

投稿2019/04/25 06:16

SuzuAya

総合スコア71

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問