Tensorflow之softmax应用实例

TensorFlow上实现Softmax回归模型 一、概述及完整代码 对MNIST(MixedNational Institute of Standard and Technology database)这个非常简单的机器视觉数据集,Tensorflow为我们进行了方便的封装,可以直接加载MNIST数据成我们期望的格式.本程序使用Softmax Regression训练手写数字识别的分类模型. 先看完整代码: import tensor 阅读详情

语言:python3.6

框架:   tensorflow

数据集:mnist数据集(图片格式)

1、准备数据集

下载地址:http://yann.lecun.com/exdb/mnist/

用以下的代码将minist数据集转化为图片(也可以通过from tensorflow.examples.tutorials.mnist import input_data获得二进格式的数据)

"""
将MNIST数据集由二进制文件转为图片形式,保存于指定文件夹下
"""
import os
import struct
import numpy as np
import matplotlib.pyplot as plt

# 读MNIST数据集的图片数据
def mnist_load_img(img_path):
    with open(img_path, "rb") as fp:
        # >是以大端模式读取,i是整型模式,读取前四位的标志位,
        # unpack()函数:是将4个字节联合后再解析成一个数,(读取后指针自动后移)
        msb = struct.unpack('>i', fp.read(4))[0]
        # 标志位为2051,后存图像数据;标志位为2049,后存图像标签
        if msb == 2051:
            # 读取样本个数60000,存入cnt
            cnt = struct.unpack('>i', fp.read(4))[0]
            # rows:行数28;cols:列数28
            rows = struct.unpack('>i', fp.read(4))[0]
            cols = struct.unpack('>i', fp.read(4))[0]
            imgs = np.empty((cnt, rows, cols), dtype="int")
            for i in range(0, cnt):
                for j in range(0, rows):
                    for k in range(0, cols):
                        # 16进制转10进制
                        pxl = int(hex(fp.read(1)[0]), 16)
                        imgs[i][j][k] = pxl
            return imgs
        else:
            return np.empty(1)

# 读MNIST数据集的图片标签
def mnist_load_label(label_path):
    with open(label_path, "rb") as fp:
        msb = struct.unpack('>i', fp.read(4))[0];
        if msb == 2049:
            cnt = struct.unpack('>i', fp.read(4))[0];
            labels = np.empty(cnt, dtype="int");
            for i in range(0, cnt):
                label = int(hex(fp.read(1)[0]), 16);
                labels[i] = label;
            return labels;
        else:
            return np.empty(1);

# 分割训练、测试集的图片数据与图片标签
def mnist_load_data(train_img_path, train_label_path, test_img_path, test_label_path):
    x_train = mnist_load_img(train_img_path);
    y_train = mnist_load_label(train_label_path);
    x_test = mnist_load_img(test_img_path);
    y_test = mnist_load_label(test_label_path);
    return (x_train, y_train), (x_test, y_test);

# 输出打印图片
def mnist_plot_img(img):
    (rows, cols) = img.shape;
    plt.figure();
    plt.gray();
    plt.imshow(img);
    plt.show();

# 按指定位置保存图片
def mnist_save_img(img, path, name):
    if not os.path.exists(path):
        os.mkdir(path)
    (rows, cols) = img.shape
    fig = plt.figure()
    plt.gray()
    plt.imshow(img)
    # 在既定路径里保存图片
    fig.savefig(path + name)



# [start]
x_train = mnist_load_img("train-images.idx3-ubyte")
y_train = mnist_load_label("train-labels.idx1-ubyte")

# 将打印出的MNIST数据集中所有的图片存入一个data文件夹下
# for i in range(0, 10):
#     path = "../CNN+Kreas框架+MNIST/data/data_a/"
#     name = str(i) + ".png"
#     mnist_save_img(x_train[i], path, name)

# 按图片标签的不同,打印MNIST数据集的图片存入不同文件夹下
for i in range(0, len(x_train)):
    path = "./data/" + str(y_train[i]) +"/"
    name = str(i)+".png"
    mnist_save_img(x_train[i], path, name)



#mnist_plot_img(x_train[0, :, :])
"""
x_test = mnist_load_img("t10k-images.idx3-ubyte")
y_test = mnist_load_label("t10k-labels.idx1-ubyte")
"""

