使用0~9生成10个随机数,并将之转换为one-hot编码代码
时间: 2023-06-04 16:06:52 浏览: 77
以下是使用Python语言实现的代码:
```python
import random
# 生成10个随机数
numbers = [random.randint(0, 9) for _ in range(10)]
# 将数字转换为one-hot编码
one_hot = []
for i in range(10):
one_hot.append([int(j==numbers[i]) for j in range(10)])
print(numbers)
print(one_hot)
```
输出结果如下:
```
[3, 7, 9, 4, 8, 1, 6, 0, 5, 7]
[[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]
```
其中,numbers是一个包含10个随机数的列表,one_hot是将这些数字转换为one-hot编码的列表。每个数字都被编码为一个长度为10的列表,其中除了对应数字位置为1,其余位置都为0。