fork download
  1. import tensorflow as tf
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  5. x = np.linspace(-4.,4.,100)
  6. y = x + np.random.normal(0,0.1,100)
  7.  
  8. X = tf.placeholder(tf.float32, shape=[None,1])
  9. Y = tf.placeholder(tf.float32, shape=[None])
  10.  
  11. def linear(X, n_input, n_output,activation=None,scope=None):
  12. with tf.variable_scope(scope or 'Linear'):
  13. W = tf.get_variable(
  14. name='W',
  15. shape=[n_input,n_output],
  16. initializer=tf.random_normal_initializer(mean=0,stddev=0.1))
  17. b = tf.get_variable(
  18. name='b',
  19. shape=[n_output],
  20. initializer=tf.random_normal_initializer(mean=0,stddev=0.1))
  21. h = tf.matmul(X,W) + b
  22. if activation is not None:
  23. h = activation(h)
  24. return h
  25.  
  26. n_neurons = [1,20,1]
  27.  
  28. current_input = X
  29.  
  30. for layer in range(1,len(n_neurons)):
  31. current_input = linear(
  32. X=current_input,
  33. n_input = n_neurons[layer-1],
  34. n_output = n_neurons[layer],
  35. activation=tf.sigmoid if (layer+1) < len(n_neurons) else None,
  36. scope='layer_' + str(layer))
  37.  
  38. Y_pred = current_input
  39.  
  40. cost = tf.reduce_mean(tf.square(Y_pred - Y))
  41.  
  42. optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(cost)
  43.  
  44. n_iterations = 1000
  45. batch_size = 100
  46.  
  47. with tf.Session() as sess:
  48. sess.run(tf.initialize_all_variables())
  49. for iteration in range(n_iterations):
  50. idxs = np.random.permutation(range(len(x)))
  51. n_batches = len(idxs) // batch_size
  52. for batch in range(n_batches):
  53. idxs_i = idxs[batch*batch_size:(batch+1)*batch_size]
  54. sess.run(optimizer, feed_dict={X:np.reshape(x[idxs_i], [len(idxs_i),1]),Y:y[idxs_i]})
  55. training_cost = sess.run(cost,feed_dict={X:np.reshape(x, [len(x),1]),Y:y})
  56.  
  57. training_xs = x
  58. training_ys = sess.run(Y_pred,feed_dict={X:np.reshape(training_xs, [len(training_xs),1])})
  59. if iteration % 20 == 0 :
  60. plt.plot(x,y)
  61. plt.plot(training_xs,training_ys)
  62. plt.savefig('./graphs/graph'+str(iteration))
  63. plt.close()
  64. print(training_cost)
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
Runtime error #stdin #stdout #stderr 0.02s 9984KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "./prog.py", line 1, in <module>
ImportError: No module named 'tensorflow'