楼主: ReneeBK
2960 20

[GitHub]Python Deep Learning [推广有奖]

  • 1关注
  • 62粉丝

VIP

已卖:4897份资源

学术权威

14%

还不是VIP/贵宾

-

TA的文库  其他...

R资源总汇

Panel Data Analysis

Experimental Design

威望
1
论坛币
49635 个
通用积分
55.7537
学术水平
370 点
热心指数
273 点
信用等级
335 点
经验
57805 点
帖子
4005
精华
21
在线时间
582 小时
注册时间
2005-5-8
最后登录
2023-11-26

楼主
ReneeBK 发表于 2017-7-8 00:05:34 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币

本帖隐藏的内容

Python-Deep-Learning-master.zip (4.81 MB, 需要: 1 个论坛币)

  1. Python Deep Learning
  2. Valentino Zocca et al.
  3. April 2017
  4. Take your machine learning skills to the next level by mastering Deep Learning concepts and algorithms using Python.
复制代码
  1. Python Deep Learning

  2. This is the code repository for Python Deep Learning, published by Packt. It contains all the supporting project files necessary to work through the book from start to finish.

  3. About the Book

  4. With an increasing interest in AI around the world, deep learning has attracted a great deal of public attention. Every day, deep learning algorithms are used broadly across different industries.

  5. The book will give you all the practical information available on the subject, including the best practices, using real-world use cases. You will learn to recognize and extract information to increase predictive accuracy and optimize results.

  6. Starting with a quick recap of important machine learning concepts, the book will delve straight into deep learning principles using Sci-kit learn. Moving ahead, you will learn to use the latest open source libraries such as Theano, Keras, Google's TensorFlow, and H20. Use this guide to uncover the difficulties of pattern recognition, scaling data with greater accuracy and discussing deep learning algorithms and techniques.

  7. Instructions and Navigation

  8. All of the code is organized into folders. Each folder starts with a number followed by the application name. For example, Chapter02.

  9. The code will look like the following:

  10. mlp.fit(data_train, labels_train)
  11. pred = mlp.predict(data_test)
  12. print('Misclassified samples: %d' % (labels_test != pred).sum())
  13. from sklearn.metrics import accuracy_score print('Accuracy: %.2f' % accuracy_score(labels_test, pred))
  14. Related Products

  15. Python: Deeper Insights into Machine Learning

  16. Deep Learning with Keras

  17. Deep Learning with Hadoop

  18. Python Machine Learning
复制代码



二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:Learning earning python GitHub Learn

