apple / turicreate

Turi Create simplifies the development of custom machine learning models.
BSD 3-Clause "New" or "Revised" License
11.2k stars 1.14k forks source link

SGraph visualization #126

Open mattzheng opened 6 years ago

mattzheng commented 6 years ago

In GraphLab Create API Documentation , we could use graphlab.SGraph()..show() to plot out , but in turicreate , In /src/unity/python/turicreate/data_structures/sgraph.py, I can not see .show() so I want to ask how to draw SGraph graph in the turicreate ?

znation commented 6 years ago

SGraph.show has been removed in the 4.0 release since the previous implementation wasn't very scalable - it could only draw graphs up to about 5,000 vertices.

Let's use this issue to track bringing back SGraph.show.

znation commented 6 years ago

@mattzheng In the meantime, you could use NetworkX or another package to draw relatively small graphs, for example:

import networkx as nx
import matplotlib.pyplot as plt
from turicreate import SGraph, Vertex, Edge

# construct an SGraph (skip this if you already have one)
sg = SGraph()
sg = sg.add_vertices([Vertex(i) for i in range(10)])
sg = sg.add_edges([Edge(i, i+1) for i in range(9)])

# convert to NetworkX graph
g = nx.Graph()
g.add_nodes_from(sg.vertices['__id'])
g.add_edges_from(sg.edges.apply(lambda row: [v for (k,v) in row.items()]))

# Draw it and show on screen
nx.draw(g)
plt.show()
mattzheng commented 6 years ago

@znation thank you ~networkx is easy to use.I provide a example I have practiced,I make use of official data from https://static.turi.com/datasets/bond/*:


### function
import networkx as nx
%matplotlib inline
from turicreate import SGraph, Vertex, Edge ,SFrame

def get_edge_list(g,direct = 'directed',weight = False):
    # directed or undirected graph
    if direct == 'directed':
        draw_g = nx.DiGraph()  
    elif direct == 'undirected':
        draw_g = nx.Graph()  
    # load data
    if weight:
        edge_list = [tuple(g_list.values()) for g_list in g.edges[['__src_id','__dst_id','weight']]]
        draw_g.add_weighted_edges_from(edge_list)
    else:
        edge_list = [tuple(g_list.values()) for g_list in g.edges[['__src_id','__dst_id']]]
        draw_g.add_edges_from(edge_list)
    return draw_g

### load data
url = 'https://static.turi.com/datasets/bond/bond_vertices.csv'
vertex_data = SFrame.read_csv(url)
url = 'https://static.turi.com/datasets/bond/bond_edges.csv'
edge_data = SFrame.read_csv(url)
csg = SGraph(vertices=SFrame(vertex_data), edges=edge_data, vid_field='name',
           src_field='src', dst_field='dst')
csg.edges['weight'] = range(len(csg.edges))     # define weight

### draw directed graph
draw_g = get_edge_list(csg,direct = 'directed',weight = True)
nx.draw(draw_g, node_color='y', with_labels=True, node_size=800)

picture