示例#1
0
文件: nn.py 项目: hans/selpref
 def train(self, save_path, log, form, dep, lang, examples, dim, batch,
           epoch):
     # TODO train for a parameter M
     exam = []
     for a, v1, v2 in examples:
         if a not in self.vocabulary or v1 not in self.vocabulary or v2 not in self.vocabulary:
             continue
         vec_a = self.embeddings[a]
         vec_v1 = self.embeddings[v1]
         vec_v2 = self.embeddings[v2]
         exam.append((tensor(vec_a), tensor(vec_v1), tensor(vec_v2)))
     self.para = M.train(save_path, log, form, dep, lang, exam, dim, batch,
                         epoch)
     return self.para
示例#2
0
#DaydayUp1
import MyDay as M
'''
def dayUP(df):
    dayup=1
    for i in range(365):
        if i % 7 in[6,0]:
            dayup=(1-0.01)*dayup
        else:
            dayup=(1+df)*dayup
    return dayup
'''
dayfactory = 0.001

while M(dayfactory) < 37.78:
    dayfactory += 0.001
print('{:.3f}'.format(dayfactory))
示例#3
0
文件: pca.py 项目: aphlysia/kaggle
#!/usr/bin/env python

if __name__ == '__main__':
	import M
	import csv
	import numpy as np
	rows = list(csv.reader(open('../csv/train.csv')))
	x, e = M.getColumns(rows, (0, 1, 3, 4), (int, float, lambda x: 1 if x=='male' else 0, float))
	x = np.matrix(x)
	y = x[0,:]   #class
	x = x[1:,:]  #attributes
	pca = M.PCA(x)
	pca.plot(x, c = ['r' if i == 0 else 'b' for i in list(np.array(y)[0])])


示例#4
0
def main():
    m=M()
    t1=T1(m)
    t2=T2(m)
    t1.join()
    t2.join()
示例#5
0
import M

print (M.hello())
print (M.hello("Manu"))

c = M.C1 (2)
print (c.method ("foo"))

print (c.id)
print (c.name)

c.prop = 5   # Calling setter
print c.prop # Calling getter

try:
    print c.wo_prop # Error
except AttributeError:
    print "Expected exception when getting wo_prop"
示例#6
0
import M

print(M.hello())
print(M.hello("Manu"))

print("%1.2f" % M.print_float(1.2))

c = M.C1 (2)
print(c.method ("foo"))

print(c.id)
print(c.name)

c.prop = 5    # Calling setter
print(c.prop) # Calling getter

try:
    print(c.wo_prop) # Error
except AttributeError:
    print("Expected exception when getting wo_prop")

l = M.MyList((1, 2))
print(l)
print(l.dump())
示例#7
0
 def count_finite_det(design, one_purpose):
     return np.linalg.det(M(purpose=one_purpose, design=design,
                            kernel=kernel, p=p, h=h))
示例#8
0
文件: mining.py 项目: aphlysia/kaggle
#!/usr/bin/env python

if __name__ == '__main__':
	import M
	import csv
	import numpy as np
	rows = list(csv.reader(open('../csv/train.csv')))
	'''
	x, e = M.getColumns(rows, (0, 3, (int, lambda x: 1 if x=='male' else 0)))
	print(M.count(x))
	'''
	x, e = M.getColumns(rows, (0, 1, 3, 4), (int, float, lambda x: 1 if x=='male' else 0, float))
	x = np.matrix(x)
	y = x[0,:]   #class
	x = x[1:,:]  #attributes
	x0, x1 = M.split(x, y, lambda _y: _y==0)
	'''
	success, failure = M.crossValidation(x0, x1, M.Fisher)
	print(success, failure)
	'''

	d = M.Gauss(x0, x1)
	rows = list(csv.reader(open('../csv/test.csv')))[1:]
	for row in rows:
		try:
			x = []
			x.append(float(row[0]))
			x.append(1 if row[2] == 'male' else 0)
			x.append(float(row[3]))
			print(d.do(np.matrix(x).T))
		except ValueError:
示例#9
0
def func():
    ...do something else...


# O.py

from M import func
from N import func        # This overwites the one we got from M
func()                    # Calls N.func only


# O.py

import M, N               # Get the whole modules, not their names
M.func()                  # We can call both names now
N.func()                  # The module names make them unique



