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

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

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

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

Q&A

解決済

1回答

9839閲覧

[Python]機械学習について

s0ra

総合スコア62

Python

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

0グッド

1クリップ

投稿2017/11/05 08:53

編集2017/11/05 08:59

お世話になっています。
下のソースコードを実行させたところ
NotADirectoryError: [Errno 20] Not a directory: '/Users/data/.DS_Store'
というエラーが出ます。調べても全く出てこないのでどなたかご教授願います。
下のソースコードはここから取ってきたものです。

Python

1import os 2import cv2 3import numpy as np 4import tensorflow as tf 5 6path=os.getcwd()+'/data/' 7class_count = 0 8folder_list=os.listdir(path) 9 10for folder in folder_list: 11 class_count = class_count+1 12 13NUM_CLASSES = class_count 14IMAGE_SIZE = 28 15IMAGE_PIXELS = IMAGE_SIZE*IMAGE_SIZE*3 16 17flags = tf.app.flags 18FLAGS = flags.FLAGS 19flags.DEFINE_string('label', 'label.txt', 'File name of label') 20flags.DEFINE_string('train_dir', './tmp/data', 'Directory to put the training data.') 21# max_step、sbatch_size、learning_rateの各パラメータは学習データによって適切な値を設定する 22flags.DEFINE_integer('max_steps', 100, 'Number of steps to run trainer.') 23flags.DEFINE_integer('batch_size', 20, 'Batch size' 24 'Must divide evenly into the dataset sizes.') 25flags.DEFINE_float('learning_rate', 1e-4, 'Initial learning rate.') 26 27# 予測モデルを作成する関数 28def inference(images_placeholder, keep_prob): 29 # 重みを標準偏差0.1の正規分布で初期化 30 def weight_variable(shape): 31 initial = tf.truncated_normal(shape, stddev=0.1) 32 return tf.Variable(initial) 33 34 # バイアスを標準偏差0.1の正規分布で初期化 35 def bias_variable(shape): 36 initial = tf.constant(0.1, shape=shape) 37 return tf.Variable(initial) 38 39 # 畳み込み層の作成 40 def conv2d(x, W): 41 return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 42 43 # プーリング層の作成 44 def max_pool_2x2(x): 45 return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], 46 strides=[1, 2, 2, 1], padding='SAME') 47 48 # 入力を28x28x3に変形 49 x_image = tf.reshape(images_placeholder, [-1, 28, 28, 3]) 50 51 # 畳み込み層1の作成 52 with tf.name_scope('conv1') as scope: 53 W_conv1 = weight_variable([5, 5, 3, 32]) 54 b_conv1 = bias_variable([32]) 55 h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) 56 57 # プーリング層1の作成 58 with tf.name_scope('pool1') as scope: 59 h_pool1 = max_pool_2x2(h_conv1) 60 61 # 畳み込み層2の作成 62 with tf.name_scope('conv2') as scope: 63 W_conv2 = weight_variable([5, 5, 32, 64]) 64 b_conv2 = bias_variable([64]) 65 h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) 66 67 # プーリング層2の作成 68 with tf.name_scope('pool2') as scope: 69 h_pool2 = max_pool_2x2(h_conv2) 70 71 # 全結合層1の作成 72 with tf.name_scope('fc1') as scope: 73 W_fc1 = weight_variable([7*7*64, 1024]) 74 b_fc1 = bias_variable([1024]) 75 h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) 76 h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) 77 # dropoutの設定 78 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 79 80 # 全結合層2の作成 81 with tf.name_scope('fc2') as scope: 82 W_fc2 = weight_variable([1024, NUM_CLASSES]) 83 b_fc2 = bias_variable([NUM_CLASSES]) 84 85 # ソフトマックス関数による正規化 86 with tf.name_scope('softmax') as scope: 87 y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) 88 89 # 各ラベルの確率のようなものを返す 90 return y_conv 91 92# lossを計算する関数 93def loss(logits, labels): 94 cross_entropy = -tf.reduce_sum(labels*tf.log(logits)) 95 tf.summary.scalar("cross_entropy", cross_entropy) 96 return cross_entropy 97 98# 訓練のOpを定義する関数 99def training(loss, learning_rate): 100 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss) 101 return train_step 102 103# 正解率(accuracy)を計算する関数 104def accuracy(logits, labels): 105 correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)) 106 accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) 107 tf.summary.scalar("accuracy", accuracy) 108 return accuracy 109 110if __name__ == '__main__': 111 count=0 112 folder_list=os.listdir(path) 113 114 train_image = [] 115 train_label = [] 116 test_image = [] 117 test_label = [] 118 119 f = open(FLAGS.label, 'w') 120 for folder in folder_list: 121 subfolder = os.path.join(path,folder) 122 file_list = os.listdir(subfolder) 123 124 filemax = 0 125 126 for file in file_list: 127 filemax = filemax + 1 128 129 # train : test = 9 : 1 130 file_rate = int(filemax/10*9) 131 132 i = 0 133 134 for file in file_list: 135 136 img = cv2.imread('./data/' + folder + '/' + file) 137 img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE)) 138 if i <= file_rate: 139 train_image.append(img.flatten().astype(np.float32)/255.0) 140 tmp = np.zeros(NUM_CLASSES) 141 tmp[int(count)] = 1 142 train_label.append(tmp) 143 else: 144 test_image.append(img.flatten().astype(np.float32)/255.0) 145 tmp = np.zeros(NUM_CLASSES) 146 tmp[int(count)] = 1 147 test_label.append(tmp) 148 149 i = i + 1 150 151 label_name = folder + '\n' 152 f.write(label_name) 153 count=count+1 154 f.close() 155 156 train_image = np.asarray(train_image) 157 train_label = np.asarray(train_label) 158 test_image = np.asarray(test_image) 159 test_label = np.asarray(test_label) 160 161 with tf.Graph().as_default(): 162 # 画像を入れる仮のTensor 163 images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS)) 164 # ラベルを入れる仮のTensor 165 labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES)) 166 # dropout率を入れる仮のTensor 167 keep_prob = tf.placeholder("float") 168 169 # inference()を呼び出してモデルを作る 170 logits = inference(images_placeholder, keep_prob) 171 # loss()を呼び出して損失を計算 172 loss_value = loss(logits, labels_placeholder) 173 # training()を呼び出して訓練 174 train_op = training(loss_value, FLAGS.learning_rate) 175 # 精度の計算 176 acc = accuracy(logits, labels_placeholder) 177 178 # 保存の準備 179 saver = tf.train.Saver() 180 # Sessionの作成 181 sess = tf.Session() 182 # 変数の初期化 183 sess.run(tf.initialize_all_variables()) 184 # TensorBoardで表示する値の設定 185 summary_op = tf.summary.merge_all() 186 summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph) 187 188 189 # 訓練の実行 190 for step in range(FLAGS.max_steps): 191 for i in range(int(len(train_image)/FLAGS.batch_size)): 192 # batch_size分の画像に対して訓練の実行 193 batch = FLAGS.batch_size*i 194 # feed_dictでplaceholderに入れるデータを指定する 195 sess.run(train_op, feed_dict={ 196 images_placeholder: train_image[batch:batch+FLAGS.batch_size], 197 labels_placeholder: train_label[batch:batch+FLAGS.batch_size], 198 keep_prob: 0.5}) 199 200 # 1 step終わるたびに精度を計算する 201 train_accuracy = sess.run(acc, feed_dict={ 202 images_placeholder: train_image, 203 labels_placeholder: train_label, 204 keep_prob: 1.0}) 205 print ("step %d, training accuracy %g"%(step, train_accuracy)) 206 207 # 1 step終わるたびにTensorBoardに表示する値を追加する 208 summary_str = sess.run(summary_op, feed_dict={ 209 images_placeholder: train_image, 210 labels_placeholder: train_label, 211 keep_prob: 1.0}) 212 summary_writer.add_summary(summary_str, step) 213 214 # 訓練が終了したらテストデータに対する精度を表示 215 print ("test accuracy %g"%sess.run(acc, feed_dict={ 216 images_placeholder: test_image, 217 labels_placeholder: test_label, 218 keep_prob: 1.0})) 219 220 # 最終的なモデルを保存 221 save_path = saver.save(sess, "./model.ckpt")

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

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

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

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

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