代码转自(https://blog.youkuaiyun.com/zzZ_CMing/article/details/81063977)

就会在所指定的目录下发现0~9文件夹,里面存放图片形式的minist数据集,接下来制作训练集(也可以用上面代码中的mnist_load_data方法)

2、制作训练集

将图片和相应标签对应起来,用以下代码实现。

class Dataset(object):
    def __init__(self,file_path,batch_size,capacity):
        self.file_path=file_path#路径文件
        self.batch_size=batch_size#batch_size
        self.capacity=capacity#队列容量
        self.image_size=28



    def num_batch(self):
        image, label = self.get_files(self.file_path)
        return len(label)//self.batch_size#一批样本中的batch个数


    def get_batch(self):
        image, label = self.get_files(self.file_path)
        batch_image, batch_label=self.get_batches(image,label,self.image_size,self.image_size,self.batch_size,self.capacity)
        return batch_image,batch_label


    def get_files(self,file_path):
        class_train = []
        label_train = []
        for train_class in os.listdir(file_path):
            for pic_name in os.listdir(file_path + train_class):
                class_train.append(file_path + train_class + '/' + pic_name)
                label_train.append(train_class)
        temp = np.array([class_train, label_train])
        temp = temp.transpose()
        np.random.shuffle(temp)

        image_list = list(temp[:, 0])
        label_list = list(temp[:, 1])
        # class is 1 2 3 4 5
        label_list = [int(i) for i in label_list]

        return image_list, label_list

    def get_batches(self,image, label, resize_w, resize_h, batch_size, capacity):
        image = tf.cast(image, tf.string)
        label = tf.cast(label, tf.int64)
        queue = tf.train.slice_input_producer([image, label])
        label = queue[1]
        image_temp = tf.read_file(queue[0])
        image = tf.image.decode_jpeg(image_temp, channels=1)

        # resize image
        # image = tf.image.resize_image_with_crop_or_pad(image, resize_w, resize_h)
        image = tf.image.resize_images(image, [resize_w, resize_h], method=0)

        image = tf.image.per_image_standardization(image)

        image_batch, label_batch = tf.train.batch([image, label], batch_size=batch_size,
                                                  num_threads=64,
                                                  capacity=capacity)
        # 1:一个batch batch_size:总共划分的batch数,784,展开为1列
        image_batch = tf.reshape(image_batch, [batch_size, resize_w * resize_w])
        images_batch = tf.cast(image_batch, tf.float32)


        labels_onehot_batch = tf.one_hot(label_batch, depth=10, on_value=1, axis=1)

        labels_batch = tf.reshape(labels_onehot_batch, [batch_size, 10])

        return images_batch, labels_batch

如果分类的类别数不为10时需要修改

label_list = tf.one_hot(label_list, depth=10, on_value=1, axis=1)中的depth(输出通道)和
labels_batch = tf.reshape(label_batch, [batch_size, 10])中的10(输出通道)

3、设计网络

    with tf.name_scope('Input'):
        X = tf.placeholder(dtype=tf.float32, shape=[None, 784], name='X_placeholder')
        Y = tf.placeholder(dtype=tf.int32, shape=[None, 10], name='Y_placeholder')

    # 2、前向网络设计
    with tf.name_scope('Inference'):
        # batch:20 输入:784,通道:1,输出:10
        W = tf.Variable(initial_value=tf.random_normal(shape=[784, 10], stddev=0.01), name='Weights')
        b = tf.Variable(initial_value=tf.zeros(shape=[10]), name='bias')
        print(W)
        logits = tf.matmul(X, W) + b
        Y_pred = tf.nn.softmax(logits=logits)
    # 3、损失函数设计
    with tf.name_scope('Loss'):
        # 求交叉熵损失
        cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=logits, name='cross_entropy')
        # cross_entropy=tf.nn.sparse_softmax_cross_entropy_with_logits(labels=Y, logits=logits, name='cross_entropy')
        # 求平均
        loss = tf.reduce_mean(cross_entropy, name='loss')

    # 4、参数学习算法设计
    with tf.name_scope('Optimization'):
        learn_rate=0.001
        optimizer = tf.train.GradientDescentOptimizer(learn_rate).minimize(loss)

    # 5、评估节点设计
    with tf.name_scope('Evaluate'):
        # 返回验证集/测试集预测正确或错误的布尔值
        correct_prediction = tf.equal(tf.argmax(Y_pred, 1), tf.argmax(Y, 1))
        # 将布尔值转换为浮点数后,求平均准确率
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
        

用一个全连接网络+softmax网络实现简单分类这里将minist的单张图片展开为[1,28*28],目的是将图片的每个像素当作其特征放入全连接网络,提取浅层特征,损失函数用交叉熵损失函数(常用于分类网络)

至此主要的工作都以做完了,加下来就是训练了,我把全部训练代码放在这里。

