Returns the index of the maximum value
import torch a=([[.1,.2,.3], [1.1,1.2,1.3], [2.1,2.2,2.3], [3.1,3.2,3.3]]) print((dim=1)) print(())
Output:
tensor([ 2, 2, 2, 2])
tensor(11)
pytorch Find Maximum
Question : Find the maximum value from an array using a neural network implementation.
Provide data: two csv files, one holds the training set: n natural numbers of m-dimensional features, and the other holds the label corresponding to each piece of data, which is the maximum value in each piece of data.
Here the training set will be constructed randomly:
#%% import numpy as np import pandas as pd import torch import random import as Data import as nn import as optim def GetData(m, n): dataset = [] for j in range(m): max_v = (0, 9) data = [(0, 9) for i in range(n)] (data) label = [max(dataset[i]) for i in range(len(dataset))] data_list = np.column_stack((dataset, label)) data_list = data_list.astype(np.float32) return data_list #%% # dataset wrapping Overloaded functions len, getitem class GetMaxEle(): def __init__(self, trainset): = trainset def __getitem__(self, index): item = [index] x = item[:-1] y = item[-1] return x, y def __len__(self): return len() # %% Define the network model class SingleNN(): def __init__(self, n_feature, n_hidden, n_output): super(SingleNN, self).__init__() = (n_feature, n_hidden) = () = (n_hidden, n_output) def forward(self, x): x = (x) x = (x) x = (x) return x def train(m, n, batch_size, PATH): # Randomly generate m training samples of n dimensions data_list =GetData(m, n) dataset = GetMaxEle(data_list) trainset = (dataset, batch_size=batch_size, shuffle=True) net = SingleNN(n_feature=10, n_hidden=100, n_output=10) criterion = () optimizer = ((), lr=0.001, momentum=0.9) # total_epoch = 100 for epoch in range(total_epoch): for index, data in enumerate(trainset): input_x, labels = data labels = () optimizer.zero_grad() output = net(input_x) # print(output) # print(labels) loss = criterion(output, labels) () () # scheduled_optimizer.step() print(f"Epoch {epoch}, loss:{()}") # %% Save parameters (net.state_dict(), PATH) #Testing def test(m, n, batch_size, PATH): data_list = GetData(m, n) dataset = GetMaxEle(data_list) testloader = (dataset, batch_size=batch_size) dataiter = iter(testloader) input_x, labels = () net = SingleNN(n_feature=10, n_hidden=100, n_output=10) net.load_state_dict((PATH)) outputs = net(input_x) _, predicted = (outputs, 1) print("Ground_truth:",()) print("predicted:",()) if __name__ == "__main__": m = 1000 n = 10 batch_size = 64 PATH = './max_list.pth' train(m, n, batch_size, PATH) test(m, n, batch_size, PATH)
The initial idea was to use a fully connected network + classification, but the results were not satisfactory, mainly due to the fact that the sample sizes of the different categories were so different that almost 90% of them were maxima.
For example, the code randomly constructs 10 numbers from 0 to 9 to form a sample [2, 3, 5, 8, 9, 5, 3, 9, 3, 6], which is labeled 9.
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.