PCA分析
一,代码
import torch
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from kmeans_pytorch import kmeans
from torch.autograd import Variable
import torch.nn.functional as F
from torch.utils.data import DataLoader, TensorDataset
import time
from sklearn.decomposition import PCA
region = pd.read_csv('./主成分分析/region.csv')
region_d = region[['x1', 'x2', 'x3', 'x4']]
region['target'] = region['y']
transfer_1 = PCA(n_components=2)
region_d = transfer_1.fit_transform(region_d)
x = torch.from_numpy(region_d)
y = torch.from_numpy(np.array(region['target']))
x, y = Variable(x), Variable(y)
net = torch.nn.Sequential(
torch.nn.Linear(2, 10),
torch.nn.ReLU(),
torch.nn.Linear(10, 3),
)
print(net)
optimizer = torch.optim.SGD(net.parameters(), lr=1e-4)
loss_func = torch.nn.CrossEntropyLoss()
for t in range(100):
out = net(x.float())
loss = loss_func(out, y.long())
optimizer.zero_grad()
loss.backward()
optimizer.step()
if t % 25 == 0:
plt.cla()
prediction = torch.max(out, 1)[1]
pred_y = prediction.data.numpy()
target_y = y.data.numpy()
plt.scatter(x.data.numpy()[:, 0],
x.data.numpy()[:, 1],
c=pred_y,
s=100,
lw=5,
cmap='coolwarm')
accuracy = float((pred_y == target_y).astype(int).sum()) / float(target_y.size)
print('Accuracy = %.2f'.format(accuracy))
plt.pause(0.1)
plt.show()
二,效果