自适应线性神经网络Adaline的python实现详解
作者:沙克的世界 发布时间:2023-11-03 03:57:40
标签:自适应,线性,神经网络,adaline,python
自适应线性神经网络Adaptive linear network, 是神经网络的入门级别网络。
相对于感知器,采用了f(z)=z的激活函数,属于连续函数。
代价函数为LMS函数,最小均方算法,Least mean square。
实现上,采用随机梯度下降,由于更新的随机性,运行多次结果是不同的。
'''
Adaline classifier
created on 2019.9.14
author: vince
'''
import pandas
import math
import numpy
import logging
import random
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
'''
Adaline classifier
Attributes
w: ld-array = weights after training
l: list = number of misclassification during each iteration
'''
class Adaline:
def __init__(self, eta = 0.001, iter_num = 500, batch_size = 1):
'''
eta: float = learning rate (between 0.0 and 1.0).
iter_num: int = iteration over the training dataset.
batch_size: int = gradient descent batch number,
if batch_size == 1, used SGD;
if batch_size == 0, use BGD;
else MBGD;
'''
self.eta = eta;
self.iter_num = iter_num;
self.batch_size = batch_size;
def train(self, X, Y):
'''
train training data.
X:{array-like}, shape=[n_samples, n_features] = Training vectors,
where n_samples is the number of training samples and
n_features is the number of features.
Y:{array-like}, share=[n_samples] = traget values.
'''
self.w = numpy.zeros(1 + X.shape[1]);
self.l = numpy.zeros(self.iter_num);
for iter_index in range(self.iter_num):
for rand_time in range(X.shape[0]):
sample_index = random.randint(0, X.shape[0] - 1);
if (self.activation(X[sample_index]) == Y[sample_index]):
continue;
output = self.net_input(X[sample_index]);
errors = Y[sample_index] - output;
self.w[0] += self.eta * errors;
self.w[1:] += self.eta * numpy.dot(errors, X[sample_index]);
break;
for sample_index in range(X.shape[0]):
self.l[iter_index] += (Y[sample_index] - self.net_input(X[sample_index])) ** 2 * 0.5;
logging.info("iter %s: w0(%s), w1(%s), w2(%s), l(%s)" %
(iter_index, self.w[0], self.w[1], self.w[2], self.l[iter_index]));
if iter_index > 1 and math.fabs(self.l[iter_index - 1] - self.l[iter_index]) < 0.0001:
break;
def activation(self, x):
return numpy.where(self.net_input(x) >= 0.0 , 1 , -1);
def net_input(self, x):
return numpy.dot(x, self.w[1:]) + self.w[0];
def predict(self, x):
return self.activation(x);
def main():
logging.basicConfig(level = logging.INFO,
format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt = '%a, %d %b %Y %H:%M:%S');
iris = load_iris();
features = iris.data[:99, [0, 2]];
# normalization
features_std = numpy.copy(features);
for i in range(features.shape[1]):
features_std[:, i] = (features_std[:, i] - features[:, i].mean()) / features[:, i].std();
labels = numpy.where(iris.target[:99] == 0, -1, 1);
# 2/3 data from training, 1/3 data for testing
train_features, test_features, train_labels, test_labels = train_test_split(
features_std, labels, test_size = 0.33, random_state = 23323);
logging.info("train set shape:%s" % (str(train_features.shape)));
classifier = Adaline();
classifier.train(train_features, train_labels);
test_predict = numpy.array([]);
for feature in test_features:
predict_label = classifier.predict(feature);
test_predict = numpy.append(test_predict, predict_label);
score = accuracy_score(test_labels, test_predict);
logging.info("The accruacy score is: %s "% (str(score)));
#plot
x_min, x_max = train_features[:, 0].min() - 1, train_features[:, 0].max() + 1;
y_min, y_max = train_features[:, 1].min() - 1, train_features[:, 1].max() + 1;
plt.xlim(x_min, x_max);
plt.ylim(y_min, y_max);
plt.xlabel("width");
plt.ylabel("heigt");
plt.scatter(train_features[:, 0], train_features[:, 1], c = train_labels, marker = 'o', s = 10);
k = - classifier.w[1] / classifier.w[2];
d = - classifier.w[0] / classifier.w[2];
plt.plot([x_min, x_max], [k * x_min + d, k * x_max + d], "go-");
plt.show();
if __name__ == "__main__":
main();
来源:https://www.cnblogs.com/thsss/p/11520673.html
0
投稿
猜你喜欢
- itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。开源地址https://github.com/littleco
- 今天写了一个简单的验证,本来前面用的组件,但是感觉写的组件在此项目不是很好用,由于用到的地方比较少,所以直接写在了页面中。<div&g
- 数据库操作当中,当数据库对象列表不只有一个普通的元素——objectname时,你将要使用objectowner.objectname来引用
- View in Browser功能不生效问题安装玩view in browser插件后,在文档中点击邮件的view in browser 不
- 通过XSL转换XML文件 最近,我喜欢上了XML编程,但又苦于它的美观程度又不够,找了许多书才搞定。用XML好是蛮好,但它还是不太适合做显示
- JavaScript 有三种弹窗 Alert (只有确定按钮), Confirmation (确定,取消等按钮), Prompt (有输入对
- 背景:准备给长辈买个手机,有关手机大小,网购平台基本只有手机尺寸和分辨率的文本数据,因而对手机屏幕大小没有直观感受,虽然网上有比较手机大小的
- 这篇分享几个在地址栏实现的Javascript有趣效果和应用。能在浏览器地址栏实现的效果太多了,字体放大、显示所有图片、显示Cookie等等
- 写入文件使用open()函数和write()函数但是有两种写法,分别是'a'和'w'。'a'
- 概述ABP框架作为后端,是一个非常不错的技术方向,但是前端再使用Asp.NET 进行开发的话,虽然会快捷一点,不过可能显得有点累赘了,因此B
- 1 Kmean图像分割按照Kmean原理,对图像像素进行聚类。优点:此方法原理简单,效果显著。缺点:实践发现对于前景和背景颜色相近或者颜色区
- mysql慢查询日志对于跟踪有问题的查询非常有用,可以分析出当前程序里有很耗费资源的sql语句,那如何打开mysql的慢查询日志记录呢?其实
- 在我的印象里面进制互相转换确实是很常见的问题,所以在Python中,自然也少不了把下面这些代码收为util。这是从网上搜索的一篇也的还可以的
- python 的虚拟环境可以为一个 python 项目提供独立的解释环境、依赖包等资源,既能够很好的隔离不同项目使用不同 python 版本
- 安装:yum -y install php php-devel php-pear
- aspx: <div id="selDiv" style=" z-index:100; visibili
- 在Python语言中,json数据与dict字典以及对象之间的转化,是必不可少的操作。在Python中自带json库。通过import js
- 前言首先,我们开发的项目会有多个版本.其次,我们的项目版本会随着更新越来越多,我们不可能因出了新版本就不维护旧版本了.那么,我们就需要对版本
- 实例如下所示:# -*- coding: UTF-8 -*-from urllib import requestif __name__ ==
- 本文教程为大家分享了mysql installer community 8.0.12.0的安装,供大家参考一、下载mysql-install