plt画图(sigmoid、relu、softmax)

文章目录

代码(总)

# -*- coding:utf-8 -*-
from matplotlib import pyplot as plt
import numpy as np
import mpl_toolkits.axisartist as axisartist
from matplotlib.pyplot import MultipleLocator

def sigmoid(x):
    return 1. / (1 + np.exp(-x))


def tanh(x):
    return (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))


def relu(x):
    return np.where(x < 0, 0, x)

def prelu(x):
    return np.where(x < 0, 0.5 * x, x)

def sigmoid(x):
    #直接返回sigmoid函数
    return 1. / (1. + np.exp(-x))
def softmax(x):
    return np.exp(x)/np.sum(np.exp(x), axis=0)

def plot_sigmoid():

    # param:起点,终点,间距
    x = np.arange(-10, 10, 0.5)
    print(x)
    y = sigmoid(x)
    #plt.plot(x, label='sigmoid')  # 添加label设置图例名称
    #plt.title("sigmoid",fontsize=20)
    plt.grid()
    plt.plot(x, y,label='sigmoid',color='r')
    plt.legend(fontsize=20)
    plt.xlabel("x",fontsize=20)
    plt.ylabel("f(x)",fontsize=20)
    # 设置刻度字体大小
    plt.xticks(fontsize=20)
    plt.yticks(fontsize=20)
    plt.xlim([-10, 10])
    plt.ylim([0, 1])
    x_major_locator = MultipleLocator(5)
    # 把x轴的刻度间隔设置为1,并存在变量里
    y_major_locator = MultipleLocator(0.2)
    # 把y轴的刻度间隔设置为10,并存在变量里
    ax = plt.gca()
    # ax为两条坐标轴的实例
    ax.xaxis.set_major_locator(x_major_locator)
    # 把x轴的主刻度设置为1的倍数
    ax.yaxis.set_major_locator(y_major_locator)
    # 把y轴的主刻度设置为10的倍数
    plt.show()

def plot_tanh():
    x = np.arange(-10, 10, 0.1)
    y = tanh(x)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.spines['top'].set_color('none')
    ax.spines['right'].set_color('none')
    # ax.spines['bottom'].set_color('none')
    # ax.spines['left'].set_color('none')
    ax.spines['left'].set_position(('data', 0))
    ax.spines['bottom'].set_position(('data', 0))
    ax.plot(x, y)
    plt.xlim([-10.05, 10.05])
    plt.ylim([-1.02, 1.02])
    ax.set_yticks([-1.0, -0.5, 0.5, 1.0])
    ax.set_xticks([-10, -5, 5, 10])
    plt.tight_layout()
    plt.savefig("tanh.png")
    plt.show()

def plot_relu():
    x = np.arange(-10, 10, 0.1)
    y = relu(x)
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # ax.spines['top'].set_color('none')
    # ax.spines['right'].set_color('none')
    # # ax.spines['bottom'].set_color('none')
    # # ax.spines['left'].set_color('none')
    # ax.spines['left'].set_position(('data', 0))
    # ax.plot(x, y)
    # plt.xlim([-10.05, 10.05])
    # plt.ylim([0, 10.02])
    # ax.set_yticks([2, 4, 6, 8, 10])
    # plt.tight_layout()
    # plt.savefig("relu.png")
    #plt.title("relu")
    plt.grid()
    plt.plot(x, y, label='relu', color='r')
    plt.legend(fontsize=20)
    plt.xlabel("x",fontsize=20)
    plt.ylabel("f(x)",fontsize=20)
    # 设置刻度字体大小
    plt.xticks(fontsize=20)
    plt.yticks(fontsize=20)
    plt.xlim([-10, 10])
    plt.ylim([0, 10])
    x_major_locator = MultipleLocator(5)
    # 把x轴的刻度间隔设置为1,并存在变量里
    y_major_locator = MultipleLocator(5)
    # 把y轴的刻度间隔设置为10,并存在变量里
    ax = plt.gca()
    # ax为两条坐标轴的实例
    ax.xaxis.set_major_locator(x_major_locator)
    # 把x轴的主刻度设置为1的倍数
    ax.yaxis.set_major_locator(y_major_locator)
    # 把y轴的主刻度设置为10的倍数
    plt.show()

def plot_prelu():
    x = np.arange(-10, 10, 0.1)
    y = prelu(x)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.spines['top'].set_color('none')
    ax.spines['right'].set_color('none')
    # ax.spines['bottom'].set_color('none')
    # ax.spines['left'].set_color('none')
    ax.spines['left'].set_position(('data', 0))
    ax.spines['bottom'].set_position(('data', 0))
    ax.plot(x, y)
    plt.xticks([])
    plt.yticks([])
    plt.tight_layout()
    plt.savefig("prelu.png")
    plt.show()

def plot_softmax():
    x = np.arange(-10, 10, 0.1)
    y = softmax(x)
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # ax.spines['top'].set_color('none')
    # ax.spines['right'].set_color('none')
    # # ax.spines['bottom'].set_color('none')
    # # ax.spines['left'].set_color('none')
    # ax.spines['left'].set_position(('data', 0))
    # ax.plot(x, y)
    # plt.xlim([-10.05, 10.05])
    # plt.ylim([0, 10.02])
    # ax.set_yticks([2, 4, 6, 8, 10])
    # plt.tight_layout()
    # plt.savefig("relu.png")
    #plt.title("softmax")
    plt.grid()
    plt.plot(x, y, label='softmax', color='r')
    plt.legend(fontsize=20)
    plt.xlabel("x",fontsize=20)
    plt.ylabel("f(x)",fontsize=20)
    plt.xlim([-10, 10])
    plt.ylim([0, 0.1])
    # 设置刻度字体大小
    plt.xticks(fontsize=20)
    plt.yticks(fontsize=20)
    x_major_locator = MultipleLocator(5)
    # 把x轴的刻度间隔设置为1,并存在变量里
    y_major_locator = MultipleLocator(0.02)
    # 把y轴的刻度间隔设置为10,并存在变量里
    ax = plt.gca()
    # ax为两条坐标轴的实例
    ax.xaxis.set_major_locator(x_major_locator)
    # 把x轴的主刻度设置为1的倍数
    ax.yaxis.set_major_locator(y_major_locator)
    # 把y轴的主刻度设置为10的倍数
    plt.show()
