擅长:python、mysql、java
<p>明白了。这将适用于任何数量的唯一值数组。你知道吗</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
target = np.array(['dog', 'dog', 'cat', 'cat', 'cat', 'dog', 'dog',
'cat', 'cat', 'hamster', 'hamster'])
def one_hot(array):
unique, inverse = np.unique(array, return_inverse=True)
onehot = np.eye(unique.shape[0])[inverse]
return onehot
print(one_hot(target))
</code></pre>
<blockquote>
<p>Out[9]: <br/>
[[0., 1., 0.], <br/>
[0., 1., 0.], <br/>
[1., 0., 0.], <br/>
[1., 0., 0.], <br/>
[1., 0., 0.], <br/>
[0., 1., 0.], <br/>
[0., 1., 0.], <br/>
[1., 0., 0.], <br/>
[1., 0., 0.], <br/>
[0., 0., 1.], <br/>
[0., 0., 1.]])</p>
</blockquote>