# PyTorch如何测试感知器模型？

p1=torch.Tensor([1.0, -1.0])
p2=torch.Tensor([-1.0, -1.5])

plt.plot(p1[0], p1[1], 'ro')
plt.plot(p2[0], p2[1], 'ko')

plt.plot(p1.numpy()[0], p1.numpy()[1], 'ro')
plt.plot(p2.numpy()[0], p2.numpy()[1], 'ko')

print("Red point positive probability={}".format(model.forward(p1).item()))
print("Black point positive probability={}".format(model.forward(p2).item()))

def predict(self, x):
pred=torch.sigmoid(self.linear(x))
if pred>=0.5:
return 1
else:
return 0

print("Red point in calss={}".format(model.predict(p1)))
print("Black point in calss={}".format(model.predict(p2)))

## 完整的代码

import torch
import numpy as np
import matplotlib.pyplot as plt
import torch.nn as nn
from sklearn import datasets
no_of_points=100
centers=[[-0.5, 0.5], [0.5, -0.5]]
x, y=datasets.make_blobs(n_samples=no_of_points, random_state=123, centers=centers, cluster_std=0.4)
xdata=torch.Tensor(x)
ydata=torch.Tensor(y.reshape(100, 1))
def Scatter():
plt.scatter(x[y==0, 0], x[y==0, 1])
plt.scatter(x[y==1, 0], x[y==1, 1])
class Perceptron_model(nn.Module):
def __init__(self, input_size, output_size):
super().__init__()
self.linear=nn.Linear(input_size, output_size)
def forward(self, x):
pred=torch.sigmoid(self.linear(x))
return pred
def predict(self, x):
pred=torch.sigmoid(self.linear(x))
If pred>=0.5:
return 1
else:
return 0
torch.manual_seed(2)
model= Perceptron_model(2, 1)
criterion=nn.BCELoss()
optimizer=torch.optim.SGD(model.parameters(), lr=0.01)
print(list(model.parameters()))
[A, B]=model.parameters()
A1, A2=A.view(2)
B1=B[0]
epochs=1000
losses=[]
fori in range(epochs):
ypred=model.forward(xdata)
loss=criterion(ypred, ydata)
print("epoch:", i, "loss:", loss.item())
losses.append(loss)
loss.backward()
optimizer.step()
def get_perameters():
return(A1.item(), A2.item(), B[0].item())
def plotfit(title):
plt.title=title
A1, A2, B1=get_perameters()
x1=np.array([-2.0, 2.0])
y1=((A1*x1)+B1)/-A2
plt.plot(x1, y1, 'r')
Scatter()
plt.show()
p1=torch.Tensor([1.0, -1.0])
p2=torch.Tensor([-1.0, -1.5])
plt.plot(p1.numpy()[0], p1.numpy()[1], 'ro')
plt.plot(p2.numpy()[0], p2.numpy()[1], 'ko')
print("Red point positive probability={}".format(model.forward(p1).item()))
print("Black point positive probability={}".format(model.forward(p2).item()))
print("Red point in calss={}".format(model.predict(p1)))
print("Black point in calss={}".format(model.predict(p2)))
plotfit('Initial Model')

• 回顶