class Operation():
"""
An Operation is a node in a "Graph". TensorFlow will also use this concept of a Graph.
This Operation class will be inherited by other classes that actually compute the specific
operation, such as adding or matrix multiplication.
"""
def __init__(self, input_nodes = []):
"""
Intialize an Operation
"""
self.input_nodes = input_nodes # The list of input nodes
self.output_nodes = [] # List of nodes consuming this node's output
# For every node in the input, we append this operation (self) to the list of
# the consumers of the input nodes
for node in input_nodes:
node.output_nodes.append(self)
# There will be a global default graph (TensorFlow works this way)
# We will then append this particular operation
# Append this operation to the list of operations in the currently active default graph
_default_graph.operations.append(self)
def compute(self):
"""
This is a placeholder function. It will be overwritten by the actual specific operation
that inherits from this class.
"""
## pass is null, it is basically use to show that this function is necessary but this should not do anything
pass
class add(Operation):
def __init__(self, x, y):
super().__init__([x, y])
def compute(self, x_var, y_var):
self.inputs = [x_var, y_var]
return x_var + y_var
类乘法(操作):
def __init__(self, a, b):
super().__init__([a, b])
def compute(self, a_var, b_var):
self.inputs = [a_var, b_var]
return a_var * b_var
matmul(Operation)类:
def __init__(self, a, b):
super().__init__([a, b])
def compute(self, a_mat, b_mat):
self.inputs = [a_mat, b_mat]
return a_mat.dot(b_mat)
Placeholder()类: “” 占位符是一个节点,需要为其提供值以计算Graph中的输出。 “”“
def __init__(self):
self.output_nodes = []
_default_graph.placeholders.append(self)
变量 类Variable(): “” 此变量是图形的可变参数。 “”“
def __init__(self, initial_value = None):
self.value = initial_value
self.output_nodes = []
_default_graph.variables.append(self)
图 Graph()类:
def __init__(self):
self.operations = []
self.placeholders = []
self.variables = []
def set_as_default(self):
"""
Sets this Graph instance as the Global Default Graph
"""
global _default_graph
_default_graph = self
g = Graph()
g.set_as_default()
A = Variable(10)
b = Variable(1)
x = Placeholder()
y = multiply(A,x)
z = add (y,b)
import numpy as np
def traverse_postorder(operation):
nodes_postorder = []
def recurse(node):
if isinstance(node, Operation):
for input_node in node.input_nodes:
recurse(input_node)
nodes_postorder.append(node)
recurse(operation)
return nodes_postorder
课堂会议:
def run(self, operation, feed_dict = {}):
"""
operation: The operation to compute
feed_dict: Dictionary mapping placeholders to input values (the data)
"""
# Puts nodes in correct order
nodes_postorder = traverse_postorder(operation)
for node in nodes_postorder:
if type(node) == Placeholder:
node.output = feed_dict[node]
elif type(node) == Variable:
node.output = node.value
else: # Operation
node.inputs = [input_node.output for input_node in node.input_nodes]
node.output = node.compute(*node.inputs)
# Convert lists to numpy arrays
if type(node.output) == list:
node.output = np.array(node.output)
# Return the requested node value
return operation.output
sess = Session()
result = sess.run(operation=z,feed_dict={x:10})
result
101
g = Graph()
g.set_as_default()
A = Variable([[10,20],[30,40]])
b = Variable([1,2])
x = Placeholder()
y = matmul(A,x)
z = add(y,b)
sess = Session()
sess.run(operation = z,feed_dict={x:10})
array([[101, 202],
[301, 402]])
import matplotlib.pyplot as pt
%matplotlib inline
def Sigmoid(z):
return 1/(1 + np.exp(-z))
sample_z = np.linspace(-10,10,100)
sample_a = Sigmoid(sample_z)
pt.plot(sample_z,sample_a)
[<matplotlib.lines.Line2D at 0x6226d2d6d8>]
class Sigmoid(Operation):
def __init__(self,z):
super().__init__([z])
def compute(self,z_value):
return 1/(1 + np.exp(-z_val))
from sklearn.datasets import make_blobs
data = make_blobs(n_samples = 50, n_features=2, centers = 2,random_state=75)
features = data[0]
labels = data[1]
pt.scatter(features[:,0],features[:,1], c=labels)
<matplotlib.collections.PathCollection at 0x6228d3b128>
x = np.linspace(0,11,10)
y = -x+5
pt.scatter(features[:,0],features[:,1], c=labels)
pt.plot(x,y)
[<matplotlib.lines.Line2D at 0x6228cf9b38>]
np.array([1,1]).dot(np.array([[8],[10]]))-5
array([13])
np.array([1,1]).dot(np.array([[4],[-10]]))-5
array([-11])
g = Graph()
g.set_as_default()
x = Placeholder()
w = Variable([1,1])
b = Variable(-5)
z = add(matmul(w,x),b)
a = Sigmoid(z)
sess = Session()
AttributeError跟踪(最近一次通话) 在()中 ----> 1 sess.run(operation = a,feed_dict = {x:[8,10]})
在运行中(self,operation,feed_dict) 22其他:#操作 23 ---> 24个node.inputs = [node.input_nodes中input_node的input_node.output] 25 26 node.output = node.compute(* node.inputs)
(.0)中的22其他:#操作 23 ---> 24个node.inputs = [node.input_nodes中input_node的input_node.output] 25 26 node.output = node.compute(* node.inputs)
AttributeError:“ matmul”对象没有属性“ output”