沙发
ReneeBK(未真实交易用户) 发表于 2017-7-8 00:05:50
  1. import numpy
  2. from matplotlib.colors import ListedColormap
  3. import matplotlib.pyplot as plt

  4. def tanh(x):     
  5.     return (1.0 - numpy.exp(-2*x))/(1.0 + numpy.exp(-2*x))

  6. def tanh_derivative(x):     
  7.     return (1 + tanh(x))*(1 - tanh(x))
  8.    
  9. class NeuralNetwork:
  10.     #network consists of a list of integers, indicating
  11.     #the number of neurons in each layer
  12.     def __init__(self, net_arch):
  13.         numpy.random.seed(0)                  
  14.         self.activity = tanh         
  15.         self.activity_derivative = tanh_derivative
  16.         self.layers = len(net_arch)         
  17.         self.steps_per_epoch = 1000
  18.         self.arch = net_arch        

  19.         self.weights = []         
  20.         #range of weight values (-1,1)         
  21.         for layer in range(len(net_arch) - 1):            
  22.             w = 2*numpy.random.rand(net_arch[layer] + 1, net_arch[layer+1]) - 1           
  23.             self.weights.append(w)

  24.     def fit(self, data, labels, learning_rate=0.1, epochs=10):         
  25.         #Add bias units to the input layer         
  26.         ones = numpy.ones((1, data.shape[0]))        
  27.         Z = numpy.concatenate((ones.T, data), axis=1)
  28.         training = epochs*self.steps_per_epoch


  29.         for k in range(training):            
  30.             if k % self.steps_per_epoch == 0:                  
  31.                 #print ('epochs:', k/self.steps_per_epoch)   
  32.                 print('epochs: {}'.format(k/self.steps_per_epoch))              
  33.                 for s in data:                     
  34.                     print(s, nn.predict(s))

  35.             sample = numpy.random.randint(data.shape[0])            
  36.             y = [Z[sample]]

  37.             for i in range(len(self.weights)-1):                     
  38.                 activation = numpy.dot(y[i], self.weights[i])                        
  39.                 activity = self.activity(activation)  
  40.                 #add the bias for the next layer                     
  41.                 activity = numpy.concatenate((numpy.ones(1), numpy.array(activity)))                     
  42.                 y.append(activity)   
  43.             
  44.             #last layer              
  45.             activation = numpy.dot(y[-1], self.weights[-1])            
  46.             activity = self.activity(activation)            
  47.             y.append(activity)
  48.                     
  49.             #error for the output layer            
  50.             error = labels[sample] - y[-1]            
  51.             delta_vec = [error * self.activity_derivative(y[-1])]

  52.             #we need to begin from the back from the next to last layer
  53.             for i in range(self.layers-2, 0, -1):  
  54.                 #delta_vec [1].dot(self.weights[i][1:].T)               
  55.                 error = delta_vec[-1].dot(self.weights[i][1:].T)
  56.                 error = error*self.activity_derivative(y[i][1:])               
  57.                 delta_vec.append(error)

  58.             # reverse
  59.             # [level3(output)->level2(hidden)]  => [level2(hidden)->level3(output)]
  60.             delta_vec.reverse()

  61.             # backpropagation
  62.             # 1. Multiply its output delta and input activation
  63.             #    to get the gradient of the weight.
  64.             # 2. Subtract a ratio (percentage) of the gradient from the weight
  65.             for i in range(len(self.weights)):
  66.                 layer = y[i].reshape(1, nn.arch[i]+1)

  67.                 delta = delta_vec[i].reshape(1, nn.arch[i+1])
  68.                 self.weights[i] += learning_rate * layer.T.dot(delta)

  69.     def predict(self, x):
  70.         val = numpy.concatenate((numpy.ones(1).T, numpy.array(x)))      
  71.         for i in range(0, len(self.weights)):
  72.             val = self.activity(numpy.dot(val, self.weights[i]))
  73.             val = numpy.concatenate((numpy.ones(1).T, numpy.array(val)))
  74.             
  75.         return val[1]

  76.     def plot_decision_regions(self, X, y, points=200):
  77.         markers = ('o', '^')
  78.         colors = ('red', 'blue')
  79.         cmap = ListedColormap(colors)
  80.         # plot the decision surface
  81.         x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
  82.         x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
  83.         
  84.         resolution = max(x1_max - x1_min, x2_max - x2_min)/float(points)
  85.         #resolution = 0.01
  86.      
  87.         xx1, xx2 = numpy.meshgrid(numpy.arange(x1_min, x1_max, resolution), numpy.arange(x2_min, x2_max, resolution))
  88.         input = numpy.array([xx1.ravel(), xx2.ravel()]).T
  89.         Z = numpy.empty(0)
  90.         for i in range(input.shape[0]):
  91.             val = nn.predict(numpy.array(input[i]))
  92.             if val < 0.5: val = 0
  93.             if val >= 0.5: val = 1
  94.             Z = numpy.append(Z, val)

  95.         Z = Z.reshape(xx1.shape)
  96.         
  97.         plt.pcolormesh(xx1, xx2, Z, cmap=cmap)
  98.         plt.xlim(xx1.min(), xx1.max())
  99.         plt.ylim(xx2.min(), xx2.max())
  100.         # plot all samples

  101.         classes = ["False", "True"]
  102.         for idx, cl in enumerate(numpy.unique(y)):
  103.             plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=1.0, c=cmap(idx), marker=markers[idx], s=80, label=classes[idx])
  104.             
  105.         plt.xlabel('x-axis')            
  106.         plt.ylabel('y-axis')
  107.         plt.legend(loc='upper left')
  108.         plt.show()            

  109. if __name__ == '__main__':

  110.     nn = NeuralNetwork([2,2,1])

  111.     X = numpy.array([[0, 0],
  112.                      [0, 1],
  113.                      [1, 0],
  114.                      [1, 1]])

  115.     y = numpy.array([0, 1, 1, 0])

  116.     nn.fit(X, y, epochs=10)

  117.     print "Final prediction"
  118.     for s in X:
  119.         print(s, nn.predict(s))
  120.         
  121.     nn.plot_decision_regions(X, y)
复制代码

