def algorithm(self, matrix, start): vertNo = int(matrix.shape[0] / 2) #start = random.randint(0, vertNo * 2 - 1) visited = [] visited.append(start) next_min = find_min(matrix, visited, start) visited.append(next_min) # for 48 verts for _ in range(0, vertNo - 2): lowest_cost_for_edges = {} best_vert_for_edges = {} to_check = list(set(range(len(matrix))) - set(visited)) # all vert not visited # for all edges check distances to all free verts and get min cost for j in range(len(visited) - 1): new_vert_cost = {} for v in to_check: # check all not visited vert new_vert_cost[v] = cost(visited[j], visited[j + 1], v, matrix) # method cost calculate distance between new vert and egdes from visited [j] &[j+1] min_cost_key = int(min(new_vert_cost, key=new_vert_cost.get)) # minimum distance lowest_cost_for_edges[(j, j + 1)] = new_vert_cost[min_cost_key] # minimum distance for all edges best_vert_for_edges[(j, j + 1)] = min_cost_key # vert # final edge cost (last in list and first) new_vert_cost = {} for v in to_check: new_vert_cost[v] = cost(visited[-1], visited[0], v, matrix) # check last and first vert(one edges) from visited min_cost_key = int(min(new_vert_cost, key=new_vert_cost.get)) lowest_cost_for_edges[(len(visited) - 1, 0)] = new_vert_cost[min_cost_key] best_vert_for_edges[(len(visited) - 1, 0)] = min_cost_key # get best vert to add best_key = min(lowest_cost_for_edges, key=lowest_cost_for_edges.get) # add it to solution visited = np.insert(np.array(visited), best_key[1], best_vert_for_edges[best_key]) distanceSum = count_distance(matrix, visited) return distanceSum, visited
def Slide_6(): import numpy as np costs = np.array( [func.random_model(), func.cost(375, 0), func.cost(0, 15625), 37000]) label = ['Aleatória', 'Levar nenhum', 'Levar todos', 'Custo 2020'] import seaborn as sns plt.title('Custos, estratégias simples e custo atual') plt.ylabel('$') sns.barplot(x=label, y=costs) plt.show()
def Prims(filename, Initial_Vertex): G = Weighted_Graph(filename) VT = {Initial_Vertex} ET = [] MST = (VT, ET) V = G.vertex_set() cost_min_edge=P.cost(G,P.min_incident_edge(G,MST)) ###PRIMS ALGORITHM while MST[0] != V: min_edge = P.min_incident_edge(G,MST) new_vertex = {min_edge[0], min_edge[1]} ET.append(min_edge) MST =[new_vertex.union(MST[0]),ET] print('MST:',MST, '\n') total_cost = 0 for e in MST[0]: total_cost += cost_min_edge print ('\n', 'Total cost of MST:', total_cost, '\n') print ('Minimum Spanning Tree SubGraph:') G.draw_subgraph(MST)
def prims_algorithm(G, starting_vertex, show_graph=False, show_cost=False): #Draws graph if True if show_graph == True: show_weighted_graph(G) T = prims_initialize(G, starting_vertex) #Draws subtree if True if show_graph == True: draw_subtree(G, T) #Adds the minimum cost edge to the graph while is_spanning(G, T) == False: e = min_prims_edge(G, T) T.add_edge(e[0], e[1]) #Draws the MST if show_graph == True: draw_subtree(G, T) #Returns cost if True if show_cost == True: c = sum([cost(G, e) for e in E(T)]) print(f'The cost of this spanning tree is: {c}') return T
def main(): """ Prints "Canadian Cities!" to the display. And call the lifeQuality function. """ df = pd.read_csv("../data/numeo.csv") print("Canadian Cities!\n") print("Quality of Life:") quality_value = quality(df.City[0], df) print(quality_value) print() print("Cost of Living:") cost_value = cost(df.City[0], df) print(cost_value) print() print("Environmental Factors") env_value = environment(df.City[0], df) print(env_value) print() print("Lifestyle") style_value = lifestyle(df.City[0], df) print(style_value) print() print("End Test!!!")
def heatmaps(): X, Y = np.linspace(0, 375), np.linspace(0, 15625) X, Y = np.meshgrid(X, Y) import matplotlib.pyplot as plt plt.style.use("seaborn") #from matplotlib.pyplot import colorbar, pcolor, show Z = func.cost(X, Y) f, ax = plt.subplots(figsize=(8, 6)) plot = ax.pcolor(Y, X, Z, cmap='bwr') plt.xlabel('Falso Positivo') plt.ylabel('Falso negativo') plt.title('Heatmap de custo, relação falso negativo x falso positivo.') f.colorbar(plot, ax=ax) plt.plot([15625, 0], [0, 312.5], color='brown') plt.plot([12270 / 10, 0], [0, 12270 / 500], color='black') plt.plot([37000 / 10, 0], [0, 37000 / 500], color='teal') plt.plot([20500 / 10, 0], [0, 20500 / 500], color='indigo') plt.show() X, Y = np.linspace(0, 38000 / 500), np.linspace(0, 38000 / 10) X, Y = np.meshgrid(X, Y) import matplotlib.pyplot as plt plt.style.use("seaborn") #from matplotlib.pyplot import colorbar, pcolor, show Z = func.cost(X, Y) f, ax = plt.subplots(figsize=(8, 6)) plot = ax.pcolor(Y, X, Z, cmap='bwr') plt.xlabel('Falso Positivo') plt.ylabel('Falso negativo') plt.title('Heatmap de custo, relação falso negativo x falso positivo.') f.colorbar(plot, ax=ax) plt.plot([12270 / 10, 0], [0, 12270 / 500], color='black') plt.plot([37000 / 10, 0], [0, 37000 / 500], color='teal') plt.plot([20500 / 10, 0], [0, 20500 / 500], color='indigo') plt.show()
def find_two_best_verts(self, matrix, visited): lowest_cost_for_edges = {} best_vert_for_edges = {} to_check = list(set(range(len(matrix))) - set(visited)) for j in range(len(visited) - 1): new_vert_cost = {} for v in to_check: new_vert_cost[v] = cost(visited[j], visited[j + 1], v, matrix) min_cost_key = int(min(new_vert_cost, key=new_vert_cost.get)) lowest_cost_for_edges[(j, j + 1)] = new_vert_cost[min_cost_key] best_vert_for_edges[(j, j + 1)] = min_cost_key new_vert_cost = {} for v in to_check: new_vert_cost[v] = cost(visited[-1], visited[0], v, matrix) min_cost_key = int(min(new_vert_cost, key=new_vert_cost.get)) lowest_cost_for_edges[(len(visited) - 1, 0)] = new_vert_cost[min_cost_key] best_vert_for_edges[(len(visited) - 1, 0)] = min_cost_key best_key = min(lowest_cost_for_edges, key=lowest_cost_for_edges.get) del (lowest_cost_for_edges[best_key]) best_key2 = min(lowest_cost_for_edges, key=lowest_cost_for_edges.get) return best_key, best_key2, best_vert_for_edges
def algorithm2(code): for j, c in enumerate(code): b = param.letters[1] prefix = "" for l in c: prefix += l if fun.cost(prefix) >= param.k: break suffix = c.replace(prefix, '') i = 0 for s in suffix: if s == b: i += 1 new = prefix + enc(i) + suffix + b code[j] = new
def prims_algorithm(G, starting_vertex, show_graph=False, show_cost=False): if show_graph == True: show_weighted_graph(G) T = initialize_prims(G, starting_vertex) while is_spanning(G, T) == False: e = min_prims_edge(G, T) T.add_edge(e[0], e[1]) if show_graph == True: draw_subtree(G, T) if show_cost == True: c = sum([cost(G, e) for e in E(T)]) print(f'The cost of this spanning tree is {c}') return T
X_test['bias'] = 1 x_test = X_test[['bias'] + features].values y_test = y_test.values y_test = y_test.reshape(y_test.shape[0], 1) print('train ', X_train.shape, y_train.shape) print('test ', X_test.shape, y_test.shape) np.random.seed(123) w = np.random.normal(loc=1e-3, scale=1e-6, size=(1, x_train.shape[1])) lmbd = 0.05 alpha = 0.005 epochs = 7000 print('w shape', w.shape) print('train cost ', functions.cost(x_train, y_train, w, lmbd)) w, J, J_t = functions.gd(X_train, y_train, x_test, y_test, w, alpha, lmbd, epochs) print('train cost ', functions.cost(X_train, y_train, w, lmbd)) w = w.reshape(-1) print(w) plt.plot(range(len(J)), J, label='Train cost') plt.plot(range(len(J_t)), J_t, label='Test cost') plt.xlabel('Iterations') plt.ylabel('Cost') plt.legend() plt.show() p = functions.h(x_train, w) # get probabilities y_hat = functions.predict(p, 0.5)
import functions h = functions.hours() d = functions.days() cost = functions.cost(h,d) print "Total Cost is : " + str(cost)
def main(argv): g = read_network.read_static_network(argv[1]) cnm_output = greedy_modularity_communities(g) print('modularité maximale détectée par CNM: ', cost(cnm_output, g))
movement = pd.DataFrame(data=volatility_array) table = pd.concat([stocks, movement], axis=1) table.columns = ['Stock', 'Value'] table = table.sort_values(by='Value', ascending=False) stockRef = 1 #number of stocks put into each table (topStocks and bottomStocks) topStocks = table.iloc[ 0:stockRef] #table of stocks with most projected upward movement bottomStocks = table.iloc[ -stockRef:] #table of stocks with most projected downward movement #record the rmse of the predictions for each of our stocks error = pd.DataFrame(data=rmse_array) table2 = pd.concat([stocks, error], axis=1) ####################################################################### #using our cost function and HoldStock function: init_invest = 10000 tradeExec_cost = 8.9 money = np.zeros(len(trueVals)) money[0] = init_invest holdings = np.zeros(len(trueVals)) #predicted array, true array values, initial investment value, cost of transacting trades, money array to keep track of leftover funds, holdings to keep track of stock values held [percentReturn, portfolioValue_array] = cost(predictedPrice_array, trueVals, prevDay, init_invest, tradeExec_cost, money, holdings) #using our holdstock function for comparison: [percent_change, portfolio_value] = HoldStock(trueVals, init_invest, tradeExec_cost)
f[i] = len(g) k_pref = k_prefix_code(graph,f) if not fun.check_prefix_free(k_pref): print("Codice non prefix-free, utilizzo dell'algoritmo 2") algorithm2(k_pref) code = {} for i,word in enumerate(param.w): code[word] = k_pref[i] return code #genero le frequenze delle parole di w param.freq = param.generate_freq(param.w) #genero il codice di costo minimo code = main() #calcolo il costo del codice total = 0 for c in code: total += fun.cost(code[c]) print(c, ":",code[c],"-",fun.cost(code[c])) print("Costo totale del codice:", fun.code_cost(code, param.w,param.freq)) mean = total / len(code) print("Costo medio delle codewords:", mean)