慕粉5601249
2018-06-17 00:31
老师,你用到的代码在哪里呀?数据呢?可以放出来给我们试一试吗?
调用sklearn包中datasets,里面有好像iris数据集
iris数据集,可以到我的百度网盘下载:
https://pan.baidu.com/s/17dK9fdGHzGY1SfI-s1pt6w
class AdalineG(object):
"""
eta:float
学习效率,处于0和1之间
n_iter:int 对训练数据进行学习改进次数
w_:一维向量
存储权重数值
error_: 存储每次迭代改进时,网络对数据进行错误判断的次数
"""
def __init__(self,eta=0.01,n_iter=50):
self.eta = eta
self.n_iter = n_iter
def net_input(self, X):
return np.dot(X, self.w_[1:]) + self.w_[0]
def activation(self, X):
return self.net_input(X)
def predict(self, X):
return np.where(self.activation(X) >=0, 1, -1)
def fit(self, X, y):
"""
X:二维数组[n_sampls, n_features]
n_samples 表示X中含有训练数据条目数
n_faetures 含有4个数据的一维向量,用于表示一条训练条目
y:一维向量
用于存储每一训练条目对应的正确分类
"""
self.w_ = np.zeros(1 + X.shape[1])
self.cost_ = []
for i in range(self.n_iter):
output = self.net_input(X)
errors = (y-output)
self.w_[1:] += self.eta * X.T.dot(errors)
self.w_[0] += self.eta * errors.sum()
cost = (errors ** 2).sum() /2.0
self.cost_.append(cost)
return self
file = "D:/PyCharm_test_file/Jupyter_test/iris1.xlsx" #此处添加iris数据集
import pandas as pd
df = pd.read_excel(file,header=None)
import matplotlib.pyplot as plt
import numpy as np
y = df.loc[0:99, 4].values
y = np.where(y == 'Iris-setosa', -1, 1)
X = df.iloc[0:100, [0, 2]].values
from matplotlib.colors import ListedColormap
def plot_decision_regions(X, y, classifier, resolution=0.02):
marker = ('s', 'x', 'o', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))])
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max()
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max()
#将x1、x2最大最小值通过arange函数得到的向量,扩展成两个二维矩阵
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))
#预测
Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) #ravel还原成单维向量
#绘制
Z= Z.reshape(xx1.shape) #将Z转换成与xx1一样的二维数组
plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap) #在两组分类结果中间画分割线-->必须线性可分
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
for idx, cl in enumerate(np.unique(y)):
plt.scatter(x=X[y==cl, 0], y=X[y==cl, 1], alpha=0.8, c=cmap(idx), marker=marker[idx], label=cl)
ada = AdalineG(eta=0.0001, n_iter=50)
ada.fit(X, y)
plot_decision_regions(X, y, classifier=ada)
plt.title('Adaline-Gradient descent')
plt.rcParams['font.sans-serif']=['SimHei']
plt.xlabel('花茎长度')
plt.ylabel('花瓣长度')
plt.legend(loc='upper left')
plt.show()
"""
打印出模型对数据判断的错误次数(迭代过程)
"""
plt.plot(range(1, len(ada.cost_)+1), ada.cost_, marker='o')
plt.xlabel('Epochs(迭代次数)')
plt.ylabel('sum-squard-error')plt.show()
机器学习-实现简单神经网络
67121 学习 · 186 问题
相似问题