if __name__ == "__main__":
    #plot_sigmoid()
    #plot_tanh()
    #plot_relu()
    plot_softmax()
    #plot_prelu()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
from scipy.io import loadmat import numpy as np import math import matplotlib.pyplot as plt import sys, os import pickle from mnist import load_mnist # 函数定义和画图 # 例子:定义step函数以及画图 def step_function(x): y=x>0 return np.array(y,int) def show_step(x): y=step_function(x) plt.plot(x,y,label='step function') plt.legend(loc="best") x = np.arange(-5.0, 5.0, 0.1) show_step(x) ''' 1. 根据阶跃函数step_function的例子,写出sigmoide和Relu函数的定义并画图。 ''' ''' 2. 定义softmax函数,根据输入x=[0.3,2.9,4.0],给出softmax函数的输出,并对输出结果求和。 ''' #获取mnist数据 def get_data(): (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, flatten=True, one_hot_label=False) return x_train,t_train,x_test, t_test #c初始化网络结构,network是字典,保存每一层网络参数W和b def init_network(): with open("sample_weight.pkl", 'rb') as f: network = pickle.load(f) return network #字典 ''' 3. 调用get_data和init_network函数, 输出x_train, t_train,x_test,t_test,以及network中每层参数的shape(一共三层) ''' ''' 4. 定义predict函数,进行手写数字的识别。 识别方法: 假设输入手写数字图像为x,维数为784(28*28的图像拉成一维向量), 第一层网络权值为W1(维数784, 50),b1(维数为50),第一层网络输出:z1=sigmoid(x*W1+b2)。 第二层网络权值为W2(维数50, 100),b2(维数为100),第二层网络输出:z2=sigmoid(z1*W2+b2)。 第三层网络权值为W3(维数100, 10),b3(维数为10),第三层网络输出(即识别结果):p=softmax(z2*W3+b3), p是向量,维数为10(类别数),表示图像x属于每一个类别的概率, 例如p=[0, 0, 0.95, 0.05, 0, 0, 0, 0, 0, 0],表示x属于第三类(数字2)的概率为0.95, 属于第四类(数字3)的概率为0.05,属于其他类别的概率为0. 由于x属于第三类的概率最大,因此,x属于第三类。 ''' ''' 5. 进行手写数字识别分类准确度的计算(总体分类精度),输出分类准确度。 例如测试数据数量为100,其中正确分类的数量为92,那么分类精度=92/100=0.92。 '''
06-02
1. Sigmoid函数的定义和画图: ``` def sigmoid(x): return 1 / (1 + np.exp(-x)) def show_sigmoid(x): y = sigmoid(x) plt.plot(x, y, label='sigmoid function') plt.legend(loc="best") x = np.arange(-5.0, 5.0, 0.1) show_sigmoid(x) ``` ReLU函数的定义和画图: ``` def relu(x): return np.maximum(0, x) def show_relu(x): y = relu(x) plt.plot(x, y, label='ReLU function') plt.legend(loc="best") x = np.arange(-5.0, 5.0, 0.1) show_relu(x) ``` 2. Softmax函数的定义: ``` def softmax(x): exp_x = np.exp(x) sum_exp_x = np.sum(exp_x) return exp_x / sum_exp_x ``` 对于输入x=[0.3,2.9,4.0],softmax函数的输出为: ``` softmax(x) array([0.01821127, 0.24519181, 0.73659691]) ``` 输出结果求和为1. 3. 调用get_data和init_network函数,输出x_train, t_train,x_test,t_test,以及network中每层参数的shape(一共三层): ``` x_train, t_train, x_test, t_test = get_data() network = init_network() for i, (w, b) in enumerate(network.items()): print(f"Layer {i+1}: W shape:{w.shape}, b shape:{b.shape}") print(f"x_train shape: {x_train.shape}") print(f"t_train shape: {t_train.shape}") print(f"x_test shape: {x_test.shape}") print(f"t_test shape: {t_test.shape}") ``` 4. 手写数字的识别代码如下: ``` def predict(network, x): W1, b1 = network['W1'], network['b1'] W2, b2 = network['W2'], network['b2'] W3, b3 = network['W3'], network['b3'] z1 = sigmoid(np.dot(x, W1) + b1) z2 = sigmoid(np.dot(z1, W2) + b2) y = softmax(np.dot(z2, W3) + b3) return y # 获取测试数据 x_train, t_train, x_test, t_test = get_data() network = init_network() # 使用测试数据进行预测 accuracy_cnt = 0 for i in range(len(x_test)): y = predict(network, x_test[i]) p = np.argmax(y) if p == t_test[i]: accuracy_cnt += 1 # 输出分类准确度 accuracy = float(accuracy_cnt) / len(x_test) print("Accuracy:" + str(accuracy)) ``` 5. 进行手写数字识别分类准确度的计算(总体分类精度): 代码中已经实现,输出分类准确度即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Studying_swz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值