示例#1
0
def SelfOrganizingMap(Feature_List):
    som = SOM(SOM_LINES, SOM_COLS, len(Feature_List[0]), SOM_ITERATIONS)
    som.train(Feature_List)

    image_grid = som.get_centroids()
    mapped = som.map_vects(Feature_List)

    return mapped, image_grid
def SelfOrganizingMap(feature_list):
    no_features = len(feature_list[0])
    print('Clustering', no_features, 'features')
    som = SOM(SOM_LINES, SOM_COLS, no_features, SOM_ITERATIONS, alpha=ALPHA, sigma=SIGMA)
    som.train(feature_list)

    image_grid = som.get_centroids()
    mapped = som.map_vects(feature_list)

    return mapped, image_grid
示例#3
0
def main():
    # Training inputs for RGBcolors
    credits_data = pd.read_csv("testdata/credit_train.csv", header=None)
    columns = credits_data.columns
    train_data = credits_data[columns[:-1]].copy().values
    label_data = credits_data[columns[-1]].copy().values
    train_data_scale = preprocessing.scale(train_data)
    # colors = np.array(
    #     [[0., 0., 0.],
    #      [0., 0., 1.],
    #      [0., 0., 0.5],
    #      [0.125, 0.529, 1.0],
    #      [0.33, 0.4, 0.67],
    #      [0.6, 0.5, 1.0],
    #      [0., 1., 0.],
    #      [1., 0., 0.],
    #      [0., 1., 1.],
    #      [1., 0., 1.],
    #      [1., 1., 0.],
    #      [1., 1., 1.],
    #      [.33, .33, .33],
    #      [.5, .5, .5],
    #      [.66, .66, .66]])
    # color_names = \
    #     ['black', 'blue', 'darkblue', 'skyblue',
    #      'greyblue', 'lilac', 'green', 'red',
    #      'cyan', 'violet', 'yellow', 'white',
    #      'darkgrey', 'mediumgrey', 'lightgrey']

    # Train a 20x30 SOM with 400 iterations
    som = SOM(1, 2, len(columns) - 1, 400)
    som.train(train_data_scale)

    # Get output grid
    image_grid = som.get_centroids()

    # Map colours to their closest neurons
    mapped = som.map_vects(train_data_scale)

    # Plot
    plt.imshow(image_grid)
    plt.title('Color SOM')
    for i, m in enumerate(mapped):
        plt.text(m[1],
                 m[0],
                 label_data[i],
                 ha='center',
                 va='center',
                 bbox=dict(facecolor='white', alpha=0.5, lw=0))
    plt.show()
示例#4
0
def som_plot(img, som_dim):
    # Method for creating a small Kohonen Self-Organizing Map (SOM) of the image and
    # plotting the SOM on the screen. RGB values of the colors are printed on the screen.

    # Select small amount of random pixels from the image.
    n_pixels = 500

    colors = shuffle(img.reshape((img.shape[0] * img.shape[1], 3)))[:n_pixels]

    print('\n')
    print('=' * 80)
    print('Self-Organized Map of {} randomly picked colors:'.format(som_dim *
                                                                    som_dim))

    # Train the SOM model with small amount of iterations.
    som = SOM(som_dim, som_dim, 3, 10)
    som.train(colors)

    #Get output grid from the SOM. This is plotted as color palette.
    image_grid = som.get_centroids()
    plt.figure(figsize=(5, 5))
    plt.imshow(image_grid)
    plt.title('Color map')
    plt.show()

    # Create RGB palette values from the image_grid.
    grid = np.array(image_grid)
    grid *= 255
    grid = grid.astype(np.int)
    rgb_df = pd.DataFrame(np.zeros((som_dim, som_dim)))
    hex_df = pd.DataFrame(np.zeros((som_dim, som_dim)))

    for i in range(som_dim):
        for j in range(som_dim):
            rgb_df.iloc[i, j] = str(grid[i, j])
            hex_color = '#{:02x}{:02x}{:02x}'.format(grid[i, j, 0],
                                                     grid[i, j, 1], grid[i, j,
                                                                         2])
            hex_df.iloc[i, j] = hex_color

    print('RGB values:')
    print(rgb_df)
    print('\n')
    print('HEX color values:')
    print(hex_df)