def main(argv=None):
    # 0、准备训练/验证/测试数据集
    log_dir='./'
    batch_size=50
    batch_image, batch_label=Dataset(data_path,50,100).get_batch()

    batch_num = Dataset(data_path,50,100).num_batch()


    # 1、数据输入设计:使用 placeholder 将数据送入网络,None 表示张量的第一个维度可以是任意长度的
    with tf.name_scope('Input'):
        X = tf.placeholder(dtype=tf.float32, shape=[None, 784], name='X_placeholder')
        Y = tf.placeholder(dtype=tf.int32, shape=[None, 10], name='Y_placeholder')

    # 2、前向网络设计
    with tf.name_scope('Inference'):
        # batch:20 输入:784,通道:1,输出:10
        W = tf.Variable(initial_value=tf.random_normal(shape=[784, 10], stddev=0.01), name='Weights')
        b = tf.Variable(initial_value=tf.zeros(shape=[10]), name='bias')
        print(W)
        logits = tf.matmul(X, W) + b
        Y_pred = tf.nn.softmax(logits=logits)
    # 3、损失函数设计
    with tf.name_scope('Loss'):
        # 求交叉熵损失
        cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=logits, name='cross_entropy')
        # cross_entropy=tf.nn.sparse_softmax_cross_entropy_with_logits(labels=Y, logits=logits, name='cross_entropy')
        # 求平均
        loss = tf.reduce_mean(cross_entropy, name='loss')

    # 4、参数学习算法设计
    with tf.name_scope('Optimization'):
        learn_rate=0.001
        optimizer = tf.train.GradientDescentOptimizer(learn_rate).minimize(loss)

    # 5、评估节点设计
    with tf.name_scope('Evaluate'):
        # 返回验证集/测试集预测正确或错误的布尔值
        correct_prediction = tf.equal(tf.argmax(Y_pred, 1), tf.argmax(Y, 1))
        # 将布尔值转换为浮点数后,求平均准确率
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
        # correct_prediction=tf.nn.in_top_k(Y_pred, Y, 1)

    print('~~~~~~~~~~~开始执行计算图~~~~~~~~~~~~~~')

    saver = tf.train.Saver(tf.global_variables(), max_to_keep=10)
    with tf.Session() as sess:
        counter = 0
        summary_writer = tf.summary.FileWriter(logdir=log_dir, graph=sess.graph)
        # 初始化所有变量
        sess.run(tf.global_variables_initializer())
        train_epoch_loss = []
        test_epoch_loss = []
        test_val_acc = []

        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)
        try:
            while not coord.should_stop():
                counter += 1
                epoch_num = batch_num
                # 训练
                while epoch_num >= 0:
                    epoch_num -= 1
                    image_batch_v, label_batch_v = sess.run([batch_image, batch_label])

                    _, loss_batch, = sess.run([optimizer, loss], feed_dict={X: image_batch_v, Y: label_batch_v})
                    train_epoch_loss.append(loss_batch)

                # 验证
                while epoch_num <= batch_num:
                    epoch_num += 1
                    image_batch_v, label_batch_v = sess.run([batch_image, batch_label])
                    test_loss, acc = sess.run([loss, accuracy], feed_dict={X: image_batch_v, Y: label_batch_v})

                    test_epoch_loss.append(test_loss)
                    test_val_acc.append(acc)

                mean_train_loss = round(np.mean(np.array(train_epoch_loss)), 3)
                mean_test_loss = round(np.mean(np.array(test_epoch_loss)), 3)
                mean_val_acc = round(np.mean(np.array(test_val_acc)), 3)

                print('{} times val_acc is {}, train_loss: {},test_loss:{}'.format(counter, mean_val_acc, mean_train_loss,
                                                                                 mean_test_loss))

                if counter % 300 == 0:

                    base_dir = './checkpoint'
                    ckpt_file = base_dir + "/batch_test_loss=%.4f.ckpt" % mean_train_loss
                    print('Save ckpt file to {}'.format(ckpt_file))
                    if os.path.exists(base_dir) == False:
                        os.makedirs(base_dir)
                    saver.save(sess, ckpt_file, global_step=counter)
                if counter > 1000:
                    break


        except tf.errors.OutOfRangeError:
            print('Done!')
        finally:
            coord.request_stop()

        coord.join(threads)
        summary_writer.close()

4、验证

我们用单张图片进行验证,注意,输入的label和图片维度与训练的维度要一致。验证代码如下:

