Beispiel #1
0
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 14 16:11:37 2014

@author: Christoph Lassner
"""
import os
import sys
sys.path.insert(0, os.path.join('..', '..', 'build', 'bindings', 'python'))

import numpy as np
import fertilized
soil = fertilized.Soil('d', 'd', 'd', fertilized.Result_Types.regression)

tree = soil.StandardRegressionTree(1, 0, 1, 5, 2, 4)

X = np.array([[0.], [0.]])
Y = np.array([[0.], [10**3]])
tree.fit(X, Y)

print('Tree: %f, STD: %f' %
      (np.sqrt(tree.predict(np.array([[0.]]))[0, 1]), np.std(Y[:, 0])))

if os.name == 'nt':
    tree.save('tree_windows.ft')
else:
    tree.save('tree_linux.ft')
import numpy as np
np.random.seed(8)
from plottools import make_spiral, point_prob_plot, probaproxy, accuracy_score
#plt.rc('text', usetex=True)
#plt.rc('font', family='serif')
np.random.seed(1)

#%% Prepare...
n_classes = 2
n_trees = 200
ploty = [-6, 6, 100]
plotx = [-6, 6, 100]
X, Y = make_spiral(n_arms=n_classes, noise=.4)

# Forest.
soil = f.Soil()
dec_name = 'quadratic'
rs = 1
suggestions = 5
depth = 5
if dec_name == 'aligned':
    feat_sel_prov = soil.StandardFeatureSelectionProvider(2,
                                                          1,
                                                          2,
                                                          2,
                                                          random_seed=rs)
else:
    feat_sel_prov = soil.StandardFeatureSelectionProvider(1, 2, 2, 2)
if dec_name == 'aligned':
    feat_calc = soil.AlignedSurfaceCalculator()
elif dec_name == 'linear':
if INTERACTIVE:
    import matplotlib.pyplot as plt

import numpy as np
from plottools import make_spiral, point_prob_plot, accuracy_score
np.random.seed(1)

# Prepare...
n_classes = 3
n_trees = 200
ploty = [-6, 6, 100]
plotx = [-6, 6, 100]
X, Y = make_spiral(n_arms=n_classes, noise=.4)

#%%
soil = f.Soil('float', 'float', 'uint', f.Result_Types.probabilities)
for depth in [3, 6, 15]:
  cls = []
  lm = []
  for i in range(n_trees):
    cls.append(soil.ThresholdDecider(
                  soil.StandardFeatureSelectionProvider(1, 2, 2, 2),
#                  soil.AlignedSurfaceCalculator(),
#                  soil.LinearSurfaceCalculator(400, random_seed=1+i),
                  soil.QuadraticSurfaceCalculator(400,
                                                  np.array([X[:, 0].min(),
                                                            X[:, 0].max(),
                                                            X[:, 1].min(),
                                                            X[:, 1].max()], dtype='float'),
                                                  random_seed=1+i),
                  soil.ClassificationThresholdOptimizer(True,
Beispiel #4
0
                os.path.join(root_dir, image_dir,
                             'image-%03d.png' % (neg_idx)))))
    assert not images[-1] is None
    annotations[pos_offset + neg_number * n_samples_neg:pos_offset +
                (neg_number + 1) * n_samples_neg,
                0] = neg_number + len(train_pos_ids)
    annotations[pos_offset+neg_number*n_samples_neg : pos_offset+(neg_number+1)*n_samples_neg, 1] = \
                  np.random.randint(patch_size[1] // 2,
                                    images[-1].shape[1] - patch_size[1] // 2,
                                    size=(n_samples_neg,))
    annotations[pos_offset+neg_number*n_samples_neg : pos_offset+(neg_number+1)*n_samples_neg, 2] = \
                  np.random.randint(patch_size[0] // 2,
                                    images[-1].shape[0] - patch_size[0] // 2,
                                    size=(n_samples_neg,))
#%% Feature extraction.
soil = fertilized.Soil('uint8', 'int16', 'int16',
                       fertilized.Result_Types.hough_map)
if os.path.isfile('feat_images.pkl'):
    with open('feat_images.pkl', 'r') as f:
        feat_images = pickle.load(f)
else:
    cvimages = []
    for im in images:
        if im.ndim == 2:
            cvimages.append(np.ascontiguousarray(skimage.color.gray2rgb(im)))
        else:
            cvimages.append(np.ascontiguousarray(im[:, :, :3]))
    feat_images = [
        soil.extract_hough_forest_features(im, full=(n_feature_channels == 32))
        for im in cvimages
    ]
    with open('feat_images.pkl', 'w') as f:
"""
Created on Fri Mar 13 11:40:48 2015

@author: christoph
"""
import os
import sys
sys.path.insert(0, os.path.join('..', '..', 'build', 'bindings', 'python'))

import numpy as np
import numpy.testing as npt
import fertilized

###############################################################################
# Check the availability (since it's an optional module).
soil = fertilized.Soil()
try:
    extractor = soil.DNNFeatureExtractor(True) # CPU only.
except:
    print("The library has been built without caffe. Features cannot be extracted.")
    sys.exit(0)

###############################################################################
# Prepare the images.
from PIL import Image
timage_zeros = np.zeros((227, 227, 3), dtype='float32')
timage_ones = np.ones((227, 227, 3), dtype='float32')
timage_opencv = np.array(Image.open(os.path.join(os.path.dirname(__file__), 'sample-resized.png'))).astype('float32')
timage_opencv = np.ascontiguousarray(timage_opencv[:, :, ::-1])

# Assume the image has had its means subtracted already.
Beispiel #6
0
                             size=(n_samples, input_dim)).astype('float32')
samplesY = (samplesX**2) - 0.2 * samplesX - 1
noise_var = 2.3
random_noise = np.random.randn(n_samples, annot_dim) * noise_var
samplesY += random_noise

# Define the plotted space
minX = samplesX.min()
maxX = samplesX.max()
deltaX = (maxX - minX)
minY = samplesY.min()
maxY = samplesY.max()
deltaY = (maxY - minY)
plotX = [minX - 0.2 * deltaX, maxX + 0.2 * deltaX, 100]
plotY = [minY - 0.2 * deltaY, maxY + 0.2 * deltaY, 100]

# Create and fit a <float> regression forest
soil = f.Soil('f', 'f', 'f', f.Result_Types.regression)
n_trees = 10
max_depth = 2
n_thresholds = 2
forest = soil.StandardRegressionForest(input_dim, max_depth, 1, n_thresholds,
                                       n_trees, 3, 6)
forest.fit(samplesX, samplesY, 8)

# Plot the result
plt.figure()
forest_probabilistic_plot(forest, samplesX, samplesY, plotX, plotY)
plt.savefig('regression_prob.png')
plt.show()