藤椅
ReneeBK(未真实交易用户) 发表于 2017-7-8 00:07:30
  1. # -*- coding: utf-8 -*-

  2. from keras.datasets import mnist
  3. from keras.models import Sequential
  4. from keras.layers.core import Dense, Activation
  5. from keras.utils import np_utils

  6. (X_train, Y_train), (X_test, Y_test) = mnist.load_data()

  7. X_train = X_train.reshape(60000, 784)     
  8. X_test = X_test.reshape(10000, 784)

  9. classes = 10
  10. Y_train = np_utils.to_categorical(Y_train, classes)     
  11. Y_test = np_utils.to_categorical(Y_test, classes)

  12. input_size = 784
  13. batch_size = 100     
  14. hidden_neurons = 100     
  15. epochs = 30

  16. model = Sequential()     
  17. model.add(Dense(hidden_neurons, input_dim=input_size))
  18. model.add(Activation('sigmoid'))     
  19. model.add(Dense(classes, input_dim=hidden_neurons))
  20. model.add(Activation('softmax'))

  21. model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='sgd')

  22. model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, verbose=1)

  23. score = model.evaluate(X_test, Y_test, verbose=1)
  24. print('Test accuracy:', score[1])


  25. weights = model.layers[0].get_weights()

  26. import matplotlib.pyplot as plt     
  27. import matplotlib.cm as cm
  28. import numpy

  29. fig = plt.figure()
  30.   
  31. w = weights[0].T         
  32. for neuron in range(hidden_neurons):         
  33.     ax = fig.add_subplot(10, 10, neuron+1)
  34.     ax.axis("off")
  35.     ax.imshow(numpy.reshape(w[neuron], (28, 28)), cmap = cm.Greys_r)

  36. plt.savefig("neuron_images.png", dpi=300)   
  37. plt.show()  
复制代码

板凳
ReneeBK(未真实交易用户) 发表于 2017-7-8 00:11:01
  1. import tensorflow as tf
  2. from tensorflow.examples.tutorials.mnist import input_data

  3. VISIBLE_NODES = 784
  4. HIDDEN_NODES = 400
  5. LEARNING_RATE = 0.01

  6. mnist = input_data.read_data_sets("MNIST_data/")

  7. input_placeholder = tf.placeholder("float", shape=(None, VISIBLE_NODES))

  8. weights = tf.Variable(tf.random_normal((VISIBLE_NODES, HIDDEN_NODES), mean=0.0, stddev=1. / VISIBLE_NODES))
  9. hidden_bias = tf.Variable(tf.zeros([HIDDEN_NODES]))
  10. visible_bias = tf.Variable(tf.zeros([VISIBLE_NODES]))

  11. hidden_activation = tf.nn.sigmoid(tf.matmul(input_placeholder, weights) + hidden_bias)
  12. visible_reconstruction = tf.nn.sigmoid(tf.matmul(hidden_activation, tf.transpose(weights)) + visible_bias)

  13. final_hidden_activation = tf.nn.sigmoid(tf.matmul(visible_reconstruction, weights) + hidden_bias)

  14. positive_phase = tf.matmul(tf.transpose(input_placeholder), hidden_activation)
  15. negative_phase = tf.matmul(tf.transpose(visible_reconstruction), final_hidden_activation)

  16. weight_update = weights.assign_add(LEARNING_RATE * (positive_phase - negative_phase))
  17. visible_bias_update = visible_bias.assign_add(LEARNING_RATE *
  18.                                               tf.reduce_mean(input_placeholder - visible_reconstruction, 0))
  19. hidden_bias_update = hidden_bias.assign_add(LEARNING_RATE *
  20.                                             tf.reduce_mean(hidden_activation - final_hidden_activation, 0))

  21. train_op = tf.group(weight_update, visible_bias_update, hidden_bias_update)

  22. loss_op = tf.reduce_sum(tf.square(input_placeholder - visible_reconstruction))

  23. session = tf.Session()

  24. session.run(tf.initialize_all_variables())

  25. current_epochs = 0

  26. for i in range(20):
  27.     total_loss = 0
  28.     while mnist.train.epochs_completed == current_epochs:
  29.         batch_inputs, batch_labels = mnist.train.next_batch(100)
  30.         _, reconstruction_loss = session.run([train_op, loss_op], feed_dict={input_placeholder: batch_inputs})
  31.         total_loss += reconstruction_loss

  32.     print("epochs %s loss %s" % (current_epochs, reconstruction_loss))
  33.     current_epochs = mnist.train.epochs_completed
复制代码