def prediect2(image):
    labels=np.array([0,1,2,3,4,5,6,7,8,9]).reshape([1,10])#单张时为[1,10],n张时为[n,10]
    trans2np=np.array(image).reshape([1,784])
    with tf.name_scope('Input'):
       x = tf.placeholder(dtype=tf.float32, shape=[None, 784], name='X_placeholder')
       y = tf.placeholder(dtype=tf.int32, shape=[None,10], name='Y_placeholder')

    # 2、前向网络设计
    with tf.name_scope('Inference'):
        # batch:20 输入:784,通道:1,输出:10
        W = tf.Variable(initial_value=tf.random_normal(shape=[784,10], stddev=0.01), name='Weights')
        b = tf.Variable(initial_value=tf.zeros(shape=[10]), name='bias')
        print(W)
        logits = tf.matmul(x, W) + b
        pred = tf.nn.softmax(logits=logits)

    saver=tf.train.Saver()

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        saver.restore(sess, save_path=  './checkpoint/batch_test_loss=0.5550.ckpt-300')

        correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
        print('accuracy: ', accuracy.eval({x:trans2np,y:labels}))

        output = tf.argmax(pred, 1)
        outputval,pre = sess.run([output,pred], feed_dict={x: trans2np, y: labels})
        print(outputval)
        print('p:',pre)

最后可以看到答应出了类别对应的ID。

在代码中用了

tf.nn.softmax_cross_entropy_with_logits(logits, labels, name=None)求交叉损失,该方法:

除去name参数用以指定该操作的name,与方法有关的一共两个参数:

第一个参数logits:就是神经网络最后一层的输出,如果有batch的话,它的大小就是[batchsize,num_classes],单样本的话,大小就是num_classes

第二个参数labels:实际的标签,shape必须和logits相同。

除了用softmax_cross_entropy_with_logits方法以外还可以用tf.nn.sparse_softmax_cross_entropy_with_logits(labels, logits, name=None)该方法用法比softmax_cross_entropy_with_logits简单,不用见label转化为one_hot编码就可以使用。见如下代码:

class Dataset(object):
    def __init__(self,file_path,batch_size,capacity):
        self.file_path=file_path#路径文件
        self.batch_size=batch_size#batch_size
        self.capacity=capacity#队列容量
        self.image_size=28



    def num_batch(self):
        image, label = self.get_files(self.file_path)
        return len(label)//self.batch_size#一批样本中的batch个数


    def get_batch(self):
        image, label = self.get_files(self.file_path)
        batch_image, batch_label=self.get_batches(image,label,self.image_size,self.image_size,self.batch_size,self.capacity)
        return batch_image,batch_label


    def get_files(self,file_path):
        class_train = []
        label_train = []
        for train_class in os.listdir(file_path):
            for pic_name in os.listdir(file_path + train_class):
                class_train.append(file_path + train_class + '/' + pic_name)
                label_train.append(train_class)
        temp = np.array([class_train, label_train])
        temp = temp.transpose()
        np.random.shuffle(temp)

        image_list = list(temp[:, 0])
        label_list = list(temp[:, 1])
        # class is 1 2 3 4 5
        label_list = [int(i) for i in label_list]

        return image_list, label_list

    def get_batches(self,image, label, resize_w, resize_h, batch_size, capacity):
        image = tf.cast(image, tf.string)
        label = tf.cast(label, tf.int64)
        queue = tf.train.slice_input_producer([image, label])
        label = queue[1]
        image_temp = tf.read_file(queue[0])
        image = tf.image.decode_jpeg(image_temp, channels=1)

        # resize image
        # image = tf.image.resize_image_with_crop_or_pad(image, resize_w, resize_h)
        image = tf.image.resize_images(image, [resize_w, resize_h], method=0)

        image = tf.image.per_image_standardization(image)

        image_batch, label_batch = tf.train.batch([image, label], batch_size=batch_size,
                                                  num_threads=64,
                                                  capacity=capacity)
        # 1:一个batch batch_size:总共划分的batch数,784,展开为1列
        image_batch = tf.reshape(image_batch, [batch_size, resize_w * resize_w])
        images_batch = tf.cast(image_batch, tf.float32)



        labels_batch = tf.reshape(label_batch, [batch_size])


        return images_batch, labels_batch

