楼主: Lisrelchen
1632 14

[Microsoft Cognitive Toolkit]Classify Cancer Using Feed Forward Network [推广有奖]

  • 0关注
  • 62粉丝

VIP

已卖:4194份资源

院士

67%

还不是VIP/贵宾

-

TA的文库  其他...

Bayesian NewOccidental

Spatial Data Analysis

东西方数据挖掘

威望
0
论坛币
50288 个
通用积分
83.6306
学术水平
253 点
热心指数
300 点
信用等级
208 点
经验
41518 点
帖子
3256
精华
14
在线时间
766 小时
注册时间
2006-5-4
最后登录
2022-11-6

楼主
Lisrelchen 发表于 2017-9-17 02:26:33 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

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

经管之家联合CDA

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

感谢您参与论坛问题回答

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

+2 论坛币
The purpose of this tutorial is to familiarize you with quickly combining components from the CNTK python library to perform a classification task. You may skip Introduction section, if you have already completed the Logistic Regression tutorial or are familiar with machine learning.
IntroductionProblem
A cancer hospital has provided data and wants us to determine if a patient has a fatal malignant cancer vs. a benign growth. This is known as a classification problem. To help classify each patient, we are given their age and the size of the tumor. Intuitively, one can imagine that younger patients and/or patient with small tumor size are less likely to have malignant cancer. The data set simulates this application where the each observation is a patient represented as a dot where red color indicates malignant and blue indicates a benign disease. Note: This is a toy example for learning, in real life there are large number of features from different tests/examination sources and doctors'  experience that play into the diagnosis/treatment decision for a patient.

本帖隐藏的内容

Classify Cancer Using Feed Forward Network.pdf (104.57 KB)



二维码

扫码加我 拉你入群

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

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

关键词:Microsoft Cognitive Toolkit Micro soft

沙发
Lisrelchen 发表于 2017-9-17 02:28:04
  1. # Import the relevant components
  2. from __future__ import print_function # Use a function definition from future version (say 3.x from 2.7 interpreter)
  3. import matplotlib.pyplot as plt
  4. %matplotlib inline

  5. import numpy as np
  6. import sys
  7. import os

  8. import cntk as C
  9. import cntk.tests.test_utils
  10. cntk.tests.test_utils.set_device_from_pytest_env() # (only needed for our build system)
  11. C.cntk_py.set_fixed_random_seed(1) # fix a random seed for CNTK components
复制代码

藤椅
Lisrelchen 发表于 2017-9-17 02:28:28
  1. # Helper function to generate a random data sample
  2. def generate_random_data_sample(sample_size, feature_dim, num_classes):
  3.     # Create synthetic data using NumPy.
  4.     Y = np.random.randint(size=(sample_size, 1), low=0, high=num_classes)

  5.     # Make sure that the data is separable
  6.     X = (np.random.randn(sample_size, feature_dim)+3) * (Y+1)
  7.     X = X.astype(np.float32)   
  8.     # converting class 0 into the vector "1 0 0",
  9.     # class 1 into vector "0 1 0", ...
  10.     class_ind = [Y==class_number for class_number in range(num_classes)]
  11.     Y = np.asarray(np.hstack(class_ind), dtype=np.float32)
  12.     return X, Y
复制代码

板凳
Lisrelchen 发表于 2017-9-17 02:29:12
  1. # Create the input variables denoting the features and the label data. Note: the input
  2. # does not need additional info on number of observations (Samples) since CNTK first create only
  3. # the network tooplogy first
  4. mysamplesize = 64
  5. features, labels = generate_random_data_sample(mysamplesize, input_dim, num_output_classes)
复制代码

报纸
Lisrelchen 发表于 2017-9-17 02:29:32
  1. # Plot the data
  2. import matplotlib.pyplot as plt
  3. %matplotlib inline

  4. # given this is a 2 class
  5. colors = ['r' if l == 0 else 'b' for l in labels[:,0]]

  6. plt.scatter(features[:,0], features[:,1], c=colors)
  7. plt.xlabel("Scaled age (in yrs)")
  8. plt.ylabel("Tumor size (in cm)")
  9. plt.show()
复制代码

地板
Lisrelchen 发表于 2017-9-17 02:29:58
  1. Model Creation
  2. Our feed forward network will be relatively simple with 2 hidden layers (num_hidden_layers) with each layer having 50 hidden nodes (hidden_layers_dim).
  3. In [10]:
  4. # Figure 3
  5. Image(url="http://cntk.ai/jup/feedforward_network.jpg", width=200, height=200)
复制代码

