markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
<h3>Visualisierung der Daten</h3>
# Ausgabe Histogramm dataset.hist() pyplot.show() # Ausgabe der Dichtefunktion dataset.plot(kind='density', subplots=True, layout=(8,8), sharex=False, legend=False) pyplot.show() # Ausgabe scatter plot matrix scatter_matrix(dataset) pyplot.show() # Ausgabe correlation matrix fig = pyplot.figure() ax = fig.add_subplo...
18-05-14-ml-workcamp/sonar-daten/Projekt-Sonardaten-Workcamp-ML.ipynb
mediagit2016/workcamp-maschinelles-lernen-grundlagen
gpl-3.0
<h3>Vorbereiten der Daten: Aufteilen in Test und Trainingsdaten </h3>
# Split-out validation dataset array = dataset.values X = array[:,0:60].astype(float) Y = array[:,60] validation_size = 0.20 seed = 7 X_train, X_validation, Y_train, Y_validation = train_test_split(X, Y, test_size=validation_size, random_state=seed) # Evaluate Algorithms # Test options and evaluation metric num_folds...
18-05-14-ml-workcamp/sonar-daten/Projekt-Sonardaten-Workcamp-ML.ipynb
mediagit2016/workcamp-maschinelles-lernen-grundlagen
gpl-3.0
Im Ergebnis sind also K-NN und SCM die Algorithmen<br> die bessere Ergebnisse liefern<br> In die weiteren Betrachtungen und Optimierungen werden nur<br> noch diese Algorithmen einbezogen.<br>
# Tuning K-NN mit skalierten Daten - Die Anzahl der Nachbarn wird variiert scaler = StandardScaler().fit(X_train) rescaledX = scaler.transform(X_train) neighbors = [1,3,5,7,9,11,13,15,17,19,21] param_grid = dict(n_neighbors=neighbors) model = KNeighborsClassifier() kfold = KFold(n_splits=num_folds, random_state=seed) g...
18-05-14-ml-workcamp/sonar-daten/Projekt-Sonardaten-Workcamp-ML.ipynb
mediagit2016/workcamp-maschinelles-lernen-grundlagen
gpl-3.0
Then, we set up the parameterizations for the torus and the knot, using a meshgrid from u,v.
# First set up the figure, the axis, and the plot element we want to animate fig = figure() ax = axes(projection='3d') # we need to fix some parameters, describing size of the inner radus of the torus/knot r = .4 # We set the parameterization for the circle and the knot u = linspace(0, 2*pi, 100) v = linspace(0, 2*pi...
3D_Animation.ipynb
mlamoureux/PIMS_YRC
mit
We need an initialization function, an animation function, and then we call the animator to put it all together.
# initialization function: plot the background of each frame def init(): thingy = ax.plot_surface([0], [0], [0], color='c') return (thingy,) # animation function. This is called sequentially def animate(i): a = sin(pi*i/100)**2 # this is an interpolation parameter. a = 0 is torus, a=1 is knot x = (1-a...
3D_Animation.ipynb
mlamoureux/PIMS_YRC
mit
Finally, we call the HMML code to conver the animation object into a video. (This depends on having a MovieWriter installed on your system. Should be fine on syzygy.ca but it does not work on my Mac unless I install ffmpeg.)
HTML(anim.to_html5_video())
3D_Animation.ipynb
mlamoureux/PIMS_YRC
mit
If you click on the image above, you will see there is a button that allows you to download the animation as an mp4 file directly. Or you can use the following command:
anim.save('knot.mp4') 2+2
3D_Animation.ipynb
mlamoureux/PIMS_YRC
mit
Graphs! A good example of a real-world graph (because it happens to be one). For now it's just important to know that this is a graph of social interactions between 34 individuals involved in the same karate club. Drawing it less because it's informative, and more because plotting is fun.
real_graph = nx.karate_club_graph() positions = nx.spring_layout(real_graph) nx.draw(real_graph, node_color = 'blue', pos = positions)
networks-201/network_analysis.ipynb
blehman/Data-Science-45min-Intros
unlicense
Now. What's the difference between that (^) drawing of nodes and edges and a completely random assembly of dots and lines? How can we quantify the difference between a social network, which we think probably has important structure, and a completely random network, whose structure contains very little useful informatio...
# Use the same number of nodes for each example num_nodes = 500 # list of the sizes of the largest components big_comp = [] # number of nodes in the graph #num_nodes = 500 # vector of edge probabilities p_values = [(1-x*.0001) for x in xrange(9850,10000)] # try it a few times to get a smoother curve iterations = 10 fo...
networks-201/network_analysis.ipynb
blehman/Data-Science-45min-Intros
unlicense
Clustering coefficient The clustering coefficient is a measure of how many trianges (completely connected triples) there are in a graph. You can think about it as the probability that if Alice knows Bob and Charlie, Bob also knows Charlie. The clustering coefficient of a graph is equal to $$ C = \frac{\text{(number of ...
# vector of edge probabilities p_values_clustering = [x*.01 for x in xrange(0,100)] # try it a few times to get a smoother curve iterations = 1 # store the clustering coefficient clustering = [] for p in p_values_clustering: size_comps = [] for h in xrange(0, iterations): edge_list = [] for i in...
networks-201/network_analysis.ipynb
blehman/Data-Science-45min-Intros
unlicense
Small diameter graphs So we know that the giant component is very likely, even for sparse graphs, and also that the clustering coefficient is very low, even for relatively dense graphs. This means that the graph is almost completely connected, and that it is, at least locally, pretty similar to a tree graph (acyclic). ...
# list of the average (over X iterations) diameters of the largest components diam = [] # the degree distribution of the network for each average degree degrees = {} # vector of edge probabilities p_values = [(1-x*.0001) for x in xrange(9850,10000)] # try it a few times to get a smoother curve iterations = 10 for p in ...
networks-201/network_analysis.ipynb
blehman/Data-Science-45min-Intros
unlicense
A comparison with a real social graph:
print("The number of nodes in the graph (all are connected): {}".format(len(real_graph.nodes()))) print("The number of edges in the graph: {}".format(len(real_graph.edges()))) print("The average degree: {}".format(sum(nx.degree(real_graph).values())/len(real_graph.nodes()))) print("The clustering coefficient: {}".forma...
networks-201/network_analysis.ipynb
blehman/Data-Science-45min-Intros
unlicense
The Configuration Model Another random graph model: the configuration model. Instead of generating our own degree sequence, we use a specified degree sequence (say, use the degree sequence of a social graph that we have) and change how the edges are connected. This allows us to ask the question: "how much of this chara...
A = [] for v in real_graph.nodes(): for x in range(0, real_graph.degree(v)): A.append(v) shuffle(A) # make the edge list _E = [(A[2*x], A[2*x+1]) for x in range(0,int(len(A)/2))] E = set([x for x in _E if x[0]!=x[1]]) # add the edges to a new graph with the name node list C = real_graph.copy...
networks-201/network_analysis.ipynb
blehman/Data-Science-45min-Intros
unlicense
Asking questions using a null model A famous example of centrality measuring on a social network is the Florentine Families graph. Padgett's reseach on this graph claims that the Medicci family's rise to power can be explained by their high centrality on the graph of business interactions between families in Italy duri...
# get the graph florentine_families = igraph.Nexus.get("padgett")["PADGB"]
networks-201/network_analysis.ipynb
blehman/Data-Science-45min-Intros
unlicense
First, let's show the relative rankings of the families with respect to vertex degree in the network and with respect to our chosen centrality measure, harmonic centrality. I won't go into various centrality measures here, beyond to say that harmonic centrality is formulated: $$ c_i = \frac{1}{n-1}\sum_{i,i\neq j}^{n-...
# degree centrality d = florentine_families.degree() d_rank = [(x, florentine_families.vs[x]['name'], d[x]) for x in range(0,len(florentine_families.vs()))] d_rank.sort(key = itemgetter(2), reverse = True) # harmonic centrality distances = florentine_families.shortest_paths_dijkstra() h = [sum([1/x for x in dist if x ...
networks-201/network_analysis.ipynb
blehman/Data-Science-45min-Intros
unlicense
Now the fun (?) part. Create a bunch of different random configuration models based on the florentine families graph, then measure the harmonic centrality on those graphs. The harmonic centality of a node on the null model will deend only on its degree (as the graph structure is now ranom).
config_model_centrality = [[] for x in florentine_families.vs()] config_model_means = [] hc_differences = [[] for x in range(0,16)] for i in xrange(0,1000): # build a random graph based on the configuration model C = florentine_families.copy() # graph with the same edge list as G C.delete_edges(None) ...
networks-201/network_analysis.ipynb
blehman/Data-Science-45min-Intros
unlicense
For the classification task, we will build a ridge regression model, and train it on a part of the full dataset
from sklearn.linear_model import * clf = RidgeClassifier(random_state = 1960) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(df[lFeatures].values, df['TGT'].values, test_size=0.2, random_state=1960) clf.fit(X_train , y_train)
doc/sklearn_reason_codes.ipynb
antoinecarme/sklearn_explain
bsd-3-clause
This is a standard linear model, that assigns a coefficient to each predictor value, these coefficients can be seen as global importance indicators for the predictors.
coefficients = dict(zip(ds.feature_names, [clf.coef_.ravel()[i] for i in range(clf.coef_.shape[1])])) df_var_importance = pd.DataFrame() df_var_importance['variable'] = list(coefficients.keys()) df_var_importance['importance'] = df_var_importance['variable'].apply(coefficients.get) %matplotlib inline df_var_importance....
doc/sklearn_reason_codes.ipynb
antoinecarme/sklearn_explain
bsd-3-clause
To put it simply, this is a global view of all the indivduals. The most important variable is 'mean radius', the higher the radius of the tumor, the higher the score of being malignant. On the oppopsite side, the higher the 'mean perimeter' is, the lower the score. Model Explanation The goal here is to be able, for a g...
df['Score'] = clf.decision_function(df[lFeatures].values) df['Decision'] = clf.predict(df[lFeatures].values) df.sample(6, random_state=1960)
doc/sklearn_reason_codes.ipynb
antoinecarme/sklearn_explain
bsd-3-clause
Predictor Effects Predictor effects describe the impact of specific predictor values on the partial score. For example, some values of a predictor can increase or decrease the partial score (and hence the score) by 10 or more points and change the negative decision to a positive one. The effect reflects how a specific...
for col in lFeatures: lContrib = df[col] * coefficients[col] df[col + '_Effect'] = lContrib - lContrib.mean() df.sample(6, random_state=1960)
doc/sklearn_reason_codes.ipynb
antoinecarme/sklearn_explain
bsd-3-clause
The previous sample, shows that the first individual lost 1.148856 score points due to the feature $X_1$, gained 2.076852 with the feature $X_3$, etc Reason Codes The reason codes are a user-oriented representation of the decision making process. These are the predictors ranked by their effects.
import numpy as np reason_codes = np.argsort(df[[col + '_Effect' for col in lFeatures]].values, axis=1) df_rc = pd.DataFrame(reason_codes, columns=['reason_' + str(NC-c) for c in range(NC)]) df_rc = df_rc[list(reversed(df_rc.columns))] df = pd.concat([df , df_rc] , axis=1) for c in range(NC): df['reason_' + str(c+1...
doc/sklearn_reason_codes.ipynb
antoinecarme/sklearn_explain
bsd-3-clause
Implement Sarsa(λ) in 21s. [x] Initialise the value function to zero. [x] Use the same step-size and exploration schedules as in the previous section. [x] Run the algorithm with parameter values λ ∈ {0, 0.1, 0.2, ..., 1}. [x] Stop each run after 1000 episodes and report the mean-squared error over all states a...
class Sarsa_Agent: def __init__(self, environment, n0, mlambda): self.n0 = float(n0) self.env = environment self.mlambda = mlambda # N(s) is the number of times that state s has been visited # N(s,a) is the number of times that action a has been selected from state s...
Joe #3 TD Learning in Easy21/Joe #3 TD Learning in Easy21.ipynb
analog-rl/Easy21
mit
Plot the mean- squared error against λ. Stop each run after 1000 episodes and report the mean-squared error over all states and actions, comparing the true values Q∗(s,a) computed in the previous section with the estimated values Q(s, a) computed by Sarsa.
mc_agent = MC_Agent(Environment(), 100) mc_agent.train(1000000) N0 = 100 lambdas = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1] agent_list = [] sme_list = [] n_elements = mc_agent.Q.shape[0]*mc_agent.Q.shape[1]*2 for l in lambdas: agent = Sarsa_Agent(Environment(), N0, l) agent_list.append(l) agent.train(100...
Joe #3 TD Learning in Easy21/Joe #3 TD Learning in Easy21.ipynb
analog-rl/Easy21
mit
For λ = 0 and λ = 1 only, plot the learning curve of mean-squared error against episode number.
import matplotlib.pyplot as plt import matplotlib.animation as animation from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm %matplotlib inline fig = plt.figure("N100") surf = plt.plot(lambdas[1:10], sme_list[1:10]) plt.show() N0 = 100 l = 0.0 learning_rate = [] learning_rate_i = [] n_elements = len(m...
Joe #3 TD Learning in Easy21/Joe #3 TD Learning in Easy21.ipynb
analog-rl/Easy21
mit
plot from #2
def animate(frame): i = agent.iterations step_size = i step_size = max(1, step_size) step_size = min(step_size, 2 ** 16) agent.train(step_size) ax.clear() surf = agent.plot_frame(ax) plt.title('MC score:%s frame:%s step_size:%s ' % (float(agent.count_wins)/agent.iterations*100, frame, ...
Joe #3 TD Learning in Easy21/Joe #3 TD Learning in Easy21.ipynb
analog-rl/Easy21
mit
Time to build the network Below you'll build your network. We've built out the structure and the backwards pass. You'll implement the forward pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes. <img src="assets/neural_network.p...
class NeuralNetwork(object): def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate): # Set number of nodes in input, hidden and output layers. self.input_nodes = input_nodes self.hidden_nodes = hidden_nodes self.output_nodes = output_nodes # Initialize we...
first-neural-network/Your_first_neural_network.ipynb
arturops/deep-learning
mit
Unit tests Run these unit tests to check the correctness of your network implementation. This will help you be sure your network was implemented correctly befor you starting trying to train it. These tests must all be successful to pass the project.
import unittest inputs = np.array([[0.5, -0.2, 0.1]]) targets = np.array([[0.4]]) test_w_i_h = np.array([[0.1, -0.2], [0.4, 0.5], [-0.3, 0.2]]) test_w_h_o = np.array([[0.3], [-0.1]]) class TestMethods(unittest.TestCase): ########## # Un...
first-neural-network/Your_first_neural_network.ipynb
arturops/deep-learning
mit
Training the network Here you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training se...
import sys ### Set the hyperparameters here ### iterations = 30000 #100 learning_rate = 0.1 #0.1 hidden_nodes = 14 #2 output_nodes = 1 #good settings: 1000, 0.5, 2; #10000, 0.1,4 ; 10000, 0.1, 6; #best ve = 0.052,vl=0.17 w 100000,0.1,6 # best ve = 0.058,vl=0.142 w 25000,0.15,8 # best ve = 0.051,vl=0.133 w 25000,0.15...
first-neural-network/Your_first_neural_network.ipynb
arturops/deep-learning
mit
Importing the datasets
redSetPath = "classification/winequality-red.csv" # whiteSetPath = "classification/winequality-white.csv" #Reading in the raw data. Note that the features are seperated by ';' character redSet = pd.read_csv(redSetPath, sep=';') # whiteSet = pd.read_csv(whiteSetPath, sep=';') # redSet.drop(['index'], axis=1, inplace=...
vagrant/dataset/hw2/ClassificationDataset.ipynb
justiceamoh/ENGS108
apache-2.0
Braking datasets into training and testing sets
#Breaking the datasets into 70% training and 30% testing red_train, red_test = train_test_split(redSet,test_size=0.30) red_train, red_valid = train_test_split(red_train,test_size=0.20) # white_train, white_test = train_test_split(whiteSet,test_size=0.30) # white_train, white_valid = train_test_split(white_train,test...
vagrant/dataset/hw2/ClassificationDataset.ipynb
justiceamoh/ENGS108
apache-2.0
Saving the train and test datasets
# Red Wine red_train_path = "classification/red_train.csv" red_valid_path = "classification/red_valid.csv" red_test_path = "classification/red_test.csv" # # White Wine # white_train_path = "classification/white_train.csv" # white_valid_path = "classification/white_valid.csv" # white_test_path = "classification/wh...
vagrant/dataset/hw2/ClassificationDataset.ipynb
justiceamoh/ENGS108
apache-2.0
Checking the saved data and their shapes:
print 'Red Wine - Number of Instances Per Set' print 'Training Set: %d'%(len(red_train)) print 'Validation Set: %d'%(len(red_valid)) print 'Testing Set: %d'%(len(red_test)) # print '' # print '' # print 'White Wine - Number of Instances Per Set' # print 'Training Set: %d'%(len(white_train)) # print 'Validation...
vagrant/dataset/hw2/ClassificationDataset.ipynb
justiceamoh/ENGS108
apache-2.0
Set the random seed:
class linear_regression(nn.Module): def __init__(self,input_size,output_size): super(linear_regression,self).__init__() self.linear=nn.Linear(input_size,output_size) def forward(self,x): yhat=self.linear(x) return yhat
DL0110EN/2.6.3.multi-target_linear_regression.ipynb
atlury/deep-opencl
lgpl-3.0
create a linear regression object, as our input and output will be two we set the parameters accordingly
model=linear_regression(2,2)
DL0110EN/2.6.3.multi-target_linear_regression.ipynb
atlury/deep-opencl
lgpl-3.0
we can use the diagram to represent the model or object <img src = "https://ibm.box.com/shared/static/icmwnxru7nytlhnq5x486rffea9ncpk7.png" width = 600, align = "center"> we can see the parameters
list(model.parameters())
DL0110EN/2.6.3.multi-target_linear_regression.ipynb
atlury/deep-opencl
lgpl-3.0
we can create a tensor with two rows representing one sample of data
x=torch.tensor([[1.0,3.0]])
DL0110EN/2.6.3.multi-target_linear_regression.ipynb
atlury/deep-opencl
lgpl-3.0
we can make a prediction
yhat=model(x) yhat
DL0110EN/2.6.3.multi-target_linear_regression.ipynb
atlury/deep-opencl
lgpl-3.0
each row in the following tensor represents a different sample
X=torch.tensor([[1.0,1.0],[1.0,2.0],[1.0,3.0]])
DL0110EN/2.6.3.multi-target_linear_regression.ipynb
atlury/deep-opencl
lgpl-3.0
we can make a prediction using multiple samples
Yhat=model(X) Yhat
DL0110EN/2.6.3.multi-target_linear_regression.ipynb
atlury/deep-opencl
lgpl-3.0
QGrid Interactive pandas dataframes: https://github.com/quantopian/qgrid pip install qgrid --upgrade
df2 = df[df['Mine_State'] != "Wyoming"].groupby('Mine_State').sum() df3 = df.groupby('Mine_State').sum() # have to run this from the home dir of this repo # cd insight/ # python setup.py develop %aimport insight.plotting insight.plotting.plot_prod_vs_hours(df3, color_index=1) # insight.plotting.plot_prod_vs_hours(d...
notebooks/08-old.ipynb
jbwhit/jupyter-tips-and-tricks
mit
Deep Dream This notebook contains the code samples found in Chapter 8, Section 2 of Deep Learning with Python. Note that the original text features far more content, in particular further explanations and figures: in this notebook, you will only find source code and related comments. [...] Implementing Deep Dream in K...
from keras.applications import inception_v3 from keras import backend as K # We will not be training our model, # so we use this command to disable all training-specific operations K.set_learning_phase(0) # Build the InceptionV3 network. # The model will be loaded with pre-trained ImageNet weights. model = inception_...
keras-notebooks/advanced/8.2-deep-dream.ipynb
infilect/ml-course1
mit
Next, we compute the "loss", the quantity that we will seek to maximize during the gradient ascent process. In Chapter 5, for filter visualization, we were trying to maximize the value of a specific filter in a specific layer. Here we will simultaneously maximize the activation of all filters in a number of layers. S...
# Dict mapping layer names to a coefficient # quantifying how much the layer's activation # will contribute to the loss we will seek to maximize. # Note that these are layer names as they appear # in the built-in InceptionV3 application. # You can list all layer names using `model.summary()`. layer_contributions = { ...
keras-notebooks/advanced/8.2-deep-dream.ipynb
infilect/ml-course1
mit
Now let's define a tensor that contains our loss, i.e. the weighted sum of the L2 norm of the activations of the layers listed above.
# Get the symbolic outputs of each "key" layer (we gave them unique names). layer_dict = dict([(layer.name, layer) for layer in model.layers]) # Define the loss. loss = K.variable(0.) for layer_name in layer_contributions: # Add the L2 norm of the features of a layer to the loss. coeff = layer_contributions[la...
keras-notebooks/advanced/8.2-deep-dream.ipynb
infilect/ml-course1
mit
Now we can set up the gradient ascent process:
# This holds our generated image dream = model.input # Compute the gradients of the dream with regard to the loss. grads = K.gradients(loss, dream)[0] # Normalize gradients. grads /= K.maximum(K.mean(K.abs(grads)), 1e-7) # Set up function to retrieve the value # of the loss and gradients given an input image. output...
keras-notebooks/advanced/8.2-deep-dream.ipynb
infilect/ml-course1
mit
Finally, here is the actual Deep Dream algorithm. First, we define a list of "scales" (also called "octaves") at which we will process the images. Each successive scale is larger than previous one by a factor 1.4 (i.e. 40% larger): we start by processing a small image and we increasingly upscale it: Then, for each su...
import scipy from keras.preprocessing import image def resize_img(img, size): img = np.copy(img) factors = (1, float(size[0]) / img.shape[1], float(size[1]) / img.shape[2], 1) return scipy.ndimage.zoom(img, factors, order=1) def save_img(img, fname): pil_i...
keras-notebooks/advanced/8.2-deep-dream.ipynb
infilect/ml-course1
mit
What TensorFlow actually did in that single line was to add new operations to the computation graph. These operations included ones to compute gradients, compute parameter update steps, and apply update steps to the parameters. The returned operation train_step, when run, will apply the gradient descent updates to the ...
for i in range(1000): batch = data_sets.train.next_batch(50) train_step.run(feed_dict={x: batch[0], y_: batch[1]})
deep_polygoggles.ipynb
silberman/polygoggles
mit
Evaluate the Model How well did our model do? First we'll figure out where we predicted the correct label. tf.argmax is an extremely useful function which gives you the index of the highest entry in a tensor along some axis. For example, tf.argmax(y,1) is the label our model thinks is most likely for each input, while ...
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
deep_polygoggles.ipynb
silberman/polygoggles
mit
Finally, we can evaluate our accuracy on the test data. (On MNIST this should be about 91% correct.)
print(accuracy.eval(feed_dict={x: data_sets.test.images, y_: data_sets.test.labels}))
deep_polygoggles.ipynb
silberman/polygoggles
mit
Build a Multilayer Convolutional Network Getting 91% accuracy on MNIST is bad. It's almost embarrassingly bad. In this section, we'll fix that, jumping from a very simple model to something moderately sophisticated: a small convolutional neural network. This will get us to around 99.2% accuracy -- not state of the art,...
def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial)
deep_polygoggles.ipynb
silberman/polygoggles
mit
To apply the layer, we first reshape x to a 4d tensor, with the second and third dimensions corresponding to image width and height, and the final dimension corresponding to the number of color channels.
x_image = tf.reshape(x, [-1, width, height,1]) # XXX not sure which is width and which is height # We then convolve x_image with the weight tensor, add the bias, apply the ReLU function, and finally max pool. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1)
deep_polygoggles.ipynb
silberman/polygoggles
mit
Densely Connected Layer Now that the image size has been reduced to 7x7, we add a fully-connected layer with 1024 neurons to allow processing on the entire image. We reshape the tensor from the pooling layer into a batch of vectors, multiply by a weight matrix, add a bias, and apply a ReLU. XXX where is the 7x7 coming ...
def get_size_reduced_to_from_input_tensor_size(input_tensor_size): size_reduced_to_squared = input_tensor_size / 64. / batch_size # last divide is 50., pretty sure it's batch size return math.sqrt(size_reduced_to_squared) print(get_size_reduced_to_from_input_tensor_size(4620800)) print(get_size_reduced_to_from_...
deep_polygoggles.ipynb
silberman/polygoggles
mit
Readout Layer Finally, we add a softmax layer, just like for the one layer softmax regression above.
W_fc2 = weight_variable([1024, num_labels]) b_fc2 = bias_variable([num_labels]) y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
deep_polygoggles.ipynb
silberman/polygoggles
mit
Train and Evaluate the Model How well does this model do? To train and evaluate it we will use code that is nearly identical to that for the simple one layer SoftMax network above. The differences are that: we will replace the steepest gradient descent optimizer with the more sophisticated ADAM optimizer; we will inclu...
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) sess.run(tf.initialize_all_variables()) for i in range(num_training_...
deep_polygoggles.ipynb
silberman/polygoggles
mit
Unit Tests Overview and Principles Testing is the process by which you exercise your code to determine if it performs as expected. The code you are testing is referred to as the code under test. There are two parts to writing tests. 1. invoking the code under test so that it is exercised in a particular way; 1. evalua...
import numpy as np # Code Under Test def entropy(ps): if any([(p < 0.0) or (p > 1.0) for p in ps]): raise ValueError("Bad input.") if sum(ps) > 1: raise ValueError("Bad input.") items = ps * np.log(ps) new_items = [] for item in items: if np.isnan(item): new_items...
Spring2019/04a_Exceptions_and_Testing/unit-tests.ipynb
UWSEDS/LectureNotes
bsd-2-clause
You see that there are many, many cases to test. So far, we've been writing special codes for each test case. We can do better. Testing Data Producing Codes Much of your python (or R) codes will be creating and/or transforming dataframes. A dataframe is structured like a table with: Columns that have values of the sam...
def makeProbabilityMatrix(column_names, nrows): """ Makes a dataframe with the specified column names such that each cell is a value in [0, 1] and columns sum to 1. :param list-str column_names: names of the columns :param int nrows: number of rows """ df = pd.DataFrame(np.random.uniform(0, ...
Spring2019/04a_Exceptions_and_Testing/unit-tests.ipynb
UWSEDS/LectureNotes
bsd-2-clause
Exercise Write a function that tests the following: - The returned dataframe has the expected columns - The returned dataframe has the expected rows - Values in columns are of the correct type and range - Values in column sum to 1 Unittest Infrastructure There are several reasons to use a test infrastructure: - If you ...
import unittest # Define a class in which the tests will run class UnitTests(unittest.TestCase): # Each method in the class to execute a test def test_success(self): self.assertEqual(1, 1) def test_success1(self): self.assertTrue(1 == 1) def test_failure(self): self.a...
Spring2019/04a_Exceptions_and_Testing/unit-tests.ipynb
UWSEDS/LectureNotes
bsd-2-clause
LinSpace:0 means output of LinSpace. TensorFlow doesn't compute the values immediately. It only specifies the nature of the output of a TF operation, also called an Op node.
x = tf.linspace(-3.0, 3.0, 100) # Doesn't compute immediately # Note that tf.linspace(-3, 3, 5) gives an error because datatypes are # mismatched print (x)
Introduction/TensorFlow Basics.ipynb
aliasvishnu/TensorFlow-Creative-Applications
gpl-3.0
We can get the elements of the graph by doing as follows. We can also get the output of a certain node in the graph
g = tf.get_default_graph() print [op.name for op in g.get_operations()] # List of ops # This next step would not work because the tensor doesn't exist yet, we will compute it later. ### print g.get_tensor_by_name('LinSpace_1:0') # Note that LinSpace has a :0 at the end of it. Without :0, it refers to the Node itself...
Introduction/TensorFlow Basics.ipynb
aliasvishnu/TensorFlow-Creative-Applications
gpl-3.0
Session In order to get run a TF program, we need a session. The session computes the graph we construct. Here's an example.
sess = tf.Session() # We can ask a session to compute the value of a node computed_x = sess.run(x) # print (computed_x) # Or we can ask the node to compute itself using the session computed_x = x.eval(session = sess) # print computed_x # We can close the session by doing this sess.close()
Introduction/TensorFlow Basics.ipynb
aliasvishnu/TensorFlow-Creative-Applications
gpl-3.0
We can ask TF to create a new graph and have it be connected to another session. We are allowed to have multiple sessions running at the same time.
g = tf.get_default_graph() # Fetch the default graph g2 = tf.Graph() print g2 sess2 = tf.Session(graph = g2) print sess2 sess2.close()
Introduction/TensorFlow Basics.ipynb
aliasvishnu/TensorFlow-Creative-Applications
gpl-3.0
Interactive Session - This is a way to run session in environments like notebooks where you don't want to pass around a session variable. But it's just like a session. Here's how to create one. Also this behaves more like a normal python program. You have to recompute the formula if you want updates. For example, z is ...
sess = tf.InteractiveSession() # print x.eval() print x.get_shape() # x.shape print x.get_shape().as_list() # x.shape.tolist()
Introduction/TensorFlow Basics.ipynb
aliasvishnu/TensorFlow-Creative-Applications
gpl-3.0
Example - Creating a Gaussian Curve
mean = 0 sigma = 1.0 z = 1.0/(tf.sqrt(2*3.14)*sigma) * (tf.exp(-1*(tf.pow(x-mean, 2)/(2*tf.pow(sigma, 2))))) res = z.eval() # Note that x is already defined from above plt.plot(res) plt.show()
Introduction/TensorFlow Basics.ipynb
aliasvishnu/TensorFlow-Creative-Applications
gpl-3.0
Making it into a 2D Gaussian
l = z.get_shape().as_list()[0] res2d = tf.matmul(tf.reshape(z, [l, 1]), tf.reshape(z, [1, l])).eval() plt.imshow(res2d) plt.show()
Introduction/TensorFlow Basics.ipynb
aliasvishnu/TensorFlow-Creative-Applications
gpl-3.0
Convolution Loading 'camera' images from sklearn
from skimage import data img = data.camera().astype(np.float32) plt.imshow(img, cmap='gray') plt.show()
Introduction/TensorFlow Basics.ipynb
aliasvishnu/TensorFlow-Creative-Applications
gpl-3.0
Convolution operation in TF takes in a 4d tensor for images. The dimensions are (Batch x Height x Width x Channel). Our image is grayscale. So we reshape it using numpy into 4d as shown below. Tensors must be float16, float32 or float64.
# Image shape is 512x512 img4d = tf.reshape(img, [1, img.shape[0], img.shape[1], 1]) print img4d.get_shape()
Introduction/TensorFlow Basics.ipynb
aliasvishnu/TensorFlow-Creative-Applications
gpl-3.0
For the convolution operation we need to provide the specifics of the kernels - Height x Width x Channel x Number of kernels. Let's now convert our gaussian kernel in this format and convolve our image.
l = res2d.shape[0] kernel = tf.reshape(res2d, [l, l, 1, 1]) print kernel.get_shape() # Convolution operation convolved = tf.nn.conv2d(img4d, kernel, strides = [1, 1, 1, 1], padding = 'SAME') plt.imshow(convolved.eval()[0, :, :, 0], cmap = 'gray') plt.show()
Introduction/TensorFlow Basics.ipynb
aliasvishnu/TensorFlow-Creative-Applications
gpl-3.0
Gabor Kernel We can take a sin wave and modulate it with the gaussian kernel to get a gabor kernel.
ksize = 100 xs = tf.linspace(-3.0, 3.0, ksize) ys = tf.sin(xs+2) # The following two statements are equivalent to # plt.plot(xs.eval(), ys.eval()) plt.figure() plt.plot(ys.eval()) plt.show()
Introduction/TensorFlow Basics.ipynb
aliasvishnu/TensorFlow-Creative-Applications
gpl-3.0
We need to convert this sine wave into a matrix and multiply with the gaussian kernel. That will be the gabor filter.
ys = tf.reshape(ys, [ksize, 1]) ones = tf.ones([1, ksize]) mat = tf.matmul(ys, ones) plt.imshow(mat.eval(), cmap = 'gray') plt.show() # Multiply with the gaussian kernel # kernel is 4 dimensional, res2d is the 2d version gabor = tf.matmul(mat, res2d) plt.imshow(gabor.eval(), cmap = 'gray') plt.show()
Introduction/TensorFlow Basics.ipynb
aliasvishnu/TensorFlow-Creative-Applications
gpl-3.0
Convolution using Placeholders We can specify parameters that we expect to fit in the graph later on, now, by using placeholders. Convolution using placeholders is presented below.
img = tf.placeholder(tf.float32, shape = [None, None], name = 'img') # Reshaping inbuilt function img3d = tf.expand_dims(img, 2) print img3d.get_shape() img4d = tf.expand_dims(img3d, 0) print img4d.get_shape() mean = tf.placeholder(tf.float32, name = 'mean') sigma = tf.placeholder(tf.float32, name = 'sigma') ksize = ...
Introduction/TensorFlow Basics.ipynb
aliasvishnu/TensorFlow-Creative-Applications
gpl-3.0
Leveraging Quantile Regression For A/B Test When launching new features to our product, we often times leverage experiments, or so called A/B tests in order to understand and quantify their impact. Popular statistical methods such as t-test often focuses on calculating average treatment effects. Not that there's anythi...
# constant column names used across the notebook arr_delay = 'arr_delay' airline_name = 'name' def read_data(path='flights.csv'): """Will try and download the data to local [path] if it doesn't exist.""" if not os.path.exists(path): base_url = 'https://media.githubusercontent.com/media/WillKoehrsen/Da...
ab_tests/quantile_regression/ab_test_regression.ipynb
ethen8181/machine-learning
mit
To start with, we'll use density plot to visualize the distribution of the arr_delay field. For those that are not familiar, think of it as a continuous version of histogram (The plot below overlays density plot on top of histogram).
# change default style figure and font size plt.rcParams['figure.figsize'] = 10, 8 plt.rcParams['font.size'] = 12 sns.distplot(df[arr_delay], hist=True, kde=True, hist_kws={'edgecolor':'black'}, kde_kws={'linewidth': 4}) plt.show()
ab_tests/quantile_regression/ab_test_regression.ipynb
ethen8181/machine-learning
mit
Now, let's say we would like to use this data and compare the arrive time delay of two airlines and once again we'll use our good old density plot to visualize and compare the two airline's arrival time distribution. Not affiliated with any one of the airline in anyway and neither is this data guaranteed to be up to d...
endeavor_airline = 'Endeavor Air Inc.' us_airway_airline = 'US Airways Inc.' for airline in [endeavor_airline, us_airway_airline]: subset = df[df[airline_name] == airline] sns.distplot(subset[arr_delay], hist=False, kde=True, kde_kws={'shade': False, 'linewidth': 3}, label=airline) p...
ab_tests/quantile_regression/ab_test_regression.ipynb
ethen8181/machine-learning
mit
After visualizing the arrival time on the two airlines, we can see that although both distribution seems to be centered around the same area, the tail-end of both side tells a different story, where one of the airline shows that it has a larger tendency of resulting in a delay. If we were to leverage the two sample t-t...
airline1_delay = df.loc[df[airline_name] == endeavor_airline, arr_delay] airline2_delay = df.loc[df[airline_name] == us_airway_airline, arr_delay] result = stats.ttest_ind(airline1_delay, airline2_delay, equal_var=True) result
ab_tests/quantile_regression/ab_test_regression.ipynb
ethen8181/machine-learning
mit
We can also leverage a single binary variable linear regression to arrive at the same conclusion as the two sample t-test above. The step to do this is do convert our airline variable into a dummy variable and fit a linear regression using the dummy variable as the input feature and the arrival delay time as the respon...
mask = df[airline_name].isin([endeavor_airline, us_airway_airline]) df_airline_delay = df[mask].reset_index(drop=True) y = df_airline_delay[arr_delay] X = pd.get_dummies(df_airline_delay[airline_name], drop_first=True) X.head()
ab_tests/quantile_regression/ab_test_regression.ipynb
ethen8181/machine-learning
mit
We'll be using statsmodel to build the linear regression as it gives R-like statistical output. For people coming from scikit-learn, y variable comes first in statsmodel and by default, it doesn't automatically fit a constant/intercept, so we'll need to add it ourselves.
# ordinary least square model = sm.OLS(y, sm.add_constant(X)) result = model.fit() result.summary()
ab_tests/quantile_regression/ab_test_regression.ipynb
ethen8181/machine-learning
mit
Notice that the numbers for the t-statistic and p-value matches the two-sample t-test result above. The benefit of using a linear regression is that, we can include many other features to see if they are the reasons behind the arrival delay. By looking at average treatment effect, we can see that we would be drawing th...
model = sm.QuantReg(y, sm.add_constant(X)) result = model.fit(q=0.9, kernel='gau') result.summary()
ab_tests/quantile_regression/ab_test_regression.ipynb
ethen8181/machine-learning
mit
At 0.9 quantile, we were able to detect a statistically significant effect! We can of course, also compute this across multiples quantiles and plot the quantile treatment effect in a single figure to get a much more nuanced insights into the treatment effect of our experiment that different quantiles. This allows us th...
def compute_quantile_treatment_effect(X, y, quantiles): coefs = [] pvalues = [] for q in quantiles: model = sm.QuantReg(y, sm.add_constant(X)) result = model.fit(q=q, kernel='gau') coef = result.params[1] coefs.append(coef) pvalue = result.pvalues[1] pvalues...
ab_tests/quantile_regression/ab_test_regression.ipynb
ethen8181/machine-learning
mit
Step 3 training the network
model = PriceHistoryAutoencoder(rng=random_state, dtype=dtype, config=config) npz_test = npz_path + '_test.npz' assert path.isfile(npz_test) path.abspath(npz_test) def experiment(): return model.run(npz_path=npz_path, epochs=50, batch_size = 53, enc_n...
04_time_series_prediction/35a_price_history_autoencoder_dyn_rnn_with_diff.ipynb
pligor/predicting-future-product-prices
agpl-3.0
This much we knew already. Now we just have to produce an instance of the BestMSM.MSM class that has the same count and transition matrices.
import bestmsm.msm as msm bhsmsm = msm.MSM(keys = range(4)) bhsmsm.count = bhs.count bhsmsm.keep_states = range(4) bhsmsm.keep_keys = range(4) bhsmsm.trans = bhs.trans bhsmsm.rate = bhs.K bhsmsm.tauK, bhsmsm.peqK = bhsmsm.calc_eigsK()
example/fourstate/fourstate_to_bestmsm.ipynb
daviddesancho/BestMSM
gpl-2.0
So now we already have a transition matrix, eigenvalues and eigenvectors which are the same for the Fourstate and BestMSM.MSM class. The important bits start next, with the flux and pfold estimations.
bhs.run_commit() bhsmsm.do_pfold(UU=[0], FF=[3]) print " These are the flux matrices" print bhs.J print bhsmsm.J print " And these are the total flux values" print " from Fourstate: %g"%bhs.sum_flux print " from BestMSM.MSM: %g"%bhs.sum_flux
example/fourstate/fourstate_to_bestmsm.ipynb
daviddesancho/BestMSM
gpl-2.0
It really looks like we have got the same exact thing, as intended. Next comes the generation of paths. This implies defining a function in the case of the Fourstate object.
def gen_path_lengths(keys, J, pfold, flux, FF, UU): nkeys = len(keys) I = [x for x in range(nkeys) if x not in FF+UU] Jnode = [] # calculate flux going through nodes for i in range(nkeys): Jnode.append(np.sum([J[i,x] for x in range(nkeys) \ if pfold[x] < pfold[i]...
example/fourstate/fourstate_to_bestmsm.ipynb
daviddesancho/BestMSM
gpl-2.0
For BestMSM.MSM everything should be built in. First we obtain the 4 highest flux paths.
bhsmsm.do_dijkstra(UU=[0], FF=[3], npath=3)
example/fourstate/fourstate_to_bestmsm.ipynb
daviddesancho/BestMSM
gpl-2.0
Then we use the alternative mechanism of giving a cutoff for the flux left. Here we want to account for 80% of the flux.
bhsmsm.do_pfold(UU=[0], FF=[3]) bhsmsm.do_dijkstra(UU=[0], FF=[3], cut=0.2)
example/fourstate/fourstate_to_bestmsm.ipynb
daviddesancho/BestMSM
gpl-2.0
Discriminator Implement discriminator to create a discriminator neural network that discriminates on images. This function should be able to reuse the variabes in the neural network. Use tf.variable_scope with a scope name of "discriminator" to allow the variables to be reused. The function should return a tuple of ...
def discriminator(images, reuse=False): """ Create the discriminator network :param image: Tensor of input image(s) :param reuse: Boolean if the weights should be reused :return: Tuple of (tensor output of the discriminator, tensor logits of the discriminator) """ # TODO: Implement Function ...
face_generation/dlnd_face_generation.ipynb
greg-ashby/deep-learning-nanodegree
mit
NumPy binary files (NPY, NPZ) Q1. Save x into temp.npy and load it.
x = np.arange(10) ... # Check if there exists the 'temp.npy' file. import os if os.path.exists('temp.npy'): x2 = ... print(np.array_equal(x, x2))
numpy/numpy_exercises_from_kyubyong/Input_and_Output.ipynb
mohanprasath/Course-Work
gpl-3.0
Q2. Save x and y into a single file 'temp.npz' and load it.
x = np.arange(10) y = np.arange(11, 20) ... with ... as data: x2 = data['x'] y2 = data['y'] print(np.array_equal(x, x2)) print(np.array_equal(y, y2))
numpy/numpy_exercises_from_kyubyong/Input_and_Output.ipynb
mohanprasath/Course-Work
gpl-3.0
Text files Q3. Save x to 'temp.txt' in string format and load it.
x = np.arange(10).reshape(2, 5) header = 'num1 num2 num3 num4 num5' ... ...
numpy/numpy_exercises_from_kyubyong/Input_and_Output.ipynb
mohanprasath/Course-Work
gpl-3.0
Q4. Save x, y, and z to 'temp.txt' in string format line by line, then load it.
x = np.arange(10) y = np.arange(11, 21) z = np.arange(22, 32) ... ...
numpy/numpy_exercises_from_kyubyong/Input_and_Output.ipynb
mohanprasath/Course-Work
gpl-3.0
Q5. Convert x into bytes, and load it as array.
x = np.array([1, 2, 3, 4]) x_bytes = ... x2 = ... print(np.array_equal(x, x2))
numpy/numpy_exercises_from_kyubyong/Input_and_Output.ipynb
mohanprasath/Course-Work
gpl-3.0
Q6. Convert a into an ndarray and then convert it into a list again.
a = [[1, 2], [3, 4]] x = ... a2 = ... print(a == a2)
numpy/numpy_exercises_from_kyubyong/Input_and_Output.ipynb
mohanprasath/Course-Work
gpl-3.0
String formatting¶ Q7. Convert x to a string, and revert it.
x = np.arange(10).reshape(2,5) x_str = ... print(x_str, "\n", type(x_str)) x_str = x_str.replace("[", "") # [] must be stripped x_str = x_str.replace("]", "") x2 = ... assert np.array_equal(x, x2)
numpy/numpy_exercises_from_kyubyong/Input_and_Output.ipynb
mohanprasath/Course-Work
gpl-3.0
Text formatting options Q8. Print x such that all elements are displayed with precision=1, no suppress.
x = np.random.uniform(size=[10,100]) np.set_printoptions(...) print(x)
numpy/numpy_exercises_from_kyubyong/Input_and_Output.ipynb
mohanprasath/Course-Work
gpl-3.0
So, this is a microstructure evolution problem, and final microstructures look very similar to each other (just looking at them). Can we check it using PyMKS tools? We have 200 files (microstructure outputs) for each simulation at every fixed Monte-Carlo step, so we can also take a look at path each simulation takes. M...
from pymks import PrimitiveBasis from pymks.stats import correlate from pymks.tools import draw_autocorrelations p_basis = PrimitiveBasis(n_states=2,domain=[1, 2]) X_auto = correlate(X, p_basis, periodic_axes=(0, 1), correlations=[(0, 0),(1, 1)]) X_auto.shape correlations = [('black', 'black'), ('white', 'white')]...
notebooks/structure_ising_2D.ipynb
davidbrough1/pymks
mit
Reduced-order representations (PCA) Using MKSStructureAnalysis we can perform 2-points statistics and dimentionality reduction (PCA) right after. So we are not going to use whatever we have done in the previous section, it was just to show how 2-point statistics look like for our data. So, total we have 5 simulations a...
from pymks import MKSStructureAnalysis analyzer = MKSStructureAnalysis(basis=p_basis, periodic_axes=[0,1]) XY_PCA=analyzer.fit_transform(X_con) XY_PCA.shape
notebooks/structure_ising_2D.ipynb
davidbrough1/pymks
mit
R1 and R2 are two different simulation results with the same initial microstructure, but different seeds for random number generation for Monte-Carlo simulations. The hope is to see that the same initial microstructure will take two different paths and will end up in quite the same spot. Let's check it! So let's take a...
from pymks.tools import draw_components_scatter draw_components_scatter([XY_PCA[0:201, :3], XY_PCA[201:402, :3], XY_PCA[402:603, :3], XY_PCA[603:804, :3], XY_PCA[804:1005, :3]], ['ising 50%', 'ising 30%', 'ising 10%', 'ising 40% run#1', 'ising ...
notebooks/structure_ising_2D.ipynb
davidbrough1/pymks
mit
Looks cool but not clear! Now, let's plot only initial and final structures.
draw_components_scatter([XY_PCA[:201:200, :3], XY_PCA[201:402:200, :3], XY_PCA[402:603:200, :3], XY_PCA[603:804:200, :3], XY_PCA[804:1005:200, :3]], ['ising 50%', 'ising 30%', 'ising 10%', 'ising 40% run#1', 'ising 40% ru...
notebooks/structure_ising_2D.ipynb
davidbrough1/pymks
mit
机器学习模型的学习效果评价基于测试集,而不依赖于训练集;过拟合的含义是模型可以很好的匹配训练集,但是对于未知的训练集数据效果不佳;下面的代码是之前的分类器模型可视化:
from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02): markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # plot th...
jupyter/machine_learning_1.ipynb
lichao890427/lichao890427.github.io
mit
感知器算法对于无法线性分割的数据集,是不收敛的,因此实际中很少只用感知器算法。后面将会介绍更强大的线性分类器,对无法线性分割的数据集可以收敛到最佳程度 1.3 使用sklearn逻辑回归实现分类器 &emsp;&emsp;前面使用最简单的感知器实现了分类,存在的一个巨大缺陷是分类器对于无法线性分割的数据无法收敛。逻辑回归是另一种用于解决线性/二进制分类问题的算法,虽然名为逻辑回归,却是分类器模型,而非回归模型。逻辑回归在工业中使用很广泛
from sklearn.linear_model import LogisticRegression lr = LogisticRegression(C=1000.0, random_state=0) lr.fit(X_train_std, y_train) plot_decision_regions(X_combined_std, y_combined, classifier=lr, test_idx=range(105,150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(loc='...
jupyter/machine_learning_1.ipynb
lichao890427/lichao890427.github.io
mit
使用正规化解决过拟合 &emsp;&emsp;过拟合是机器学习很常见的问题,在过拟合时,模型对训练数据集表现良好而对测试数据集表现欠佳。可能的原因是包含太多参数导致模型过于复杂;同样的欠拟合是模型过于简单,对训练数据集和测试数据集表现都不理想;使用正规化可以从数据中去除噪声从而防止过拟合 1.4 使用sklearn SVM实现分类器 &emsp;&emsp;另一个有效且广泛实用的学习算法是SVM(支持向量机),可以认为是感知器的扩展。使用感知器算法可以最小化误分类,而使用SVM可以最小化类间距(松弛变量),并解决非线性分割问题。
from sklearn.svm import SVC svm = SVC(kernel='linear', C=1.0, random_state=0) svm.fit(X_train_std, y_train) plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105,150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(loc='upper left') plt.show(...
jupyter/machine_learning_1.ipynb
lichao890427/lichao890427.github.io
mit
核函数SVM解决非线性分类问题 &emsp;&emsp;SVM算法另一个吸引人的地方是可以使用核函数解决非线性分类问题。典型的非线性问题例子如下图。
np.random.seed(0) X_xor = np.random.randn(200, 2) y_xor = np.logical_xor(X_xor[:, 0] > 0, X_xor[:, 1] > 0) y_xor = np.where(y_xor, 1, -1) plt.scatter(X_xor[y_xor==1, 0], X_xor[y_xor==1, 1], c='b', marker='x', label='1') plt.scatter(X_xor[y_xor==-1, 0], X_xor[y_xor==-1, 1], c='r', marker='s', label='-1') plt.ylim(-3.0) ...
jupyter/machine_learning_1.ipynb
lichao890427/lichao890427.github.io
mit