### file: module2.py

print('starting to load...')
import sys
name = 42

def func(): pass

class klass: pass

print('done loading.')
示例#10
0
def self_play(storage, player1, player2=None, explore=True, num_games=1, joseki=False):
    for n in range(num_games):
        if not parallell:
            print("Self-play game: %s" % n)
            
        #Handle the fact that ordinary self-play uses a single tree structure
        #whereas evaluation uses two different ones
        if player2 != None: evaluation = True
        else: evaluation = False
        
        #Initialize game structure
        game = santorini.Game() 

        #Initialize players with networks and tree structures. Make the structures
        #globally available to facilitiate inspection or debugging
        p1 = M.MCTS(game, player1, sess, explore) 
        global P1
        P1 = p1
        
        if player2 != None:
            evaluation = True
            p2 = M.MCTS(game, player2, sess, explore) 
            global P2
            P2 = p2
            players = [p1, p2]
        else:
            evaluation = False
                   
        #Store state history, but don't add it to global history yet as we need 
        #to know the outcome first
        temp_history = []
    
        done = False
        while done == False:
            if evaluation:
                player = game.turn_count%2    
                tree = players[player]
                other_tree = players[(player+1)%2]
            else:
                tree = p1
                
            #Execute tree search and make move
            t0 = time.time()
            done = tree.consider_resigning(v_resign, observe_games)  
            a, pi_s, P, v = tree.run_simulation(search_depth)  
            temp_history.extend([[game.stack_s(), pi_s, game.legal_moves(binaryV=True)]])
            if evaluation: #This is not very neat, and I should fix it up at some point...
                other_tree.prepare_adversarial_move(a)
            game.move(a)
            done = game.done
            if evaluation:
                other_tree.finish_adversarial_move(a)
            tree.prepare_next_move()
    
            if observe_games:
                for i in range(10):
                    print("\n")
                print("P (predicted tree search probs):\n%s\n\n" % np.reshape(P, [5,5]),
                      "pi (actual tree search probs):\n%s\n\n" % np.reshape(pi_s, [5,5]),
                      "v: %s\n" % v, 
                      "Chosen move: %s\n" % a,
                      "Overall game state:\n%s\n\n" % game.render())
                print("time: ", time.time()-t0)
        z = game.outcome
        
        #store data
        t = len(temp_history)
        for entry in temp_history:
            storage.add(entry[0], entry[1], discount_rs(z, t), entry[2])
            t -= 1
        
    return z
示例#11
0
# import가 필요한 경우

# M.py
def func():
    ...무엇인가를 수행함...


# N.py
def func():
    ...다른 무엇인가를 수행함...


# O.py
from M import func
from N import func              # M으로부터 가져온 func를 덮어씀
func()                          # N.func만 호출함


# O.py
import M, N                     # 모듈의 이름들이 아니라, 전체 모듈을 가져옴
M.func()                        # 이제 두 이름 모두 호출할 수 있음
N.func()                        # 모듈 이름이 두 이름을 유일하게 만들어줌


# O.py
from M import func as mfunc     # "as"를 이용하여 이름을 유일하게 재명명
from N import func as nfunc
mfunc(), nfunc();               # 하나 또는 나머지의 하나를 호출함
示例#12
0
def calc_gpu_fraction(fraction_string):
    idx, num = fraction_string.split('/')
    idx, num = float(idx), float(num)

    fraction = 1 / (num - idx + 1)
    print "[*] GPU : %.4f" % fraction
    return fraction


config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = calc_gpu_fraction('1/3')
config.gpu_options.allow_growth = True

with tf.Session(config=config) as sess:
    # Instantiate simulators for synthetic gradient and synthetic input
    gradient_simulator = M(output_dimension, num_parameters, n_layer, sess)
    input_simulator = I(IMAGE_PIXELS * IMAGE_PIXELS, input_dimension, n_layer,
                        sess)

    iteration = 0
    while iteration < 20000:
        iteration += 1

        batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batch_size)

        if n_layer != 1:
            syn_input_val = input_simulator.get_syn_input(batch_xs, iteration)

        else:
            syn_input_val = batch_xs.astype(np.float32)
            syn_input_val = append_ones(syn_input_val)