代码
import matplotlib.pyplot as plt import numpy as np import pandas as pd df = pd.read_csv('train.csv') df=df.drop(['ID'],axis=1) nmp=df.to_numpy() feature=nmp[:-20,:-1] label=nmp[:-20,-1]#(210,240)test_feature=nmp[-20:,:-1] test_label=nmp[-20:,-1]#(210,240)
from torch import nn import torch loss=nn.MSELoss() feature=torch.Tensor(feature) label=torch.Tensor(label) label=label.reshape(-1,1)
test_feature=torch.Tensor(test_feature) test_label=torch.Tensor(test_label) test_label=test_label.reshape(-1,1)
network=nn.Sequential(nn.Linear(240,1),nn.Sigmoid()) import torch.optim as optim optimizer = optim.Adam(network.parameters(), lr=0.004) for epoch in range(5000): optimizer.zero_grad() out=network(feature) l=loss(out,label) l.backward() optimizer.step() Y = torch.ge(out, 0.5).float() acc=Y.eq(label).float().sum()/len(label) out=network(test_feature) Y = torch.ge(out, 0.5).float() test_acc=Y.eq(test_label).float().sum()/len(test_label) print(epoch,l,acc,test_acc) if test_acc==0.50 and acc>0.93: break ax1 = plt.subplot(2,1,1) ax2 = plt.subplot(2,1,2) out=network(feature) out=out.detach().numpy() plt.sca(ax1) for i in range(out.shape[0]): if label[i]==1: plt.scatter(out[i],0,color='red') if label[i]==0: plt.scatter(out[i],0,color='blue') out=network(test_feature) out=out.detach().numpy() plt.sca(ax2) for i in range(out.shape[0]): if test_label[i]==1: plt.scatter(out[i],0,color='red') if test_label[i]==0: plt.scatter(out[i],0,color='blue')
plt.show()
标签:plt,torch,feature,label,test,神经网络,序列,时序,out From: https://www.cnblogs.com/hahaah/p/16938090.html