对于题2,给个使用sklearn的版本(ps:一般都会让用sklearn) python3: from sklearn.linear_model import Ridge import numpy as np import sys import json input = lambda: sys.stdin.readline().strip() def sigmoid(x): return 1 / (1 + np.exp(-x)) data = json.loads(input()) X = np.array(data['nodes']) edges = np.array(data['edges']) train_idx = data['train_idx'] train_y = data['train_y'] test_idx = data['test_idx'] n, d = X.shape adj = np.eye(n) if len(edges) > 0: adj[edges[:, 0], edges[:, 1]] = 1 adj[edges[:, 1], edges[:, 0]] = 1 row_sums = adj.sum(axis=1) H = (adj @ X) / row_sums[:, np.newaxis] model = Ridge(alpha=0.01, fit_intercept=False, solver='cholesky') model.fit(H[train_idx], train_y) w = model.coef_ test_h = H[test_idx] z = test_h @ w proba = sigmoid(z) pred = (proba >= 0.5).astype(int) ans = { "weights": np.round(w, 6).tolist(), "test_proba": np.round(proba, 6).tolist(), "test_pred": pred.tolist(), } print(json.dumps(ans))
1 1

相关推荐

牛客网
牛客网在线编程
牛客网题解
牛客企业服务