python 实现 Peceptron Learning Algorithm ( 一) 几个函数的记录

numpy.random.normal( )

                            

对应于numpy中

numpy.random.normal(loc=0.0, scale=1.0, size=None)

参数的意义为:

loc:float
    此概率分布的均值(对应着整个分布的中心centre)
scale:float
    此概率分布的标准差(对应于分布的宽度,scale越大越矮胖,scale越小,越瘦高)
size:int or tuple of ints
    输出的shape,默认为None,只输出一个值

np.random.randn(size)所谓标准正态分布(μ=0,σ=1μ=0,σ=11 ), 对应于np.random.normal(loc=0, scale=1, size)。 

【zip() 】

参考   http://www.runoob.com/python/python-func-zip.html

 

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

 

【numpy.dot( )】

如果参数是一维数组,返回两个数组的点乘,即内积

如果参数是二维数组(矩阵),返回矩阵相乘之积。

(1)一维数组:

(2)二维数组:(矩阵相乘,第i行依次乘以第i列然后相加)

【numpy.where( )】

参考:https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

"

the output array contains elements of x where condition is True, and elements from y elsewhere.

If only condition is given, return the tuple condition.nonzero(), the indices where condition is True.

"

[condition , x , y]    ——>   如果condition为TRUE,返回x对应位置的值;为FALSE,返回y对应位置的值

【numpy.linalg.norm( )】

求范数

norm(x, ord=None, axis=None, keepdims=False)

默认为求二范数。 order = 2 二范数; order = 1 ,L1范数 ;order = np.inf 无穷范数

【ListedColormap()】

参考文章  https://matplotlib.org/api/_as_gen/matplotlib.colors.ListedColormap.html#matplotlib.colors.ListedColormap

【meshgrid( )】

[X,Y] = meshgrid(x,y) 将向量x和y定义的区域转换成矩阵X和Y,其中矩阵X的行向量是向量x的简单复制,而矩阵Y的列向量是向量y的简单复制。

【ravel( ) 和 flatten( )】

将数组平铺展开,ravel()返回view,对原始数组进行了改变;flatten()返回copy数组,不影响原始数组

参考 http://blog.csdn.net/liuweiyuxiang/article/details/78220080

 

【plt.contourf( )】

 

参考 http://blog.csdn.net/quincuntial/article/details/71104405

      https://www.cnblogs.com/huanggen/p/7533088.html

contour(X,Y,Z) 需要三维数据,X,Y代表二维坐标,在二维面上生成对应的网格,z代表高度,高度Z相等的颜色相同

 

 

 

 

 

以下是使用蜣螂算法优化LSTM超参数的Python代码: ```python import random import numpy as np import math import tensorflow as tf from sklearn.datasets import load_iris from sklearn.preprocessing import MinMaxScaler # 加载数据集 iris = load_iris() X = iris.data y = iris.target # 归一化数据 scaler = MinMaxScaler() X = scaler.fit_transform(X) # 设置LSTM网络结构 def lstm_model(n_input, n_hidden, n_classes): inputs = tf.keras.layers.Input(shape=(n_input, 1)) x = tf.keras.layers.LSTM(n_hidden, activation='tanh', return_sequences=True)(inputs) x = tf.keras.layers.LSTM(n_hidden, activation='tanh')(x) outputs = tf.keras.layers.Dense(n_classes, activation='softmax')(x) model = tf.keras.models.Model(inputs=inputs, outputs=outputs) return model # 计算模型的损失函数和准确率 def model_eval(model, X, y): y_pred = model.predict(X) y_pred = np.argmax(y_pred, axis=1) accuracy = np.mean(y_pred == y) loss = tf.keras.losses.sparse_categorical_crossentropy(y, y_pred) return accuracy, loss # 定义蜣螂算法 def firefly_algorithm(X, y, n_input, n_hidden, n_classes, max_generation, alpha=0.5, betamin=0.2, gamma=1.0): # 初始化火蝗 n_fireflies = 20 fireflies = [] for i in range(n_fireflies): n_hidden_layer = random.randint(8, 128) learning_rate = 10 ** random.uniform(-5, -2) model = lstm_model(n_input, n_hidden_layer, n_classes) accuracy, loss = model_eval(model, X, y) fireflies.append({'model': model, 'accuracy': accuracy, 'loss': loss, 'n_hidden_layer': n_hidden_layer, 'learning_rate': learning_rate}) # 开始迭代 for t in range(max_generation): # 计算每个火蝗的亮度 for i in range(n_fireflies): for j in range(n_fireflies): if fireflies[i]['accuracy'] < fireflies[j]['accuracy']: r = sum([(fireflies[i]['model'].get_weights()[k] - fireflies[j]['model'].get_weights()[k]) ** 2 for k in range(6)]) beta = betamin * math.exp(-gamma * r ** 2) # 移动火蝗 new_model_weights = [] for k in range(6): new_weight = fireflies[i]['model'].get_weights()[k] * (1 - beta) + fireflies[j]['model'].get_weights()[k] * beta + alpha * np.random.uniform(-1, 1, size=fireflies[i]['model'].get_weights()[k].shape) new_model_weights.append(new_weight) new_model = lstm_model(n_input, fireflies[i]['n_hidden_layer'], n_classes) new_model.set_weights(new_model_weights) new_accuracy, new_loss = model_eval(new_model, X, y) # 更新火蝗的亮度 if new_accuracy >= fireflies[i]['accuracy']: fireflies[i]['model'] = new_model fireflies[i]['accuracy'] = new_accuracy fireflies[i]['loss'] = new_loss # 找到最优的模型 best_model = None best_accuracy = -1 for i in range(n_fireflies): if fireflies[i]['accuracy'] > best_accuracy: best_model = fireflies[i]['model'] best_accuracy = fireflies[i]['accuracy'] return best_model, best_accuracy # 调用蜣螂算法进行优化 best_model, best_accuracy = firefly_algorithm(X, y, n_input=X.shape[1], n_hidden=64, n_classes=len(np.unique(y)), max_generation=50) # 输出结果 print('Best accuracy:', best_accuracy) print('Best model:', best_model.summary()) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值