簡體   English   中英

嘗試運行我的 tensorflow 代碼時出錯

[英]error when trying to run my tensorflow code

這是我最新帖子中的一個后續問題: 將輸入放入 tensorflow 神經網絡

我使用 tensorflow 和 MNIST 數據集對神經網絡進行了預編碼,並且在 @FinnE 的幫助下能夠更改我的一些代碼,下面列出了這兩個文件:

主要.py:

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

mnist=tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train=tf.keras.utils.normalize(x_train, axis=1)
x_test=tf.keras.utils.normalize(x_test, axis=1)

model=tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(x_train, y_train, epochs=3)

val_loss, val_acc = model.evaluate(x_test, y_test)
print(val_loss, val_acc)

model.save("num_reader.model")
new_model=tf.keras.models.load_model('num_reader.model')
predictions=new_model.predict([x_test])
print(predictions)

屏幕.py:

import tensorflow as tf
import pygame
import sys
import numpy as np
from main import *
import main as nn

class Screen:
    def __init__(self):
        pygame.init()
        #self.screen=pygame.display.set_mode((28,28),pygame.FULLSCREEN)
        self.screen=pygame.display.set_mode((280,280))
        self.array=[]
        self.setArr()
        self.bg_color=(250, 250,250)
        self.ok=False
        self.full=[]
        self.done=False
        print(new_model)
        self.result=0

    def runGame(self):
        self.screen.fill(self.bg_color)
        while True:
            pygame.display.flip()
            self._check_events()
            self.draw()
            if self.full != []:
                break

    def _check_events(self):
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                sys.exit()
            if event.type==pygame.KEYDOWN:
                if event.key==pygame.K_ESCAPE:
                    sys.exit()
                if event.key==pygame.K_d:
                    self.done=True
                    self.decode()
                    print(len(self.full))
                if event.key==pygame.K_c:
                    self.done=False
                    self.setArr()
                    self.screen.fill(self.bg_color)
            if event.type==pygame.MOUSEBUTTONDOWN:
                #print("mouseDown")
                self.ok=True
            elif event.type==pygame.MOUSEBUTTONUP:
                self.ok=False

    def setArr(self):
        self.shortArr=[]
        for y in range(28):
            self.shortArr.append(0)
        for x in range(28):
            self.array.append(self.shortArr)

    def draw(self):
        if self.ok==True:
            x,y=pygame.mouse.get_pos()
            x=round(x/10)*10
            y=round(y/10)*10

            #print(x,y)
            #print(self.array[int(x)//10][int(y)//10])
            self.array[int(x)//10][int(y)//10]=1

            pygame.draw.rect(self.screen, (0,0,0), pygame.Rect(x, y, 10, 10))
            #print("draw")

    def decode(self):
        self.full=[]
        for x in range(28):
            for y in range(28):
                self.full.append(self.array[x][y])

if __name__ == '__main__':
    Sc=Screen()
    Sc.runGame()
    result = nn.new_model.predict(tf.keras.utils.normalize(np.array(Sc.full), axis=1))
    print(result)

但是運行代碼時出現以下錯誤。

Traceback (most recent call last):
  File "C:\Users\user\Documents\Jake\machine learning\MNIST dataset SOLVED\screen.py", line 81, in <module>
    result = nn.new_model.predict(tf.keras.utils.normalize(np.array(Sc.full), axis=1))
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\utils\np_utils.py", line 89, in normalize
    l2 = np.atleast_1d(np.linalg.norm(x, order, axis))
  File "<__array_function__ internals>", line 180, in norm
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\numpy\linalg\linalg.py", line 2547, in norm
    return sqrt(add.reduce(s, axis=axis, keepdims=keepdims))
numpy.AxisError: axis 1 is out of bounds for array of dimension 1

幾乎沒有問題。

  1. 您返回具有 786 個值的平面數組,但它需要 28x28 的 2D 數組 - 這會導致axis=1normalize中出現問題 - 您必須使用self.array而不是self.full

  2. 您創建數組28x28但預測需要1x28x28 - 所以它需要[self.array]而不是 `self.array

result = nn.new_model.predict(tf.keras.utils.normalize(np.array([Sc.array]), axis=1))    
  1. 它返回所有數字的概率,您必須使用np.argmax()來獲得概率最大的數字。 因為predict()可以獲得包含許多圖像的列表,所以它返回包含許多結果的列表 - 即使您檢查單個圖像 - 它需要[0]來檢查第一張圖像的結果。
digit = np.argmax(result[0])
  1. 我認為數組中的數據有問題。 您將其保留為x,ynumpy使用y,xrow, column )(數學中的矩陣也是如此)。 它需要self.array[y][x] = 1 instea self.array[x][y] = 1

  2. 您導入main ,這將運行main中的所有代碼,並在每次啟動時再次訓練 model 。 您不必導入main ,只需使用load_model()

  3. 在我的計算機上,有時mouse.get_pos()給出值280 ,這給出了array[...][28] ,這會引發錯誤,因為 array 只有[27] 它需要檢查xy並將280轉換為279 (或稍后將28轉換為27

  4. setArr()是錯誤的。 你 append 相同的列表self.shortArrself.array但是(這是 Python 中的常見問題)它沒有放置數組的副本,但它引用了同一個數組 - 最后當你在行中更改一個值時它會改變它們在所有行中。


我的完整工作代碼:

screen.py

編輯:我添加了鼠標右鍵清除單個像素

import pygame
import tensorflow as tf
import numpy as np

class Screen:
    
    def __init__(self):
        pygame.init()

        #self.screen = pygame.display.set_mode((28,28),pygame.FULLSCREEN)
        self.screen = pygame.display.set_mode((280,280))
        self.bg_color = (250, 250,250)
        
        self.array = []
        self.set_arr()

        self.ok = False    # exit with prediction
        self.done = False
        #self.button = False

    def run(self):
        self.screen.fill(self.bg_color)
        while not self.done:
            pygame.display.flip()
            self._check_events()
            self.draw()
        pygame.quit()  # some systems need it to close window
        return self.ok
    
    def _check_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                # end program without OK
                self.done = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    # end program without OK
                    self.done = True
                if event.key == pygame.K_d:
                    # end program with OK
                    self.ok = True
                    self.done = True
                if event.key == pygame.K_c:
                    # clear array and screen
                    self.set_arr()
                    self.screen.fill(self.bg_color)
            #if event.type == pygame.MOUSEBUTTONDOWN:
            #    #print("mouseDown")
            #    self.button = True
            #elif event.type == pygame.MOUSEBUTTONUP:
            #    self.button = False

    def set_arr(self):
        """Create empty array 2D for image."""
        self.array = [[0 for x in range(28)] for y in range(28)]

    def draw(self):
        buttons = pygame.mouse.get_pressed()
        if buttons[0] or buttons[2]:  # left or right button
        #if self.button:
            x0, y0 = pygame.mouse.get_pos()
            
            if x0 >= 280:
                x0 = 279
            if y0 >= 280:
                y0 = 279
                
            x = int(round(x0/10)*10)
            y = int(round(y0/10)*10)

            try:
                #self.array[int(x)//10][int(y)//10] = 1
                if buttons[0]:  # left draw
                    self.array[int(y)//10][int(x)//10] = 1
                    pygame.draw.rect(self.screen, (0,0,0), pygame.Rect(x, y, 10, 10))
                if buttons[2]:  # right clear
                    self.array[int(y)//10][int(x)//10] = 0                
                    pygame.draw.rect(self.screen, (255,255,255), pygame.Rect(x, y, 10, 10))
            except Exception as ex:
                print('Exception:', ex)
                print('Debug:', x0, y0, x, y, int(x)//10, int(y)//10)

            #print("draw")

if __name__ == '__main__':
    print('loading model ...')
    model = tf.keras.models.load_model('num_reader.model')

    print('starting screen')
    screen = Screen()
    ok = screen.run()
    
    if not ok:
        print('finish without prediction')
    else:
        print('--- predict as is ---')
        
        arr = np.array([screen.array])
        #print(arr.shape)
        #print(arr[:,:2])
        results = model.predict(arr)
        print('results:', results)
        digit = np.argmax(results[0])
        print('digit:', digit)

        print('--- predict normalized ---')

        arr = tf.keras.utils.normalize(np.array([screen.array]), axis=1)
        #print(arr.shape)
        #print(arr[:,:2])
        results = model.predict(arr)
        print('results:', results)
        digit = np.argmax(results[0])
        print('digit:', digit)

train_model.py

import tensorflow as tf

mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = tf.keras.utils.normalize(x_train, axis=1)
x_test = tf.keras.utils.normalize(x_test, axis=1)

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=3)

val_loss, val_acc = model.evaluate(x_test, y_test)
print('val_loss:', val_loss)
print('val_acc :', val_acc)

#predictions = model.predict([x_test])
#print(predictions)

model.save("num_reader.model")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM