python3中的zip函数
python2中(
python3中(https://docs.python.org/3.3/library/functions.html#zip)
背景:
这篇博客时,把文章中的python2语法改成python3时遇到了一个让我感觉到有些意外的情况;
先放一下对应python3下的代码:
from functools import reduce from itertools import tee class Perceptron: def __init__(self,input_num,activator): self.activator = activator self.weights = [0.0 for _ in range(input_num)] self.bias = 0.0 def __str__(self): return 'weights\t:%s\nbias\t:%f\n' % (self.weights, self.bias) def predict(self, input_vec): return self.activator(\ reduce(lambda a,b:a+b,\ map(lambda x_w:x_w[0]*x_w[1], \ zip(input_vec,self.weights)) \ ,0.0)+self.bias) def _update_weight(self,input_vec,output,label,rate): delta = label - output self.weights = list(map( lambda x_w:x_w[1]+rate*delta*x_w[0], zip(input_vec,self.weights))) self.bias += rate * delta def _one_iteration(self,input_vecs,labels,rate): samples = zip(input_vecs,labels) #print(list(samples)) for(input_vec,label) in samples: output = self.predict(input_vec) self._update_weight(input_vec,output,label,rate) def train(self,input_vecs,labels,iteration,rate): for i in range(iteration): self._one_iteration(input_vecs,labels,rate) def and_f(x): return 1 if x>0 else 0 if __name__ == '__main__': x = [[0,0],[0,1],[1,0],[1,1]] y = [0,0,0,1] and_perception = Perceptron(2,and_f) and_perception.train(x,y,10,0.1) print(and_perception) print('1 and 1 = %d'%and_perception.predict([1,1])) print('0 and 0 = %d'%and_perception.predict([0,0])) print('1 and 0 = %d'%and_perception.predict([1,0])) print('0 and 1 = %d'%and_perception.predict([0,1]))
现象就是当我将注释的print(list(samples))打开时会影响到后续的结果,感觉就像list类型强转改变了samples一样;
查了查原来问题出现在zip上,python3的zip返回迭代器(从性能方面看这样也许确实更好吧);
当修改成
samples = list(zip(input_vecs,labels)) print(list(samples))
或者
samples = zip(input_vecs,labels) samples,second_it = tee(samples) print(list(samples)) samples = second_it
就好了;
同样可以注意到python3 map返回也是个迭代器;
参考:
https://stackoverflow.com/questions/8689184/nameerror-name-reduce-is-not-defined-in-python
https://stackoverflow.com/questions/40912089/python-map-on-zipped-object
https://stackoverflow.com/questions/50671360/map-in-python-3-vs-python-2
https://stackoverflow.com/questions/19777612/python-range-and-zip-object-type
https://stackoverflow.com/questions/42132731/how-to-create-a-copy-of-python-iterator
https://stackoverflow.com/questions/31683959/the-zip-function-in-python-3
https://blog.csdn.net/benpaodelulu_guajian/article/details/81869462
/*************************************************************************************************/
下面我们对上面的python感知机作一些可视化
from matplotlib import pyplot from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D import numpy as np if __name__ == '__main__': # 训练数据 x = np.array([[0,0,0],[1,1,1],[1,1,0],[1,0,1],[0,1,1]]) y = [1,0,0,0,0] and_perception = Perceptron(3,and_f) and_perception.train(x,y,10,0.1) print(and_perception) fig = pyplot.figure() pyplot.xlim(0, 1) pyplot.ylim(0, 1) ax = Axes3D(fig) ax.set_zlim3d(0,1) length = len(y) for i in range(length): if y[i]==1: ax.scatter(x[0:,0:1][i],x[0:,1:2][i],x[0:,2:3][i], c = 'r', marker='*') else: ax.scatter(x[0:,0:1][i],x[0:,1:2][i],x[0:,2:3][i], c = 'b', marker='*') x2 = np.linspace(0,1,10) y2 = np.linspace(0,1,10) X,Y = np.meshgrid(x2,y2) Z = (and_perception.weights[0]*X + and_perception.weights[1]*Y + + and_perception.bias)/(-and_perception.weights[2]) for idx1, zz in enumerate(Z): for idx2, zzz in enumerate(zz): if Z[idx1][idx2]<0 : Z[idx1][idx2] = and_perception.bias/(-and_perception.weights[2])#Z[idx1][idx2] if Z[idx1][idx2]>0 else np.nan X[idx1][idx2] = 0 Y[idx1][idx2] = 0 surf = ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1,cmap = 'viridis', edgecolor = 'none',vmin=np.nanmin(Z), vmax=np.nanmax(Z)) #使用模型对100个随机三维点进行分类 test = np.random.randint(0,1000,(100,3))/1000 for t in test: if and_perception.predict(t)==1: ax.scatter(t[0],t[1],t[2], c = 'r', marker='*') else: ax.scatter(t[0],t[1],t[2], c = 'b', marker='*') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_zlabel('Z-axis') pyplot.show()
参考:
感知机搞不定逻辑XOR?Science新研究表示人脑单个神经元就能做到
Calculate the Decision Boundary of a Single Perceptron - Visualizing Linear Separability
Python Machine Learning Tutorial
[資料分析&機器學習] 第3.2講:線性分類-感知器(Perceptron) 介紹
Perceptron Learning Algorithm: A Graphical Explanation Of Why It Works
python matplotlib 2D 散点图的制作(输入二维坐标)
how to do the scatter plot for the lists or 2d array or matrix python?
python - Python-Matplotlib-如何从方程式绘制平面?
Set zlim in matplotlib scatter3d
.pyplot has not attribute zlim
Python/matplotlib mplot3d- how do I set a maximum value for the z-axis?
Getting the class name of an instance?
Most efficient way to map function over numpy array
Iterate and modify array with NumPy
Python:有没有办法用Matplotlib绘制“局部”表面图?
Simple way to create matrix of random numbers
Python time.sleep() 阻塞指定秒杀 random.randint()返回指定闭区间内的随机数
https://github.com/cezannec/intro-computervision intro-computervision
https://cezannec.github.io/Convolutional_Neural_Networks/ 卷积神经网络
https://github.com/ahmedfgad/NumPyCNN NumPyCNN
https://stackoverflow.com/questions/55807920/python-how-to-install-scikit-image-when-the-installation-appears-broken Python, how to install scikit-image when the installation appears broken
https://stackoverflow.com/questions/14812342/matplotlib-has-no-attribute-pyplot matplotlib-has-no-attribute-pyplot
https://towardsdatascience.com/convolutional-neural-networks-for-beginners-practical-guide-with-python-and-keras-dc688ea90dca 初学者的卷积神经网络
https://towardsdatascience.com/building-a-convolutional-neural-network-cnn-in-keras-329fbbadc5f5 Building a Convolutional Neural Network (CNN) in Keras
https://www.datacamp.com/community/tutorials/convolutional-neural-networks-python Convolutional Neural Networks in Python with Keras
https://www.tensorflow.org/tutorials/images/cnn Convolutional Neural Network (CNN)
https://missinglink.ai/guides/convolutional-neural-networks/python-convolutional-neural-network-creating-cnn-keras-tensorflow-plain-python/ Python卷积神经网络:在Keras,TensorFlow和Plain Python中创建CNN
https://www.kdnuggets.com/2018/04/building-convolutional-neural-network-numpy-scratch.html Building Convolutional Neural Network using NumPy from Scratch
http://www.skcircle.com/?id=329 滤波的概念和作用(滤波器、掩模、核、模板、窗口是一个意思)
https://cloud.tencent.com/developer/article/1198216 卷积滤波器与边缘检测
https://cloud.tencent.com/developer/article/1600526 数字图像处理中常见的变换核及其用途
https://zhuanlan.zhihu.com/p/45585819 opencv处理图像
https://zhuanlan.zhihu.com/p/81792708 卷积的通俗理解——从傅里叶变换到滤波器
https://opencv-python-tutorials.readthedocs.io/zh/latest/4.%20OpenCV%E4%B8%AD%E7%9A%84%E5%9B%BE%E5%83%8F%E5%A4%84%E7%90%86/4.4.%20%E5%9B%BE%E5%83%8F%E6%BB%A4%E6%B3%A2/ 2D卷积(图像过滤)
https://www.cnblogs.com/carsonzhu/p/10831624.html 计算机视觉】OpenCV篇(6) - 平滑图像(卷积/滤波/模糊/降噪)
- 点赞
- 收藏
- 关注作者
评论(0)