

pytorchでの機械学習用のコードを実装し，次に予測するコードを実装しています．  
pytorchで学習したモデルを呼び出そうとしたら，モデルの呼び出しではなく，なぜか，呼び出したプログラムが開始してしまします．どなたか，正しい学習済みのモデルとクラス及び変数の呼び出し方を教えてください．2つのプログラムファイルは同じディレクトリにあり，学習プログラムはRECurrentSNN.py，予測プログラムはpredicted.pyです．

モデルのコードとクラス

[code]

        import torch
        import torch.nn as nn
        import numpy as np
        from bindsnet.network import Network
        from bindsnet.network.nodes import Input, LIFNodes
        from bindsnet.network.topology import Connection
        from bindsnet.network.monitors import Monitor
        from sklearn.model_selection import train_test_split
        from bindsnet.encoding.loaders import poisson_loader
        # モデルの定義
        class LogisticRegression(nn.Module):
            def __init__(self, input_size, num_classes):
                super(LogisticRegression, self).__init__()
                self.linear = nn.Linear(input_size, num_classes)
            def forward(self, x):
                output = self.linear(x)
               _, predicted = torch.max(output,1) #定義しなおしました
                return output
    
         network = Network(dt=1.0)
         input_size = 64
         num_classes = 6
         time = 32      
         _BATCH_SIZE = 300
         num_epochs = 100
    
         inpt = Input(64, shape=(1,64))
         output = LIFNodes(64, thresh=-52 + torch.randn(64))  # m1のb
         network.add_layer(inpt, name='A')
         network.add_layer(output, name='E')
         network.add_connection(Connection(inpt, output, w=torch.randn(inpt.n, output.n)), 'A', 'E')
         network.add_connection(Connection(output, output, w=0.5*torch.randn(output.n, output.n)), 'E', 'E')
    
         spikes = {}
         for l in network.layers:
             spikes[l] = Monitor(network.layers[l], state_vars=["s"], time=time)
             network.add_monitor(spikes[l], name="%s_spikes" % l)
             voltages = {"E": Monitor(network.layers["E"], ["v"], time=time)}
             network.add_monitor(voltages["E"], name="E_voltages")
    
        npzfile = np.load("C:/Users/nama/Desktop/myo-python-1.0.4/myo-armband-nn-master/data/train_set.npz")
        x = npzfile['x']
        y = npzfile['y']
        x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)
        # tensor型に変換
        x_train = torch.from_numpy(x_train).float()
        y_train = torch.from_numpy(y_train).float()
        x_train = torch.clamp(x_train, min=0, max=1000)
        x_test = torch.from_numpy(x_test).float()
        y_test = torch.from_numpy(y_test).long()
        x_test = torch.clamp(x_test, min=0, max=1000)
        loader = zip(poisson_loader(x_train * 0.64, time=64), iter(y_train))
        training_pairs = []
        for i, (datum, y_train) in enumerate(loader):
            network.run(inputs={"A": datum}, time=time, input_time_dim=1)
            training_pairs.append([spikes['E'].get('s').sum(0), y_train])
            network.reset_state_variables()
            if (i + 1) % 10 == 0: print('Train progress: (%d / 40)' % (i + 1))
            if (i + 1) == 40: print(); break
    
        model = LogisticRegression(input_size, num_classes); criterion = nn.CrossEntropyLoss()   # m2に相当
        optimizer = torch.optim.SGD(model.parameters(), lr=0.005)
        # スパイクとラベルのトレーニング
        correct, total = 0, 0
        for epoch in range(num_epochs):
               for i, (s, y_train) in enumerate(training_pairs):
                   optimizer.zero_grad()
                   output = model(s.float())
                   y_train = torch.reshape(y_train, (-1,))  # y_trainのサイズを[1], output=[1.6]
                   y_train = y_train.view(-1, 6)
                   y_train = torch.argmax(y_train, dim=-1)
                   loss = criterion(output,  y_train.long())
                   loss.backward(); optimizer.step()
                   _, predicted = torch.max(output, 1)
                    total += 1
                   correct += int(predicted == y_train.long())
           print('Accuracy of logistic regression on train examples: %2f %%\n ' % (100 * correct / total))
    
    
         loader = zip(poisson_loader(x_test * 0.64, time=64), iter(y_test))
         test_pairs = []
         model.eval()
         for i, (datum, y_test) in enumerate(loader):
             network.run(inputs={"A": datum}, time=time, input_time_dim=1)
             test_pairs.append([spikes['E'].get('s').sum(0), y_test])
             network.reset_state_variables()
             if (i + 1) % 100 == 0: print('Test progress: (%d / 500)' % (i + 1))
             if (i + 1) == 500: print(); break
    
         correct, total = 0, 0
         for s, y_test in test_pairs:
             output = model(s.float()); _, predicted = torch.max(output, 1)
             y_test = torch.argmax(y_test)
             total += 1
             correct += int(predicted == y_test)
     
        print('Accuracy of logistic regression on test examples: %2f %%\n ' % (100 * correct / total))
        torch.save({
                'epoch': epoch,
                'model_state_dict': model.state_dict(),
                'optimizer_state_dict': optimizer.state_dict(),
                'loss': loss,
                }, "C:/Users/name/Desktop/myo-python-1.0.4/bindsnet-master/bindsnet/pytorchsession/snn.pth")
    
        checkpoint = torch.load("C:/Users/name/Desktop/myo-python-1.0.4/bindsnet- 
        master/bindsnet/pytorchsession/snn.pth")
        model.load_state_dict(checkpoint["model_state_dict"])
        optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
        epoch = checkpoint["epoch"]
    
        optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
        torch.save(optimizer.state_dict(), "C:/Users/name/Desktop/myo-python-1.0.4/bindsnet- 
        master/bindsnet/pytorchsession/optimizer.pth" )
        optimizer2 = torch.optim.SGD(model.parameters(), lr=0.1)
        optimizer2.load_state_dict(torch.load("C:/Users/name/Desktop/myo-python-1.0.4/bindsnet- 
        master/bindsnet/pytorchsession/optimizer.pth"))
    
[/code]

[code]

    """
    予測プログラム
    """
        from collections import deque
        from threading import Lock
        import myo
        import time
        import numpy as np
        from time import sleep
        import torch
        import torch.nn as nn
        from bindsnet.RECurrentSNN import LogistiRegression
        model_path = "C:/Users/name/Desktop/myo-python-1.0.4/bindsnet- 
        master/bindsnet/pytorchsession/snn.pth"
    
        class MyListener(myo.DeviceListener):
            def __init__(self, queue_size=8):
              self.lock = Lock()
            self.emg_data_queue = deque(maxlen=queue_size)
            self.orientation_data_queue = deque(maxlen=queue_size)
            self.acceleration_data_queue = deque(maxlen=queue_size)
            self.gyroscope_data_queue = deque(maxlen=queue_size)
            self.rssi_data_queue = deque(maxlen=100)
            self.pose = myo.Pose.rest
            self.connected = False
            self.battery_level = 100
            self.emg_enabled = False
            self.locked = False
            self.rssi = None
            self.emg = None
            self.device_name = None
            self.device = None
            self.myo_firmware = None
            self.arm = None
            self.x_direction = None
            self.sync = None
    
          def get_emg_data(self):
            with self.lock:
                return list(self.emg_data_queue)
    
        def get_orientation_data(self):
            with self.lock:
                return list(self.orientation_data_queue)
    
        def get_gyroscope_data(self):
            with self.lock:
                return list(self.gyroscope_data_queue)
    
        def get_accelerometor_data(self):
            with self.lock:
                return list(self.acceleration_data_queue)
    
          if __name__ == '__main__':
    
            myo.init(bin_path=r'C:\Users\name\Desktop\myo-sdk-win-0.9.0\bin')
            HUB = myo.Hub()
            listener = MyListener()
            start = time.time()
            temp = []
            with HUB.run_in_background(listener.on_event):
                while True:
                data = listener.get_emg_data()
                if time.time() - start >= 1:
                    response = np.argmax(np.bincount(temp))
                    print("Predicted gesture: {0}".format(response))
                    temp = []
                    start = time.time()
                if len(data) > 0:
                    tmp = []
                    for v in listener.get_emg_data():
                        tmp.append(v[1])
                    tmp = list(np.stack(tmp).flatten())
                    if len(tmp) >= 64:
                        pred = torch.mean(predicted, feed_dict={x: np.array([tmp])})
                        #pred = sess.run(y_pred_cls, feed_dict={x: np.array([tmp])})
                        temp.append(pred[0])
                sleep(0.01)
    
[/code]


CC BY-SA 4.0
2020-12-29T09:26:34.330
72964
2021-01-02T09:01:55.623
2021-01-02T09:01:55.623
41671
41671
question
python pytorch
pytorchでの学習したモデルの呼び出しとクラスの呼び出しの方法


おかしな点としては、以下で

[code]

    pred = torch.mean(predicted, feed_dict={x: np.array([tmp])})
    
[/code]

`predicted`を引数で渡しているけど、`predicted`は貰ったソースコード上定義されて無さそう


CC BY-SA 4.0
2021-01-02T04:25:40.800
73019
2021-01-02T04:25:40.800
4715
72964
answer