神经网络

单层感知器










单层感知器代码

import numpy as np
import matplotlib.pyplot as plt
#输入数据
X = np.array([[1,3,3],[1,4,3],[1,1,1],[1,0,2]])
#标签
Y = np.array([[1],[1],[-1],[-1]])#权值初始化,3行1列,取值范围-1到1
W = (np.random.random([3,1])-0.5)*2print(W)
#学习率设置
lr = 0.11
#神经网络输出
O = 0def update():global X,Y,W,lrO = np.sign(np.dot(X,W)) # shape:(3,1)W_C = lr*(X.T.dot(Y-O))/int(X.shape[0])W = W + W_C

for i in range(100):update()#更新权值print(W)#打印当前权值print(i)#打印迭代次数O = np.sign(np.dot(X,W))#计算当前输出  if(O == Y).all(): #如果实际输出等于期望输出,模型收敛,循环结束print('Finished')print('epoch:',i)break#正样本
x1 = [3,4]
y1 = [3,3]
#负样本
x2 = [1,0]
y2 = [1,2]#计算分界线的斜率以及截距
k = -W[1]/W[2]
d = -W[0]/W[2]
print('k=',k)
print('d=',d)xdata = (0,5)plt.figure()
plt.plot(xdata,xdata*k+d,'r')
plt.scatter(x1,y1,c='b')
plt.scatter(x2,y2,c='y')
plt.show()


单层感知器异或问题代码

'''
异或
0^0 = 0
0^1 = 1
1^0 = 1
1^1 = 0
'''

import numpy as np
import matplotlib.pyplot as plt
#输入数据
X = np.array([[1,0,0],[1,0,1],[1,1,0],  [1,1,1]])
#标签
Y = np.array([[-1],[1],[1],[-1]])#权值初始化,3行1列,取值范围-1到1
W = (np.random.random([3,1])-0.5)*2print(W)
#学习率设置
lr = 0.11
#神经网络输出
O = 0def update():global X,Y,W,lrO = np.sign(np.dot(X,W)) # shape:(3,1)W_C = lr*(X.T.dot(Y-O))/int(X.shape[0])W = W + W_C

for i in range(100):update()#更新权值print(W)#打印当前权值print(i)#打印迭代次数O = np.sign(np.dot(X,W))#计算当前输出  if(O == Y).all(): #如果实际输出等于期望输出,模型收敛,循环结束print('Finished')print('epoch:',i)break#正样本
x1 = [0,1]
y1 = [1,0]
#负样本
x2 = [0,1]
y2 = [0,1]#计算分界线的斜率以及截距
k = -W[1]/W[2]
d = -W[0]/W[2]
print('k=',k)
print('d=',d)xdata = (-2,3)plt.figure()
plt.plot(xdata,xdata*k+d,'r')
plt.scatter(x1,y1,c='b')
plt.scatter(x2,y2,c='y')
plt.show()



线性神经网络

import numpy as np
import matplotlib.pyplot as plt
#输入数据
X = np.array([[1,3,3],[1,4,3],[1,1,1],[1,0,2]])
#标签
Y = np.array([[1],[1],[-1],[-1]])#权值初始化,3行1列,取值范围-1到1
W = (np.random.random([3,1])-0.5)*2print(W)
#学习率设置
lr = 0.11
#神经网络输出
O = 0def update():global X,Y,W,lrO = np.dot(X,W)W_C = lr*(X.T.dot(Y-O))/int(X.shape[0])W = W + W_C

for _ in range(100):update()#更新权值#正样本x1 = [3,4]y1 = [3,3]#负样本x2 = [1,0]y2 = [1,2]#计算分界线的斜率以及截距k = -W[1]/W[2]d = -W[0]/W[2]print('k=',k)print('d=',d)xdata = (0,5)plt.figure()plt.plot(xdata,xdata*k+d,'r')plt.scatter(x1,y1,c='b')plt.scatter(x2,y2,c='y')plt.show()




激活函数







BP神经网络Back Propagation Neural Network







BP神经网络-异或问题

import numpy as np
#输入数据
X = np.array([[1,0,0],[1,0,1],[1,1,0],[1,1,1]])
#标签
Y = np.array([[0,1,1,0]])
#权值初始化,取值范围-1到1
V = np.random.random((3,4))*2-1
W = np.random.random((4,1))*2-1
print(V)
print(W)
#学习率设置
lr = 0.11def sigmoid(x):return 1/(1+np.exp(-x))def dsigmoid(x):return x*(1-x)def update():global X,Y,W,V,lrL1 = sigmoid(np.dot(X,V))#隐藏层输出(4,4)L2 = sigmoid(np.dot(L1,W))#输出层输出(4,1)L2_delta = (Y.T - L2)*dsigmoid(L2)L1_delta = L2_delta.dot(W.T)*dsigmoid(L1)W_C = lr*L1.T.dot(L2_delta)V_C = lr*X.T.dot(L1_delta)W = W + W_CV = V + V_C