7
auirzxp 学生认证  发表于 2017-9-17 02:30:15
提示: 作者被禁止或删除 内容自动屏蔽

8
Lisrelchen 发表于 2017-9-17 02:32:44
  1. Feed forward network setup

  2. In [13]:
  3. def linear_layer(input_var, output_dim):
  4. input_dim = input_var.shape[0]

  5. weight = C.parameter(shape=(input_dim, output_dim))
  6. bias = C.parameter(shape=(output_dim))

  7. return bias + C.times(input_var, weight)

  8. In [14]:
  9. def dense_layer(input_var, output_dim, nonlinearity):
  10. l = linear_layer(input_var, output_dim)

  11. return nonlinearity(l)

  12. In [15]:
  13. # Define a multilayer feedforward classification model
  14. def fully_connected_classifier_net(input_var, num_output_classes, hidden_layer_dim,
  15. num_hidden_layers, nonlinearity):

  16. h = dense_layer(input_var, hidden_layer_dim, nonlinearity)
  17. for i in range(1, num_hidden_layers):
  18. h = dense_layer(h, hidden_layer_dim, nonlinearity)

  19. return linear_layer(h, num_output_classes)

  20. The network output z will be used to represent the output of a network across.
  21. In [16]:
  22. # Create the fully connected classfier
  23. z = fully_connected_classifier_net(input, num_output_classes, hidden_layers_dim,
  24. num_hidden_layers, C.sigmoid)

  25. In [17]:
  26. def create_model(features):
  27. with C.layers.default_options(init=C.layers.glorot_uniform(), activation=C.sigmoid):
  28. h = features
  29. for _ in range(num_hidden_layers):
  30. h = C.layers.Dense(hidden_layers_dim)(h)
  31. last_layer = C.layers.Dense(num_output_classes, activation = None)

  32. return last_layer(h)

  33. z = create_model(input)
复制代码

9
Lisrelchen 发表于 2017-9-17 02:33:36
  1. # Instantiate the trainer object to drive the model training
  2. learning_rate = 0.5
  3. lr_schedule = C.learning_rate_schedule(learning_rate, C.UnitType.minibatch)
  4. learner = C.sgd(z.parameters, lr_schedule)
  5. trainer = C.Trainer(z, (loss, eval_error), [learner])

  6. First lets create some helper functions that will be needed to visualize different functions associated with training.
  7. In [21]:
  8. # Define a utility function to compute the moving average sum.
  9. # A more efficient implementation is possible with np.cumsum() function
  10. def moving_average(a, w=10):   
  11.     if len(a) < w:
  12.         return a[:]    # Need to send a copy of the array
  13.     return [val if idx < w else sum(a[(idx-w):idx])/w for idx, val in enumerate(a)]


  14. # Defines a utility that prints the training progress
  15. def print_training_progress(trainer, mb, frequency, verbose=1):   
  16.     training_loss = "NA"
  17.     eval_error = "NA"

  18.     if mb%frequency == 0:
  19.         training_loss = trainer.previous_minibatch_loss_average
  20.         eval_error = trainer.previous_minibatch_evaluation_average
  21.         if verbose:
  22.             print ("Minibatch: {}, Train Loss: {}, Train Error: {}".format(mb, training_loss, eval_error))
  23.         
  24.     return mb, training_loss, eval_error
复制代码

10
Lisrelchen 发表于 2017-9-17 02:35:02

Run the trainer

  1. In [22]:
  2. # Initialize the parameters for the trainer
  3. minibatch_size = 25
  4. num_samples = 20000
  5. num_minibatches_to_train = num_samples / minibatch_size
复制代码
  1. In [23]:
  2. # Run the trainer and perform model training
  3. training_progress_output_freq = 20

  4. plotdata = {"batchsize":[], "loss":[], "error":[]}

  5. for i in range(0, int(num_minibatches_to_train)):
  6.     features, labels = generate_random_data_sample(minibatch_size, input_dim, num_output_classes)
  7.    
  8.     # Specify the input variables mapping in the model to actual minibatch data for training
  9.     trainer.train_minibatch({input : features, label : labels})
  10.     batchsize, loss, error = print_training_progress(trainer, i,
  11.                                                      training_progress_output_freq, verbose=0)
  12.    
  13.     if not (loss == "NA" or error =="NA"):
  14.         plotdata["batchsize"].append(batchsize)
  15.         plotdata["loss"].append(loss)
  16.         plotdata["error"].append(error)
复制代码

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

本版微信群
加好友,备注jltj
拉您入交流群
GMT+8, 2025-12-31 21:38