diff --git a/knn/README.md b/knn/README.md index 3fa8dd99439fad84267e2c6b0fd79825dac0585c..458f35cfcccb1740a15057a7f0d69a8f3392a802 100644 --- a/knn/README.md +++ b/knn/README.md @@ -8,7 +8,7 @@ K近邻算法(K-Nearest-Neighbor, KNN)是一种用于分类和回归的非 - 距离度量,反映了特征空间中两个样本间的相似度,距离越小,越相似。常用的有Lp距离(p=2时,即为欧式距离)、曼哈顿距离、海明距离等。 - 分类决策规则,通常是多数表决,或者基于距离加权的多数表决(权值与距离成反比)。 -本实验主要介绍使用MindSpore在部分Iris数据集上进行KNN实验。 +本实验主要介绍使用MindSpore在部分wine数据集上进行KNN实验。 ## 实验目的 @@ -24,7 +24,7 @@ K近邻算法(K-Nearest-Neighbor, KNN)是一种用于分类和回归的非 ## 实验环境 -- MindSpore 0.2.0(MindSpore版本会定期更新,本指导也会定期刷新,与版本配套); +- MindSpore 0.5.0(MindSpore版本会定期更新,本指导也会定期刷新,与版本配套); - 华为云ModelArts:ModelArts是华为云提供的面向开发者的一站式AI开发平台,集成了昇腾AI处理器资源池,用户可以在该平台下体验MindSpore。ModelArts官网:https://www.huaweicloud.com/product/modelarts.html ## 实验准备 @@ -45,13 +45,43 @@ K近邻算法(K-Nearest-Neighbor, KNN)是一种用于分类和回归的非 - 归档数据直读:关闭 - 企业项目、标签等配置:免 +### 数据准备 + +Wine数据集是模式识别最著名的数据集之一。这些数据是对来自意大利同一地区但来自三个不同品种的葡萄酒进行化学分析的结果。分析了三种葡萄酒中每种所含13种成分的量。这些13种属性是 + +1. Alcohol,酒精 +2. Malic acid,苹果酸 +3. Ash,灰 +4. Alcalinity of ash,灰的碱度 +5. Magnesium,镁 +6. Total phenols,总酚 +7. Flavanoids,类黄酮 +8. Nonflavanoid phenols,非黄酮酚 +9. Proanthocyanins,原花青素 +10. Color intensity,色彩强度 +11. Hue,色调 +12. OD280/OD315 of diluted wines,稀释酒的OD280/OD315 +13. Proline,脯氨酸 + +在Wine数据集的官网[Wine Data Set](http://archive.ics.uci.edu/ml/datasets/Wine)上下载[wine.data](http://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data)文件。 + +| Data Set Characteristics: | Multivariate | Number of Instances: | 178 | +| Attribute Characteristics: | Integer, Real | Number of Attributes: | 13 | +| Associated Tasks: | Classification | Missing Values? | No | + ### 脚本准备 -从[课程gitee仓库](https://gitee.com/mindspore/course)上下载本实验相关脚本。 +从[课程gitee仓库](https://gitee.com/mindspore/course)中下载本实验相关脚本。 ### 上传文件 -将脚本上传到OBS桶中。 +将脚本和数据集上传到OBS桶中,组织为如下形式: + +``` +knn +├── main.py +└── wine.data +``` ## 实验步骤 @@ -74,46 +104,49 @@ from mindspore.ops import functional as F context.set_context(device_target="Ascend") ``` -读取Iris数据集`iris.data`,并查看部分数据。 +读取Wine数据集`wine.data`,并查看部分数据。 ```python -with open('iris.data') as csv_file: +with open('wine.data') as csv_file: data = list(csv.reader(csv_file, delimiter=',')) -print(data[40:60]) # 打印部分数据 +print(data[56:62]+data[130:133]) # 打印部分数据 ``` - [['5.0', '3.5', '1.3', '0.3', 'Iris-setosa'], ['4.5', '2.3', '1.3', '0.3', 'Iris-setosa'], ['4.4', '3.2', '1.3', '0.2', 'Iris-setosa'], ['5.0', '3.5', '1.6', '0.6', 'Iris-setosa'], ['5.1', '3.8', '1.9', '0.4', 'Iris-setosa'], ['4.8', '3.0', '1.4', '0.3', 'Iris-setosa'], ['5.1', '3.8', '1.6', '0.2', 'Iris-setosa'], ['4.6', '3.2', '1.4', '0.2', 'Iris-setosa'], ['5.3', '3.7', '1.5', '0.2', 'Iris-setosa'], ['5.0', '3.3', '1.4', '0.2', 'Iris-setosa'], ['7.0', '3.2', '4.7', '1.4', 'Iris-versicolor'], ['6.4', '3.2', '4.5', '1.5', 'Iris-versicolor'], ['6.9', '3.1', '4.9', '1.5', 'Iris-versicolor'], ['5.5', '2.3', '4.0', '1.3', 'Iris-versicolor'], ['6.5', '2.8', '4.6', '1.5', 'Iris-versicolor'], ['5.7', '2.8', '4.5', '1.3', 'Iris-versicolor'], ['6.3', '3.3', '4.7', '1.6', 'Iris-versicolor'], ['4.9', '2.4', '3.3', '1.0', 'Iris-versicolor'], ['6.6', '2.9', '4.6', '1.3', 'Iris-versicolor'], ['5.2', '2.7', '3.9', '1.4', 'Iris-versicolor']] + [['1', '14.22', '1.7', '2.3', '16.3', '118', '3.2', '3', '.26', '2.03', '6.38', '.94', '3.31', '970'], ['1', '13.29', '1.97', '2.68', '16.8', '102', '3', '3.23', '.31', '1.66', '6', '1.07', '2.84', '1270'], ['1', '13.72', '1.43', '2.5', '16.7', '108', '3.4', '3.67', '.19', '2.04', '6.8', '.89', '2.87', '1285'], ['2', '12.37', '.94', '1.36', '10.6', '88', '1.98', '.57', '.28', '.42', '1.95', '1.05', '1.82', '520'], ['2', '12.33', '1.1', '2.28', '16', '101', '2.05', '1.09', '.63', '.41', '3.27', '1.25', '1.67', '680'], ['2', '12.64', '1.36', '2.02', '16.8', '100', '2.02', '1.41', '.53', '.62', '5.75', '.98', '1.59', '450'], ['3', '12.86', '1.35', '2.32', '18', '122', '1.51', '1.25', '.21', '.94', '4.1', '.76', '1.29', '630'], ['3', '12.88', '2.99', '2.4', '20', '104', '1.3', '1.22', '.24', '.83', '5.4', '.74', '1.42', '530'], ['3', '12.81', '2.31', '2.4', '24', '98', '1.15', '1.09', '.27', '.83', '5.7', '.66', '1.36', '560']] -取前两类样本(共100条),将数据集的4个属性作为自变量$X$。将数据集的2个类别映射为{0, 1},作为因变量$Y$。 +取三类样本(共178条),将数据集的13个属性作为自变量$X$。将数据集的3个类别作为因变量$Y$。 ```python -label_map = { - 'Iris-setosa': 0, - 'Iris-versicolor': 1, -} - -X = np.array([[float(x) for x in s[:-1]] for s in data[:100]], np.float32) -Y = np.array([label_map[s[-1]] for s in data[:100]], np.int32) +X = np.array([[float(x) for x in s[1:]] for s in data[:178]], np.float32) +Y = np.array([s[0] for s in data[:178]], np.int32) ``` -取样本的前两个属性进行2维可视化,可以看到在前两个属性上两类样本是线性可分的。 +取样本的某两个属性进行2维可视化,可以看到在某两个属性上样本的分布情况以及可分性。 ```python -from matplotlib import pyplot as plt -plt.scatter(X[:50, 0], X[:50, 1], label='Iris-setosa') -plt.scatter(X[50:, 0], X[50:, 1], label='Iris-versicolor') -plt.xlabel('sepal length') -plt.ylabel('sepal width') -plt.legend() +attrs = ['Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', + 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', + 'OD280/OD315 of diluted wines', 'Proline'] +plt.figure(figsize=(10, 8)) +for i in range(0, 4): + plt.subplot(2, 2, i+1) + a1, a2 = 2 * i, 2 * i + 1 + plt.scatter(X[:59, a1], X[:59, a2], label='1') + plt.scatter(X[59:130, a1], X[59:130, a2], label='2') + plt.scatter(X[130:, a1], X[130:, a2], label='3') + plt.xlabel(attrs[a1]) + plt.ylabel(attrs[a2]) + plt.legend() +plt.show() ``` -![png](images/setosa-versicolor.png) +![wine](images/wine.png) -将数据集按8:2划分为训练集(已知类别样本)和验证集(待验证样本): +将数据集按128:50划分为训练集(已知类别样本)和验证集(待验证样本): ```python -train_idx = np.random.choice(100, 80, replace=False) -test_idx = np.array(list(set(range(100)) - set(train_idx))) +train_idx = np.random.choice(178, 128, replace=False) +test_idx = np.array(list(set(range(178)) - set(train_idx))) X_train, Y_train = X[train_idx], Y[train_idx] X_test, Y_test = X[test_idx], Y[test_idx] ``` @@ -131,11 +164,11 @@ class KnnNet(nn.Cell): def construct(self, x, X_train): # Tile input x to match the number of samples in X_train - x_tile = self.tile(x, (80, 1)) + x_tile = self.tile(x, (128, 1)) square_diff = F.square(x_tile - X_train) square_dist = self.sum(square_diff, 1) dist = F.sqrt(square_dist) - # '-dist' means the bigger the value is, the nearer the samples are + # -dist mean the bigger the value is, the nearer the samples are values, indices = self.topk(-dist, self.k) return indices @@ -150,7 +183,7 @@ def knn(knn_net, x, X_train, Y_train): return cls ``` -在验证集上验证KNN算法的有效性,验证精度接近100%,说明KNN算法在该任务上十分有效。 +在验证集上验证KNN算法的有效性,取$k = 5$,验证精度接近80%,说明KNN算法在该3分类任务上有效,能根据酒的13种属性判断出酒的品种。 ```python acc = 0 @@ -158,31 +191,61 @@ knn_net = KnnNet(5) for x, y in zip(X_test, Y_test): pred = knn(knn_net, x, X_train, Y_train) acc += (pred == y) - print('sample: %s, label: %d, prediction: %s' % (x, y, pred)) + print('label: %d, prediction: %s' % (y, pred)) print('Validation accuracy is %f' % (acc/len(Y_test))) ``` - sample: [5.1 3.5 1.4 0.2], label: 0, prediction: 0 - sample: [4.6 3.4 1.4 0.3], label: 0, prediction: 0 - sample: [5.1 3.5 1.4 0.3], label: 0, prediction: 0 - sample: [5.4 3.4 1.7 0.2], label: 0, prediction: 0 - sample: [4.8 3.1 1.6 0.2], label: 0, prediction: 0 - sample: [5.5 4.2 1.4 0.2], label: 0, prediction: 0 - sample: [4.9 3.1 1.5 0.1], label: 0, prediction: 0 - sample: [5. 3.2 1.2 0.2], label: 0, prediction: 0 - sample: [5.5 3.5 1.3 0.2], label: 0, prediction: 0 - sample: [4.5 2.3 1.3 0.3], label: 0, prediction: 0 - sample: [5. 3.3 1.4 0.2], label: 0, prediction: 0 - sample: [7. 3.2 4.7 1.4], label: 1, prediction: 1 - sample: [6.3 3.3 4.7 1.6], label: 1, prediction: 1 - sample: [6.6 2.9 4.6 1.3], label: 1, prediction: 1 - sample: [5.2 2.7 3.9 1.4], label: 1, prediction: 1 - sample: [5.9 3. 4.2 1.5], label: 1, prediction: 1 - sample: [6. 2.2 4. 1. ], label: 1, prediction: 1 - sample: [5.5 2.4 3.8 1.1], label: 1, prediction: 1 - sample: [5.8 2.7 3.9 1.2], label: 1, prediction: 1 - sample: [6.3 2.3 4.4 1.3], label: 1, prediction: 1 - Validation accuracy is 1.000000 + label: 1, prediction: 1 + label: 3, prediction: 2 + label: 3, prediction: 3 + label: 1, prediction: 1 + label: 1, prediction: 1 + label: 1, prediction: 1 + label: 3, prediction: 3 + label: 1, prediction: 1 + label: 1, prediction: 1 + label: 3, prediction: 3 + label: 3, prediction: 3 + label: 3, prediction: 3 + label: 1, prediction: 1 + label: 1, prediction: 1 + label: 1, prediction: 3 + label: 1, prediction: 1 + label: 1, prediction: 1 + label: 3, prediction: 2 + label: 3, prediction: 1 + label: 1, prediction: 1 + label: 3, prediction: 2 + label: 1, prediction: 1 + label: 1, prediction: 1 + label: 3, prediction: 2 + label: 3, prediction: 3 + label: 3, prediction: 3 + label: 1, prediction: 1 + label: 1, prediction: 1 + label: 1, prediction: 1 + label: 1, prediction: 1 + label: 1, prediction: 1 + label: 2, prediction: 2 + label: 2, prediction: 2 + label: 2, prediction: 2 + label: 2, prediction: 2 + label: 2, prediction: 2 + label: 2, prediction: 3 + label: 2, prediction: 2 + label: 2, prediction: 3 + label: 2, prediction: 2 + label: 2, prediction: 3 + label: 2, prediction: 2 + label: 2, prediction: 2 + label: 2, prediction: 2 + label: 2, prediction: 3 + label: 2, prediction: 2 + label: 2, prediction: 2 + label: 2, prediction: 2 + label: 2, prediction: 2 + label: 2, prediction: 2 + Validation accuracy is 0.800000 ### 创建训练作业 @@ -191,10 +254,10 @@ print('Validation accuracy is %f' % (acc/len(Y_test))) 创建训练作业的参考配置: - 算法来源:常用框架->Ascend-Powered-Engine->MindSpore -- 代码目录:选择上述新建的OBS桶中的experiment目录 -- 启动文件:选择上述新建的OBS桶中的experiment目录下的`main.py` -- 数据来源:数据存储位置->选择上述新建的OBS桶中的experiment目录,本实验使用其中的iris.data -- 训练输出位置:选择上述新建的OBS桶中的experiment目录并在其中创建output目录 +- 代码目录:选择上述新建的OBS桶中的knn目录 +- 启动文件:选择上述新建的OBS桶中的knn目录下的`main.py` +- 数据来源:数据存储位置->选择上述新建的OBS桶中的knn目录,本实验使用其中的wine.data +- 训练输出位置:选择上述新建的OBS桶中的knn目录并在其中创建output目录 - 作业日志路径:同训练输出位置 - 规格:Ascend:1*Ascend 910 - 其他均为默认 @@ -218,10 +281,10 @@ args, unknown = parser.parse_known_args() MindSpore暂时没有提供直接访问OBS数据的接口,需要通过MoXing提供的API与OBS交互。将OBS中存储的数据拷贝至执行容器: ```python -import moxing as mox -mox.file.copy_parallel(src_url=os.path.join(args.data_url, 'iris.data'), dst_url='iris.data') +import moxing +moxing.file.copy_parallel(src_url=os.path.join(args.data_url, 'wine.data'), dst_url='wine.data') ``` ## 实验结论 -本实验使用MindSpore实现了KNN算法,用来解决分类问题。取Iris数据集上的2类样本,按8:2分为已知类别样本和待验证样本,结果发现KNN算法在该任务上十分有效。 +本实验使用MindSpore实现了KNN算法,用来解决3分类问题。取wine数据集上的3类样本,分为已知类别样本和待验证样本,从验证结果可以看出KNN算法在该任务上有效,能根据酒的13种属性判断出酒的品种。 diff --git a/knn/images/setosa-versicolor.png b/knn/images/setosa-versicolor.png deleted file mode 100644 index 092e8128523ede7eb377416f6b1c51cc0c45501b..0000000000000000000000000000000000000000 Binary files a/knn/images/setosa-versicolor.png and /dev/null differ diff --git a/knn/images/wine.png b/knn/images/wine.png new file mode 100644 index 0000000000000000000000000000000000000000..772880cba7782d92e0a58868a670e979bd9ea8af Binary files /dev/null and b/knn/images/wine.png differ diff --git a/knn/main.py b/knn/main.py index 2114f5f5bb8ccc8fc47c26decfa62394b5d176e1..60bb1c44b2bf2df0aab05d0e9d6d477f24808dd1 100644 --- a/knn/main.py +++ b/knn/main.py @@ -15,20 +15,15 @@ context.set_context(mode=context.GRAPH_MODE, device_target="Ascend") def create_dataset(): - with open('iris.data') as csv_file: + with open('wine.data') as csv_file: data = list(csv.reader(csv_file, delimiter=',')) - print(data[40:60]) # 打印部分数据 + print(data[56:62]+data[130:133]) # 打印部分数据 - label_map = { - 'Iris-setosa': 0, - 'Iris-versicolor': 1, - } + X = np.array([[float(x) for x in s[1:]] for s in data[:178]], np.float32) + Y = np.array([s[0] for s in data[:178]], np.int32) - X = np.array([[float(x) for x in s[:-1]] for s in data[:100]], np.float32) - Y = np.array([label_map[s[-1]] for s in data[:100]], np.int32) - - train_idx = np.random.choice(100, 80, replace=False) - test_idx = np.array(list(set(range(100)) - set(train_idx))) + train_idx = np.random.choice(178, 128, replace=False) + test_idx = np.array(list(set(range(178)) - set(train_idx))) X_train, Y_train = X[train_idx], Y[train_idx] X_test, Y_test = X[test_idx], Y[test_idx] @@ -45,7 +40,7 @@ class KnnNet(nn.Cell): def construct(self, x, X_train): # Tile input x to match the number of samples in X_train - x_tile = self.tile(x, (80, 1)) + x_tile = self.tile(x, (128, 1)) square_diff = F.square(x_tile - X_train) square_dist = self.sum(square_diff, 1) dist = F.sqrt(square_dist) @@ -70,15 +65,16 @@ def test_knn(X_train, Y_train, X_test, Y_test): for x, y in zip(X_test, Y_test): pred = knn(knn_net, x, X_train, Y_train) acc += (pred == y) - print('sample: %s, label: %d, prediction: %s' % (x, y, pred)) + print('label: %d, prediction: %s' % (y, pred)) print('Validation accuracy is %f' % (acc/len(Y_test))) + """ -# Code for PyNative mode +# Code for PyNative mode, P.TopK is not supported def knn(x, X_train, Y_train, k): x, X_train = ms.Tensor(x), ms.Tensor(X_train) # Tile input x to match the number of samples in X_train - x_tile = P.Tile()(x, (X_train.shape()[0], 1)) + x_tile = P.Tile()(x, (X_train.shape[0], 1)) square_diff = F.square(x_tile - X_train) square_dist = P.ReduceSum()(square_diff, axis=1) dist = F.sqrt(square_dist) @@ -98,13 +94,14 @@ def test_knn(X_train, Y_train, X_test, Y_test): print('Validation accuracy is %f' % (acc/len(Y_test))) """ + if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('--data_url', required=True, default=None, help='Location of data.') args, unknown = parser.parse_known_args() - import moxing as mox - mox.file.copy_parallel(src_url=os.path.join(args.data_url, 'iris.data'), dst_url='iris.data') + import moxing + moxing.file.copy_parallel(src_url=os.path.join(args.data_url, 'wine.data'), dst_url='wine.data') test_knn(*create_dataset()) diff --git a/linear_regression/README.md b/linear_regression/README.md index f98fca2b362052faa2100d4b13fef5c1a6bf001d..c341c5cb8bbc72cfb1000ddae3d27f12762e1ef2 100644 --- a/linear_regression/README.md +++ b/linear_regression/README.md @@ -24,7 +24,7 @@ ## 实验环境 -- MindSpore 0.2.0(MindSpore版本会定期更新,本指导也会定期刷新,与版本配套); +- MindSpore 0.5.0(MindSpore版本会定期更新,本指导也会定期刷新,与版本配套); - 华为云ModelArts:ModelArts是华为云提供的面向开发者的一站式AI开发平台,集成了昇腾AI处理器资源池,用户可以在该平台下体验MindSpore。ModelArts官网:https://www.huaweicloud.com/product/modelarts.html ## 实验准备 @@ -47,11 +47,16 @@ ### 脚本准备 -从[课程gitee仓库](https://gitee.com/mindspore/course)上下载本实验相关脚本。 +从[课程gitee仓库](https://gitee.com/mindspore/course)中下载本实验相关脚本。 ### 上传文件 -将脚本上传到OBS桶中。 +将脚本上传到OBS桶中,组织为如下形式: + +``` +linear_regression +└── main.py +``` ## 实验步骤 @@ -131,7 +136,7 @@ for epoch in range(20): wb = [x.default_input.asnumpy() for x in net.trainable_params()] w, b = np.squeeze(wb[0]), np.squeeze(wb[1]) print('The true linear function is y = -5 * x + 0.1') -# print('The trained linear model is y = {0} * x + {1}'.format(w, b)) +print('The trained linear model is y = {0} * x + {1}'.format(w, b)) for i in range(-10, 11, 5): print('x = {0}, predicted y = {1}'.format(i, net(ms.Tensor([[i]], ms.float32)))) @@ -164,10 +169,10 @@ plt.legend() 创建训练作业的参考配置: - 算法来源:常用框架->Ascend-Powered-Engine->MindSpore -- 代码目录:选择上述新建的OBS桶中的experiment目录 -- 启动文件:选择上述新建的OBS桶中的experiment目录下的`main.py` -- 数据来源:数据存储位置->选择上述新建的OBS桶中的experiment目录,本实验没有使用OBS中的数据 -- 训练输出位置:选择上述新建的OBS桶中的experiment目录并在其中创建output目录 +- 代码目录:选择上述新建的OBS桶中的linear_regression目录 +- 启动文件:选择上述新建的OBS桶中的linear_regression目录下的`main.py` +- 数据来源:数据存储位置->选择上述新建的OBS桶中的linear_regression目录,本实验实际上没有使用OBS中的数据 +- 训练输出位置:选择上述新建的OBS桶中的linear_regression目录并在其中创建output目录 - 作业日志路径:同训练输出位置 - 规格:Ascend:1*Ascend 910 - 其他均为默认 diff --git a/linear_regression/main.py b/linear_regression/main.py index 057e6570d783882c245994ac015993e77a54ae94..2e1d516e299d93b7318c6431f086df12915a13cf 100644 --- a/linear_regression/main.py +++ b/linear_regression/main.py @@ -26,8 +26,8 @@ for epoch in range(20): wb = [x.default_input.asnumpy() for x in net.trainable_params()] w, b = np.squeeze(wb[0]), np.squeeze(wb[1]) print('The true linear function is y = -5 * x + 0.1') -# uncomment it in MindSpore0.3.0 or later. -# print('The trained linear model is y = {0} * x + {1}'.format(w, b)) +# works in MindSpore0.3.0 or later. +print('The trained linear model is y = {0} * x + {1}'.format(w, b)) for i in range(-10, 11, 5): print('x = {0}, predicted y = {1}'.format(i, net(ms.Tensor([[i]], ms.float32)))) diff --git a/logistic_regression/README.md b/logistic_regression/README.md index 96bb24c29b2e63ccf027b083ae736e9ab50c7bc8..52c742e65f69f62b2a33a99094367d6bcba75834 100644 --- a/logistic_regression/README.md +++ b/logistic_regression/README.md @@ -24,7 +24,7 @@ ## 实验环境 -- MindSpore 0.2.0(MindSpore版本会定期更新,本指导也会定期刷新,与版本配套); +- MindSpore 0.5.0(MindSpore版本会定期更新,本指导也会定期刷新,与版本配套); - 华为云ModelArts:ModelArts是华为云提供的面向开发者的一站式AI开发平台,集成了昇腾AI处理器资源池,用户可以在该平台下体验MindSpore。ModelArts官网:https://www.huaweicloud.com/product/modelarts.html ## 实验准备 @@ -71,14 +71,14 @@ Iris数据集是模式识别最著名的数据集之一。数据集包含3类, ### 脚本准备 -从[课程gitee仓库](https://gitee.com/mindspore/course)上下载本实验相关脚本。 +从[课程gitee仓库](https://gitee.com/mindspore/course)中下载本实验相关脚本。 ### 上传文件 将脚本和数据集上传到OBS桶中,组织为如下形式: ``` -experiment +logistic_regression ├── main.py └── iris.data ``` @@ -105,7 +105,7 @@ from mindspore.ops import operations as P context.set_context(mode=context.GRAPH_MODE, device_target="Ascend") ``` -读取Iris数据集`iris.data`,并作检查。 +读取Iris数据集`iris.data`,并查看部分数据。 ```python with open('iris.data') as csv_file: @@ -216,11 +216,21 @@ model = ms.train.Model(net, loss, opt) model.train(5, ds_train, callbacks=[LossMonitor(per_print_times=ds_train.get_dataset_size())], dataset_sink_mode=False) ``` - epoch: 1 step: 2, loss is 0.62444687 - epoch: 2 step: 2, loss is 0.57417274 - epoch: 3 step: 2, loss is 0.5119211 - epoch: 4 step: 2, loss is 0.46839413 - epoch: 5 step: 2, loss is 0.44478357 + epoch: 1 step 2, loss is 0.6358570456504822 + Epoch time: 9946.221, per step time: 4973.111, avg loss: 0.666 + ************************************************************ + epoch: 2 step 2, loss is 0.5617856979370117 + Epoch time: 132.066, per step time: 66.033, avg loss: 0.595 + ************************************************************ + epoch: 3 step 2, loss is 0.5153790712356567 + Epoch time: 4.302, per step time: 2.151, avg loss: 0.540 + ************************************************************ + epoch: 4 step 2, loss is 0.5422952771186829 + Epoch time: 4.457, per step time: 2.229, avg loss: 0.512 + ************************************************************ + epoch: 5 step 2, loss is 0.42156651616096497 + Epoch time: 4.481, per step time: 2.241, avg loss: 0.439 + ************************************************************ 然后计算模型在测试集上精度,测试集上的精度达到了1.0左右,即逻辑回归模型学会了区分2类鸢尾花。 @@ -234,6 +244,24 @@ print('Test accuracy is', acc) Test accuracy is 1.0 +### 适配训练作业 + +创建训练作业时,运行参数会通过脚本传参的方式输入给脚本代码,脚本必须解析传参才能在代码中使用相应参数。如data_url对应数据存储路径(OBS路径),脚本对传参进行解析后赋值到`args`变量里,在后续代码里可以使用。 + +```python +import argparse +parser = argparse.ArgumentParser() +parser.add_argument('--data_url', required=True, default=None, help='Location of data.') +args, unknown = parser.parse_known_args() +``` + +MindSpore暂时没有提供直接访问OBS数据的接口,需要通过MoXing提供的API与OBS交互。将OBS中存储的数据拷贝至执行容器: + +```python +import moxing +moxing.file.copy_parallel(src_url=os.path.join(args.data_url, 'iris.data'), dst_url='iris.data') +``` + ### 创建训练作业 可以参考[使用常用框架训练模型](https://support.huaweicloud.com/engineers-modelarts/modelarts_23_0238.html)来创建并启动训练作业。 @@ -241,10 +269,10 @@ print('Test accuracy is', acc) 创建训练作业的参考配置: - 算法来源:常用框架->Ascend-Powered-Engine->MindSpore -- 代码目录:选择上述新建的OBS桶中的experiment目录 -- 启动文件:选择上述新建的OBS桶中的experiment目录下的`main.py` -- 数据来源:数据存储位置->选择上述新建的OBS桶中的experiment目录,本实验使用其中的iris.data -- 训练输出位置:选择上述新建的OBS桶中的experiment目录并在其中创建output目录 +- 代码目录:选择上述新建的OBS桶中的logistic_regression目录 +- 启动文件:选择上述新建的OBS桶中的logistic_regression目录下的`main.py` +- 数据来源:数据存储位置->选择上述新建的OBS桶中的logistic_regression目录,本实验使用其中的iris.data +- 训练输出位置:选择上述新建的OBS桶中的logistic_regression目录并在其中创建output目录 - 作业日志路径:同训练输出位置 - 规格:Ascend:1*Ascend 910 - 其他均为默认 @@ -256,22 +284,6 @@ print('Test accuracy is', acc) 3. 点击运行中的训练作业,在展开的窗口中可以查看作业配置信息,以及训练过程中的日志,日志会不断刷新,等训练作业完成后也可以下载日志到本地进行查看; 4. 参考上述代码梳理,在日志中找到对应的打印信息,检查实验是否成功。 -创建训练作业时,运行参数会通过脚本传参的方式输入给脚本代码,脚本必须解析传参才能在代码中使用相应参数。如data_url对应数据存储路径(OBS路径),脚本对传参进行解析后赋值到`args`变量里,在后续代码里可以使用。 - -```python -import argparse -parser = argparse.ArgumentParser() -parser.add_argument('--data_url', required=True, default=None, help='Location of data.') -args, unknown = parser.parse_known_args() -``` - -MindSpore暂时没有提供直接访问OBS数据的接口,需要通过MoXing提供的API与OBS交互。将OBS中存储的数据拷贝至执行容器: - -```python -import moxing as mox -mox.file.copy_parallel(src_url=os.path.join(args.data_url, 'iris.data'), dst_url='iris.data') -``` - ## 实验结论 本实验使用MindSpore实现了逻辑回归,用来解决2分类问题。在Iris数据集上进行训练后,所得的模型可以很好的表示每个样本类别y和属性x的关系。 diff --git a/logistic_regression/main.py b/logistic_regression/main.py index 81f14a39115fe1cbe841e2ba33f464980acfc977..12027ac773d494a6943539d244e0c4f4120a31b3 100644 --- a/logistic_regression/main.py +++ b/logistic_regression/main.py @@ -78,7 +78,7 @@ if __name__ == "__main__": parser.add_argument('--data_url', required=True, default=None, help='Location of data.') args, unknown = parser.parse_known_args() - import moxing as mox - mox.file.copy_parallel(src_url=os.path.join(args.data_url, 'iris.data'), dst_url='iris.data') + import moxing + moxing.file.copy_parallel(src_url=os.path.join(args.data_url, 'iris.data'), dst_url='iris.data') logistic_regression(*create_dataset()) diff --git a/softmax_regression/README.md b/softmax_regression/README.md index 51c734211c657431476e1905c62745e86d36edd1..36b48ffd7703c347f20efc26ee25ff864d91f49b 100644 --- a/softmax_regression/README.md +++ b/softmax_regression/README.md @@ -22,7 +22,7 @@ Logistic函数针对的是二分类问题,而Softmax解决的是多分类问 ## 实验环境 -- MindSpore 0.2.0(MindSpore版本会定期更新,本指导也会定期刷新,与版本配套); +- MindSpore 0.5.0(MindSpore版本会定期更新,本指导也会定期刷新,与版本配套); - 华为云ModelArts:ModelArts是华为云提供的面向开发者的一站式AI开发平台,集成了昇腾AI处理器资源池,用户可以在该平台下体验MindSpore。ModelArts官网:https://www.huaweicloud.com/product/modelarts.html ## 实验准备 @@ -69,14 +69,14 @@ Iris数据集是模式识别最著名的数据集之一。数据集包含3类, ### 脚本准备 -从[课程gitee仓库](https://gitee.com/mindspore/course)上下载本实验相关脚本。 +从[课程gitee仓库](https://gitee.com/mindspore/course)中下载本实验相关脚本。 ### 上传文件 将脚本和数据集上传到OBS桶中,组织为如下形式: ``` -experiment +softmax_regression ├── main.py └── iris.data ``` @@ -190,32 +190,62 @@ metrics = model.eval(ds_test) print(metrics) ``` - epoch: 1 step: 3, loss is 1.0499132 - epoch: 2 step: 3, loss is 0.80460316 - epoch: 3 step: 3, loss is 0.59671795 - epoch: 4 step: 3, loss is 0.42732072 - epoch: 5 step: 3, loss is 0.4477523 - epoch: 6 step: 3, loss is 0.41942167 - epoch: 7 step: 3, loss is 0.3937024 - epoch: 8 step: 3, loss is 0.38259077 - epoch: 9 step: 3, loss is 0.3015437 - epoch: 10 step: 3, loss is 0.39157566 - epoch: 11 step: 3, loss is 0.25795114 - epoch: 12 step: 3, loss is 0.25916606 - epoch: 13 step: 3, loss is 0.24023157 - epoch: 14 step: 3, loss is 0.26471105 - epoch: 15 step: 3, loss is 0.27128816 - epoch: 16 step: 3, loss is 0.20776722 - epoch: 17 step: 3, loss is 0.13790263 - epoch: 18 step: 3, loss is 0.23461342 - epoch: 19 step: 3, loss is 0.19309351 - epoch: 20 step: 3, loss is 0.21184918 - epoch: 21 step: 3, loss is 0.2028614 - epoch: 22 step: 3, loss is 0.22474629 - epoch: 23 step: 3, loss is 0.25131774 - epoch: 24 step: 3, loss is 0.18746883 - epoch: 25 step: 3, loss is 0.18296722 - {'loss': 0.17929109930992126, 'acc': 0.9666666666666667} + epoch: 1 step 3, loss is 0.9914441108703613 + Epoch time: 15227.800, per step time: 5075.933, avg loss: 1.053 + ************************************************************ + epoch: 2 step 3, loss is 0.7714572548866272 + Epoch time: 8.709, per step time: 2.903, avg loss: 0.872 + ************************************************************ + epoch: 3 step 3, loss is 0.6451367735862732 + Epoch time: 6.033, per step time: 2.011, avg loss: 0.761 + ************************************************************ + epoch: 4 step 3, loss is 0.626476526260376 + Epoch time: 5.793, per step time: 1.931, avg loss: 0.578 + ************************************************************ + epoch: 5 step 3, loss is 0.530356764793396 + Epoch time: 5.858, per step time: 1.953, avg loss: 0.475 + ************************************************************ + + ...... + + epoch: 20 step 3, loss is 0.17989404499530792 + Epoch time: 5.808, per step time: 1.936, avg loss: 0.267 + ************************************************************ + epoch: 21 step 3, loss is 0.126459002494812 + Epoch time: 5.734, per step time: 1.911, avg loss: 0.229 + ************************************************************ + epoch: 22 step 3, loss is 0.15500077605247498 + Epoch time: 5.763, per step time: 1.921, avg loss: 0.194 + ************************************************************ + epoch: 23 step 3, loss is 0.1676429957151413 + Epoch time: 5.737, per step time: 1.912, avg loss: 0.178 + ************************************************************ + epoch: 24 step 3, loss is 0.23107928037643433 + Epoch time: 5.881, per step time: 1.960, avg loss: 0.165 + ************************************************************ + epoch: 25 step 3, loss is 0.19285285472869873 + Epoch time: 5.709, per step time: 1.903, avg loss: 0.156 + ************************************************************ + + {'acc': 0.9333333333333333, 'loss': 0.23569035530090332} + +### 适配训练作业 + +创建训练作业时,运行参数会通过脚本传参的方式输入给脚本代码,脚本必须解析传参才能在代码中使用相应参数。如data_url对应数据存储路径(OBS路径),脚本对传参进行解析后赋值到`args`变量里,在后续代码里可以使用。 + +```python +import argparse +parser = argparse.ArgumentParser() +parser.add_argument('--data_url', required=True, default=None, help='Location of data.') +args, unknown = parser.parse_known_args() +``` + +MindSpore暂时没有提供直接访问OBS数据的接口,需要通过MoXing提供的API与OBS交互。将OBS中存储的数据拷贝至执行容器: + +```python +import moxing +moxing.file.copy_parallel(src_url=os.path.join(args.data_url, 'iris.data'), dst_url='iris.data') +``` ### 创建训练作业 @@ -224,10 +254,10 @@ print(metrics) 创建训练作业的参考配置: - 算法来源:常用框架->Ascend-Powered-Engine->MindSpore -- 代码目录:选择上述新建的OBS桶中的experiment目录 -- 启动文件:选择上述新建的OBS桶中的experiment目录下的`main.py` -- 数据来源:数据存储位置->选择上述新建的OBS桶中的experiment目录,本实验使用其中的iris.data -- 训练输出位置:选择上述新建的OBS桶中的experiment目录并在其中创建output目录 +- 代码目录:选择上述新建的OBS桶中的softmax_regression目录 +- 启动文件:选择上述新建的OBS桶中的softmax_regression目录下的`main.py` +- 数据来源:数据存储位置->选择上述新建的OBS桶中的softmax_regression目录,本实验使用其中的iris.data +- 训练输出位置:选择上述新建的OBS桶中的softmax_regression目录并在其中创建output目录 - 作业日志路径:同训练输出位置 - 规格:Ascend:1*Ascend 910 - 其他均为默认 @@ -239,22 +269,6 @@ print(metrics) 3. 点击运行中的训练作业,在展开的窗口中可以查看作业配置信息,以及训练过程中的日志,日志会不断刷新,等训练作业完成后也可以下载日志到本地进行查看; 4. 参考上述代码梳理,在日志中找到对应的打印信息,检查实验是否成功。 -创建训练作业时,运行参数会通过脚本传参的方式输入给脚本代码,脚本必须解析传参才能在代码中使用相应参数。如data_url对应数据存储路径(OBS路径),脚本对传参进行解析后赋值到`args`变量里,在后续代码里可以使用。 - -```python -import argparse -parser = argparse.ArgumentParser() -parser.add_argument('--data_url', required=True, default=None, help='Location of data.') -args, unknown = parser.parse_known_args() -``` - -MindSpore暂时没有提供直接访问OBS数据的接口,需要通过MoXing提供的API与OBS交互。将OBS中存储的数据拷贝至执行容器: - -```python -import moxing as mox -mox.file.copy_parallel(src_url=os.path.join(args.data_url, 'iris.data'), dst_url='iris.data') -``` - ## 实验结论 本实验使用MindSpore实现了Softmax + CrossEntropy的多分类模型,用来解决3分类问题。在Iris数据集上进行训练后,所得的模型可以很好地对三类鸢尾花植物进行分类。 diff --git a/softmax_regression/main.py b/softmax_regression/main.py index 73ffda3fae4a8cb3cf10ae387094b1035464f4c4..08fb0b19405bdc478e609bab33c134a6f602dfb6 100644 --- a/softmax_regression/main.py +++ b/softmax_regression/main.py @@ -64,7 +64,7 @@ if __name__ == "__main__": parser.add_argument('--data_url', required=True, default=None, help='Location of data.') args, unknown = parser.parse_known_args() - import moxing as mox - mox.file.copy_parallel(src_url=os.path.join(args.data_url, 'iris.data'), dst_url='iris.data') + import moxing + moxing.file.copy_parallel(src_url=os.path.join(args.data_url, 'iris.data'), dst_url='iris.data') softmax_regression(*create_dataset())