tied autoencoder 学习

今天简单实现了一下tied weight autoencoder,但是效果不地,不知道是什么原因,记录一下

emb_dim=2

import os
#os.chdir("/DATA1/zhangjingxiao/yxk/center_loss/pytorch-center-loss-master")
import sys
import argparse
import datetime
import time
import os.path as osp
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import random
import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
import argparse
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
import matplotlib.pyplot as plt
import h5py
import numpy as np

class AutoEncoder(nn.Module):
    def __init__(self,input_dim,hidden_dim,embed_dim):
        super(AutoEncoder, self).__init__()
        
        self.weight1 = nn.Parameter(torch.randn(input_dim, hidden_dim))
        self.weight2 = nn.Parameter(torch.randn(hidden_dim, embed_dim))
        
    def encoder(self,x):
        x=F.linear(x,self.weight1.T)
        x=F.relu(x)
        x=F.linear(x,self.weight2.T)
        return x
    
    def decoder(self,x):
        x=F.linear(x,self.weight2)
        x=F.relu(x)
        x=F.linear(x,self.weight1)
        return x
        
    def forward(self, x):
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return decoded,encoded
    

# print(en)
# x = torch.randn(1, 10)
# out,emb = en(x)
# print(out.shape)
hf = h5py.File("/data/wangdongxue/yxk/dataset/USPS/data.h5", 'r')
X_train= np.asarray(hf.get('data'), dtype='float32')

y_train = np.asarray(hf.get('labels'), dtype='int32')
X_train=X_train.reshape((11000,256))
X_train=X_train/255.0


train_set = torch.utils.data.TensorDataset(torch.FloatTensor(X_train), torch.LongTensor(y_train))
batch_size = 128
train_loader = DataLoader(train_set, batch_size=batch_size, num_workers=0,shuffle=True)

en = AutoEncoder(256,64,2)
print(en)
EPOCH=100

optimizer = optim.Adam(en.parameters(),lr=0.001)
loss_func = nn.MSELoss()

train_loss=[]
for epoch in range(EPOCH):
    for step,(x,y) in enumerate(train_loader):
        b_x = Variable(x)
        decoded,encoded = en(b_x)

        loss = loss_func(decoded,b_x)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        train_loss.append(loss.item())
        if step % 100 ==0:
            print('Epoch:',epoch,'|train loss:%.4f'%loss.item())

train_loss=np.array(train_loss)
fig=plt.figure(figsize=(18,12))
plt.plot(range(len(train_loss)),train_loss)
plt.show()

train_all=torch.FloatTensor(X_train)            
en.eval()
with torch.no_grad():
    decoded,encoded = en(train_all)

    
embeddings=encoded.data.numpy()
target=y_train

fig=plt.figure(figsize=(20,12))
for label in np.unique(target):
    plt.scatter(embeddings[label==target,0], embeddings[label==target,1],label=label)
plt.legend(loc="upper left")
plt.show()

结果如下
在这里插入图片描述
在这里插入图片描述

emb_dim=32

%matplotlib inline
import os
#os.chdir("/DATA1/zhangjingxiao/yxk/center_loss/pytorch-center-loss-master")
import sys
import argparse
import datetime
import time
import os.path as osp
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import random
import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
import argparse
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
import matplotlib.pyplot as plt
import h5py
import numpy as np

class AutoEncoder(nn.Module):
    def __init__(self,input_dim,hidden_dim,embed_dim):
        super(AutoEncoder, self).__init__()
        
        self.weight1 = nn.Parameter(torch.randn(input_dim, hidden_dim))
        self.weight2 = nn.Parameter(torch.randn(hidden_dim, embed_dim))
        
    def encoder(self,x):
        x=F.linear(x,self.weight1.T)
        x=F.relu(x)
        x=F.linear(x,self.weight2.T)
        return x
    
    def decoder(self,x):
        x=F.linear(x,self.weight2)
        x=F.relu(x)
        x=F.linear(x,self.weight1)
        return x
        
    def forward(self, x):
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return decoded,encoded
    

