예제 #1
0
    def procedure(self):
        best_ = np.Inf
        best_sol = []

        self.gd.build(self.greedyness, best_sol)
        best_ = f(best_sol, self._adj_matrix)

        for iter in range(self.Max):
            new_sol = []
            self.gd.build(self.greedyness, new_sol)
            #Entrada que o shift 2 piora
            #new_sol = [0, 2, 4, 1, 3, 0]
            new_ = f(new_sol, self._adj_matrix)
            aux_sol = [i for i in new_sol]
            aux_ = new_
            print('s=', aux_)

            iterIls = 0
            while iterIls < self.MaxIls:
                #debug
                #print((new_sol, new_))

                new_sol = RVND(new_sol, self._adj_matrix, self.cache).execute()
                new_ = f(new_sol, self._adj_matrix)
                #debug
                #print((new_sol, new_))

                if aux_ > new_:
                    aux_ = new_
                    aux_sol = [i for i in new_sol]
                    iterIls = 0

                #falta a pertubação
                n = 5
                x = (len(aux_sol)) // n
                s = [aux_sol[1:x], aux_sol[(n - 1) * x:len(aux_sol) - 1]]
                for i in range(1, n - 1):
                    a = choice([-1, 1])
                    s.append(aux_sol[i * x:(i + 1) * x][::a])
                shuffle(new_sol)
                a = []
                for e in s:
                    a += e
                new_sol = [0] + a + [0]
                new_ = f(new_sol, self._adj_matrix)
                print("p =", new_)

                iterIls += 1

            if best_ > aux_:
                best_sol = aux_sol
                best_ = aux_

            Verbosity.show("{}/{} b={} a={}".format(iter + 1, self.Max, best_,
                                                    aux_))
        return (best_sol, best_)
예제 #2
0
def one_epoch():
    is_changed = 0
    for x in dataset:
        x1, x2 = x
        correct = tools.f(x1, x2)
        neuron_output = weights[0] + weights[1] * x1 + weights[2] * x2
        result = tools.signum(neuron_output)

        d = correct - result

        if not d:
            continue

        weights[0] += tools.weight_delta(d, 1, weights[0])
        weights[1] += tools.weight_delta(d, x1, weights[1])
        weights[2] += tools.weight_delta(d, x2, weights[2])
        tools.save_weights(weights)

        is_changed = 1

    return is_changed
예제 #3
0
    def ml_features_normal(self, features):
        from pyspark.ml.linalg import Vectors
        from pyspark.ml.feature import Normalizer
        from pyspark.ml.classification import NaiveBayes
        from tools import f
        features.foreach(print)
        fea_df = features.map(lambda i: Row(**f(i))).toDF()
        # fea_df.show()
        normalizer = Normalizer().setInputCol('features').setOutputCol(
            'norfeatures').setP(1.0)
        norfea_df = normalizer.transform(fea_df)
        # norfea_df.show()
        train_dt, test_dt = norfea_df.randomSplit([0.8, 0.2])
        nvby = NaiveBayes(modelType="multinomial", smoothing=0.1)
        nvby_mod = nvby.fit(dataset=train_dt)

        predictRDD = nvby_mod.transform(test_dt).rdd
        count = predictRDD.count()
        print(
            predictRDD.map(lambda i: (i.label, i.prediction)).filter(
                lambda i: i[0] == i[1]).count() / count)
예제 #4
0
        os.makedirs(savepath)
except:
    pass

if not Path.exists(
        savepath / 'config.json'):  # Only create json if it does not exist
    with open(savepath / 'config.json', 'w') as fd:
        json.dump(vars(args), fd)

# Generate data and create dataset
torch.manual_seed(args.dataset_seed)
np.random.seed(args.dataset_seed)
random.seed(args.dataset_seed)

X = (np.random.rand(10).reshape(-1, 1) - 1) / 2  # x between -0.5 and 0.
Y = f(X)
X = torch.from_numpy(X).type(torch.FloatTensor)
Y = torch.from_numpy(Y).type(torch.FloatTensor)

dataset = RegressionDataset(X, Y)

# Reproducibility
if args.seed is not None:
    torch.manual_seed(args.seed)
    np.random.seed(args.seed)
    random.seed(args.seed)

net = MLP()
criterion = nn.MSELoss()
optimizer = optim.Adam(net.parameters(), lr=args.lr, weight_decay=args.wd)
예제 #5
0
import numpy
import sys
import tools
import TypeX
import TypeY
from matplotlib.pylab import *

I = numpy.arange(0.0,1.05,0.05)
f = []

string = "Plotting the firing rate of the neuron versus the amplitude"
string += "\r\n"
string += "of injecting step current. It may take several minutes ... "
string += "\r\n"

print string

for x in I:
    # watch progress
    print x
    sys.stdout.flush()
    f.append(tools.f(TypeX,x))

figure()
plot(I,f)
xlabel('Amplitude of Injecting step current (pA)')
ylabel('Firing rate (Hz)')
grid()
show()
예제 #6
0
###################################################

# try genetic algorithm ###########################
bests_percent, bests_min, bests_max = (10, 30, 500)
iter_count = 1000
resets_count = 100
mutations_count_percent = 60
generation = all_attributes.copy()

f_min = sys.float_info.max
opt_values = []
time_to_reset = int(iter_count / resets_count)
time_to_reset_initial = int(iter_count / resets_count)
for i in range(iter_count):
    f_vals = [f(*attributes) for attributes in generation]

    bests_count = int(np.ceil(len(f_vals) * bests_percent / 100))
    if bests_count < bests_min:
        bests_count = bests_min
    elif bests_count > bests_max:
        bests_count = bests_max

    f_vals_bests_sorted = sorted(f_vals)[:bests_count]

    f_min = f_vals_bests_sorted[0]

    generation_bests = [
        generation[f_vals.index(best)] for best in f_vals_bests_sorted
    ]
예제 #7
0
        d = correct - result

        if not d:
            continue

        weights[0] += tools.weight_delta(d, 1, weights[0])
        weights[1] += tools.weight_delta(d, x1, weights[1])
        weights[2] += tools.weight_delta(d, x2, weights[2])
        tools.save_weights(weights)

        is_changed = 1

    return is_changed


i = 0
while one_epoch():
    i += 1
print(i, 'epochs passed.')

# Тесты
for x in dataset:
    x1, x2 = x
    correct = tools.f(x1, x2)
    neuron_output = weights[0] + weights[1] * x1 + weights[2] * x2
    result = tools.signum(neuron_output)
    if result != correct:
        print('Error! Input values: ({}, {})'.format(*x))
        break
예제 #8
0
        os.makedirs(savepath)
except:
    pass

if not Path.exists(
        savepath / 'config.json'):  # Only create json if it does not exist
    with open(savepath / 'config.json', 'w') as fd:
        json.dump(vars(args), fd)

# Generate data and create dataset
torch.manual_seed(args.dataset_seed)
np.random.seed(args.dataset_seed)
random.seed(args.dataset_seed)

X = (np.random.rand(10).reshape(-1, 1) - 1) / 2  # x between -0.5 and 0.
Y = f(X)
X = torch.from_numpy(X).type(torch.FloatTensor)
Y = torch.from_numpy(Y).type(torch.FloatTensor)

# Adding a single point at 0.35
nx = torch.tensor([[.25]]).float()
ny = torch.from_numpy(f(nx)).type(torch.FloatTensor)
X = torch.cat([X, nx])
Y = torch.cat([Y, ny])

dataset = RegressionDataset(X, Y)

# Reproducibility
if args.seed is not None:
    torch.manual_seed(args.seed)
    np.random.seed(args.seed)