def try_model(gpu_id): try: # Run model model.main(gpu_id) except KeyboardInterrupt: quit('Quit by KeyboardInterrupt')
def try_model(save_fn, gpu_id = None): # Specify GPU Id as a string # Leave blank to use CPU try: model.main(save_fn, gpu_id) except KeyboardInterrupt: print('Quit by KeyboardInterrupt.')
def main(): st.title("Deployment Challenge :trophy:") st.image("img\download.jpeg",use_column_width='auto') load_sidebar() st.subheader("Predictions using SVM with rbf kernel") m.main()
def main(): """This is the entry point to the application.""" # This is for text mode. if len(sys.argv) == 2 and sys.argv[1] == '-t': model.main() sys.exit(0) # Do initialization. pygame.init() screen = pygame.display.set_mode(DISPLAY_MODE) pygame.display.set_caption(TITLE) clock = pygame.time.Clock() background = pygame.Surface(screen.get_size()).convert() background.fill(BACKGROUND) pygame.display.flip() game_model = model.Game() board_view = view.Board(game_model) score_board = view.ScoreBoard(game_model) rendering_groups = [board_view, score_board] while True: clock.tick(FRAMES_PER_SEC) scheduler.tick() # Handle user input. for event in pygame.event.get(): if event.type == KEYDOWN: if event.key in (K_ESCAPE, K_q) or event.type == QUIT: sys.exit(0) elif event.key == K_h: url = "file://" + os.path.abspath(data.find("help.html")) webbrowser.open(url, new=True) elif event.key == K_r: game_model.reset() elif event.type == MOUSEBUTTONDOWN: for square_view in board_view: if square_view.rect.collidepoint(*pygame.mouse.get_pos()): xyz = square_view.square_model.xyz try: game_model.move(xyz) except ValueError: pass break # Provide the simulation and render it. for i in rendering_groups: i.update() i.clear(screen, background) pygame.display.update(i.draw(screen))
def try_model(save_fn): # To use a GPU, from command line do: python model.py <gpu_integer_id> # To use CPU, just don't put a gpu id: python model.py try: if len(sys.argv) > 1: model.main(save_fn, sys.argv[1]) else: model.main(save_fn) except KeyboardInterrupt: print('Quit by KeyboardInterrupt.')
def run(path): dataset_name = util.dataset_name(path) doc = data.Document(path) sentences = TextProcessor.get_allsentarray(doc) # mention mentions = util.set_mentions(dataset_name, doc) #段落分け sep_mentions = TextProcessor.mention_separater(mentions) #モデルに段落分けしたmentionを入力 model.main(sep_mentions, sentences)
def try_model(updates): print('Updating parameters...') update_parameters(updates) t0 = time.time() try: model.main() print('Model run concluded. Run time: {:5.3f} s.\n\n'.format(time.time()-t0)) except KeyboardInterrupt: quit('Quit by KeyboardInterrupt. Run time: {:5.3f} s.\n\n'.format(time.time()-t0))
def try_model(): try: if len(sys.argv) > 1: print('Running on GPU {}.'.format(sys.argv[1])) model.main(gpu_id=sys.argv[1], code_state=code_state) else: print('Running on CPU.') model.main(code_state=code_state) except KeyboardInterrupt: quit('Quit by KeyboardInterrupt')
def try_model(save_fn, gpu_id): # GPU designated by first argument (must be integer 0-3) try: print('Selecting GPU ', sys.argv[1]) assert (int(sys.argv[1]) in [0, 1, 2, 3]) except AssertionError: quit('Error: Select a valid GPU number.') try: # Run model model.main(save_fn, sys.argv[1]) except KeyboardInterrupt: quit('Quit by KeyboardInterrupt')
def get_input_text_for_visualization_demo(): """ Function to POST/GET for demo.js. :return: String/JSON """ if request.method == 'POST': print(f'Incoming...') if request.is_json: request_json = request.get_json() user_input_string = request_json.get('user_input_text') # Call GPT-2 model, which returns predictions and other data. my_data = model.main(user_input_string) if debug: print(f"User input text received") print(f"From HTML/Javascript: {request.get_json()}" ) # parse as JSON print(f"User input text: {user_input_string}") print(f"Data from GPT-2 Model: {my_data}") return jsonify(my_data), 200 else: print(f"Data is not in JSON format!") return 'Failed to receive user input text.', 200
def submit(): if request.method == 'POST': input_text = request.form.get("input_text") final_summary=main(input_text) return render_template('app.html',summary=final_summary, input_text=input_text) else: return render_template('app.html')
def main(): filter_keywords = [ 'smoking', 'tobacco', 'cigarette', 'cigar', 'hookah', 'hooka'] [doc_topic, num_of_topics] = model.main(filter_keywords) # various search params to get best combination # n_components is Number of topics. search_params = {'n_components': [ 4, 10, 20], 'learning_decay': [.8, .12]} for i in range(num_of_topics): print 'Sub-Topic for Topic ' + str(i) filter_doc = doc_topic.loc[doc_topic['dominant_topic'] == i] processed_docs = list(filter_doc['doc']) [best_lda_model_sub_topic, num_of_sub_topics, vectorizer] = model.train_lda(processed_docs, search_params) model.show_result( best_lda_model_sub_topic, processed_docs, num_of_sub_topics, vectorizer)
def run_model(): try: acc = model.main(gpu_id='3') except KeyboardInterrupt: quit('\nQuit via KeyboardInterrupt.') return acc
def classify_review(): starttime = time.time() response = None if request.method == 'POST': try: if request.get_json(): req_data = request.get_json() overall_sentiment, return_data = model.main(req_data['data']) if not return_data: response = {'review': req_data['data'], 'data': 'None'} else: response = { 'review': req_data['data'], 'sentiment': overall_sentiment, 'data': return_data } endtime = time.time() print "Time taken for the call: " + str( (endtime - starttime)) + " ms" else: response = {'status': 'failed , invalid request'} except Exception as e: return respond(e) else: response = {'status': 'failed'} return respond(None, res=response)
def reply_to_mention(mention): username = mention['user']['screen_name'] subject, verb, adj = extract_subject(mention['text']) reply = model.main(N=1, subject=subject, verbose=False, get_related=False, verb=verb, adj=adj) if not reply: return None return '.@{0} {1}'.format(username, reply[0])
def test_main(): """Main just does goose_write, so this is the mostly same test as test_goose_write""" subprocess.run("rm -rf tests/db", shell=True) fnames = model.main("tests/db") assert os.path.exists("tests/db/sqlite3") assert len(fnames) >= 1 for fname in fnames: assert os.path.exists(fname)
def index(request): rutas = Demanda.objects.all() fabricas = Fabrica.objects.all() tiendas = Tienda.objects.all() modelo = model.main(rutas, fabricas, tiendas) fob = value(modelo.objective) status = LpStatus[modelo.status] context = {'rutas': rutas, 'modelo': modelo, 'fob': fob, 'status': status} return render(request, 'modelo1/index.html', context)
def turn_dic_from_dic(dic, a_func): ''' Computes a single turn ''' d_settings = get_settings_from_dic_ret(dic) for func in a_func: d_settings = func(d_settings) ret = model.main(**d_settings) return ret
def benchmark(n=10): pol, level = None, None p = {'policy': pol, 'level': level} # For each run policy, when dictionary with all runs is saved. # Thus, result collected is a dictionary of dictionaries containing DataFrames results = {pol: dict()} for i in range(n): s = model.main(p, verbose, seed=seed) results[pol][i] = s.report plotting(results, n)
def create_song(artist): if os.path.isfile("lyrics_" + artist + ".txt") is False or FORCE_TRAINING: # create the lyrics create(artist) else: print("File with lyrics already exists, we use it") if os.path.isfile(artist + ".rap") is False or FORCE_TRAINING: # train the model main(5, True, artist, MAX_SYLLABLES, LINES) else: print("Model already trained") # write the lyrics main(5, False, artist, MAX_SYLLABLES, LINES)
def loop(d_settings, num_loops, a_func): dic_ret = model.main(**d_settings) a_dic_ret = [dic_ret] for i in range(num_loops-1): print(i) if np.isnan(dic_ret['a_profit'][0]): print('ended with NAN') break dic_ret = turn_dic_from_dic(dic_ret, a_func) a_dic_ret.append(dic_ret) print(a_dic_ret) return a_dic_ret
def main(): buystate = 0 buy_res = [] sell_res = [] date = [] i = 0 f = open('result.txt', 'w') data = pd.read_csv('../Data/' + comp + '.csv') if len(sys.argv) > 3: days = int(sys.argv[3]) else: days = len(data.index) print(days) close_p = np.flipud(data['Close'].values[0:days]) open_p = np.flipud(data['Open'].values[0:days]) low_p = np.flipud(data['Low'].values[0:days]) high_p = np.flipud(data['High'].values[0:days]) volume = np.flipud(data['Total Trade Quantity'].values[0:days]) Date = np.flipud(data['Date'].values[0:days]) buy_a, sell_a, stoploss_a = model.main(comp, days) while (i < len(buy_a)): if buystate == 0 and buy_a[i] == 1: buystate = 1 date.append(Date[i]) buy_res.append(close_p[i]) f.write(str(date[-1]) + "\t") f.write(str(buy_res[-1]) + "\n") if buystate and (sell_a[i] == 1 or stoploss_a[i] == 1): buystate = 0 date.append(Date[i]) sell_res.append(close_p[i]) f.write(str(date[-1]) + "\t") f.write(str(sell_res[-1]) + "\n") f.write("\n") i += 1 if buystate == 1: date.append(Date[-1]) sell_res.append(close_p[-1]) f.write(str(date[-1]) + "\t") f.write(str(sell_res[-1]) + "\n") f.write("\n") f.write("total Profit/Loss % : ") total = 100 * np.sum([(i - j) / (j + 1) for (i, j) in zip(sell_res, buy_res)]) f.write(str(total)) print("total Profit/Loss % : ", total) f.close()
def upload(): if request.method == 'POST' and 'photo' in request.files: try: filename = photos.save(request.files['photo']) filename = app.config['UPLOADED_PHOTOS_DEST'] + '/' + filename except: return render_template('index.html') new_filename = file_rename(filename) model_output = model.main(new_filename) return render_template('output.html', title='output', filename=new_filename, model_output=model_output) return render_template('index.html')
def trainModel(): #Get data from the Get request... # Then train model for the specific stock... # Then return data with json.... content = {} if (request.method == "GET"): #print(request.args) stockName = request.args.get('stockName') print(stockName) modelType = request.args.get('modelType') print(modelType) returnData = model.main(stockName, modelType) #print(returnData) #content=returnData plotlyDiv = model.plotThis(returnData['train']['x'], returnData['train']['y'], returnData['test']['x'], returnData['test']['y'], returnData['actual']['x'], returnData['actual']['y'], modelType=modelType) content['plotDiv'] = plotlyDiv return jsonify(content)
_string = [ 'av_degree', 'mut_prop', 'clustering_coefficient', 'segreg_ind2', 'segreg_ind1', 'segreg_ind0' ] extraruns = { 'av_degree': [], 'clustering_coefficient': [], 'mut_prop': [], 'segreg_ind0': [], 'segreg_ind1': [], 'segreg_ind2': [] } # 100 normal runs data = model.main(settings, [4] * 100) pickle.dump(data, open('pickles\\100xschool4.pkl', 'wb')) # 100 runs with extra X column for i in range(100): print('--', i, end='\r') big_x = pickle.load(open(r"C:\Users\FlorisFok\Downloads\x_list.pkl", 'rb')) X = big_x[4] new = np.random.randint(0, 5, (len(X), )) X['new'] = new pickle.dump([X], open('custom_x.pkl', 'wb')) new_data = model.main(settings, [0]) for s in _string: extraruns[s].append(new_data[s][0]) pickle.dump(extraruns, open('pickles\\100xschool4extra.pkl', 'wb'))
if options.extract != "": options.extract = options.extract.strip() d = config.get(config.path("..", "data", options.datafile, "data", "dHandler.p"), dc.Data, datafile=options.datafile) if options.extract not in d.tags: print "%s is not a feature in %s" % (options.extract, options.datafile) sys.exit() path = config.path("..", "data", options.datafile, "models", "config_%s.p" % options.extract) if not os.path.exists(path): m.main(select, [options.extract], d, include_costs=options.include, trees=int(options.trees), test=False) m.extract_model(options.datafile, options.extract, d) sys.exit() if options.model != "": m.use_model(options.model.strip().upper()) sys.exit() d = config.get(config.path("..", "data", options.datafile, "data", "dHandler.p"), dc.Data, datafile=options.datafile) m.main(select, costs,
def get_message(handle, subject=None): messages = model.main(N=1, subject=subject, verbose=False) assert len(messages[0]) message = messages[0] assert len(message) <= TWEET_LENGTH return message
import numpy as np from parameters import * import model import sys task_list = ['OICDMC'] #task_list = ['spatialDMS'] for task in task_list: #j = sys.argv[1] print('Training network on ', task) save_fn = task + '.pkl' updates = {'trial_type': task, 'save_fn': save_fn} update_parameters(updates) #model.train_and_analyze() model.main()
if options.clean: config.clean([\ "data",\ "features",\ "models",\ ], datafile = options.datafile) select = options.select.replace("[","").replace("]","").strip().split(",") costs = options.costs.replace("[","").replace("]","").strip().split(",") if options.extract != "": options.extract = options.extract.strip() d = config.get(config.path("..","data",options.datafile,"data","dHandler.p"), dc.Data, datafile = options.datafile) if options.extract not in d.tags: print "%s is not a feature in %s" % (options.extract, options.datafile) sys.exit() path = config.path("..","data", options.datafile, "models", "config_%s.p" % options.extract) if not os.path.exists(path): m.main(select, [options.extract], d, include_costs = options.include, trees = int(options.trees), test = False) m.extract_model(options.datafile, options.extract, d) sys.exit() if options.model != "": m.use_model(options.model.strip().upper()) sys.exit() d = config.get(config.path("..","data",options.datafile,"data","dHandler.p"), dc.Data, datafile = options.datafile) m.main(select, costs, d, include_costs = options.include, trees = int(options.trees))
from telethon import TelegramClient, sync, events # from telethon.sync import TelegramClient from telethon import connection from datetime import date, datetime # import sqlite3 from model import main # Считываем учетные данные config = configparser.ConfigParser() config.read("config.ini") # Присваиваем значения внутренним переменным api_id = config['Param']['api_id'] api_hash = config['Param']['api_hash'] username = config['Param']['session'] channel = config['Param']['channel'] phone = '+79788784857' client = TelegramClient(username, api_id, api_hash) client.connect() if not client.is_user_authorized(): client.send_code_request(phone) client.sign_in(phone, input('Enter code:')) with client: client.loop.run_until_complete(main(client, channel))
import sys import data import model import web if len(sys.argv) < 2: web.open_in_browser() else: nbr_videos = int(sys.argv[1]) data.main() model.main(nbr_videos)
def uploaded(): flash('JD & Resume have been successfully uploaded!') model.main() return render_template('webpage.html')
import numpy as np from parameters import * import model import sys gpu_id = sys.argv[1] save_fn = 'test' + '_' + str(0) + '.pkl' updates = {'save_fn': save_fn} update_parameters(updates) model.main(gpu_id=gpu_id)