# print(en)
# x = torch.randn(1, 10)
# out,emb = en(x)
# print(out.shape)
hf = h5py.File("/data/wangdongxue/yxk/dataset/USPS/data.h5", 'r')
X_train= np.asarray(hf.get('data'), dtype='float32')

y_train = np.asarray(hf.get('labels'), dtype='int32')
X_train=X_train.reshape((11000,256))
X_train=X_train/255.0


train_set = torch.utils.data.TensorDataset(torch.FloatTensor(X_train), torch.LongTensor(y_train))
batch_size = 128
train_loader = DataLoader(train_set, batch_size=batch_size, num_workers=0,shuffle=True)

en = AutoEncoder(256,64,32)
print(en)
EPOCH=50

optimizer = optim.Adam(en.parameters(),lr=0.001)
loss_func = nn.MSELoss()

train_loss=[]
for epoch in range(EPOCH):
    for step,(x,y) in enumerate(train_loader):
        b_x = Variable(x)
        decoded,encoded = en(b_x)

        loss = loss_func(decoded,b_x)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        train_loss.append(loss.item())
        if step % 100 ==0:
            print('Epoch:',epoch,'|train loss:%.4f'%loss.item())

train_loss=np.array(train_loss)
fig=plt.figure(figsize=(18,12))
plt.plot(range(len(train_loss)),train_loss)
plt.show()

train_all=torch.FloatTensor(X_train)            
en.eval()
with torch.no_grad():
    decoded,encoded = en(train_all)

print(encoded.data.numpy().shape) 
# embeddings=encoded.data.numpy()
# target=y_train

import umap
from sklearn.manifold import TSNE
target=y_train
reducer=umap.UMAP(random_state=0)
data_umap=reducer.fit_transform(encoded.data.numpy())
fig=plt.figure(figsize=(18,12))
for label in np.unique(target):
    plt.scatter(data_umap[label==target,0], data_umap[label==target,1],label=label)
plt.legend(loc="best")
plt.show()

结果如下
在这里插入图片描述
在这里插入图片描述

### 解决网络连接超时错误方案 对于遇到的 `network connection timeout` 错误,不同的技术栈有不同的处理方式。 #### Yarn 安装依赖库时发生超时 当使用Yarn安装包时如果遭遇网络问题,可以通过设置更长的网络超时期限来缓解这个问题。命令如下所示[^1]: ```bash yarn install --network-timeout 1000000 ``` #### Java 连接 Oracle 数据库出现超时异常 针对Java应用程序访问Oracle数据库过程中发生的间歇性连接失败现象,建议调整JDBC驱动程序配置参数,优化TCP/IP协议栈性能,并考虑启用保持活动状态的心跳检测机制以维持会话有效[^2]。 #### Kafka 生产者客户端抛出 NetworkException 和 TimeoutExceptions 为了减少Kafka生产者的网络异常次数,在客户机端缩短最大空闲时间至较短周期(例如4分钟),有助于防止因长时间无操作而导致的服务端主动断开连接行为[^3]: ```properties connections.max.idle.ms=240000 ``` #### SSH 登录远程服务器提示 "connection timeout" MobaXterm 使用SSH协议登录CentOS虚拟机实例时碰到此类状况,则需确认目标机器防火墙策略允许入站流量经过指定端口;另外还可以适当延长首次认证阶段等待响应的时间长度限制[^4]. #### LDAP 查询请求执行期间触发超时限定告警 在Active Directory环境中利用LDAP API发起查询指令前设定合理的超时时长,避免因为目录服务暂时繁忙而造成整个应用层逻辑阻塞过久影响用户体验[^5]. ```csharp int connectionTimeOut = 30 * 1000; // Set appropriate value based on environment. var response = ldapConnection.SendRequest(request, connectionTimeOut) as SearchResponse; ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值