コード例 #1
0
def main():
    X_train, y_train, X_test, y_test = load_income('./income.csv')

    lr = LogisticRegression(C=1000, lr_decay='step').fit(X_train, y_train)

    # lr.score(X_train, y_train)
    # lr.score(X_test, y_test)
    y_pred = lr.predict(X_train)
    print('\n==> train:\n', classification_report(y_train, y_pred))
    y_pred = lr.predict(X_test)
    print('\n==> test:\n', classification_report(y_test, y_pred))
コード例 #2
0
class SdA(object):
    """Stacked denoising auto-encoder class (SdA)
    A stacked denoising autoencoder model is obtained by stacking several
    dAs. The hidden layer of the dA at layer `i` becomes the input of
    the dA at layer `i+1`. The first layer dA gets as input the input of
    the SdA, and the hidden layer of the last dA represents the output.
    Note that after pretraining, the SdA is dealt with as a normal MLP,
    the dAs are only used to initialize the weights.
    """

    def __init__(self, numpy_rng, n_ins, hidden_layers_sizes, corruption_levels=[0.1, 0.1], theano_rng=None, n_outs=7):
        """ This class is made to support a variable number of layers.
        :type numpy_rng: numpy.random.RandomState
        :param numpy_rng: numpy random number generator used to draw initial
                    weights
        :type theano_rng: theano.tensor.shared_randomstreams.RandomStreams
        :param theano_rng: Theano random generator; if None is given one is
                           generated based on a seed drawn from `rng`
        :type n_ins: int
        :param n_ins: dimension of the input to the sdA
        :type n_layers_sizes: list of ints
        :param n_layers_sizes: intermediate layers size, must contain
                               at least one value
        :type n_outs: int
        :param n_outs: dimension of the output of the network
        :type corruption_levels: list of float
        :param corruption_levels: amount of corruption to use for each
                                  layer
        """

        self.sigmoid_layers = []
        self.dA_layers = []
        self.params = []
        self.n_layers = len(hidden_layers_sizes)
        self.n_ins = n_ins
        self.n_outs = n_outs

        # allocate symbolic variables for the data
        self.x = T.matrix("x")  # the data is presented as rasterized images
        self.y = T.iscalar("y")  # the labels are presented as 1D vector of
        # [int] labels

        assert self.n_layers > 0

        if not theano_rng:
            theano_rng = RandomStreams(numpy_rng.randint(2 ** 30))
        # end-snippet-1

        # The SdA is an MLP, for which all weights of intermediate layers
        # are shared with a different denoising autoencoders
        # We will first construct the SdA as a deep multilayer perceptron,
        # and when constructing each sigmoidal layer we also construct a
        # denoising autoencoder that shares weights with that layer
        # During pretraining we will train these autoencoders (which will
        # lead to chainging the weights of the MLP as well)
        # During finetunining we will finish training the SdA by doing
        # stochastich gradient descent on the MLP

        # start-snippet-2
        for i in xrange(self.n_layers):
            # construct the sigmoidal layer

            # the size of the input is either the number of hidden units of
            # the layer below or the input size if we are on the first layer
            if i == 0:
                input_size = n_ins
            else:
                input_size = hidden_layers_sizes[i - 1]

            # the input to this layer is either the activation of the hidden
            # layer below or the input of the SdA if you are on the first
            # layer
            if i == 0:
                layer_input = self.x
            else:
                layer_input = self.sigmoid_layers[-1].output

            sigmoid_layer = HiddenLayer(
                rng=numpy_rng,
                input=layer_input,
                n_in=input_size,
                n_out=hidden_layers_sizes[i],
                activation=T.nnet.sigmoid,
            )
            # add the layer to our list of layers
            self.sigmoid_layers.append(sigmoid_layer)
            # its arguably a philosophical question...
            # but we are going to only declare that the parameters of the
            # sigmoid_layers are parameters of the StackedDAA
            # the visible biases in the dA are parameters of those
            # dA, but not the SdA
            self.params.append(sigmoid_layer.theta)

            # Construct a denoising autoencoder that shared weights with this
            # layer
            dA_layer = dA(
                numpy_rng=numpy_rng,
                theano_rng=theano_rng,
                input=layer_input,
                n_visible=input_size,
                n_hidden=hidden_layers_sizes[i],
                theta=sigmoid_layer.theta,
            )
            self.dA_layers.append(dA_layer)
        # end-snippet-2
        # We now need to add a logistic layer on top of the MLP
        self.logLayer = LogisticRegression(
            input=self.sigmoid_layers[-1].output, n_in=hidden_layers_sizes[-1], n_out=n_outs
        )
        self.params.append(self.logLayer.params)

        self.finetune_cost = self.logLayer.negative_log_likelihood(self.y)
        # compute the gradients with respect to the model parameters
        # symbolic variable that points to the number of errors made on the
        # minibatch given by self.x and self.y
        self.errors = self.logLayer.errors(self.y)
        self.predict = self.logLayer.predict()