报纸
ReneeBK(未真实交易用户) 发表于 2017-7-8 00:12:32
  1. # -*- coding: utf-8 -*-

  2. import numpy  
  3. import theano  
  4. import matplotlib.pyplot as plt
  5. import theano.tensor as T
  6. from theano.tensor.nnet import conv
  7. import skimage.data

  8. import matplotlib.cm as cm

  9. depth = 4
  10. filter_shape = (3, 3)
  11.    
  12. input = T.tensor4(name='input')  
  13.    
  14. w_shape = (depth, 3, filter_shape[0], filter_shape[1])
  15. dist = numpy.random.uniform(-0.2, 0.2, size=w_shape)
  16. W = theano.shared(numpy.asarray(dist, dtype=input.dtype), name = 'W')                             
  17. conv_output = conv.conv2d(input, W)   
  18. output = T.nnet.sigmoid(conv_output)
  19. f = theano.function([input], output)

  20. astronaut = skimage.data.astronaut()
  21. img = numpy.asarray(astronaut, dtype='float32') / 255
  22. filtered_img = f(img.transpose(2, 0, 1).reshape(1, 3, 512, 512))


  23. plt.axis('off')
  24. plt.imshow(img)
  25. plt.show()  
  26. for img in range(depth):
  27.   fig = plt.figure()   
  28.   plt.axis( 'off')   
  29.   plt.imshow(filtered_img[0, img, :, :, ], cmap = cm.gray)
  30.   plt.show()

  31.   filename = "astro" + str(img)
  32.   fig.savefig(filename, bbox_inches='tight')
  33.   
复制代码

地板
ReneeBK(未真实交易用户) 发表于 2017-7-8 00:13:13
  1. # -*- coding: utf-8 -*-

  2. import numpy               

  3. from keras.datasets import cifar10
  4. from keras.models import Sequential
  5. from keras.layers.core import Dense, Activation
  6. from keras.layers import Convolution2D, MaxPooling2D, Flatten
  7. from keras.layers import Dropout
  8. from keras.utils import np_utils

  9. batch_size = 100     
  10. hidden_neurons = 200
  11. classes = 10     
  12. epochs = 20

  13. (X_train, Y_train), (X_test, Y_test) = cifar10.load_data()


  14. Y_train = np_utils.to_categorical(Y_train, classes)     
  15. Y_test = np_utils.to_categorical(Y_test, classes)

  16. model = Sequential()
  17. model.add(Convolution2D(32, (3, 3), input_shape=(32, 32, 3)))
  18. model.add(Activation('relu'))
  19. model.add(Convolution2D(32, (3, 3)))  
  20. model.add(Activation('relu'))
  21. model.add(MaxPooling2D(pool_size=(2, 2)))
  22. model.add(Dropout(0.25))   

  23. model.add(Convolution2D(64, (3, 3)))
  24. model.add(Activation('relu'))     
  25. model.add(Convolution2D(64, (3, 3)))     
  26. model.add(Activation('relu'))     
  27. model.add(MaxPooling2D(pool_size=(2, 2)))     
  28. model.add(Dropout(0.25))
  29.                
  30. model.add(Flatten())

  31. model.add(Dense(hidden_neurons))
  32. model.add(Activation('relu'))
  33. model.add(Dropout(0.5))      
  34. model.add(Dense(classes))
  35. model.add(Activation('softmax'))
  36.      

  37. model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adadelta')

  38. model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, validation_split = 0.1, verbose=1)

  39. score = model.evaluate(X_test, Y_test, verbose=1)
  40. print('Test accuracy:', score[1])

  41. numpy.set_printoptions(threshold='nan')  
  42. index = 0   
  43. for layer in model.layers:      
  44.   filename = "conv_layer_" + str(index)      
  45.   f1 = open(filename, 'w+')      
  46.   f1.write(repr(layer.get_weights()))      
  47.   f1.close()      
  48.   print (filename + " has been opened and closed")     
  49.   index = index+1
复制代码

7
cloudoversea(真实交易用户) 发表于 2017-7-8 00:21:38
看看     

8
tlw1987(未真实交易用户) 发表于 2017-7-8 00:23:33
22222222

9
ekscheng(真实交易用户) 发表于 2017-7-8 02:36:36

10
cszcszcsz(真实交易用户) 发表于 2017-7-8 05:33:26
谢谢 分享!

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注jltj
拉您入交流群
GMT+8, 2026-1-1 10:08