[{"data":1,"prerenderedAt":400},["ShallowReactive",2],{"content-query-WLB5sARtTi":3},{"_path":4,"_dir":5,"_draft":6,"_partial":6,"_locale":7,"title":8,"description":9,"date":10,"cover":11,"type":12,"body":13,"_type":394,"_id":395,"_source":396,"_file":397,"_stem":398,"_extension":399},"/technology-blogs/en/1440","en",false,"","Support for macOS Added in MindSpore 1.6","More systems and hardware will be supported in future versions to provide better usability.","2022-04-01","https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2022/04/22/8be9f2913f3e484680e7a371934fa254.png","technology-blogs",{"type":14,"children":15,"toc":391},"root",[16,24,33,38,47,55,60,67,72,85,96,101,111,116,124,132,137,145,150,158,163,171,185,190,195,203,208,216,221,229,234,242,247,255,260,268,273,281,286,294,302,307,315,320,328,333,338,345,361,369,380],{"type":17,"tag":18,"props":19,"children":21},"element","h1",{"id":20},"support-for-macos-added-in-mindspore-16",[22],{"type":23,"value":8},"text",{"type":17,"tag":25,"props":26,"children":27},"p",{},[28],{"type":17,"tag":29,"props":30,"children":32},"img",{"alt":7,"src":31},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2022/04/22/d37959d0b3cf4ae599b511c7456e07b4.gif",[],{"type":17,"tag":25,"props":34,"children":35},{},[36],{"type":23,"value":37},"MindSpore is an open source AI framework that facilitates easy development, efficient execution (training and inference), and device-edge-cloud deployments. As an open framework, it supports popular Linux distributions and Windows since v1.5.0, and macOS on x86 and M1 in v1.6.0. MindSpore equips you with the perfect tools for training and inference of typical networks such as LeNet, ResNet, CRNN, and TinyBERT on macOS.",{"type":17,"tag":25,"props":39,"children":40},{},[41],{"type":17,"tag":42,"props":43,"children":44},"strong",{},[45],{"type":23,"value":46},"How Do I Install MindSpore for macOS?",{"type":17,"tag":25,"props":48,"children":49},{},[50],{"type":17,"tag":42,"props":51,"children":52},{},[53],{"type":23,"value":54},"Pre-installation Check and Preparation",{"type":17,"tag":25,"props":56,"children":57},{},[58],{"type":23,"value":59},"The following table lists the software and hardware supported by MindSpore for macOS. Due to Python's limited support for Apple M1, Python 3.9.1 or later is required for macOS running on M1.",{"type":17,"tag":25,"props":61,"children":62},{},[63],{"type":17,"tag":29,"props":64,"children":66},{"alt":7,"src":65},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2022/04/22/e04f352a94b4445988c8e28571a83bcf.png",[],{"type":17,"tag":25,"props":68,"children":69},{},[70],{"type":23,"value":71},"By default, Python is installed on macOS. If you need to install a later version, download the installation package from either of the following links:",{"type":17,"tag":25,"props":73,"children":74},{},[75,77],{"type":23,"value":76},"Python 3.9.0: ",{"type":17,"tag":78,"props":79,"children":83},"a",{"href":80,"rel":81},"https://repo.huaweicloud.com/python/3.9.0/python-3.9.0-macosx10.9.pkg",[82],"nofollow",[84],{"type":23,"value":80},{"type":17,"tag":25,"props":86,"children":87},{},[88,90],{"type":23,"value":89},"Python 3.9.1 (for M1): ",{"type":17,"tag":78,"props":91,"children":94},{"href":92,"rel":93},"https://www.python.org/ftp/python/3.9.1/python-3.9.1-macos11.0.pkg",[82],[95],{"type":23,"value":92},{"type":17,"tag":25,"props":97,"children":98},{},[99],{"type":23,"value":100},"You can also use Conda to prepare the Python environment. You are advised to use MiniConda3 and run the following commands to install Python:",{"type":17,"tag":102,"props":103,"children":105},"pre",{"code":104},"conda create -n py39 -c conda-forge python=3.9.0\nconda activate py39\n",[106],{"type":17,"tag":107,"props":108,"children":109},"code",{"__ignoreMap":7},[110],{"type":23,"value":104},{"type":17,"tag":25,"props":112,"children":113},{},[114],{"type":23,"value":115},"Or",{"type":17,"tag":102,"props":117,"children":119},{"code":118},"conda create -n py391 -c conda-forge python=3.9.1\nconda activate py391\n",[120],{"type":17,"tag":107,"props":121,"children":122},{"__ignoreMap":7},[123],{"type":23,"value":118},{"type":17,"tag":25,"props":125,"children":126},{},[127],{"type":17,"tag":42,"props":128,"children":129},{},[130],{"type":23,"value":131},"Installing MindSpore",{"type":17,"tag":25,"props":133,"children":134},{},[135],{"type":23,"value":136},"Installing MindSpore using pip:",{"type":17,"tag":102,"props":138,"children":140},{"code":139},"pip install https://ms-release.obs.cn-north-4.myhuaweicloud.com/1.6.1/MindSpore/cpu/x86_64/mindspore-1.6.1-cp39-cp39-macosx_10_15_x86_64.whl --trusted-host ms-release.obs.cn-north-4.myhuaweicloud.com -i https://pypi.tuna.tsinghua.edu.cn/simple   # For x86 CPUs\npip install https://ms-release.obs.cn-north-4.myhuaweicloud.com/1.6.1/MindSpore/cpu/aarch64/mindspore-1.6.1-cp39-cp39-macosx_11_0_arm64.whl --trusted-host ms-release.obs.cn-north-4.myhuaweicloud.com -i https://pypi.tuna.tsinghua.edu.cn/simple   # For M1 CPUs\n",[141],{"type":17,"tag":107,"props":142,"children":143},{"__ignoreMap":7},[144],{"type":23,"value":139},{"type":17,"tag":25,"props":146,"children":147},{},[148],{"type":23,"value":149},"Installing MindSpore using Conda:",{"type":17,"tag":102,"props":151,"children":153},{"code":152},"conda install mindspore-cpu=1.6.1 -c mindspore -c conda-forge\n",[154],{"type":17,"tag":107,"props":155,"children":156},{"__ignoreMap":7},[157],{"type":23,"value":152},{"type":17,"tag":25,"props":159,"children":160},{},[161],{"type":23,"value":162},"After the commands are executed, run the python -c \"import mindspore;mindspore.run_check()\" command to check whether the installation is successful.",{"type":17,"tag":25,"props":164,"children":165},{},[166],{"type":17,"tag":42,"props":167,"children":168},{},[169],{"type":23,"value":170},"Running MindSpore on macOS",{"type":17,"tag":25,"props":172,"children":173},{},[174,176,183],{"type":23,"value":175},"You can further verify the MindSpore installation on macOS by performing a handwritten digit recognition task using a simple LeNet model. For details, see ",{"type":17,"tag":78,"props":177,"children":180},{"href":178,"rel":179},"https://www.mindspore.cn/tutorials/en/master/beginner/quick_start.html",[82],[181],{"type":23,"value":182},"MindSpore Tutorials",{"type":23,"value":184},".",{"type":17,"tag":25,"props":186,"children":187},{},[188],{"type":23,"value":189},"1. Download the MNIST dataset.",{"type":17,"tag":25,"props":191,"children":192},{},[193],{"type":23,"value":194},"Create a data.py file, enter the following content, and run the python data.py command:",{"type":17,"tag":102,"props":196,"children":198},{"code":197},"import os\nimport requests\n\nrequests.packages.urllib3.disable_warnings()\n\ndef download_dataset(dataset_url, path):\n    filename = dataset_url.split(\"/\")[-1]\n    save_path = os.path.join(path, filename)\n    if os.path.exists(save_path):\n        return\n    if not os.path.exists(path):\n        os.makedirs(path)\n    res = requests.get(dataset_url, stream=True, verify=False)\n    with open(save_path, \"wb\") as f:\n        for chunk in res.iter_content(chunk_size=512):\n            if chunk:\n                f.write(chunk)\n    print(\"The {} file is downloaded and saved in the path {} after processing\".format(os.path.basename(dataset_url), path))\n\ntrain_path = \"datasets/MNIST_Data/train\"\ntest_path = \"datasets/MNIST_Data/test\"\n\ndownload_dataset(\"https://mindspore-website.obs.myhuaweicloud.com/notebook/datasets/mnist/train-labels-idx1-ubyte\", train_path)\ndownload_dataset(\"https://mindspore-website.obs.myhuaweicloud.com/notebook/datasets/mnist/train-images-idx3-ubyte\", train_path)\ndownload_dataset(\"https://mindspore-website.obs.myhuaweicloud.com/notebook/datasets/mnist/t10k-labels-idx1-ubyte\", test_path)\ndownload_dataset(\"https://mindspore-website.obs.myhuaweicloud.com/notebook/datasets/mnist/t10k-images-idx3-ubyte\", test_path)\n",[199],{"type":17,"tag":107,"props":200,"children":201},{"__ignoreMap":7},[202],{"type":23,"value":197},{"type":17,"tag":25,"props":204,"children":205},{},[206],{"type":23,"value":207},"data.py will download the MINIST dataset and organize it into the following directory structure:",{"type":17,"tag":102,"props":209,"children":211},{"code":210},"./datasets/MNIST_Data\n├── test\n│   ├── t10k-images-idx3-ubyte\n│   └── t10k-labels-idx1-ubyte\n└── train\n    ├── train-images-idx3-ubyte\n    └── train-labels-idx1-ubyte\n",[212],{"type":17,"tag":107,"props":213,"children":214},{"__ignoreMap":7},[215],{"type":23,"value":210},{"type":17,"tag":25,"props":217,"children":218},{},[219],{"type":23,"value":220},"2. Create train.py to process the data using the dataset module of MindSpore.",{"type":17,"tag":102,"props":222,"children":224},{"code":223},"import mindspore.dataset as ds\nimport mindspore.dataset.transforms.c_transforms as C\nimport mindspore.dataset.vision.c_transforms as CV\nfrom mindspore.dataset.vision import Inter\nfrom mindspore import dtype as mstype\n\ndef create_dataset(data_path, batch_size=32, repeat_size=1,\n                   num_parallel_workers=1):\n    # Define the dataset.\n    mnist_ds = ds.MnistDataset(data_path)\n    resize_height, resize_width = 32, 32\n    rescale = 1.0 / 255.0\n    shift = 0.0\n    rescale_nml = 1 / 0.3081\n    shift_nml = -1 * 0.1307 / 0.3081\n\n    # Define the mapping operations.\n    resize_op = CV.Resize((resize_height, resize_width), interpolation=Inter.LINEAR)\n    rescale_nml_op = CV.Rescale(rescale_nml, shift_nml)\n    rescale_op = CV.Rescale(rescale, shift)\n    hwc2chw_op = CV.HWC2CHW()\n    type_cast_op = C.TypeCast(mstype.int32)\n\n    # Use the map function to apply data operations to the dataset.\n    mnist_ds = mnist_ds.map(operations=type_cast_op, input_columns=\"label\", num_parallel_workers=num_parallel_workers)\n    mnist_ds = mnist_ds.map(operations=[resize_op, rescale_op, rescale_nml_op, hwc2chw_op], input_columns=\"image\", num_parallel_workers=num_parallel_workers)\n\n    # Perform shuffle, batch, and repeat operations.\n    buffer_size = 10000\n    mnist_ds = mnist_ds.shuffle(buffer_size=buffer_size)\n    mnist_ds = mnist_ds.batch(batch_size, drop_remainder=True)\n    mnist_ds = mnist_ds.repeat(count=repeat_size)\n\n    return mnist_ds\n",[225],{"type":17,"tag":107,"props":226,"children":227},{"__ignoreMap":7},[228],{"type":23,"value":223},{"type":17,"tag":25,"props":230,"children":231},{},[232],{"type":23,"value":233},"3. Add the following code to lenet.py to define the network using nn.Cell of MindSpore:",{"type":17,"tag":102,"props":235,"children":237},{"code":236},"import mindspore.nn as nn\nfrom mindspore.common.initializer import Normal\n\nclass LeNet5(nn.Cell):\n    \"\"\"\n    LeNet network structure\n    \"\"\"\n    def __init__(self, num_class=10, num_channel=1):\n        super(LeNet5, self).__init__()\n        # Define the required operations.\n        self.conv1 = nn.Conv2d(num_channel, 6, 5, pad_mode='valid')\n        self.conv2 = nn.Conv2d(6, 16, 5, pad_mode='valid')\n        self.fc1 = nn.Dense(16 * 5 * 5, 120, weight_init=Normal(0.02))\n        self.fc2 = nn.Dense(120, 84, weight_init=Normal(0.02))\n        self.fc3 = nn.Dense(84, num_class, weight_init=Normal(0.02))\n        self.relu = nn.ReLU()\n        self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)\n        self.flatten = nn.Flatten()\n\n    def construct(self, x):\n        # Use the defined operations to build a forward network.\n        x = self.conv1(x)\n        x = self.relu(x)\n        x = self.max_pool2d(x)\n        x = self.conv2(x)\n        x = self.relu(x)\n        x = self.max_pool2d(x)\n        x = self.flatten(x)\n        x = self.fc1(x)\n        x = self.relu(x)\n        x = self.fc2(x)\n        x = self.relu(x)\n        x = self.fc3(x)\n        return x\n",[238],{"type":17,"tag":107,"props":239,"children":240},{"__ignoreMap":7},[241],{"type":23,"value":236},{"type":17,"tag":25,"props":243,"children":244},{},[245],{"type":23,"value":246},"4. Define and optimize the loss function.",{"type":17,"tag":102,"props":248,"children":250},{"code":249},"# Define the loss function.\nnet_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')\n\n# Define the optimizer.\nnet_opt = nn.Momentum(net.trainable_params(), learning_rate=0.01, momentum=0.9)\n",[251],{"type":17,"tag":107,"props":252,"children":253},{"__ignoreMap":7},[254],{"type":23,"value":249},{"type":17,"tag":25,"props":256,"children":257},{},[258],{"type":23,"value":259},"5. Add the following training code to train.py:",{"type":17,"tag":102,"props":261,"children":263},{"code":262},"import os\nfrom mindspore.train.callback import ModelCheckpoint, CheckpointConfig\n# Import libraries required for model training.\nfrom mindspore.nn import Accuracy\nfrom mindspore.train.callback import LossMonitor\nfrom mindspore import Model\nfrom lenet import Lenet5\n\ndef train_net(model, epoch_size, data_path, repeat_size, ckpoint_cb, sink_mode):\n    \"\"\" Define the training method.\"\"\"\n    # Load the training dataset.\n    ds_train = create_dataset(os.path.join(data_path, \"train\"), 32, repeat_size)\n    model.train(epoch_size, ds_train, callbacks=[ckpoint_cb, LossMonitor(125)], dataset_sink_mode=sink_mode)\n\n# Set the model saving parameters.\nconfig_ck = CheckpointConfig(save_checkpoint_steps=1875, keep_checkpoint_max=10)\n# Apply the model saving parameters.\nckpoint = ModelCheckpoint(prefix=\"checkpoint_lenet\", config=config_ck)\n\n# Set the training parameters to run only one epoch.\n\ntrain_epoch = 1\nmnist_path = \"./datasets/MNIST_Data\"\ndataset_size = 1\nmodel = Model(net, net_loss, net_opt, metrics={\"Accuracy\": Accuracy()})\ntrain_net(model, train_epoch, mnist_path, dataset_size, ckpoint, False)\ntest_net(model, mnist_path)\n",[264],{"type":17,"tag":107,"props":265,"children":266},{"__ignoreMap":7},[267],{"type":23,"value":262},{"type":17,"tag":25,"props":269,"children":270},{},[271],{"type":23,"value":272},"6. Run the python train.py command to start training. After 1875 steps are performed according to the model saving parameter, the loss function converges to approximately 0.05.",{"type":17,"tag":102,"props":274,"children":276},{"code":275},"python train.py\nepoch: 1 step: 125, loss is 2.2945752143859863\nepoch: 1 step: 250, loss is 2.2834312915802\nepoch: 1 step: 375, loss is 2.286731004714966\nepoch: 1 step: 500, loss is 2.2865426540374756\nepoch: 1 step: 625, loss is 2.1827993392944336\nepoch: 1 step: 750, loss is 0.6413211226463318\nepoch: 1 step: 875, loss is 0.3101319372653961\nepoch: 1 step: 1000, loss is 0.1193467304110527\nepoch: 1 step: 1125, loss is 0.09959482401609421\nepoch: 1 step: 1250, loss is 0.11662383377552032\nepoch: 1 step: 1375, loss is 0.13491152226924896\nepoch: 1 step: 1500, loss is 0.11873210221529007\nepoch: 1 step: 1625, loss is 0.019252609461545944\nepoch: 1 step: 1750, loss is 0.011969765648245811\nepoch: 1 step: 1875, loss is 0.0546155609190464\n",[277],{"type":17,"tag":107,"props":278,"children":279},{"__ignoreMap":7},[280],{"type":23,"value":275},{"type":17,"tag":25,"props":282,"children":283},{},[284],{"type":23,"value":285},"7. Evaluate the model accuracy. Add the following code to train.py:",{"type":17,"tag":102,"props":287,"children":289},{"code":288},"def test_net(model, data_path):\n    \"\"\" Define the evaluation method.\"\"\"\n    ds_eval = create_dataset(os.path.join(data_path, \"test\"))\n    acc = model.eval(ds_eval, dataset_sink_mode=False)\n    print(\"{}\".format(acc))\n\ntest_net(model, mnist_path)\nRun the python train.py command to view the model accuracy evaluation result.\n",[290],{"type":17,"tag":107,"props":291,"children":292},{"__ignoreMap":7},[293],{"type":23,"value":288},{"type":17,"tag":102,"props":295,"children":297},{"code":296},"{'Accuracy': 0.9663461538461539}\n",[298],{"type":17,"tag":107,"props":299,"children":300},{"__ignoreMap":7},[301],{"type":23,"value":296},{"type":17,"tag":25,"props":303,"children":304},{},[305],{"type":23,"value":306},"8. Test the model using the test dataset. Create test.py and enter the following content:",{"type":17,"tag":102,"props":308,"children":310},{"code":309},"import numpy as np\nimport os\nimport mindspore.dataset as ds\nimport mindspore.dataset.transforms.c_transforms as C\nimport mindspore.dataset.vision.c_transforms as CV\nfrom mindspore.dataset.vision import Inter\nfrom mindspore import dtype as mstype\nfrom mindspore import load_checkpoint, load_param_into_net\nfrom mindspore import Tensor\nfrom mindspore import Model\nfrom lenet import LeNet5\n\n\ndef create_dataset(data_path, batch_size=32, repeat_size=1,\n                   num_parallel_workers=1):\n    # Define the dataset.\n    mnist_ds = ds.MnistDataset(data_path)\n    resize_height, resize_width = 32, 32\n    rescale = 1.0 / 255.0\n    shift = 0.0\n    rescale_nml = 1 / 0.3081\n    shift_nml = -1 * 0.1307 / 0.3081\n\n    # Define the mapping operations.\n    resize_op = CV.Resize((resize_height, resize_width), interpolation=Inter.LINEAR)\n    rescale_nml_op = CV.Rescale(rescale_nml, shift_nml)\n    rescale_op = CV.Rescale(rescale, shift)\n    hwc2chw_op = CV.HWC2CHW()\n    type_cast_op = C.TypeCast(mstype.int32)\n\n    # Use the map function to apply data operations to the dataset.\n    mnist_ds = mnist_ds.map(operations=type_cast_op, input_columns=\"label\", num_parallel_workers=num_parallel_workers)\n    mnist_ds = mnist_ds.map(operations=[resize_op, rescale_op, rescale_nml_op, hwc2chw_op], input_columns=\"image\", num_parallel_workers=num_parallel_workers)\n\n    # Perform shuffle, batch, and repeat operations.\n    buffer_size = 10000\n    mnist_ds = mnist_ds.shuffle(buffer_size=buffer_size)\n    mnist_ds = mnist_ds.batch(batch_size, drop_remainder=True)\n    mnist_ds = mnist_ds.repeat(count=repeat_size)\n\n    return mnist_ds\n\n# Initialize the network instance.\nnet = LeNet5()\n# Load the saved model to be tested.\nparam_dict = load_checkpoint(\"checkpoint_lenet-1_1875.ckpt\")\n# Load parameters to the network.\nload_param_into_net(net, param_dict)\nmodel = Model(net)\n\nmnist_path = \"./datasets/MNIST_Data\"\n\n# Define the test data set. Set batch_size to 1 to obtain one image.\nds_test = create_dataset(os.path.join(mnist_path, \"test\"), batch_size=1).create_dict_iterator()\ndata = next(ds_test)\n\n# images is the test image, and labels is the actual classification of the test image.\nimages = data[\"image\"].asnumpy()\nlabels = data[\"label\"].asnumpy()\n\n# Use the model.predict function to predict the classification of the image.\noutput = model.predict(Tensor(data['image']))\npredicted = np.argmax(output.asnumpy(), axis=1)\n\n# Output the predicted classification and the actual classification.\nprint(f'Predicted: \"{predicted[0]}\", Actual: \"{labels[0]}\"')\n",[311],{"type":17,"tag":107,"props":312,"children":313},{"__ignoreMap":7},[314],{"type":23,"value":309},{"type":17,"tag":25,"props":316,"children":317},{},[318],{"type":23,"value":319},"Run python test.py. The command output is as follows:",{"type":17,"tag":102,"props":321,"children":323},{"code":322},"Predicted: \"8\", Actual: \"8\"\n",[324],{"type":17,"tag":107,"props":325,"children":326},{"__ignoreMap":7},[327],{"type":23,"value":322},{"type":17,"tag":25,"props":329,"children":330},{},[331],{"type":23,"value":332},"In the code, we selected an image marked as 8 from the test dataset. The prediction result of the model is also 8, which is the same as the actual label.",{"type":17,"tag":25,"props":334,"children":335},{},[336],{"type":23,"value":337},"Looking forward, more systems and hardware will be supported in future versions of MindSpore to provide better usability for developers. Stay tuned and feel free to give your feedback!",{"type":17,"tag":25,"props":339,"children":340},{},[341],{"type":17,"tag":29,"props":342,"children":344},{"alt":7,"src":343},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2022/04/22/c62fa0b21ab54228b448c44f9be194f7.png",[],{"type":17,"tag":25,"props":346,"children":347},{},[348,353,355],{"type":17,"tag":42,"props":349,"children":350},{},[351],{"type":23,"value":352},"MindSpore website",{"type":23,"value":354},": ",{"type":17,"tag":78,"props":356,"children":359},{"href":357,"rel":358},"https://www.mindspore.cn/en",[82],[360],{"type":23,"value":357},{"type":17,"tag":25,"props":362,"children":363},{},[364],{"type":17,"tag":42,"props":365,"children":366},{},[367],{"type":23,"value":368},"MindSpore Repositories",{"type":17,"tag":25,"props":370,"children":371},{},[372,374],{"type":23,"value":373},"Gitee: ",{"type":17,"tag":78,"props":375,"children":378},{"href":376,"rel":377},"https://gitee.com/mindspore/mindspore",[82],[379],{"type":23,"value":376},{"type":17,"tag":25,"props":381,"children":382},{},[383,385],{"type":23,"value":384},"GitHub: ",{"type":17,"tag":78,"props":386,"children":389},{"href":387,"rel":388},"https://github.com/mindspore-ai/mindspore",[82],[390],{"type":23,"value":387},{"title":7,"searchDepth":392,"depth":392,"links":393},4,[],"markdown","content:technology-blogs:en:1440.md","content","technology-blogs/en/1440.md","technology-blogs/en/1440","md",1776506102926]