这是我自己写的代码,看到其他人都是有偿分享,我就无偿分享吧
相信聪明的你不需要我的注释也能看懂
import torch.nn as nn
import torch.nn.functional as F
import torch
from torch.autograd import Variable
class Net(nn.Module):
def __init__(self, inC, outC):
super(Net,self).__init__()
self.fc1 = nn.Linear(inC, 64)
self.fc2 = nn.Linear(64, 16)
self.fc3 = nn.Linear(16, outC)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return self.fc3(x)
criteria = nn.MSELoss()
def train(net, optimizer, x, y, epoch):
predic = net(x)
loss = criteria(predic, y)
print('epoch {} loss:{:.3f}'.format(epoch, loss))
optimizer.zero_grad()
loss.backward()
optimizer.step()
def test(net, x, y):
predic = net(x)
loss = criteria(predic, y)
print('test loss:{:.3f}'.format(loss))
if __name__ == '__main__':
lr = 0.05
epoch = 20
x1 = []
y1 = []
with open('PhishingData.arff', 'r+') as f1:
for i in f1:
k = [int(i) for i in i.split(',')]
x1.append(k[:9])
y1.append([k[9]])
x1 = Variable(torch.FloatTensor(x1), requires_grad = False)
y1 = Variable(torch.FloatTensor(y1), requires_grad = False)
net = Net(9,1)
optimizer = torch.optim.SGD(net.parameters(), lr, momentum=0.5)
for i in range(epoch):
train(net, optimizer, x1, y1, i)
x2 = []
y2 = []
with open('testData.arff','r+') as f2:
for i in f2:
k = [int(i) for i in i.split(',')]
x2.append(k[:9])
y2.append([k[9]])
x2 = Variable(torch.FloatTensor(x2), requires_grad = False)
y2 = Variable(torch.FloatTensor(y2), requires_grad = False)
test(net, x2, y2)
数据取自UCI:Website Phishing Data Set,训练数据和测试数据都是这个数据集里分出来的。