fruit.py
1import tensorflow as tf 2from tensorflow import keras 3from tensorflow.keras.models import Sequential 4from tensorflow.keras.layers import Activation, Dense, Dropout 5from tensorflow.keras.utils import to_categorical 6from tensorflow.keras.optimizers import Adagrad 7from tensorflow.keras.optimizers import Adam 8import numpy as np 9from PIL import Image 10import os 11 12# 学習用のデータを作る. 13image_list = [] 14label_list = [] 15 16# ./data/train 以下のorange,appleディレクトリ以下の画像を読み込む。 17for dir in os.listdir("data/train"): 18 if dir == ".DS_Store": 19 continue 20 21 dir1 = "data/train/" + dir 22 label = 0 23 24 if dir == "apple": # appleはラベル0 25 label = 0 26 elif dir == "orange": # orangeはラベル1 27 label = 1 28 29 for file in os.listdir(dir1): 30 if file != ".DS_Store": 31 # 配列label_listに正解ラベルを追加(りんご:0 オレンジ:1) 32 label_list.append(label) 33 filepath = dir1 + "/" + file 34 # 画像を25x25pixelに変換し、1要素が[R,G,B]3要素を含む配列の25x25の2次元配列として読み込む。 35 # [R,G,B]はそれぞれが0-255の配列。 36 image = np.array(Image.open(filepath).resize((25, 25))) 37 print(filepath) 38 # 配列を変換し、[[Redの配列],[Greenの配列],[Blueの配列]] のような形にする。 39 image = image.transpose(2, 0, 1) 40 # さらにフラットな1次元配列に変換。最初の1/3はRed、次がGreenの、最後がBlueの要素がフラットに並ぶ。 41 image = image.reshape(1, image.shape[0] * image.shape[1] * image.shape[2]).astype("float32")[0] 42 # 出来上がった配列をimage_listに追加。 43 image_list.append(image / 255.) 44 45# kerasに渡すためにnumpy配列に変換。 46image_list = np.array(image_list) 47 48# ラベルの配列を1と0からなるラベル配列に変更 49# 0 -> [1,0], 1 -> [0,1] という感じ。 50Y = to_categorical(label_list) 51 52# モデルを生成してニューラルネットを構築 53model = Sequential() 54model.add(Dense(200, input_dim=1875)) 55model.add(Activation("relu")) 56model.add(Dropout(0.2)) 57 58model.add(Dense(200)) 59model.add(Activation("relu")) 60model.add(Dropout(0.2)) 61 62model.add(Dense(2)) 63model.add(Activation("softmax")) 64 65# オプティマイザにAdamを使用 66opt = Adam(lr=0.001) 67# モデルをコンパイル 68model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"]) 69# 学習を実行。10%はテストに使用。 70model.fit(image_list, Y, epochs=1500, batch_size=100, validation_split=0.1) 71 72# テスト用ディレクトリ(./data/train/)の画像でチェック。正解率を表示する。 73total = 0. 74ok_count = 0. 75 76for dir in os.listdir("data/train"): 77 if dir == ".DS_Store": 78 continue 79 80 dir1 = "data/test/" + dir 81 label = 0 82 83 if dir == "apple": 84 label = 0 85 elif dir == "orange": 86 label = 1 87 88 for file in os.listdir(dir1): 89 if file != ".DS_Store": 90 label_list.append(label) 91 filepath = dir1 + "/" + file 92 image = np.array(Image.open(filepath).resize((25, 25))) 93 print(filepath) 94 image = image.transpose(2, 0, 1) 95 image = image.reshape(1, image.shape[0] * image.shape[1] * image.shape[2]).astype("float32")[0] 96 result = model.predict_classes(np.array([image / 255.])) 97 print("label:", label, "result:", result[0]) 98 99 total += 1. 100 101 if label == result[0]: 102 ok_count += 1. 103 104print("seikai: ", ok_count / total * 100, "%")
これをコマンドプロンプトで実行すると、
IndentationError: unexpected indent
というエラーが最後に出て、おそらくこのエラーが原因か、結果らしきものが出てきません、
たぶんtensorflowが対応していないことが原因と思われるのですが、どこをどうなおせばよいのでしょう?ちなみに、コマンドプロンプトで、
pip install tensorflow==1.15.5 --user
とすると、
ERROR: Could not find a version that satisfies the requirement tensorflow==1.15.5 (from versions: 2.5.0, 2.5.1, 2.5.2, 2.5.3, 2.6.0rc0, 2.6.0rc1, 2.6.0rc2, 2.6.0, 2.6.1, 2.6.2, 2.6.3, 2.6.4, 2.6.5, 2.7.0rc0, 2.7.0rc1, 2.7.0, 2.7.1, 2.7.2, 2.7.3, 2.7.4, 2.8.0rc0, 2.8.0rc1, 2.8.0, 2.8.1, 2.8.2, 2.8.3, 2.8.4, 2.9.0rc0, 2.9.0rc1, 2.9.0rc2, 2.9.0, 2.9.1, 2.9.2, 2.9.3, 2.10.0rc0, 2.10.0rc1, 2.10.0rc2, 2.10.0rc3, 2.10.0, 2.10.1, 2.11.0rc0, 2.11.0rc1, 2.11.0rc2, 2.11.0, 2.11.1, 2.12.0rc0, 2.12.0rc1, 2.12.0, 2.13.0rc0, 2.13.0rc1)
(略)
Epoch 1500/1500
1/1 [==============================] - 0s 56ms/step - loss: 4.9603e-06 - accuracy: 1.0000 - val_loss: 0.0314 - val_accuracy: 1.0000
data/test/apple/1.jpg
Traceback (most recent call last):
File "C:\Users\TOSHIBA\Desktop\python\fruit.py", line 96, in <module>
result = model.predict_classes(np.array([image / 255.]))
AttributeError: 'Sequential' object has no attribute 'predict_classes'
という謎なエラーが出て、古いバージョンもインストールできないようになっています。
参考サイトは、https://zenn.dev/hiroe_orz17/articles/53af65f491122e
です。

回答2件
あなたの回答
tips
プレビュー