quickquip

2017/11/05 09:45

例外の名前が「読んで字のごとく」だと思うんですが
s0ra

2017/11/05 09:54

いや、それは僕もわかってます。しかし、.DS_Storeを無理やり作成しても同じようなエラーが出ます。
退会済みユーザー

退会済みユーザー

2017/11/05 12:34

Q.1何行目でエラーが出てくるかエラーメッセージに書いてありませんか?Q.2このコードのある場所のフォルダ一覧かフォルダのスクリーンショットか何かをつけてもらえませんか?
WathMorks

2017/11/05 15:55

.DS_Storeはフォルダ表示設定に関するメタデータを記録するための隠しファイルです。画像データが入っているフォルダだけを指定するように修正しましょう。
guest

回答1

0

ベストアンサー

Not a directory: '/Users/data/.DS_Store'は、'/Users/data/.DS_Store'がディレクトリではない。というエラーです。

os.listdir(path)では、ディレクトリないの要素をリストにするので、ファイルもディレクトリのどちらともを取得します。
ですので、ディレクトリ内のディレクトリのリストを作りたい場合は、os.listdir(path)で取得した要素がディレクトリであるかチェックし、
ディレクトリでない場合はリストから削除してください。

それか、'/Users/data/.DS_Store'を削除してください。

投稿2017/11/07 02:40

cpthgli

総合スコア76

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

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

mkgrei

2017/11/08 16:23

folder_list = [f for f in os.listdir(path) if os.path.isdir('{0}/{1}'.format(path, f))]
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問