python - python中的简单感知器模型
问题描述
我在运行 fit 函数时遇到这种类型的错误。许多人说它在 python 2.7 中运行。我想知道如何在 python 3 中完成它。还有其他方法可以做到吗?
class Perceptron:
def __init__(self):
self.w=None
self.b=None
def model(self,x):
return 1 if (np.dot(self.w,x)>=self.b) else 0
def predict(self,X):
Y=[]
for x in X:
result = self.model(x)
Y.append(result)
return np.array(Y)
def fit(self, X, Y, epochs = 1, lr=1):
self.w = np.ones(X.shape[1])
self.b = 0
accuracy = {}
max_accuracy = 0
wt_matrix = []
for i in range(epochs):
for x, y in zip(X,Y):
y_pred = self.model(x)
if y==1 and y_pred == 0:
self.w = self.w +lr* x
self.b = self.b + lr*1
elif y==0 and y_pred== 1:
self.w = self.w-lr*x
self.b = self.b-lr*1
wt_matrix.append(self.w)
accuracy[i] = accuracy_score(self.predict(X),Y)
if(accuracy[i]>max_accuracy):
max_accuracy = accuracy[i]
chkptw=self.w
chkptb=self.b
self.w =chkptw
self.b=chkptb
print(max_accuracy)
plt.plot(accuracy.values())
plt.ylim([0,1])
plt.show
return np.array(wt_matrix)
这是代码:
wt_matrix = perceptron.fit(X_train,Y_train,100)
当我调用该函数时,它显示了这种类型的错误
TypeError Traceback (most recent call last)
<ipython-input-76-8b850a516f0e> in <module>()
----> 1 wt_matrix = perceptron.fit(X_train,Y_train,100)
8 frames
/usr/local/lib/python3.6/dist-packages/numpy/core/_asarray.py in asarray(a, dtype, order)
83
84 """
---> 85 return array(a, dtype, copy=False, order=order)
86
87
TypeError: float() argument must be a string or a number, not 'dict_values'
解决方案
这是一个简单的类型转换问题。改变
plt.plot(accuracy.values())
至
plt.plot(list(accuracy.values()))
推荐阅读
- chart.js - ChartJS 轴刻度回调函数中的条件不返回预期的标签
- android - 如何访问 DJI 移动端 UX SDK FPVWidget?
- python - 在 Matplotlib 中为文本添加没有轴刻度/标签的空子图作为子图
- ruby-on-rails - 如何迭代以查找表中是否存在任何记录
- three.js - 渲染时的 THREE.js 对角线。showdow.bias 有帮助,但“castShadow”没有帮助
- c - 使用正确的地址和数据为 C 创建一个堆栈图
- react-native - 使用 React Native 打开位置
- reactjs - 带有 Material UI 的 React Router 不会渲染组件
- flutter - Flutter:我希望我的屏幕在选择 Textfield 时自动向上滚动,这样我的提交按钮就不会被隐藏?
- swift - 即使在添加 indexOn 之后,Firebase 安全规则也会继续询问“考虑添加“.indexOn”:”