def main(argv=None):
    # 0、准备训练/验证/测试数据集
    log_dir='./'
    batch_size=50
    batch_image, batch_label=Dataset(data_path,batch_size,100).get_batch()

    batch_num = Dataset(data_path,50,100).num_batch()


    # 1、数据输入设计:使用 placeholder 将数据送入网络,None 表示张量的第一个维度可以是任意长度的
    with tf.name_scope('Input'):
        X = tf.placeholder(dtype=tf.float32, shape=[None, 784], name='X_placeholder')
        Y = tf.placeholder(dtype=tf.int32, shape=[None], name='Y_placeholder')

    # 2、前向网络设计
    with tf.name_scope('Inference'):
        # batch:20 输入:784,通道:1,输出:10
        W = tf.Variable(initial_value=tf.random_normal(shape=[784, 10], stddev=0.01), name='Weights')
        b = tf.Variable(initial_value=tf.zeros(shape=[10]), name='bias')
        print(W)
        logits = tf.matmul(X, W) + b
        Y_pred = tf.nn.softmax(logits=logits)
    # 3、损失函数设计
    with tf.name_scope('Loss'):
        # 求交叉熵损失
        # cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=logits, name='cross_entropy')
        cross_entropy=tf.nn.sparse_softmax_cross_entropy_with_logits(labels=Y, logits=logits, name='cross_entropy')
        # 求平均
        loss = tf.reduce_mean(cross_entropy, name='loss')

    # 4、参数学习算法设计
    with tf.name_scope('Optimization'):
        learn_rate=0.001
        optimizer = tf.train.GradientDescentOptimizer(learn_rate).minimize(loss)

    # 5、评估节点设计
    with tf.name_scope('Evaluate'):
        # 返回验证集/测试集预测正确或错误的布尔值
        # correct_prediction = tf.equal(tf.argmax(Y_pred, 1), tf.argmax(Y, 1))
        # 将布尔值转换为浮点数后,求平均准确率
        correct_prediction = tf.nn.in_top_k(Y_pred, Y, 1)
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))


    print('~~~~~~~~~~~开始执行计算图~~~~~~~~~~~~~~')

    saver = tf.train.Saver(tf.global_variables(), max_to_keep=10)
    with tf.Session() as sess:
        counter = 0
        summary_writer = tf.summary.FileWriter(logdir=log_dir, graph=sess.graph)
        # 初始化所有变量
        sess.run(tf.global_variables_initializer())
        train_epoch_loss = []
        test_epoch_loss = []
        test_val_acc = []

        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)
        try:
            while not coord.should_stop():
                counter += 1
                epoch_num = batch_num
                # 训练
                while epoch_num >= 0:
                    epoch_num -= 1
                    image_batch_v, label_batch_v = sess.run([batch_image, batch_label])

                    _, loss_batch, = sess.run([optimizer, loss], feed_dict={X: image_batch_v, Y: label_batch_v})
                    train_epoch_loss.append(loss_batch)

                # 验证
                while epoch_num <= batch_num:
                    epoch_num += 1
                    image_batch_v, label_batch_v = sess.run([batch_image, batch_label])
                    test_loss, acc = sess.run([loss, accuracy], feed_dict={X: image_batch_v, Y: label_batch_v})

                    test_epoch_loss.append(test_loss)
                    test_val_acc.append(acc)

                mean_train_loss = round(np.mean(np.array(train_epoch_loss)), 3)
                mean_test_loss = round(np.mean(np.array(test_epoch_loss)), 3)
                mean_val_acc = round(np.mean(np.array(test_val_acc)), 3)

                print('{} times val_acc is {}, train_loss: {},test_loss:{}'.format(counter, mean_val_acc, mean_train_loss,
                                                                                 mean_test_loss))

                if counter % 300 == 0:

                    base_dir = './checkpoint'
                    ckpt_file = base_dir + "/batch_test_loss=%.4f.ckpt" % mean_train_loss
                    print('Save ckpt file to {}'.format(ckpt_file))
                    if os.path.exists(base_dir) == False:
                        os.makedirs(base_dir)
                    saver.save(sess, ckpt_file, global_step=counter)
                if counter > 1000:
                    break


        except tf.errors.OutOfRangeError:
            print('Done!')
        finally:
            coord.request_stop()

        coord.join(threads)
        summary_writer.close()


  注意:用tf.nn.sparse_softmax_cross_entropy_with_logits方法时在Dataset中用labels_batch = tf.reshape(label_batch, [batch_size])替换以下两句:

labels_onehot_batch = tf.one_hot(label_batch, depth=10, on_value=1, axis=1)
labels_batch = tf.reshape(labels_onehot_batch, [batch_size, 10])
,同时计算accuracy时也要将tf.equal替换为:tf.nn.in_top_k。

验证代码也要做相应的改变,主要是将label改为一维数据。

