8 examples of 'one hot encoding pandas' in Python

Every line of 'one hot encoding pandas' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
26def one_hot_encode(X, K):
27 # input is N x D
28 # output is N x D x K
29 N, D = X.shape
30 Y = np.zeros((N, D, K))
31 for n, d in zip(*X.nonzero()):
32 # 0.5...5 --> 1..10 --> 0..9
33 k = int(X[n,d]*2 - 1)
34 Y[n,d,k] = 1
35 return Y
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

29def one_hot_encoder(a):
30 length = len(a)
31 b = np.zeros( (length, 10) )
32 b[np.arange(length), a] = 1
33 return b
26def onehot(self,arr):
27 n, w, h = arr.shape
28 arr = arr.reshape(n, -1)
29 arr = self.onehotencoder.fit_transform(arr)
30 arr = arr.reshape(n, w, h, self.k)
31 arr = arr.transpose(0, 3, 1, 2)
32 return arr
29def to_onehot(seq):
30 x = np.zeros((seq.shape[0], 4), dtype=np.float32)
31 alphabet = ["A", "C", "G", "T"]
32 for i in range(len(alphabet)):
33 sel = np.where(seq == alphabet[i])
34 x[sel[0], i] = 1
35 return x
15def encode_one_hot(s):
16 all = []
17 for c in s:
18 if c not in characters:
19 continue
20 x = np.zeros((INPUT_VOCAB_SIZE))
21 index = char_indices[c]
22 x[index] = 1
23 all.append(x)
24 return all
4def one_hot_encode_y(y, n_classes=135):
5 y = np.asarray(y)
6 if n_classes == 1:
7 return reshape_add_axis(y, len(y.shape)-1)
8 else:
9 from keras.utils import to_categorical
10 shape = y.shape
11 y = to_categorical(y, num_classes=n_classes).astype(np.uint8)
12 y = y.reshape(shape + (n_classes,))
13 return y
21def one_hot(*,
22 index: Union[None, int, Sequence[int]] = None,
23 shape: Union[int, Sequence[int]],
24 value: Any = 1,
25 dtype: Type[np.number]) -> np.ndarray:
26 """Returns a numpy array with all 0s and a single non-zero entry(default 1).
27
28 Args:
29 index: The index that should store the `value` argument instead of 0.
30 If not specified, defaults to the start of the array.
31 shape: The shape of the array.
32 value: The hot value to place at `index` in the result.
33 dtype: The dtype of the array.
34
35 Returns:
36 The created numpy array.
37 """
38 if index is None:
39 index = 0 if isinstance(shape, int) else (0,) * len(shape)
40 result = np.zeros(shape=shape, dtype=dtype)
41 result[index] = value
42 return result
22def decode_one_hot(x):
23 s = []
24 for onehot in x:
25 one_index = np.argmax(onehot)
26 s.append(indices_char[one_index])
27 return ''.join(s)

Related snippets