42 lines
970 B
Python
42 lines
970 B
Python
|
#!/usr/bin/python3
|
||
|
|
||
|
import torch
|
||
|
import pandas as pd
|
||
|
|
||
|
|
||
|
data = pd.read_csv('iris.data',sep = ',', header = None)
|
||
|
data[5] = data[4].apply(lambda x: 1 if x == 'Iris-versicolor' else 0)
|
||
|
|
||
|
x = torch.tensor(data[[0,1]].values, dtype=torch.float)
|
||
|
y = torch.tensor(data[5], dtype=torch.float)
|
||
|
|
||
|
y = y.reshape(100,1)
|
||
|
|
||
|
class Network(torch.nn.Module):
|
||
|
|
||
|
def __init__(self):
|
||
|
super(Network, self).__init__()
|
||
|
self.fc = torch.nn.Linear(2,1)
|
||
|
|
||
|
def forward(self,x):
|
||
|
x = self.fc(x)
|
||
|
x = torch.nn.functional.sigmoid(x)
|
||
|
|
||
|
return x
|
||
|
|
||
|
network = Network()
|
||
|
optimizer = torch.optim.SGD(network.parameters(), lr=0.002)
|
||
|
criterion = torch.nn.BCELoss()
|
||
|
|
||
|
for _ in range(3000):
|
||
|
optimizer.zero_grad()
|
||
|
ypredicted = network(x)
|
||
|
|
||
|
loss = criterion(ypredicted,y)
|
||
|
accuracy = 100 * sum((ypredicted > 0.5) == y).item() / len(ypredicted)
|
||
|
print('{:.3}'.format(loss.item()), "\t => ", accuracy, '% accuracy')
|
||
|
|
||
|
loss.backward()
|
||
|
optimizer.step()
|
||
|
|