python感知机:怎么解决这个报错呢?
`import pandas as pd
import numpy as np
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn import datasets
def data_pro(x, y):
x_end = preprocessing.scale(x) #特征标准化
y_end = np.array([1 if i == 1 else -1 for i in y]) #将标签中的0替换为-1
return x_end, y_end
def data_split(x,y):
x_train,x_test,y_train,y_test=train_test_split(x,y,train_size=0.8,random_state=1234)
return x_train,x_test,y_train,y_test
def perceptron_model(x_train, y_train):
w = np.zeros(30) #设置权重
b = 0 #设置偏置
lr = 0.1 #设置学习率
train_num = 1000000 #设置迭代次数
for d in range(train_num):
X = x_train[d]
y = y_train[d]
if y * (np.dot(w, X.T) + b) <= 0:
w = w + lr * np.dot(y, X)
b = b + lr * y
return w, b
def test(w, b, x_test, y_test):
m = np.shape(x_test)
auc = 0
for i in range(m):
classify = np.dot(x_test, w.T) + b
if classify > 0:
predict = 1
else:
predict = -1
if predict == y_test[i]:
auc += 1
print("正确率:%.2f%%"%(auc/m*100))
def main(x, y):
x_end, y_end = data_pro(x, y)
x_train, y_train, x_test, y_test = data_split(x_end, y_end)
w, b = perceptron_model(x_train, y_train)
test(w, b, x_test, y_test)
if __name__=='__main__':
breast_cancer_data = datasets.load_breast_cancer()
features = breast_cancer_data.data # 特征
targets = breast_cancer_data.target # 类别
print(main(features, targets))
`
if y * (np.dot(w, X.T) + b) <= 0这句总是会报错:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
想知道是为什么,该怎么解决呢?求好心人解答,谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查你的
y
和np.dot(w, X.T) + b
的 shape,你这两者之一不是 scalar,shape 不同。