1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
| import torch from torch.utils.data import Dataset, DataLoader import pandas as pd import numpy as np from sklearn.model_selection import train_test_split import time
class Iris: def __init__(self, sepal_length, sepal_width, petal_length, petal_width, species): self.sepal_length = sepal_length self.sepal_width = sepal_width self.petal_length = petal_length self.petal_width = petal_width self.species = species
def feature(self): return [self.sepal_length, self.sepal_width, self.petal_length, self.petal_width]
def label(self): if self.species == 'Iris-setosa': return 0 elif self.species == 'Iris-versicolor': return 1 elif self.species == 'Iris-virginica': return 2
class IrisDataset(Dataset): def __init__(self, features, labels): self.features = features self.labels = labels
def __len__(self): return len(self.features)
def __getitem__(self, index): item_feature = self.features[index] item_label = self.labels[index] return item_feature, item_label
class Model(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_label): super(Model, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.output = torch.nn.Linear(n_hidden, n_label)
def forward(self, x): x = torch.nn.functional.relu(self.hidden(x)) x = torch.nn.functional.softmax(self.output(x), dim=1) return x
def get_data(): tic = time.time() print('读取cvs文件') csv_path = '/Users/bakako/Downloads/archive/Iris.csv' datasource = pd.read_csv(csv_path) datasource_len = len(datasource)
iris_features = np.zeros((datasource_len, 4), dtype=float) iris_labels = []
print('构造数据结构') for i in range(datasource_len): iris = Iris(datasource.SepalLengthCm[i], datasource.SepalWidthCm[i], datasource.PetalLengthCm[i], datasource.PetalWidthCm[i], datasource.Species[i])
iris_features[[i], :] = iris.feature() iris_labels.append(iris.label())
train_features, \ test_features, \ train_labels, \ test_labels = train_test_split(iris_features, iris_labels, test_size=0.2)
print('构造训练集') train_dataset = IrisDataset(torch.FloatTensor(train_features), torch.LongTensor(train_labels)) test_features = torch.FloatTensor(test_features) test_labels = torch.LongTensor(test_labels)
toc = time.time() print('Loading Time: ' + str(1000 * (toc - tic)) + 'ms') print('') return train_dataset, test_features, test_labels
def train_model(dataset, epochs, gpu): tic = time.time() device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model = Model(n_feature=4, n_hidden=40, n_label=3) if gpu: model.to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=0.02) loss_func = torch.nn.CrossEntropyLoss() batch_size = 5 dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=0, pin_memory=True)
for epoch in range(epochs): for step, (features, labels) in enumerate(dataloader): if gpu: features = features.to(device) labels = labels.to(device)
output = model(features) loss = loss_func(output, labels)
optimizer.zero_grad() loss.backward() optimizer.step() print('Epoch: ', epoch + 1, '| Step: ', step + 1, '| Loss: ', loss.item())
toc = time.time() print('训练结束') print('Train time:' + str(1000 * (toc - tic)) + 'ms') print('')
return model
if __name__ == '__main__': gpu = False train_dataset, test_features, test_labels = get_data() model = train_model(train_dataset, 100, gpu) result = model(test_features) prediction = torch.max(result, 1)[1] correct = (prediction == test_labels).sum().item() accuracy = float(correct) / float(len(test_features)) print("莺尾花预测准确率:", accuracy)
|