labels=[0,1,2,3,4,5,6,7,8,9]
def prediect2(image):
    trans2np=np.array(image).reshape([1,784])
    with tf.name_scope('Input'):
       x = tf.placeholder(dtype=tf.float32, shape=[None, 784], name='X_placeholder')
       y = tf.placeholder(dtype=tf.int32, shape=[None], name='Y_placeholder')

    # 2、前向网络设计
    with tf.name_scope('Inference'):
        # batch:20 输入:784,通道:1,输出:10
        W = tf.Variable(initial_value=tf.random_normal(shape=[784,10], stddev=0.01), name='Weights')
        b = tf.Variable(initial_value=tf.zeros(shape=[10]), name='bias')
        print(W)
        logits = tf.matmul(x, W) + b
        pred = tf.nn.softmax(logits=logits)

    saver=tf.train.Saver()

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        saver.restore(sess, save_path=  './checkpoint/batch_test_loss=0.5550.ckpt-300')

        # correct_prediction = tf.nn.in_top_k(pred, y, 1)
        # accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
        # 
        # 
        # 
        # 
        # print('accuracy: ', accuracy.eval({x:trans2np,y:labels}))

        output = tf.argmax(pred, 1)
        outputval,pre = sess.run([output,pred], feed_dict={x: trans2np, y: labels})
        print(outputval)
        print('p:',pre)
基于deepseek本地模型的本地知识库构建 通过以上步骤,你已经成功构建了一个基于 AnythingLLM 和 LM Studio 的本地知识库。这个系统不仅能够高效地存储和检索知识,还能结合强大的语言模型生成准确的回答。你可以根据自己的需求进一步扩展和优化这个系统,比如增加更多的文档格式支持、优化检索算法等。 阅读详情

相关推荐

AVEVA PDMS 二次开发之PML实战:从宏到自定义窗体的效率提升

本文详细介绍了AVEVA PDMS二次开发中PML语言的应用,从基础宏编写到高级窗体开发,全面提升工程设计效率。通过实战案例展示如何利用PML实现批量操作、流程自动化和交互优化,帮助工程师快速掌握这一强大工具。

weixin_42549451的博客 341

[重要] tensorflow二元或softmax分类例子(手写体)

参考这个官方文档   王津的例子   from tensorflow.examples.tutorials.mnist import input_data #或import input_data import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' mnist = input_data.read_data_sets('MNIST_data'...

lyb3b3b的专栏 1510

卫星载荷应用方案

本文将从技术和应用层面探讨卫星载荷的应用方案,分析各个领域的特点和挑战,以期为卫星载荷的应用提供一定的指导和参考。卫星载荷应用方案涵盖了通信、地球观测、气象预报、导航定位等诸多领域在每一个领域中,都存在着不同的技术挑战和应用需求。随着技术的进步和需求的变化,卫星载荷应用方案将不断发展和完善,为人类社会的进步和发展做出更大的贡献。用户可以通过接收多颗卫星的信号,计算自身的位置和速度信息。在覆盖扩展方面,可以采用多星座、MEO、GEO 等不同轨道高度的卫星布局,结合卫星的特点和应用需求,实现覆盖范围的扩展。

muyangjun的专栏 904

机器学习 逻辑回归(2)softmax回归多类别分类-鸢尾花案例

PS:softmax回归损失函数梯度下降,求导部分没使用指示函数和向量,直接针对单变量进行推导。网上其他资料都比较抽象,找了很久没找到容易理解的,硬刚了几天终于整出来了。 一、前言 二、假设函数 三、One-Hot 独热编码 四、代价函数 五、梯度下降 六、原生代码实现 6.1 加载并查看数据 6.2 添加前置与数据分割 6.3 迭代训练 6.4 验证数据 七、sklearn代码实现 八、参考资料

李乾文的博客 3028

【入门篇】第五章 第一次与 AI Agent 交互

本文介绍了OpenClaw中最基本的用户与AI Agent交互方式,剖析了Agent和Gateway两个核心组件的作用,通过简单示例展示了从用户请求到结果返回的完整执行流程,说明了最小交互过程对验证系统可用性的重要意义,为后续学习复杂任务执行机制奠定基础。

lanyv的博客 512

Django Cookie/Session

Cookie是一种小型的文本文件,通常由Web服务器发送到用户浏览器,并存储在用户的本地计算机上。当用户再次访问该网站时,浏览器会将Cookie发送回服务器,从而实现用户身份验证、个性化设置等功能。Session是一种在服务器端存储用户会话信息的方式。与Cookie不同,Session数据存储在服务器上,而不是客户端。Django框架通过在客户端存储一个Session ID来实现Session的跟踪。Django框架的Cookie/Session机制为开发者提供了方便的数据存储和会话管理功能。

