https://github.com/tflearn/tflearn/blob/master/examples/others/recommender_wide_and_deep.py

 1 import numpy as np
 2 import matplotlib.pyplot as plt
 3 import tensorflow as tf
 4 import tflearn
 5 from tflearn.data_utils import to_categorical
 6 #matplotlib inline
 7 plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
 8 plt.rcParams['image.interpolation'] = 'nearest'
 9 plt.rcParams['image.cmap'] = 'gray'
10 
11 # for auto-reloading extenrnal modules
12 # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
13 #%load_ext autoreload
14 #%autoreload 2
15 
16 # 模块1-1 画图 展示样本形式
17 np.random.seed(0)
18 N = 100 # number of points per class
19 D = 2 # dimensionality
20 K = 3 # number of classes
21 X = np.zeros((N*K,D))
22 y = np.zeros(N*K, dtype='uint8')
23 for j in range(K):
24   ix = range(N*j,N*(j+1))
25   r = np.linspace(0.0,1,N) # radius
26   t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta
27   X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
28   y[ix] = j
29 fig = plt.figure()
30 plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
31 plt.xlim([-1,1])
32 plt.ylim([-1,1])
33 #fig.savefig('spiral_raw.png')
34 
35 
36 #模块1-2 训练 两层
37 import tensorflow as tf
38 import tflearn
39 from tflearn.data_utils import to_categorical
40 
41 with tf.Graph().as_default():
42     net = tflearn.input_data([None, 2])
43     net = tflearn.fully_connected(net, 100, activation='relu', weights_init='normal',
44                                   regularizer='L2', weight_decay=0.001)
45     net = tflearn.fully_connected(net, 3, activation='softmax')
46     sgd = tflearn.SGD(learning_rate=1.0, lr_decay=0.96, decay_step=500)
47     net = tflearn.regression(net, optimizer=sgd, loss='categorical_crossentropy')
48     
49 #    gd=tf.train.GradientDescentOptimizer(learning_rate=1.0)
50 #    net = tflearn.regression(net, optimizer=gd, loss='categorical_crossentropy')
51 
52     Y = to_categorical(y, 3)
53     model = tflearn.DNN(net)
54     model.fit(X, Y, show_metric=True, batch_size=len(X), n_epoch=100, snapshot_epoch=False)
55     #print model.predict(X)
56     Z = np.argmax(model.predict(X))
57     #print Z
58 
59 
60     
61 # 模块1-3  画图展示效果 plot the resulting classifier
62 h = 0.02
63 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
64 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
65 xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
66                      np.arange(y_min, y_max, h))
67 Z = np.argmax(model.predict(np.c_[xx.ravel(), yy.ravel()]), axis=1)
68 Z = Z.reshape(xx.shape)
69 fig = plt.figure()
70 plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8)
71 plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
72 plt.xlim(xx.min(), xx.max())
73 plt.ylim(yy.min(), yy.max())
74 #fig.savefig('spiral_net.png')
75 print("Accuracy: {}%".format(100 * np.mean(y == np.argmax(model.predict(X), axis=1))))

 

代码2 自己的数据

 

 1 import numpy as np
 2 import matplotlib.pyplot as plt
 3 import tensorflow as tf
 4 import tflearn
 5 from tflearn.data_utils import to_categorical
 6 import os
 7 
 8 label=[]
 9 feature=[]
10 f_tain=open("smp_pub_50d",'r')
11 for line in f_tain.readlines()[0:50000]:
12     samp=eval(line)
13     gender=int(samp[2])
14     feature1=samp[5:]
15     feature.append(feature1)
16     label.append(gender)
17 f_tain.close()
18 
19 X=np.array(feature)
20 Y=np.array(label)
21 
22 
23 #模块1-2 训练 两层
24 import tensorflow as tf
25 import tflearn
26 from tflearn.data_utils import to_categorical
27 
28 with tf.Graph().as_default():
29     net = tflearn.input_data([None, 50])
30     net = tflearn.fully_connected(net, 100, activation='relu', weights_init='normal',
31                                   regularizer='L2', weight_decay=0.001)
32     net = tflearn.fully_connected(net, 2, activation='softmax')
33     sgd = tflearn.SGD(learning_rate=1.0, lr_decay=0.96, decay_step=500)
34     net = tflearn.regression(net, optimizer=sgd, loss='categorical_crossentropy')
35     
36 #    gd=tf.train.GradientDescentOptimizer(learning_rate=1.0)
37 #    net = tflearn.regression(net, optimizer=gd, loss='categorical_crossentropy')
38 
39     Y = to_categorical(Y, 2)
40     model = tflearn.DNN(net)
41     model.fit(X, Y, validation_set=0.3,show_metric=True, batch_size=20000, n_epoch=100, snapshot_epoch=False)
42     #print model.predict(X)
43     Z = np.argmax(model.predict(X))
44     #print Z