for i in range(20000):update()#更新权值if i%500==0:L1 = sigmoid(np.dot(X,V))#隐藏层输出(4,4)L2 = sigmoid(np.dot(L1,W))#输出层输出(4,1)print('Error:',np.mean(np.abs(Y.T-L2)))L1 = sigmoid(np.dot(X,V))#隐藏层输出(4,4)
L2 = sigmoid(np.dot(L1,W))#输出层输出(4,1)
print(L2)def judge(x):if x>=0.5:return 1else:return 0for i in map(judge,L2):print(i)

BP网络-数字识别

import numpy as np
from sklearn.datasets import load_digits
from sklearn.preprocessing import LabelBinarizer
from sklearn.cross_validation import train_test_splitdef sigmoid(x):return 1/(1+np.exp(-x))def dsigmoid(x):return x*(1-x)class NeuralNetwork:def __init__(self,layers):#(64,100,10)#权值的初始化,范围-1到1self.V = np.random.random((layers[0]+1,layers[1]+1))*2-1self.W = np.random.random((layers[1]+1,layers[2]))*2-1def train(self,X,y,lr=0.11,epochs=10000):#添加偏置temp = np.ones([X.shape[0],X.shape[1]+1])temp[:,0:-1] = XX = tempfor n in range(epochs+1):i = np.random.randint(X.shape[0]) #随机选取一个数据x = [X[i]]x = np.atleast_2d(x)#转为2维数据L1 = sigmoid(np.dot(x,self.V))#隐层输出L2 = sigmoid(np.dot(L1,self.W))#输出层输出L2_delta = (y[i]-L2)*dsigmoid(L2)L1_delta= L2_delta.dot(self.W.T)*dsigmoid(L1)self.W += lr*L1.T.dot(L2_delta)self.V += lr*x.T.dot(L1_delta)#每训练1000次预测一次准确率if n%1000==0:predictions = []for j in range(X_test.shape[0]):o = self.predict(X_test[j])predictions.append(np.argmax(o))#获取预测结果accuracy = np.mean(np.equal(predictions,y_test))print('epoch:',n,'accuracy:',accuracy)def predict(self,x):#添加偏置temp = np.ones(x.shape[0]+1)temp[0:-1] = xx = tempx = np.atleast_2d(x)#转为2维数据L1 = sigmoid(np.dot(x,self.V))#隐层输出L2 = sigmoid(np.dot(L1,self.W))#输出层输出return L2digits = load_digits()#载入数据
X = digits.data#数据
y = digits.target#标签
#输入数据归一化
X -= X.min()
X /= X.max()nm = NeuralNetwork([64,100,10])#创建网络X_train,X_test,y_train,y_test = train_test_split(X,y) #分割数据1/4为测试数据,3/4为训练数据labels_train = LabelBinarizer().fit_transform(y_train)#标签二值化     0,8,6   0->1000000000  3->0001000000
labels_test = LabelBinarizer().fit_transform(y_test)#标签二值化print('start')nm.train(X_train,labels_train,epochs=20000)print('end')


sklearn-神经网络-手写数字识别

# pip install scikit-learn --upgrade
from sklearn.neural_network import MLPClassifier
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report,confusion_matrix
digits = load_digits()#载入数据
x_data = digits.data #数据
y_data = digits.target #标签# 标准化
scaler = StandardScaler()
x_data = scaler.fit_transform(x_data)
x_train,x_test,y_train,y_test = train_test_split(x_data,y_data) #分割数据1/4为测试数据,3/4为训练数据
mlp = MLPClassifier(hidden_layer_sizes=(100,50) ,max_iter=500)
mlp.fit(x_train,y_train )

predictions = mlp.predict(x_test)
print(classification_report(y_test, predictions))

print(confusion_matrix(y_test,predictions))

神经网络-葡萄酒分类

import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import classification_report,confusion_matrix
# 载入数据
data = np.genfromtxt("wine_data.csv", delimiter=",")
x_data = data[:,1:]
y_data = data[:,0]
print(x_data.shape)
print(y_data.shape)

# 数据切分
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data)
# 数据标准化
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)
x_test = scaler.fit_transform(x_test)
# 建模
mlp = MLPClassifier(hidden_layer_sizes=(100,50),max_iter=500)
# 训练
mlp.fit(x_train,y_train)

# 评估
predictions = mlp.predict(x_test)
print(classification_report(y_test,predictions))

print(confusion_matrix(y_test,predictions))

