有什么方法可以将Single array转换为一种热编码?

时间:2020-07-17 07:00:59

标签: python-3.x machine-learning scikit-learn one-hot-encoding

我已经将输入字符串转换为数组,但是现在我希望此数组以一种热编码方式在模型中运行。

  from sklearn.preprocessing import OneHotEncoder
  Smi = input("Enter Smile")
  inn = [Smi]
  details = np.array(inn)
  details = details.reshape(1,-1)
  encoder = OneHotEncoder(handle_unknown='ignore')
  encoder.fit(X)
  me = encoder.transform(details).toarray()
  me

  ValueError: Expected 2D array, got 1D array instead:
  

我也正在分享我的Google colab,以便更好地理解。

Code done on google colab

1 个答案:

答案 0 :(得分:0)

尝试如下操作:

# Let fit an enocode first
X = np.array([":)",":(",":!",":}",":|"]).reshape(-1,1)
print (X)

encoder = OneHotEncoder(handle_unknown='ignore')
encoder.fit(X)

Smi = input("Enter Smile")
# Assuming that you typed :!
details = np.array([Smi]).reshape(1,-1)
print (encoder.transform(details).toarray())

输出:

[[':)']
 [':(']
 [':!']
 [':}']
 [':|']]
Enter Smile:!
[[1. 0. 0. 0. 0.]]
``