froginwe11的博客 467

动手学深度学习pytorch版练习解答-3.4softmax回归

d2l-pytorch 3.4习题解答

qq_43853021的博客 1680

MOOS-ivp 实验一 MOOS软件的安装与执行

MOOS-ivp实验一 实验一步骤总结 文章目录MOOS-ivp实验一前言一、实验一1.下载软件2.安装必要的插件3.安装后检查4.路径添加5.执行示例文件总结 前言 在moos学习过程中,我觉得最好把学习的每一步骤都总结一下,方便日后进行回顾。moos官网设置了十八个实验,涉及到了moos的各个方面,完成这些实验也是moos入门的好办法。 一、实验一 实验一主要内容仅仅是软件的安装,仅仅这一步就花费了我接近两天的时间。主要问题发生在linux系统的配置问题上。 1.下载软件 svn co https:

weixin_44151170的博客 6671

【动手学深度学习】之softmax回归 练习解答

动手学深度学习 softmax回归内容的练习答案

weixin_51580530的博客 329

JAVA:Spring Boot3 集成 ShardingSphere 实现数据分库分表

本文介绍了基于Spring Boot和ShardingSphere-JDBC实现分库分表与读写分离的解决方案。针对高并发、大数据量场景下单库单表的性能瓶颈,通过配置ShardingSphere-JDBC实现:1)订单表按user_id和order_id分片到两个库和两张表;2)读写分离,写操作路由至主库,读操作在从库间负载均衡。方案使用Druid连接池优化,支持业务透明,无需修改SQL。

木头 661

深度学习-155-RAG技术之嵌入模型Embedding怎么选

Embedding技术在大型语言模型中发挥着至关重要的作用。它将文本转化为向量,使模型能够理解和处理复杂的语言信息。通过选择合适的Embedding方法和优化文本匹配策略,我们可以在搜索引擎、问答系统、推荐系统等领域实现高效且精准的文本匹配。

qq_20466211的博客 406

采用softmax函数进行

采用softmax函数进行

weixin_62547655的博客 208

Raspberry Pi 4B 蓝牙串口(SPP)配置与使用

Linux、Android、Windows 等操作系统带有在引导期间启动的蓝牙守护进程/蓝牙服务。 对于与监视器连接并使用 GUI(如 GTK 等)运行的设备,只需多次单击即可轻松启用并连接到附近的设备。 但是在无头设备的情况下,我们必须依赖于需要在命令行上运行的不同命令。 这篇博客我们将讨论如何在无头树莓派上通过蓝牙设备连接附近。

视觉与物联智能 2745

softmax regression tensorflow实现 matlablib显示