机器学习基础-神经网络-10相关推荐

  1. Python机器学习基础教程10

    文章目录 处理文本数据 用字符串表示的数据类型 电影评论的情感分析 将文本数据表示为词袋 将词袋应用于玩具数据集 将词袋应用于电影评论 停用词 用td-idf缩放数据 多个单词的词袋(n元分词) 高级 ...

  2. [Python人工智能] 三.theano实现分类神经网络及机器学习基础

    从本篇文章开始,作者正式开始研究Python深度学习.神经网络及人工智能相关知识.前两篇文章讲解了神经网络基础概念.Theano库的安装过程及基础用法.theano实现回归神经网络,这篇文章主要讲解机 ...

  3. 神经网络——机器学习基础

    机器学习基础 本章会将你对这些问题的直觉固化为解决深度学习问题的可靠的概念框架.我们将把所有这些概念--模型评估.数据预处理.特征工程.解决过拟合--整合为详细的七步工作流程,用来解决任何机器学习任务 ...

  4. 机器学习基础(一)——人工神经网络与简单的感知器

    机器学习基础(一)--人工神经网络与简单的感知器 (2012-07-04 19:57:20) 转载▼ 标签: 杂谈 分类: machineのlearning 从最开始做数据挖掘而接触人工智能的知识开始 ...

  5. 1.3 机器学习基础-深度学习第二课《改善深层神经网络》-Stanford吴恩达教授

    ←上一篇 ↓↑ 下一篇→ 1.2 偏差/方差 回到目录 1.4 正则化 机器学习基础 (Basic "Recipe" for Machine Learning) 上节课我们讲的是如 ...

  6. 神经网络与深度学习(一)——机器学习基础

    神经网络与深度学习 (一)--机器学习基础 1.人工智能基础概念 2. 机器学习 2.1 基本概念 2.2 机器学习的三个基本要素 2.2.1 模型 2.2.2 学习准则 2.2.2.1 损失函数 L ...

  7. Python 机器学习库 Top 10,你值得拥有!

    随着人工智能技术的发展与普及,Python 超越了许多其他编程语言,成为了机器学习领域中最热门最常用的编程语言之一.有许多原因致使 Python 在众多开发者中如此受追捧,其中之一便是其拥有大量的与机 ...

  8. 【机器学习基础】机器学习训练中常见的问题和挑战!

    ↑↑↑关注后"星标"Datawhale 每日干货 & 每月组队学习,不错过 Datawhale干货 作者:奥雷利安·杰龙 由于我们的主要任务是选择一种学习算法,并对某些数据 ...

  9. 【机器学习基础】数学推导+纯Python实现机器学习算法26:随机森林

    Python机器学习算法实现 Author:louwill Machine Learning Lab 自从第14篇文章结束,所有的单模型基本就讲完了.而后我们进入了集成学习的系列,整整花了5篇文章的篇 ...

最新文章

  1. 转载:谈我所经历的区块链历程
  2. 《碟中谍4:幽灵协议》蓝光1080P 720P首发!!汤姆克鲁斯主演
  3. 螺旋遍历_螺旋形式的水平阶遍历
  4. 转载 ---资深HR告诉你:我如何筛选简历与选择人员的
  5. 自定义控件之瀑布流与水波纹实现
  6. 12. GD32F103C8T6入门教程-定时器-3路pwm输出
  7. Java编程测试1M内存可用来缓存多少对象
  8. linux机顶盒线刷工具,机顶盒刷机包通用版|PhoenixSuitpacket一键刷机工具 V1.10 官方最新版 下载_当下软件园_软件下载...
  9. Linux下解压和压缩jar文件
  10. 计算机无法安装新字体,如何解决XP系统中无法安装新字体
  11. 富爸爸穷爸爸读书感言
  12. Unregistering application *** with eureka with status DOWN
  13. r matlab spss,特别放送 | 零基础编程入门:Python、Matlab、R、SPSS资料大放送
  14. Android P Settings默认显示开发者选项
  15. Windows变慢原因分析及解决方法·系统篇
  16. 交叉验证方法思想简介
  17. 【阿里云短信服务SMS】使用阿里云发送短信
  18. 根据汉字,获取拼音首字母(转)
  19. 【Python实战】用Scrapyd把Scrapy爬虫一步一步部署到腾讯云上,有彩蛋
  20. linux ftp登录530错误,Linux系统中用ftp连接530错误怎么办

热门文章

  1. 手机qq2008触屏版_天猫精灵 CC10 电池版体验:只卖 799 元的平板电脑,比 iPad 更适合老人小孩...
  2. uni-app中使用lodash_uniapp适配到微信小程序注意事项
  3. java soap 头_如何将java头添加到java中的soaprequest
  4. 一、pytorch搭建实战以及sequential的使用
  5. android按钮点击变化,Android实现按钮点击效果(第一次点击变色,第二次恢复)...
  6. 计算机网络的体系结构与协议基本概念,计算机网络技术基础-第3章网络体系结构与协议.ppt...
  7. java ArrayList转数组
  8. 【Apache】 alias+proxy 将资源路径指向某个本地目录
  9. 【Centos 7】【Docker】 安装 redis
  10. 微信小程序发布后,真机调用接口失败:ERR_CERT_AUTHORITY_INVALID