import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
torch.manual_seed(1)x_data= np.float32(np.random.rand(500,2))
y_data = np.float32( np.sign(x_data[:,0]-0.5)* np.sign(x_data[:,1]-0.5) +1)/2
class MyModel(nn.Module):def __init__(self):super(MyModel, self).__init__()self.hidden1 = nn.Linear(in_features=2, out_features=6) self.hidden2 = nn.Linear(in_features=6, out_features=4) self.output = nn.Linear(in_features=4, out_features=1) def forward(self, x):x = torch.tanh(self.hidden1(x)) x = torch.tanh(self.hidden2(x)) x = self.output(x)return xmodel = MyModel()
loss_fn = nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
x_tensor = torch.from_numpy(x_data)
y_tensor = torch.from_numpy(y_data)
epochs = 5000
losses = []predictions = torch.sigmoid(model(x_tensor))
pre_arr=predictions[:,0]
pre_arr=pre_arr.detach().numpy()plt.subplot(131)
plt.scatter(x_data[:,0],x_data[:,1],c=pre_arr,cmap='viridis',label='Untrained')
plt.legend()for epoch in range(1, epochs + 1):y_pred = model(x_tensor)loss = loss_fn(y_pred.reshape(500), y_tensor)optimizer.zero_grad() loss.backward() optimizer.step() losses.append(loss.item())if epoch % 500 == 0:print(f'Epoch {epoch}: Loss = {loss.item()}')predictions = torch.sigmoid(model(x_tensor))
pre_arr=predictions[:,0]
pre_arr=pre_arr.detach().numpy()plt.subplot(132)
plt.scatter(x_data[:,0],x_data[:,1],c=pre_arr,cmap='viridis',label='Trained')
plt.legend()
plt.subplot(133)
plt.scatter(x_data[:,0],x_data[:,1],c=y_data,cmap='viridis',label='Real Data')
plt.legend()
plt.show()