コード例 #3
0
ファイル: plot.py プロジェクト: wp-lai/xmachinelearning
import numpy as np
import matplotlib.pyplot as plt
from logistic import LogisticRegression

# read data
X = np.loadtxt('logistic_x.txt')
y = np.loadtxt('logistic_y.txt')

# build model
lr = LogisticRegression()
lr.fit(X, y)
y_ = lr.predict(X)

# create a mesh to plot in
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
h = 0.1  # step_size
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
data = np.vstack((xx.ravel(), yy.ravel())).T
labels = lr.predict(data)

# plot
fig, ax = plt.subplots()
ax.scatter(data[:, 0],
           data[:, 1],
           c=np.where(labels == 1, 'green', 'red'),
           alpha=0.01)
plt.title('Decision Boundary of Logistic Regression')
ax.scatter(X[y == 1, 0],
           X[y == 1, 1],
           c='green',
コード例 #4
0
def main():
    bodies, stances, index, body_IDs, stance_IDs, labels = generateSentences(
        'train_bodies.csv', 'train_stances.csv')
    encoder = LabelEncoder()
    encoder.fit(label_headers)
    encoded_labels = encoder.transform(labels)

    combined = matchStance(bodies, stances, body_IDs, stance_IDs)
    sorted_bodies = linkBodies(body_IDs, stance_IDs, bodies)

    training_bodies = sorted_bodies[0:index + 1]
    training_stances = stances[0:index + 1]
    training_labels = encoded_labels[0:index + 1]

    cv, tfidf = vectorise(training_bodies, training_stances, training_labels)

    # b_cv = cv.transform(training_bodies)
    # s_cv = cv.transform(training_stances)
    # b_tf = tfidf.transform(b_cv)
    # s_tf = tfidf.transform(s_cv)
    # cosineSim(training_bodies,training_stances,cv,training_labels,'plots/CS-vect.png')
    # cosineSim(b_tf,s_tf,tfidf,training_labels,'plots/CS-tfidf.png')
    #
    # kldivergence(b_cv.toarray(),s_cv.toarray(),training_labels,'plots/KL-vect.png')
    # kldivergence(b_tf.toarray(),s_tf.toarray(),training_labels,'plots/KL-tfidf.png')

    # valid_bodies = sorted_bodies[index+1:len(sorted_bodies)]
    # valid_stances = stances[index+1:len(stances)]
    valid_labels = encoded_labels[index + 1:len(encoded_labels)]
    valid_b_cv = cv.transform(sorted_bodies)
    valid_s_cv = cv.transform(stances)
    valid_b_tf = list(tfidf.transform(valid_b_cv).toarray())
    valid_s_tf = list(tfidf.transform(valid_s_cv).toarray())

    dists = calcDistances(valid_b_tf, valid_s_tf)
    distanceShow(dists[0:index + 1], training_labels)
    linear_dists = [
        dists[i][len(dists[i]) - 5:len(dists[i])]
        for i in range(0, len(dists))
    ]

    test_b, test_s, test_index, test_b_ids, test_s_ids, test_labels = generateSentences(
        'competition_test_bodies.csv', 'competition_test_stances.csv')
    encoded_test = encoder.transform(test_labels)
    test_sorted_b = linkBodies(test_b_ids, test_s_ids, test_b)

    test_b_tf = list(tfidf.transform(cv.transform(test_sorted_b)).toarray())
    test_s_tf = list(tfidf.transform(cv.transform(test_s)).toarray())
    test_dists = calcDistances(test_b_tf, test_s_tf)
    test_linear_dists = [
        test_dists[i][len(test_dists[i]) - 5:len(test_dists[i])]
        for i in range(0, len(test_dists))
    ]

    lrs = [0.0005, 0.001, 0.005, 0.01, 0.05, 0.1]
    for i in range(0, len(lrs)):
        logistic = LogisticRegression(lr=lrs[i], steps=10000)
        logistic.fit(input=dists[0:index + 1], labels=training_labels)
        y_pred = logistic.predict(test_dists)

        linear = LinearRegression(lr=lrs[i], steps=50)
        linear.fit(input=linear_dists[0:index + 1], labels=training_labels)
        y_pred2 = linear.predict(test_linear_dists)

        print "Logistic Classification, LR: {}".format(lrs[i])
        print(
            classification_report(y_true=list(encoded_test),
                                  y_pred=list(y_pred)))
        print(matthews_corrcoef(encoded_test, y_pred))

        print "Linear Classification, LR: {}".format(lrs[i])
        print(
            classification_report(y_true=list(encoded_test),
                                  y_pred=list(y_pred2)))
        print(matthews_corrcoef(encoded_test, y_pred2))