2017-01-19 10:46:00      个评论    来源：SrdLaplace的博客

```# -*- coding: utf-8 -*-
"""
Created on Tue Jan 17 12:43:15 2017

"""
import numpy as np
import random as rd
fid = open('./data/abalone/data/abalone.data')
fid.close()
X = [[0]*10 for i in range(len(Mat))]
Y = [0]*len(Mat)
for i in range(len(Mat)):
line = Mat[i]
p = line.index(',')
if line[0:p] == 'F':
X[i][0] = 1
else:
if line[0:p] == 'M':
X[i][1] = 1
lineAx = line[p+1:]
p = lineAx.index(',')
X[i][2] = float(lineAx[0:p])
lineAx = lineAx[p+1:]
p = lineAx.index(',')
X[i][3] = float(lineAx[0:p])
lineAx = lineAx[p+1:]
p = lineAx.index(',')
X[i][4] = float(lineAx[0:p])
lineAx = lineAx[p+1:]
p = lineAx.index(',')
X[i][5] = float(lineAx[0:p])
lineAx = lineAx[p+1:]
p = lineAx.index(',')
X[i][6] = float(lineAx[0:p])
lineAx = lineAx[p+1:]
p = lineAx.index(',')
X[i][7] = float(lineAx[0:p])
lineAx = lineAx[p+1:]
p = lineAx.index(',')
X[i][8] = int(lineAx[p+1:len(lineAx)-1])
X[i][9] = 1
Y[i] = float(lineAx[0:p])

L = 500
'''

'''
XAx = np.array(X[0:len(X)-L])
YAx = np.array(Y[0:len(Y)-L])
w = np.dot(np.dot(np.linalg.inv(np.dot(np.transpose(XAx),XAx)),np.transpose(XAx)),YAx)
print(w)
print(np.sqrt(sum(np.square(np.dot(X[len(X)-L:],w) - Y[len(Y)-L:])/L)))

'''

'''
eta = 0.001;
XAx = np.array(X[0:len(X)-L])
YAx = np.array(Y[0:len(Y)-L])
w0 = np.array([1]*10)
w1 = np.array(w + [rd.uniform(0,10**-6) for i in range(10)])
ii = 0
while np.linalg.norm(w0 - w1) > 10**-10:
ii += 1
#print(ii)
#print(np.linalg.norm(w0 - w1))
w0 = w1
w1 = w1 - eta*(np.dot(np.dot(np.transpose(XAx),XAx),w1) - np.dot(np.transpose(XAx),YAx))/len(YAx)
w0 = w1
print(w0)
print(np.sqrt(sum(np.square(np.dot(X[len(X)-L:],w0) - Y[len(Y)-L:])/L)))

'''

'''
eta = 0.001;
XAx = np.array(X[0:len(X)-L])
YAx = np.array(Y[0:len(Y)-L])
w0 = np.array([1]*10)
w1 = np.array(w + [rd.uniform(0,10**-8) for i in range(10)])
ii = 0
while np.linalg.norm(w0 - w1) > 10**-4:
ii += 1
#print(ii)
#print(np.linalg.norm(w0 - w1))
w0 = w1
for i in range(len(XAx)):
w1 = w1 - eta*(np.dot(np.dot(np.transpose([XAx[i]]),[XAx[i]]),w1) - \
np.dot(np.transpose([XAx[i]]),[YAx[i]]))
w0 = w1
print(w0)
print(np.sqrt(sum(np.square(np.dot(X[len(X)-L:],w0) - Y[len(Y)-L:])/L)))

'''
LASSO
'''
from sklearn import linear_model
clf = linear_model.Lasso(alpha = 0.00001)
XAx = np.array(X[0:len(X)-L])
YAx = np.array(Y[0:len(Y)-L])
clf.fit(XAx, YAx)
print(clf.coef_)#w
print(np.sqrt(sum(np.square(np.dot(X[len(X)-L:],clf.coef_) - Y[len(Y)-L:])/L)))```