代码之家  ›  专栏  ›  技术社区  ›  NoBugs

这个简单的Keras神经网络计算结果如何?

  •  1
  • NoBugs  · 技术社区  · 6 年前

    我想了解一个简单的正向神经网络是如何工作的…从示例开始,这里是

    导入必要的包 来自sklearn.preprocessing import labelencoder 来自sklearn.model_selection import train_test_split 从keras.models导入序列 从keras.layers导入激活 从keras.optimizers导入SGD 从keras.layers导入密集 从keras.utils导入np-utils 从imutils导入路径 将numpy导入为np 导入AgPARSE 导入CV2 导入操作系统 def image_to_feature_vector(图像,大小=(32,32)): #将图像调整为固定大小,然后将图像展平为 #原始像素强度列表 返回cv2.resize(图像,大小).flatten()。 #构造参数解析并分析参数 ap=argparse.argumentParser()。 ap.add_参数(“-m”,“-model”,必需=true, 帮助=“输出模型文件的路径”) args=vars(ap.parse_args()) #获取我们将要描述的图像列表 #打印(“[信息]描述图像…) #imagepaths=list(paths.list_images(args[“dataset”])) ##初始化数据矩阵和标签列表 数据=[] 标签[= ] ##循环输入图像 #对于枚举(imagepaths)中的(i,imagepath): ##加载图像并提取类标签(假设 ##路径格式为:/path/to/dataset/class.image.jpg #image=cv2.imread(图像路径) #label=imagepath.split(os.path.sep)[-1].split(“.”)拆分[0] ##构造特征向量原始像素强度,然后更新 ##数据矩阵和标签列表 #特征=图像到特征向量(图像) #data.append(功能) #labels.append(标签) ##每1000个图像显示一次更新 #如果i>0和i%1000==0: #打印(“[信息]已处理/”。格式(i,len(imagepaths))) 打印(标签) (x)退出() 数据=[[0,0]、[0,1]、[1,0]、[1,1]] 标签=[0,0,0,1] #对标签进行编码,将其从字符串转换为整数 le=标签编码器()) labels=le.fit_转换(标签) #将输入图像像素缩放到范围[0,1],然后转换 #标签转换为范围[0,num_classes]中的向量——这个 #为每个标签生成一个向量,其中标签的索引 #设置为“1”,所有其他条目设置为“0”` 数据=np.数组(数据)/255.0 labels=np-utils.to-u分类(labels,2) #将数据分成培训和测试部分,使用75% #培训数据和剩余25%的测试数据 打印(“[信息]构建培训/测试拆分…) (traindata、testdata、trainlabels、testlabels)=train-test-split( 数据,标签,测试尺寸=0.0,随机状态=42) 打印(“火车”) 打印(traindata) 打印(训练标签) 打印(“测试”) 打印(测试数据)oopse,空… 打印(测试标签) 测试数据=训练数据 testLabels=训练标签 #定义网络的体系结构 模型=顺序() model.add(密集(2,input_dim=2,kernel_initializer=“uniform”, activation=“relu”)) model.add(激活(“softmax”)) #使用SGD培训模型 打印(“[信息]编译模型…) sgd=sgd(lr=0.35) model.compile(loss=“binary_cross熵”,optimizer=sgd, 指标=[“准确度”]) 打印(型号匹配文件) 型号匹配(traindata,trainlabels,epochs=50,批量大小=128, 冗长=假 print(model.predict(np.array([[0,1]]))) print('应该是[1,0]')false print(model.predict(np.array([[1,0]]))) print('应该是[1,0]')false print(model.predict(np.array([[0,0]]))) print('应该是[1,0]')false print(model.predict(np.array([[1,1]]))) print('应为[0,1]真') #显示测试集的精度 打印(“[信息]测试集评估…”) (损失,准确度)=model.evaluate(测试数据,测试标签, 批处理大小=128,详细信息=1) 打印(“[info]loss=:.4f,精度::.4f%”。格式(loss, 精度*100) #将网络架构和权重转储到文件 打印(“[信息]将架构和权重转储到文件…) model.save(参数[“model”]) < /代码>

    现在,当使用 python3./simple ou andnn.py--model./outputfile.hdf5 i可以在hdfview应用程序中打开输出模型,这就是我看到的:

    现在,我希望[1 1]的值(唯一一个在正组中分类的值, result=[smaller,larger number] )是矩阵的点积( the kernel. matrix in this simple case?加上一些恒定的偏差,但当我尝试时,它似乎不加上输出所说的任何内容。我是否误解了这个“神经元”基于这些数据应该做什么?我把它简化成一个训练器,它通常能给出100%准确的“和”神经元:

    # import the necessary packages
    from sklearn.preprocessing import LabelEncoder
    from sklearn.model_selection import train_test_split
    from keras.models import Sequential
    from keras.layers import Activation
    from keras.optimizers import SGD
    from keras.layers import Dense
    from keras.utils import np_utils
    from imutils import paths
    import numpy as np
    import argparse
    import cv2
    import os
    
    def image_to_feature_vector(image, size=(32, 32)):
        # resize the image to a fixed size, then flatten the image into
        # a list of raw pixel intensities
        return cv2.resize(image, size).flatten()
    
    # construct the argument parse and parse the arguments
    ap = argparse.ArgumentParser()
    ap.add_argument("-m", "--model", required=True,
        help="path to output model file")
    args = vars(ap.parse_args())
    
    # grab the list of images that we'll be describing
    #print("[INFO] describing images...")
    #imagePaths = list(paths.list_images(args["dataset"]))
    
    ## initialize the data matrix and labels list
    #data = []
    #labels = []
    
    ## loop over the input images
    #for (i, imagePath) in enumerate(imagePaths):
        ## load the image and extract the class label (assuming that our
        ## path as the format: /path/to/dataset/{class}.{image_num}.jpg
        #image = cv2.imread(imagePath)
        #label = imagePath.split(os.path.sep)[-1].split(".")[0]
    
        ## construct a feature vector raw pixel intensities, then update
        ## the data matrix and labels list
        #features = image_to_feature_vector(image)
        #data.append(features)
        #labels.append(label)
    
        ## show an update every 1,000 images
        #if i > 0 and i % 1000 == 0:
            #print("[INFO] processed {}/{}".format(i, len(imagePaths)))
    #print(labels)
    #exit()
    data = [[0,0],[0,1],[1,0],[1,1]]
    labels = [0,0,0,1]
    
    # encode the labels, converting them from strings to integers
    le = LabelEncoder()
    labels = le.fit_transform(labels)
    
    # scale the input image pixels to the range [0, 1], then transform
    # the labels into vectors in the range [0, num_classes] -- this
    # generates a vector for each label where the index of the label
    # is set to `1` and all other entries to `0`
    data = np.array(data)# / 255.0
    labels = np_utils.to_categorical(labels, 2)
    
    # partition the data into training and testing splits, using 75%
    # of the data for training and the remaining 25% for testing
    print("[INFO] constructing training/testing split...")
    (trainData, testData, trainLabels, testLabels) = train_test_split(
        data, labels, test_size=0.0, random_state=42)
    print('train')
    print(trainData)
    print(trainLabels)
    print('test')
    print(testData) #oopse, empty...
    print(testLabels)
    testData = trainData
    testLabels = trainLabels
    
    # define the architecture of the network
    model = Sequential()
    model.add(Dense(2, input_dim=2, kernel_initializer="uniform",
        activation="relu"))
    model.add(Activation("softmax"))
    
    # train the model using SGD
    print("[INFO] compiling model...")
    sgd = SGD(lr=0.35)
    model.compile(loss="binary_crossentropy", optimizer=sgd,
        metrics=["accuracy"])
    print(model.fit.__doc__)
    model.fit(trainData, trainLabels, epochs=50, batch_size=128,
        verbose=False)
    
    print(model.predict(np.array([[0,1]])))
    print('Should be [1,0]')#false
    print(model.predict(np.array([[1,0]])))
    print('Should be [1,0]')#false
    print(model.predict(np.array([[0,0]])))
    print('Should be [1,0]')#false
    print(model.predict(np.array([[1,1]])))
    print('Should be [0,1] true.')
    # show the accuracy on the testing set
    print("[INFO] evaluating on testing set...")
    (loss, accuracy) = model.evaluate(testData, testLabels,
        batch_size=128, verbose=1)
    print("[INFO] loss={:.4f}, accuracy: {:.4f}%".format(loss,
        accuracy * 100))
    
    # dump the network architecture and weights to file
    print("[INFO] dumping architecture and weights to file...")
    model.save(args["model"])
    

    现在运行它时 python3 ./simple_andNN.py --model ./outputfile.hdf5 我可以在hdfview应用程序中打开输出模型,如下所示:

    output of command

    现在,我期望[1 1]的值(唯一一个属于正组的值, 结果=[较小,较大的数字] )是矩阵的点积( 这个 内核 矩阵在这个简单的例子中? ,再加上一些恒定的偏差,但当我尝试时,它似乎并没有加上输出所说的任何内容。我是否误解了这个“神经元”基于这些数据应该做什么?

    1 回复  |  直到 6 年前
        1
  •  1
  •   dashnick    6 年前

    你在你的 print 语句位于 softmax 操作。

    [1 1] . [-.70 .77; -.64 .81] + [1.9 -0.62] = [.53 .96]

    然后

    exp(.53) = 1.69, exp(.96) = 2.62

    结果就是

    [1.69/(1.69+2.62) 2.62/(1.69+2.62)] = [.39 .61]

    (明显有舍入误差)

    同样要注意的是,在使用SoftMax之前, relu 激活,但由于这是正数的标识,因此它对 [1 1] 例子。这将对 [1 0] 例如,作为 Wx + b 为负,然后将其归零。