def knn_curve():

    # Load training and test data
    train_data, train_labels, train_feature_labels = util.create_dataset(
        1, 1, 'brain')
    test_data, test_labels, test_feature_labels = util.create_dataset(
        2, 1, 'brain')
    # Normalize data
    train_data, test_data = seg.normalize_data(train_data, test_data)

    #Define parameters
    num_iter = 3
    train_size = 100
    k = np.array([1, 3, 5, 9, 15, 25, 100])
    # k = np.array([1, 5, 9])

    #Store errors
    test_error = np.empty([len(k), num_iter])
    test_error[:] = np.nan
    dice = np.empty([len(k), num_iter])
    dice[:] = np.nan

    ## Train and test with different values

    for i in np.arange(len(k)):
        for j in np.arange(num_iter):
            print('k = {}, iter = {}'.format(k[i], j))
            #Subsample training set
            ix = np.random.randint(len(train_data), size=train_size)
            subset_train_data = train_data[ix, :]
            subset_train_labels = train_labels[ix, :]

            predicted_test_labels = seg.knn_classifier(subset_train_data,
                                                       subset_train_labels,
                                                       test_data, k[i])

            # #Train classifier
            # neigh = KNeighborsClassifier(n_neighbors=k[i])
            # neigh.fit(subset_train_data, subset_train_labels)
            # #Evaluate
            # predicted_test_labels = neigh.predict(test_data)

            test_error[i,
                       j] = util.classification_error(test_labels,
                                                      predicted_test_labels)
            dice[i, j] = util.dice_overlap(test_labels, predicted_test_labels)

    ## Display results
    fig = plt.figure(figsize=(8, 8))
    ax1 = fig.add_subplot(111)
    p1 = ax1.plot(k, np.mean(test_error, 1), 'r', label='error')
    p2 = ax1.plot(k, np.mean(dice, 1), 'k', label='dice')
    ax1.set_xlabel('k')
    ax1.set_ylabel('error')
    ax1.grid()
    ax1.legend()
def segmentation_mymethod(train_data,
                          train_labels,
                          test_data,
                          test_labels,
                          task='brain',
                          method='nearest neighbour',
                          testDice=True):
    # segments the image based on your own method!
    # Input:
    # train_data_matrix   num_pixels x num_features x num_subjects matrix of
    # features
    # train_labels_matrix num_pixels x num_subjects matrix of labels
    # test_data           num_pixels x num_features test data
    # task           String corresponding to the segmentation task: either 'brain' or 'tissue'
    # Output:
    # predicted_labels    Predicted labels for the test slice

    #------------------------------------------------------------------#
    #TODO: Implement your method here
    if method == 'kmeans':
        predicted_labels = seg.kmeans_clustering(test_data, K=4)
    elif method == 'nearest neighbour':
        predicted_labels = seg.nn_classifier(train_data, train_labels,
                                             test_data)
    elif method == 'knn':
        predicted_labels = seg.knn_classifier(train_data,
                                              train_labels,
                                              test_data,
                                              k=4)
    elif method == 'atlas':
        predicted_labels = seg.segmentation_atlas(train_data, train_labels,
                                                  test_data)

    predicted_labels = predicted_labels.astype(bool)
    test_labels = test_labels.astype(bool)

    err = util.classification_error(test_labels, predicted_labels)
    print('Error:\n{}'.format(err))

    if testDice:
        dice = util.dice_multiclass(test_labels, predicted_labels)
        print('Dice coefficient:\n{}'.format(dice))
    #------------------------------------------------------------------#
    return predicted_labels
Beispiel #3
0
def segmentation_mymethod(train_data_matrix, train_labels_matrix, test_data, task='tissue'):
    # segments the image based on your own method!
    # Input:
    # train_data_matrix   num_pixels x num_features x num_subjects matrix of
    # features
    # train_labels_matrix num_pixels x num_subjects matrix of labels
    # test_data           num_pixels x num_features test data
    # task           String corresponding to the segmentation task: either 'brain' or 'tissue'
    # Output:
    # predicted_labels    Predicted labels for the test slice

    #------------------------------------------------------------------#
    #TODO: Implement your method here

    choice_br=[0,1,5,6,7]
    train_data= train_data_matrix[:,:,1]
    train_labels=train_labels_matrix[:,1]
    ix = np.random.randint(len(train_data), size=1000)

    train_datann = train_data[:,choice_br]
    train_datann = train_datann[ix,:]

    train_labels_brain = train_labels>0
    train_labelsnn = train_labels_brain[ix]

    test_datann = test_data[:,choice_br]

    predicted_labelsnn = seg.knn_classifier(train_datann, train_labelsnn, test_datann, 35)
    predicted_masknn = predicted_labelsnn.reshape(I.shape)
    openimage = scipy.ndimage.morphology.binary_opening(predicted_masknn, iterations=2)
    op_imf = openimage.flatten().T.astype(float)
    op_imf = op_imf.reshape(-1, 1)

    train_data_brain = train_data*op_imf
    train_labels_brain = train_data*op_imf




    #------------------------------------------------------------------#
    return predicted_labels