示例#5
0
    def som3(self, m, n, dim, iterations):
        # step 4
        trainData = numpy.zeros((len(self.contrastPoints), 3))

        for i in range(len(self.contrastPoints)):
            trainData[i] = [self.diagonalContrast[i], self.verticalContrast[i], self.horizontalContrast[i]]

        som = SOM(m, n, dim, iterations)
        som.train(trainData)    
        mapped = som.map_vects(trainData)
        d0 = 0
        d1 = 0
        d2 = 0

        for d, m in zip(trainData, mapped):
            mapv = m[0] + m[1]
            
            if (d0 == 0 and mapv == 0):
                d0 = d[0] if d0 < d[0] else d0

            if (d1 == 0  and mapv == 1):    
                d1 = d[0] if d1 < d[0] else d1
                
            if (d2 == 0  and mapv == 2): 
                d2 = d[0] if d2 < d[0] else d2
                
        arr = numpy.array([d0, d1, d2])
        most = numpy.argmax(arr)
        numpy.delete(arr, most, 0)
        least = numpy.argmin(arr)
        numpy.delete(arr, least, 0)
        mean = 0 if (arr[most] == d1 or arr[most] == d2) and (arr[least] == d1 or arr[least] == d2) else (1 if (arr[most] == d0 or arr[most] == d2) and (arr[least] == d0 or arr[least] == d2) else 2)
       
        self.mappingDict = {'least':  least, 'mean': mean, 'most': most}  
        self.blocksMapping = mapped
        self.neuronsMap = som.get_centroids()
    inputFilename = 'myo_raw_data.csv'
    header = '% qx, qy, qz, qw, ax, ay, az, gx, gy, gz\n'

    try:
        f = open(inputFilename, 'r')
    except Exception as error:
        print("ERROR: Couldn't read from {}".format(inputFilename))
    else:
        with f:
            reader = csv.reader(f)
            for row in reader:
                if row[0][0] is not '%':
                    myo_data.append(row)
            print myo_data[0]

    #Training inputs for Myo data (quat, accel, gyro)
    som_data = np.array(myo_data)

    #Train a 20x30 SOM with 400 iterations
    som = SOM(SOM_X, SOM_Y, MYO_DATA_DIM, SOM_ITER)
    som.train(som_data)

    #Get output grid
    image_grid = som.get_centroids()

    #Plot
    plt.imshow(image_grid)
    plt.title('Myo SOM')
    plt.show()
def SelfOrganizingMap(Feature_List, where):
    if not os.path.exists(where):
        os.makedirs(where)

    som = SOM(SOM_LINES, SOM_COLS, len(Feature_List[0]), NUM_ITERATIONS)
    som.train(Feature_List)
    # Get output grid
    image_grid = som.get_centroids()
    #print 'Image grid shows weights for all the input features'
    #print image_grid
    # Get vector mappings
    mapped = som.map_vects(Feature_List)
    #print 'Mapping', mapped

    # Visualization part
    # Needs to be refactored to produce output for any number of clusters
    avg_line = []
    for i in range(NUM_CLUST):
        avg_line.append(0)
    avg_column = []
    for i in range(NUM_CLUST):
        avg_column.append(0)

    for i in range(0, len(mapped), NUM_CLUST):
        for j in range(NUM_CLUST):
            avg_line[(i + j) % NUM_CLUST] += mapped[i + j][0]
            avg_column[(i + j) % NUM_CLUST] += mapped[i + j][1]

    for i in range(len(avg_line)):
        avg_line[i] = avg_line[i] / (len(mapped) / NUM_CLUST)

    for i in range(len(avg_column)):
        avg_column[i] = avg_column[i] / (len(mapped) / NUM_CLUST)

    'Average location'
    print avg_line, avg_column

    # Grayscale landscape
    sorting_landscape = []
    for i in range(NUM_CLUST):
        sorting_landscape.append(np.zeros((SOM_LINES, SOM_COLS), np.float16))

    for i in range(len(mapped)):
        lin = mapped[i][0]
        col = mapped[i][1]
        sorting_landscape[i % NUM_CLUST][lin][col] += 0.05
        if sorting_landscape[i % NUM_CLUST][lin][col] > 1.0:
            sorting_landscape[i % NUM_CLUST][lin][col] = 1.0

    for i in range(NUM_CLUST):
        sorting_landscape[i][avg_line[i]][avg_column[i]] = 1.0

    for i in range(NUM_CLUST):
        io.imsave(where + str(i) + '_sorting_cluster.png',
                  sorting_landscape[i])

    # Colored landscape
    colored_landscape = np.zeros((SOM_LINES, SOM_COLS, 3), np.float16)
    white = np.array([1.0, 1.0, 1.0])

    # sorting
    insertion_color = np.array([0.0, 0.0, 1.0])  # blue
    bubble_color = np.array([0.0, 1.0, 0.0])  # green
    heap_color = np.array([1.0, 0.0, 0.0])  # red
    quick_color = np.array([1.0, 0.0, 1.0])  # magenta
    random_color = np.array([1.0, 1.0, 0.0])  # yellow

    # non-sorting
    reverseSorted_color = np.array([0.0, 1.0, 1.0])  # cyan
    intervalSwapSorted_color = np.array([1.0, 0.5, 0.0])  # orange
    reverse_color = np.array([0.5, 1.0, 0.0])  # lime-green
    intervalSwap_color = np.array([1.0, 0.0, 0.5])  # fuchsia

    colored = [
        insertion_color, bubble_color, heap_color, quick_color, random_color
    ]
    #add_colored = [reverseSorted_color, intervalSwapSorted_color, reverse_color, intervalSwap_color]
    #colored.extend(add_colored)

    grad = 0.005
    for i in range(len(mapped)):
        lin = mapped[i][0]
        col = mapped[i][1]
        colored_landscape[lin][col] += grad * colored[i % NUM_CLUST]
        #if colored_landscape[lin][col].any() > 1.0:
        #	colored_landscape[lin][col] -= 0.05*colored[i%NUM_CLUST]

    for i in range(NUM_CLUST):
        colored_landscape[avg_line[i]][
            avg_column[i]] = 0.3 * white + 0.7 * colored[i]

    io.imsave(where + 'all_sorting_clusters.png', colored_landscape)