非监督学习——鸢尾花数据集

import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np


EPOCH = 900
BATCH_SIZE = 150
LR = 0.5        # learning rate
DOWNLOAD_MNIST = False
N_TEST_IMG = 5

Data__=np.loadtxt("Iris.txt")

Data__=Data__[:,1:5]


torch_dataset = torch.from_numpy(Data__).type(torch.FloatTensor)
loader = Data.DataLoader(
    dataset=torch_dataset,      # torch TensorDataset format
    batch_size=BATCH_SIZE,      # mini batch size
    shuffle=True,               # random shuffle for training
    #num_workers=2,              # subprocesses for loading data 多线程 windows为1
    # 多线程来读数据
)
#
# # plot one example
# print(train_data.train_data.size())     # (60000, 28, 28)
# print(train_data.train_labels.size())   # (60000)
# # plt.imshow(train_data.train_data[2].numpy(), cmap='gray')
# # plt.title('%i' % train_data.train_labels[2])
# # plt.show()
#
# # Data Loader for easy mini-batch return in training, the image batch shape will be (50, 1, 28, 28)
# train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)
#

class AutoEncoder(nn.Module):
    def __init__(self):
        super(AutoEncoder, self).__init__()

        self.encoder = nn.Sequential(
            nn.Linear(4, 2),
            ## nn.ELU(),
            # nn.Linear(2, 2),

        )
        self.decoder = nn.Sequential(
            # nn.Linear(2, 2),
            # nn.ELU(),
            nn.Linear(2, 4),
            #nn.Sigmoid(),       # compress to a range (0, 1)
        )

    def forward(self, x):
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return encoded, decoded


autoencoder = AutoEncoder()

optimizer = torch.optim.Adam(autoencoder.parameters(), lr=LR)
loss_func = nn.MSELoss()

# initialize figure
for epoch in range(EPOCH):
    for step, (x) in enumerate(loader):
        b_x = x.view(-1, 4*1)   # batch x, shape (batch, 28*28)
        b_y = x.view(-1, 4*1)   # batch y, shape (batch, 28*28)

        encoded, decoded = autoencoder(b_x)

        loss = loss_func(decoded, b_y)      #非监督学习 不需要输出  mean square error
        optimizer.zero_grad()               # clear gradients for this training step
        loss.backward()                     # backpropagation, compute gradients
        optimizer.step()                    # apply gradients

        if step % 100 == 0:
            print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy())

            # plotting decoded image (second row)


# # 网络测试
view_data = loader.dataset.view(-1, 4*1).type(torch.FloatTensor)
encoded_data, decoder_data = autoencoder(view_data)
encoded_data = encoded_data.data.numpy() # 原数据的编码

decoder_data = decoder_data.view(-1, 4*1).type(torch.FloatTensor)
Re_encoded_data,_= autoencoder(decoder_data) #对原数据的解码码再带入相同的网络进行编码
Re_encoded_data = Re_encoded_data.data.numpy()

# print(encoded_data)
# 绘制原数据的编码
plt.scatter(encoded_data[0:49,0],encoded_data[0:49,1], color='',edgecolors='r',marker='o')
plt.scatter(encoded_data[50:99,0],encoded_data[50:99,1],color='',edgecolors='g',marker='o')
plt.scatter(encoded_data[100:149,0],encoded_data[100:149,1],color='',edgecolors='y',marker='o')

# 绘制原数据的编码后解码的编码
plt.scatter(Re_encoded_data[0:49,0],Re_encoded_data[0:49,1],c='r',marker='x')
plt.scatter(Re_encoded_data[50:99,0],Re_encoded_data[50:99,1],c='g',marker='x')
plt.scatter(Re_encoded_data[100:149,0],Re_encoded_data[100:149,1],c='y',marker='x')
plt.show()
# fig = plt.figure(2); ax = Axes3D(fig)
# X, Y, Z = encoded_data.data[:, 0].numpy(), encoded_data.data[:, 1].numpy(), encoded_data.data[:, 2].numpy()
# values = train_data.train_labels[:200].numpy()
# for x, y, z, s in zip(X, Y, Z, values):
#     c = cm.rainbow(int(255*s/9)); ax.text(x, y, z, s, backgroundcolor=c)
# ax.set_xlim(X.min(), X.max()); ax.set_ylim(Y.min(), Y.max()); ax.set_zlim(Z.min(), Z.max())
# plt.show()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值