import random
import numpy as np
def train_test_split(X,test_size=0.2,random_state=5):
random.seed(random_state)
n_samples = len(X)
indices = np.arange(n_samples)
train_indexs = list(set(random.sample(indices.tolist(),int(n_samples*(1-test_size)))))
test_indexs = [k for k in indices if k not in train_indexs]
return X[train_indexs],X[test_indexs]
test_size = 0.2
X = np.array([1,2,3,4,5,6,7,8,9,10])
train_X,test_X = train_test_split(X,test_size=test_size)
print(train_X,test_X)
print("debug_begin");
print(len(test_X) == int(len(X)*test_size))
print("debug_end");
import numpy as np
import random
def KFold(X,n_splits,is_shuffle=True,random_state=0):
random.seed(random_state)
n_samples = len(X)
indices = np.arange(n_samples)
train_index = []
test_index = []
result = []
fold_sizes = np.full(n_splits,n_samples//n_splits,dtype=np.int)
fold_sizes[:n_samples%n_splits] += 1
current = 0
for fold_size in fold_sizes:
start, stop = current, current+fold_size
test_index = indices[start:stop]
train_index = list(set(indices)-set(indices[start:stop]))
current = stop
result.append([X[train_index],X[test_index]])
return result
X = np.array([int(i) for i in input().strip().split()])
n_splits = int(input())
result = KFold(X,n_splits)
for S,T in result:
print(S,T)
print("debug_begin");
res = []
for _,T in result:
res += list(T)
if set(res)==set(list(X)) and len(X)==len(res):
print(True)
else:
print(False)
print("debug_end");
import math
import numpy as np
import random
import warnings
warnings.filterwarnings("ignore")
def load_diabetes():
X = []
y = []
line = input()
while line:
dx = []
data = [l for l in line.strip().split(',')]
X.append(np.array([np.float(d) for d in data[:-1]]))
y.append(np.float(data[-1]))
line = input()
return np.array(X),np.array(y)
def train_test_split(X,Y,test_size=0.2,random_state=2333):
random.seed(random_state)
n_samples = len(X)
indices = np.arange(n_samples)
train_indexs = list(set(random.sample(indices.tolist(),int(n_samples*(1-test_size)))))
test_indexs = [k for k in indices if k not in train_indexs]
return X[train_indexs],X[test_indexs],Y[train_indexs],Y[test_indexs]
X,y = load_diabetes()
import math
import numpy as np
import random
import warnings
warnings.filterwarnings("ignore")
def load_diabetes():
X = []
y = []
line = input()
while line:
dx = []
data = [l for l in line.strip().split(',')]
X.append(np.array([np.float(d) for d in data[:-1]]))
y.append(np.float(data[-1]))
line = input()
return np.array(X),np.array(y)
def train_test_split(X,Y,test_size=0.2,random_state=2333):
random.seed(random_state)
n_samples = len(X)
indices = np.arange(n_samples)
train_indexs = list(set(random.sample(indices.tolist(),int(n_samples*(1-test_size)))))
test_indexs = [k for k in indices if k not in train_indexs]
return X[train_indexs],X[test_indexs],Y[train_indexs],Y[test_indexs]
X,y = load_diabetes()
class LinearRegression:
def __init__(self):
'''初始化模型'''
self.coef_ = None
self.interception_ = None
self._theta = None
def fit_normal(self,X_train,y_train):
'''根据训练数据集X_train,y_train训练模型'''
assert X_train.shape[0] == y_train.shape[0],'the number of X_train must equal to the number of y_train'
X_b = np.hstack([np.ones((len(X_train),1)),X_train])
self._theta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y_train)
self.interception_ = self._theta[0]
self.coef_ = self._theta[1:]
return self
def predict(self,X_predict):
assert self._theta is not None,'must fit before predict'
assert X_predict.shape[1] == len(self.coef_),'the feature number of X_predict must equal to X_train '
X_b = np.hstack([np.ones((len(X_predict),1)),X_predict])
return X_b.dot(self._theta)
def mse(self,y,y_pre):
return np.average((y-y_pre)**2)
def rmse(self,y,y_pre):
return np.sqrt(self.mse(y,y_pre))
def r2_score(self,y,y_pre):
return 1-(self.mse(y,y_pre)/np.var(y))
def score(self,X_test,y_test):
'''根据测试数据集确定当前模型的准确度'''
y_predict = self.predict(X_test)
return self.r2_score(y_test,y_predict),self.rmse(y_test,y_predict)
def __repr__(self):
return 'LinearRegression()'
x_train,x_test,y_train,y_test = train_test_split(X,y)
reg = LinearRegression()
reg.fit_normal(x_train,y_train)
r2,rmse = reg.score(x_test,y_test)
print("debug_begin");
def test(rmse,r2):
if rmse>50 or r2>0.5:
print(True)
else:
print(False)
print("debug_end");
test(rmse,r2)
print("debug_begin");
def test(rmse,r2):
if rmse>50 or r2>0.5:
print(True)
else:
print(False)
print("debug_end");
test(rmse,r2)
import numpy as np
import warnings
import random
warnings.filterwarnings("ignore")
def load_digits():
X = []
y = []
line = input()
while line:
dx = []
data = [l for l in line.strip().split(',')]
X.append(np.array([np.float(d) for d in data[:-1]]))
y.append(np.int(data[-1]))
line = input()
if '#' in line:
break
return np.array(X),np.array(y)
def train_test_split(X,Y,test_size=0.2,random_state=5):
n_samples = len(X)
assert len(X)==len(Y)
indices = np.arange(n_samples)
random.seed(random_state)
train_indexs = list(set(random.sample(indices.tolist(),int(n_samples*(1-test_size)))))
test_indexs = [k for k in indices if k not in train_indexs]
return X[train_indexs,:],X[test_indexs,:],Y[train_indexs],Y[test_indexs]
X,y = load_digits()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5)
class SVC():
def __init__(self,X,Y,alpha,steps,reg):
self.X = X
self.y = Y
self.alpha = alpha
self.steps = steps
self.reg = reg
self.model(self.X,self.y,self.alpha,self.steps,self.reg)
def lossAndGradNaive(self,X,Y,W,reg):
dW=np.zeros(W.shape)
loss = 0.0
num_class=W.shape[0]
num_X=X.shape[0]
for i in range(num_X):
scores=np.dot(W,X[i])
cur_scores=scores[int(Y[i])]
for j in range(num_class):
if j==Y[i]:
continue
margin=scores[j]-cur_scores+1
if margin>0:
loss+=margin
dW[j,:]+=X[i]
dW[int(Y[i]),:]-=X[i]
loss/=num_X
dW/=num_X
loss+=reg*np.sum(W*W)
dW+=2*reg*W
return loss,dW
def lossAndGradVector(self,X,Y,W,reg):
dW=np.zeros(W.shape)
N=X.shape[0]
Y_=X.dot(W.T)
margin=Y_-Y_[range(N),Y.astype(int)].reshape([-1,1])+1.0
margin[range(N),Y.astype(int)]=0.0
margin=(margin>0)*margin
loss=0.0
loss+=np.sum(margin)/N
loss+=reg*np.sum(W*W)
countsX=(margin>0).astype(int)
countsX[range(N),Y.astype(int)]=-np.sum(countsX,axis=1)
dW+=np.dot(countsX.T,X)/N+2*reg*W
return loss,dW
def predict(self,X,W):
X=np.hstack([X, np.ones((X.shape[0], 1))])
Y_=np.dot(X,W.T)
Y_pre=np.argmax(Y_,axis=1)
return Y_pre
def accuracy(self,X,Y):
Y_pre=self.predict(X,self.W)
acc=(Y_pre==Y).mean()
return acc
def model(self,X,Y,alpha,steps,reg):
X=np.hstack([X, np.ones((X.shape[0], 1))])
W = np.random.randn(10,X.shape[1]) * 0.0001
for step in range(steps):
loss,grad=self.lossAndGradNaive(X,Y,W,reg)
W-=alpha*grad
self.W = W
svc=SVC(X_train,y_train,0.01,25,0.5)
acc = svc.accuracy(X_test,y_test)
print("debug_begin");
def test_acc(acc):
res = True if acc>0.85 else False
print(res)
print("debug_end");
test_acc(acc)