Pytorchでロジスティック回帰
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data[:100]
y = iris.target[:100]
X = torch.tensor(X, dtype=torch.float32)
y = torch.tensor(y, dtype=torch.float32)
net = nn.Linear(4, 1)
loss_fn = nn.BCEWithLogitsLoss()
optimizer = optim.SGD(net.parameters(), lr=0.25)
losses = []
for epoch in range(100):
optimizer.zero_grad()
y_pred = net(X)
loss = loss_fn(y_pred.view_as(y), y)
loss.backward()
optimizer.step()
losses.append(loss.item())
print("epoch: %d , loss: %f" % (epoch+1, loss))
if(epoch != 0):
if(abs(losses[epoch-1] - losses[epoch]) < 0.00001):
break
%matplotlib inline
from matplotlib import pyplot as plt
plt.plot(losses)
plt.savefig('losses.png')
plt.show()
出力
参考