微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 vscode 上复制粘贴朴素贝叶斯示例代码但出现错误

如何解决在 vscode 上复制粘贴朴素贝叶斯示例代码但出现错误

我从 datacamp 复制了代码,在 python 3.8 上自己尝试朴素贝叶斯分类。但是当运行代码时,编译器给出了这个错误

Traceback (most recent call last):
  File "c:\Users\USER\Desktop\DATA MINING\NaiveTest.py",line 34,in <module>
    model.fit(features,label)
  File "C:\Users\USER\AppData\Local\Programs\Python\python38-32\lib\site-packages\sklearn\naive_bayes.py",line 207,in fit
    X,y = self._validate_data(X,y)
  File "C:\Users\USER\AppData\Local\Programs\Python\python38-32\lib\site-packages\sklearn\base.py",line 433,in _validate_data
    X,y = check_X_y(X,y,**check_params)
  File "C:\Users\USER\AppData\Local\Programs\Python\python38-32\lib\site-packages\sklearn\utils\validation.py",line 63,in inner_f
    return f(*args,**kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\python38-32\lib\site-packages\sklearn\utils\validation.py",line 814,in check_X_y
    X = check_array(X,accept_sparse=accept_sparse,File "C:\Users\USER\AppData\Local\Programs\Python\python38-32\lib\site-packages\sklearn\utils\validation.py",line 630,in check_array
    raise ValueError(
ValueError: Expected 2D array,got scalar array instead:
array=<zip object at 0x0F2C4C28>.
Reshape your data either using array.reshape(-1,1) if your data has a single feature or array.reshape(1,-1) if it contains a single sample.

我发布了整个代码,因为我不确定是哪个部分导致了这个问题,所以我请求帮助解决这个问题。

# Assigning features and label variables
weather=['Sunny','Sunny','Overcast','Rainy','Rainy']
temp=['Hot','Hot','Mild','Cool','Mild']
play=['No','No','Yes','No']

# Import LabelEncoder
from sklearn import preprocessing
#creating labelEncoder
le = preprocessing.LabelEncoder()

# Converting string labels into numbers.
weather_encoded=le.fit_transform(weather)
print (weather_encoded)
temp_encoded=le.fit_transform(temp)
label=le.fit_transform(play)
print ("Temp:",temp_encoded)
print ("Play:",label)


#Combinig weather and temp into single listof tuples
features=zip(weather_encoded,temp_encoded)
print(list(zip(weather_encoded,temp_encoded)))
print([i for i in zip(weather_encoded,temp_encoded)])


from sklearn.naive_bayes import GaussianNB
#Create a Gaussian Classifier
model = GaussianNB()
# Train the model using the training sets
model.fit(features,label)
#Predict Output
predicted= model.predict([[0,2]]) # 0:Overcast,2:Mild
print ("Predicted Value:",predicted)

据说结果是这样的Predicted Value: [1] 但它却给了这个错误

解决方法

发生的情况是,features 应该是一个要传递给 model.fit 的列表,目前它们是 zip 类型

#Combinig weather and temp into single listof tuples
features=zip(weather_encoded,temp_encoded)

您可能需要将特征转换为列表,例如

#Combinig weather and temp into single listof tuples
features=list(zip(weather_encoded,temp_encoded))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。