This is the code I have written, I have tried modifying here and there and have always gotten the same error. As I am a beginner to PyTorch, I am just trying things out to see if machine learning will work on a linear dataset. So, with random, I initialized a dataset. Then, made a single linear neural network. Then, train the neural network on the linear data. Nevertheless, I have an error stating that matmul expects a 1d data, but then my data is at least 1d but is read as 0d instead.
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import random
class LinearNetwork(nn.Module):
def __init__(self):
super(LinearNetwork, self).__init__()
self.fc1 = nn.Linear(1, 1)
def forward(self, input):
x = self.fc1(input)
return x;
#Generate a Dataset to train on. Just a linear function, and we wanna see if this thing is working
DataSet = []
grad = random.randint(0,100)
const = random.randint(0,100)
for i in range(0, 1000):
DataSet.append([i, grad*i + const])
DataSet = torch.tensor(DataSet,dtype = torch.double, requires_grad = True)
#Declare a Linear Network
Net = LinearNetwork()
criterion = nn.MSELoss()
optimizer = optim.SGD(Net.parameters(), lr = 0.01)
print(DataSet)
#Train Model
for i, data in enumerate(DataSet, 0):
Input, Target = data
optimizer.zero_grad()
Output = Net(Input)
loss = criterion(Output, Target)
loss.backward()
optimizer.step()
print("Gradient of the Function is : " + str(grad))
print("Constant Value of the Function is : " + str(const))
print("Learned Gradient and Constant : " + list(Net.parameters()))