softmax regression 是在 logistic regression 基础上做的推广,logistic regression只要用于处理二分类问题,二softmax regression用于处理多分类问题 softmax regression模型 假设有m个训练样本,{(X1,y1),(X2,y2)......(Xm,ym)}\left \{ (X^{1},y^{1}),(X^{...

xzccfzy的博客 218

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

tensorflow sparse_softmax_cross_entropy_with_logits()函数

  函数:tf.nn.sparse_softmax_cross_entropy_with_logits(logits=x, labels=y) 作用:计算logits和labels之间的稀疏softmax交叉熵,该函数为常用函数。 函数:tf.nn.softmax_cross_entropy_with_logits(logits=x, labels=y) 作用:计算logits和label...

人工智能,深度学习,人脸识别 1461

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

tensorflow入门基础-softmax_cross_entropy_with_logits

softmax_cross_entropy_with_logits函数 tf.nn.softmax_cross_entropy_with_logits(logits, labels, name=None) 除去name参数用以指定该操作的name,与方法有关的一共两个参数: 第一个参数logits:就是神经网络最后一层的输出,如果有batch的话,它的大小就是[batchsize,num_cl...

Dream_Faquir 574

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

跟我学算法-吴恩达老师(超参数调试, batch归一化, softmax使用,tensorflow框架举例)...

1. 在我们学习中,调试超参数是非常重要的。 超参数的调试可以是a学习率,(β1和β2,ε)在Adam梯度下降中使用, layers层数, hidden units 隐藏层的数目, learning_rate_dacay 学习率衰减, mini-batch size 每次迭代的样本数目 当需要调节的参数的数目较多时,我们通常使用随机参数选择进行参数调节. 比如学习率的范围为0.0001 -...

weixin_34004750的博客 381

tf.nn.softmax 函数

tf.nn.softmax( logits, axis=None, name=None, dim=None ) 其实softmax的作用就是归一化,将不管多大范围的数据变到0-1之间,下面举例说明 #softmax 函数 import tensorflow as tf import numpy as np a = np.array([3.1, 0.2, -2.2, 1.1]) print('a = ', a) with tf.Session() as sess..

诚朴勇毅 1169

tensorflow学习之softmax使用详解

1. 什么是Softmax Softmax 在机器学习和深度学习中有着非常广泛的应用。尤其在处理多分类(C &gt; 2)问题,分类器最后的输出单元需要Softmax 函数进行数值处理。关于Softmax 函数的定义如下所示: 其中,Vi 是分类器类别的输出。i 表示类别索引,总的类别个数为 C。Si 表示的是当前元素的指数与所有元素指数和的比值。Softmax 将多分类的输出数值转化为相...

大雄没有叮当猫的博客 2万+

TensorFlow softmax VS sparse softmax

Difference between sparse_softmax_cross_entropy_with_logits and softmax_cross_entropy_with_logits差别在tensorflow中使用softmax loss的时候,会发现有两个softmax cross entropy。刚开始很难看出什么差别,结合程序看的时候,就很容易能看出两者差异。总的来说两者都是计算分

好记性不如烂笔头 1万+

softmax详解

softmax又称归一化指数函数。它是二分类函数sigmoid在多分类上的推广,目的是将多分类的结果以概率的形式展现出来。它将多个神经元的输出,映射到(0,1)区间内,可以看成概率来理解,从而来进行多分类!假设我们有一个数组,V,Vi表示V中的第i个元素,那么这个元素的softmax值就是 下图展示了softmax的计算方法: 指数函数的值域是(0,∞)。...

苦逼的程序猿 4万+

Tensorflow实现Softmax回归

1 前言 在 上一篇文章 中笔者介绍了如何通过Tensorflow来实现线性回归。在接下来的这篇文章中,笔者将会以Fashion MNIST数据集为例来介绍如何用Tensorflow实现一个Softmax多分类模型。在这篇文章中,我们会开始慢慢接触到Tensoflow中用于实现分类模型的API,例如tf.nn.softmax(),softmax_cross_entropy_with_logits_v2等。 2 数据处理 2.1 导入相关包 import tensorflow as tf import num

空字符 714

TensorFlow实践——Softmax Regression

Softmax Regression是Logistic回归在多分类上的推广,对于Logistic回归以及Softmax Regression的详细介绍可以参见: 简单易学的机器学习算法——Logistic回归 利用Theano理解深度学习——Logistic Regression 深度学习算法原理——Softmax Regression 下面的代码是利用TensorFlow基本API实现的...

null的专栏 1418

基于tensorflow的mnist的softmax分类

基于tensorflow的mnist的softmax分类 softmax回归是一个简单的分类模型,正确率在mnist测试集上达到91.74%。 主要由以下几个模块构成: 预处理部分:数据的读取,占位符和变量的定义; 迭代处理部分:损失函数和优化损失函数的优化方法定义; 后续评估部分:准确率的定义; 最后,启动sess实现,通过优化损失函数得到最优的参数,并在测试集上进行预测得到模型准确率。 ...

weixin_40711045的博客 344

TensorFlow实现Softmax回归

相比线性回归,Softmax只多一个分类的操作,即预测结果由连续值变为离散值,为了实现这样的结果,我们可以使最后一层具有多个神经元,而输入不变,其结构如图所示:为了实现分类,我们使用一个Softmax操作,Softmax函数能够将未规范化的预测变换为非负数并且总和为1,同时让模型保持可导的性质。为了完成这一目标,我们首先对每个未规范化的预测求幂,这样可以确保输出非负。为了确保最终输出的概率值总和为1,我们再让每个求幂后的结果除以它们的总和。

2301_79335566的博客 1276

TensorFlow Softmax

TensorFlow Softmax The softmax 函数可以把它的输入,通常被称为 logits 或者 logit scores,处理成 0 到 1 之间,并且能够把输出归一化到和为 1。这意味着 softmax 函数与分类的概率分布等价。它是一个网络预测多酚类问题的最佳输出激活函数。 softmax

ncst 840
上一篇: torch中关于torch.max()和torch.min()函数的理解
下一篇: tensorflow之pb文件保存与载入
LiBin1103
博客等级 码龄9年 38粉丝 68原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值