mindspore快速入门

mindspore快速入门

张量(Tensor)

概念

形状:张量每个轴的长度(元素数量)

秩:张量轴数(标量0,向量2,矩阵2)

轴:张量的一个特殊维度

大小:总项数

初始化

#直接创建张量
data = [1, 0, 1, 0]
x_data = Tensor(data)
print(data)
print(type(data))
print(x_data)
print(type(x_data))
#transforms data into tensor
print('-------------------------------')
#从Numpy数组中生成
np_array = np.array(data)
x_np = Tensor(np_array)
print(type(np_array))
print(type(x_np))

#使用init初始化器构造张量
from mindspore.common.initializer import One, Normal

# Initialize a tensor with ones
tensor1 = mindspore.Tensor(shape=(2, 2), dtype=mindspore.float32, init=One())
# Initialize a tensor from normal distribution
tensor2 = mindspore.Tensor(shape=(2, 2), dtype=mindspore.float32, init=Normal())

print("tensor1:\n", tensor1)
print("tensor2:\n", tensor2)

#输出结果
#<class 'numpy.ndarray'>
#<class 'mindspore.common.tensor.Tensor'>
#tensor1:
#[[1. 1.]
#[1. 1.]]
#tensor2:
 #[[-0.00575006 -0.00057997]
 #[-0.00012976  0.00756478]]

 #构造

from mindspore.common.initializer import One, Normal

# Initialize a tensor with ones
tensor1 = mindspore.Tensor(shape=(2, 2), dtype=mindspore.float32, init=One())
# Initialize a tensor from normal distribution
tensor2 = mindspore.Tensor(shape=(2, 2), dtype=mindspore.float32, init=Normal())

print("tensor1:\n", tensor1)
print("tensor2:\n", tensor2)

#结果
#tensor1:
# [[1. 1.]
# [1. 1.]]
#tensor2:
# [[ 0.00721691  0.02522347]
# [-0.01034305  0.01017608]]

属性

  • 形状(shape):Tensor的shape,是一个tuple。
  • 数据类型(dtype):Tensor的dtype,是MindSpore的一个数据类型。
  • 单个元素大小(itemsize): Tensor中每一个元素占用字节数,是一个整数。
  • 占用字节数量(nbytes): Tensor占用的总字节数,是一个整数。
  • 维数(ndim): Tensor的秩,也就是len(tensor.shape),是一个整数。
  • 元素个数(size): Tensor中所有元素的个数,是一个整数。
  • 每一维步长(strides): Tensor每一维所需要的字节数,是一个tuple。

索引

tensor = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))

print("First row: {}".format(tensor[0]))#第一列
print("value of bottom right corner: {}".format(tensor[1, 1]))#第二列第二个
#切片
print("Last column: {}".format(tensor[:, -1]))
print("First column: {}".format(tensor[..., 0]))

#结果
#First row: [0. 1.]
#value of bottom right corner: 3.0
#Last column: [1. 3.]
#First column: [0. 2.]

运算

#普通运算
x = Tensor(np.array([1, 2, 3]), mindspore.float32)
y = Tensor(np.array([4, 5, 6]), mindspore.float32)

output_add = x + y
output_sub = x - y
output_mul = x * y
output_div = y / x
output_mod = y % x
output_floordiv = y // x

print("add:", output_add)
print("sub:", output_sub)
print("mul:", output_mul)
print("div:", output_div)
print("mod:", output_mod)
print("floordiv:", output_floordiv)
#结果
#add: [5. 7. 9.]
#sub: [-3. -3. -3.]
#mul: [ 4. 10. 18.]
#div: [4.  2.5 2. ]
#mod: [0. 1. 0.]
#floordiv: [4. 2. 2.]

#张量的链接

data1 = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))
data2 = Tensor(np.array([[4, 5], [6, 7]]).astype(np.float32))
output = ops.concat((data1, data2), axis=0)

print(output)
print("shape:\n", output.shape)

#结果
#[[0. 1.]
# [2. 3.]
# [4. 5.]
# [6. 7.]]
#shape:
# (4, 2)

数据处理

流程:Load–Transform–Train

load

加载到内存空间

from mindvision.dataset import Mnist
# 设置下载根目录
dataset_dir = "./Mnist"
# 设置数据集
dataset = Mnist(path=dataset_dir, split="train", batch_size=32, repeat_num=1, shuffle=True, resize=32, download=True)
# 加载数据集
dataset = dataset.run()
迭代数据集
#迭代数据集
data = next(dataset.create_dict_iterator())
print(f"Data type:{type(data['image'])}\nImage shape: {data['image'].shape}\nLabel: {data['label']}")
#Data type:<class 'mindspore.common.tensor.Tensor'>
#Image shape: (32, 1, 32, 32)//32*32,单通道,第一个32:每一批塞到数据集里的数量
#Label: [1 2 1 7 4 6 2 5 8 0 1 4 2 7 7 2 6 3 0 9 2 9 7 0 5 4 4 3 1 4 0 6]

#数据处理
dataset = Mnist(path=dataset_dir, split="train", batch_size=6, repeat_num=1, shuffle=True, resize=28)
#batch_size是每组包含的个数;repeat_num是重复次数;shuffle是是否打乱
dataset = dataset.run()
dataset = next(dataset.create_dict_iterator())

images = dataset["image"].asnumpy()
print('Image shape: ', images.shape)

# 打印出数据看看
images = data["image"].asnumpy()
labels = data["label"].asnumpy()
plt.figure()
for i in range(1, 7):
    plt.subplot(2, 3, i)
    plt.imshow(images[i-1][0], interpolation="None", cmap="gray")
plt.show()
增强数据

# 定义图像增强操作
trans = [
    vision.RandomCrop((32, 32), (4, 4, 4, 4)),#自动裁剪,参数为图像的输出尺寸大小,填充图像的左侧、上侧、右侧和下侧的像素值
    vision.RandomHorizontalFlip(prob=0.7),# 对图像进行随机水平翻转,prob为概率
    vision.HWC2CHW()# (h, w, c)转换为(c, h, w)
]

# 在数据处理参数中添加transform(
dataset = Mnist(path=dataset_dir, batch_size=6, repeat_num=1, shuffle=True, resize=32, transform=trans)
dataset = dataset.run()
data = next(dataset.create_dict_iterator())

images = data['image'].asnumpy()
plt.figure()
for i in range(1, 7):
    plt.subplot(2, 3, i)
    plt.imshow(images[i-1][0], interpolation="None", cmap="gray")
plt.show()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值