FrontPage
B3 前期授業スケジュール
月曜日 火曜日 水曜日 木曜日 金曜日
1-2 研究会
3-4 卒論1 研究会
5-6 卒論1 ディジタル信号処理 卒論1 卒論1
7-8 技術者倫理
9-10 研究会 &size(px){Text you want to change};
11-12
&ref(): File not found: "ダッシュストーム.jpg" at page "中島";
&ref(): File not found: "ダッシュストーム.jpg" at page "中島";
&ref(): File not found: "ダッシュストーム.jpg" at page "中島";
&ref(): File not found: "ダッシュストーム.jpg" at page "中島";
&ref(): File not found: "ダッシュストーム.jpg" at page "中島";
&ref(): File not found: "ダッシュストーム.jpg" at page "中島";
&ref(): File not found: "栗松.jpg" at page "中島";
&ref(): File not found: "栗松.jpg" at page "中島";
&ref(): File not found: "栗松.jpg" at page "中島";
&ref(): File not found: "栗松.jpg" at page "中島";
&ref(): File not found: "栗松.jpg" at page "中島";
&ref(): File not found: "栗松.jpg" at page "中島";
メモ
n problem.solve(solver="OSQP", max_iter=self.max_iter)\n\n if problem.status != "optimal":\n raise ConvergenceWarning(\n f"Solver did not reach optimum (Status: {problem.status})"\n )\n\n beta_sol = np.concatenate([b.value for b in beta_variables], axis=0)\n beta_sol[np.abs(beta_sol) < self.tol] = 0\n\n intercept, coef = beta_sol[0], beta_sol[1:]\n coef = np.maximum(coef, 0) if self.positive else coef\n\n return coef, intercept\n\n\nfrom sklearn.linear_model import ElasticNetCV\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.datasets import make_regression\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\n\n# CSVファイルのパスを指定してください\nfile_path = "C:/Users/nt011/Desktop/研究/富山取引のほう富山市のみ/変数選択/変数作成後新新.csv"\n\n# CSVファイルの読み込み\ndf = pd.read_csv(file_path, encoding='cp932') # 文字コードが異なる場合は、'utf-8' を他のエンコーディングに変更してください\n\n# 特徴量とターゲットの分割\nX = df.drop(columns=['取引価格(㎡単価)']) # 取引価格(㎡単価)をyとして分離\ny = df['取引価格(㎡単価)'] # ターゲット変数\n\n# 🔥 標準化の実施\nscaler_X = StandardScaler()\nscaler_y = StandardScaler()\n\nX_scaled = scaler_X.fit_transform(X) # Xの標準化\ny_scaled = scaler_y.fit_transform(y.values.reshape(-1, 1)).ravel() # yの標準化\n\n\n# データ分割\nX_train, X_test, y_train, y_test = train_test_split(X_scaled, y_scaled, test_size=0.35, random_state=42)\n\n# 訓練データの一部を使用\nX_sample, _, y_sample, _ = train_test_split(X_train, y_train, test_size=0.8, random_state=42)\n\n# 第一段階: ElasticNetCVを使用した最適パラメータの導出\nenet_cv = ElasticNetCV(\n l1_ratio=np.linspace(0.0001, 1, 25), # l1_ratioの候補\n alphas=np.logspace(-5, 0, 25), # alphaの候補\n cv=5, # 交差検証の分割数\n random_state=42,\n n_jobs=-1\n)\nenet_cv.fit(X_train, y_train)\n\n# 第一段階の最適パラメータと係数を取得\nalpha1_opt = enet_cv.alpha_\nl1_ratio1_opt = enet_cv.l1_ratio_\nenet_coef = enet_cv.coef_\n\nprint(f"第一段階の最適パラメータ: alpha1={alpha1_opt}, l1_ratio1={l1_ratio1_opt}")\n\n\nsession = requests.session()\nres = session.get(\n url = "https://www.machi-info.jp/machikado/police_pref_toyama/smartphone/map/mapindex.jsp", \n headers = {"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.66 Mobile Safari/537.36 Edg/103.0.1264.44"}\n)\nres = session.get(\n url = f"https://www.machi-info.jp/machikado/police_pref_toyama/FoiView.jsp?uid=115&mode=1&layer=00100040005000510060007000800090&minlon= {deg2str(west)}&minlat={deg2str(south)}&maxlon={deg2str(east)}&maxlat={deg2str(north)}&scale=10000&start={date2str(since)}&end={date2str(until)}&flag2=&flag=&init=2",\n headers = {"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.66 Mobile Safari/537.36 Edg/103.0.1264.44"}\n))
やること
from sklearn.linear_model import ElasticNet
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import make_regression
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
# CSVファイルのパスを指定してください
file_path = "C:/Users/nt011/Desktop/研究/富山取引のほう富山市のみ/変数選択/変数作成後新.csv"
# CSVファイルの読み込み
df = pd.read_csv(file_path, encoding='cp932') # 文字コードが異なる場合は、'utf-8' を他のエンコーディングに変更してください
# 特徴量とターゲットの分割
X = df.drop(columns=['取引価格(㎡単価)']) # 取引価格(㎡単価)をyとして分離
y = df['取引価格(㎡単価)'] # ターゲット変数
# 🔥 標準化の実施
scaler_X = StandardScaler()
scaler_y = StandardScaler()
X_scaled = scaler_X.fit_transform(X) # Xの標準化
y_scaled = scaler_y.fit_transform(y.values.reshape(-1, 1)).ravel() # yの標準化
# データ分割
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y_scaled, test_size=0.2, random_state=42)
# 訓練データの一部を使用
X_sample, _, y_sample, _ = train_test_split(X_train, y_train, test_size=0.8, random_state=42)
# 2. パラメータグリッドの設定
param_grid = {
'alpha': np.logspace(-5, 0, 10), # alpha1の探索範囲 (正則化パラメータ)
'l1_ratio': np.linspace(0.0001, 1.0, 10) # l1_ratio1の探索範囲 (L1とL2の比率)
}
# パラメータ名を変更(alpha -> alpha1, l1_ratio -> l1_ratio1)
param_grid = {'alpha1': param_grid['alpha'], 'l1_ratio1': param_grid['l1_ratio']}
# 3. ElasticNetモデルの初期化
elastic_net = ElasticNet(max_iter=10000, random_state=42)
# 4. グリッドサーチCVの設定
grid_search = GridSearchCV(
estimator=elastic_net,
param_grid={'alpha': param_grid['alpha1'], 'l1_ratio': param_grid['l1_ratio1']}, # 変更した名前に対応
cv=5, # 5分割交差検証
scoring='neg_mean_squared_error', # 評価指標: 平均二乗誤差の負値
verbose=1,
n_jobs=-1 # 並列実行
)
# 5. グリッドサーチの実行
grid_search.fit(X_sample, y_sample)
# 6. 最適なパラメータとスコアの取得
best_params = grid_search.best_params_
best_params_renamed = {'alpha1': best_params['alpha'], 'l1_ratio1': best_params['l1_ratio']}
best_score = grid_search.best_score_
print("最適なパラメータ:")
print(best_params_renamed)
print("最良のスコア (平均二乗誤差の負値):")
print(best_score)
class TQDMGridSearchCV(GridSearchCV):
def __init__(self, estimator, param_grid, cv=5, scoring=None, n_jobs=None, verbose=0,
refit=True, return_train_score=True, pre_dispatch='2*n_jobs', error_score='raise', **kwargs):
# iid引数を削除して、super()に渡さない
super().__init__(estimator=estimator, param_grid=param_grid, cv=cv, scoring=scoring,
n_jobs=n_jobs, verbose=verbose, refit=refit, return_train_score=return_train_score,
pre_dispatch=pre_dispatch, error_score=error_score, **kwargs)
# tqdmを使って進捗表示
self.tqdm = tqdm(total=1, position=0, leave=True)
def fit(self, X, y=None, **fit_params):
# 進捗バーを更新
self.tqdm.set_description("Fitting model")
result = super().fit(X, y, **fit_params)
self.tqdm.close() # 進捗バーを閉じる
return result
# 第二段階のGridSearchCVで交差検証(進捗表示を追加)
grid_search = TQDMGridSearchCV(
estimator=model,
param_grid=param_grid,
cv=5, # 交差検証の分割数
scoring='neg_mean_squared_error', # 評価指標(MSEの負の値を使用)
#n_jobs=-1, # 並列実行
verbose=1 # 実行状況を表示しない
)
import numba
from numba import jit
import numpy as np
import pandas as pd
from sklearn.linear_model import ElasticNet
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import cross_val_score
# Numbaを使った交差検証の高速化
@jit(nopython=True)
def cross_val_score_numba(X, y, model, cv=5):
"""
Numbaを使用した交差検証の実装
"""
n_samples = X.shape[0]
fold_size = n_samples // cv
scores = np.zeros(cv)
for i in range(cv):
# フォールドの分割
val_idx = list(range(i * fold_size, (i + 1) * fold_size))
train_idx = list(set(range(n_samples)) - set(val_idx))
X_train, X_val = X[train_idx], X[val_idx]
y_train, y_val = y[train_idx], y[val_idx]
model.fit(X_train, y_train)
y_pred = model.predict(X_val)
# MSEスコアの計算
scores[i] = mean_squared_error(y_val, y_pred)
return scores
# CSVファイルのパスを指定してください
file_path = "C:/Users/tn011/Desktop/変数作成後新新.csv"
# CSVファイルの読み込み
df = pd.read_csv(file_path, encoding='cp932')
# 特徴量とターゲットの分割
X = df.drop(columns=['取引価格(㎡単価)'])
y = df['取引価格(㎡単価)']
# 標準化の実施
scaler_X = StandardScaler()
scaler_y = StandardScaler()
X_scaled = scaler_X.fit_transform(X)
y_scaled = scaler_y.fit_transform(y.values.reshape(-1, 1)).ravel()
# 訓練データとテストデータに分割
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y_scaled, test_size=0.35, random_state=42)
# 第一段階のElasticNetのハイパーパラメータチューニング
alpha_values = np.logspace(-5, 0, 25)
l1_ratio_values = np.linspace(0.0001, 1, 25)
best_score = float('inf')
best_alpha = None
best_l1_ratio = None
best_model = None
# numbaを使用した交差検証を実行
for alpha in alpha_values:
for l1_ratio in l1_ratio_values:
model = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, max_iter=10000)
scores = cross_val_score(model, X_train, y_train, cv=5, scoring='neg_mean_squared_error')
mean_score = np.mean(scores)
if mean_score < best_score:
best_score = mean_score
best_alpha1 = alpha
best_l1_ratio1 = l1_ratio
best_model = model
print(f"最適なalpha: {best_alpha1}, 最適なl1_ratio: {best_l1_ratio1}")
# 最適なモデルのトレーニング
best_model.fit(X_train, y_train)
y_pred = best_model.predict(X_test)
# テストデータでの性能を評価
test_score = mean_squared_error(y_test, y_pred)
print(f"テストデータのMSE: {test_score}")
高速化
import numbers
import warnings
from numba import njit, prange
import numpy as np
import cvxpy
from asgl import ASGL
from sklearn.base import MultiOutputMixin
from sklearn.base import RegressorMixin
from sklearn.exceptions import ConvergenceWarning
from sklearn.linear_model import ElasticNet
from sklearn.utils import check_X_y
from sklearn.utils.validation import check_is_fitted
from numba import njit, prange
class AdaptiveElasticNet(ASGL, ElasticNet, MultiOutputMixin, RegressorMixin):
"""
Adaptive ElasticNet implementation with customizable parameters.
"""
def __init__(
self,
alpha1=0.008, # First-stage ElasticNet alpha
alpha2=0.0009443498043343188, # Second-stage ElasticNet alpha
*,
l1_ratio1=0.875, # First-stage ElasticNet L1 ratio
l1_ratio2=0.778, # Second-stage ElasticNet L1 ratio
gamma=0.5, # Weight adjustment exponent
fit_intercept=True,
precompute=False,
max_iter=5000,
copy_X=True,
solver=None,
tol=None,
positive=False,
positive_tol=1e-3,
random_state=None,
eps_coef=1e-6,
verbose=True,
):
params_asgl = dict(model="lm", penalization="asgl")
if solver is not None:
params_asgl["solver"] = solver
if tol is not None:
params_asgl["tol"] = tol
super().__init__(**params_asgl)
self.alpha1 = alpha1
self.alpha2 = alpha2
self.l1_ratio1 = l1_ratio1
self.l1_ratio2 = l1_ratio2
self.gamma = gamma
self.fit_intercept = fit_intercept
self.max_iter = max_iter
self.precompute = precompute
self.copy_X = copy_X
self.positive = positive
self.positive_tol = positive_tol
self.random_state = random_state
self.eps_coef = eps_coef
self.verbose = verbose
if not self.fit_intercept:
raise NotImplementedError
@staticmethod
@njit(parallel=True)
def adaptive_weight_calculation(coef, eps_coef, gamma):
"""
Accelerated weight calculation using numba.
"""
weights = np.empty_like(coef)
for i in prange(len(coef)):
weights[i] = 1.0 / (max(abs(coef[i]), eps_coef) ** gamma)
return weights
def fit(self, X, y, check_input=True):
if check_input:
X_copied = self.copy_X and self.fit_intercept
X, y = self._validate_data(
X,
y,
accept_sparse="csc",
order="F",
dtype=[np.float64, np.float32],
copy=X_copied,
multi_output=True,
y_numeric=True,
)
# First-stage ElasticNet
enet_model_1 = self.elastic_net(self.l1_ratio1, alpha=self.alpha1)
enet_model_1.fit(X, y)
enet_coef = enet_model_1.coef_
# Compute adaptive weights
weights = self.adaptive_weight_calculation(enet_coef, self.eps_coef, self.gamma)
# Second-stage optimization
self.coef_, self.intercept_ = self._optimize_second_stage(X, y, weights)
# Store model attributes
self.enet_coef_ = enet_coef
self.weights_ = weights
return self
def predict(self, X):
check_is_fitted(self, ["coef_", "intercept_"])
return super(ElasticNet, self).predict(X)
def elastic_net(self, l1_ratio1, **params):
"""
Create an ElasticNet model with the specified parameters.
"""
elastic_net = ElasticNet(l1_ratio=l1_ratio1)
for k, v in self.get_params().items():
try:
elastic_net = elastic_net.set_params(**{k: v})
except ValueError:
pass
elastic_net = elastic_net.set_params(**params)
return elastic_net
@staticmethod
@njit(parallel=True, fastmath=True)
def fista(X, y, weights, alpha1, l1_ratio1, alpha2, l1_ratio2, max_iter=5000, tol=1e-6):
"""
FISTAによる適応ElasticNetの第2段階最適化処理。
Parameters
----------
X : ndarray
特徴量行列 (n_samples, n_features)
y : ndarray
目的変数 (n_samples,
1段階のElasticNetの正則化係数\n l1_ratio1 : float\n 第1段階のL1比率\n alpha2 : float\n 第2段階のElasticNetの正則化係数\n l1_ratio2 : float\n 第2段階のL1比率\n max_iter : int, optional\n 最大反復回数 (default=5000)\n tol : float, optional\n 収束許容誤差 (default=1e-6)\n\n Returns\n -------\n beta : ndarray\n 推定された係数 (n_features,)\n """\n\n n_samples, n_features = X.shape\n beta = np.zeros(n_features) # 係数の初期化\n beta_old = beta.copy()\n t = 1\n\n # Lipschitz定数の計算(手動でL2ノルム計算)\n L = np.sqrt(np.sum(X**2)) ** 2 / n_samples \n\n # L2 正則化項(第一段階のパラメータを利用)\n L2_penalty = alpha1 * (1 - l1_ratio1)\n\n for _ in prange(max_iter):\n # 勾配計算\n grad = -X.T @ (y - X @ beta) / n_samples \n\n # ソフトしきい値処理(L1 正則化)\n z = beta - grad / L\n shrink = alpha2 * l1_ratio2 * weights / L\n beta_new = np.sign(z) * np.maximum(np.abs(z) - shrink, 0)\n\n # Nesterov 加速\n t_new = (1 + np.sqrt(1 + 4 * t ** 2)) / 2\n beta = beta_new + *1 .ravel()\n\n# Split data\nX_train, X_test, y_train, y_test = train_test_split(X_scaled, y_scaled, test_size=0.35, random_state=42)\n\n# 訓練データの一部を使用\nX_sample, _, y_sample, _ = train_test_split(X_train, y_train, test_size=0.8, random_state=42)\n\n# First-stage ElasticNet\nmodel = AdaptiveElasticNet(alpha1=0.00825404185268019, l1_ratio1=0.8750125, gamma=0.5)\n\n# Second-stage parameter grid\nparam_grid = {\n "alpha2": np.logspace(-4, 0, 5),\n "l1_ratio2": np.linspace(0.0001, 1.0, 5),\n}\n\n# GridSearchCV with accelerated weight calculation\ngrid_search = GridSearchCV(\n estimator=model,\n param_grid=param_grid,\n cv=3,\n scoring="neg_mean_squared_error",\n n_jobs=-1,\n verbose=1,\n)\n\n# Fit GridSearchCV\ngrid_search.fit(X_sample, y_sample)\n\n# Output best parameters and score\nprint(f"Best parameters: {grid_search.best_params_}")\nprint(f"Best negative MSE: {grid_search.best_score_}")\n\n\n\n\n\ndef mesh_code_to_latlon_borders(mesh_code: str, apply_correction: bool = True):\n """\n 日本の地域メッシュコードを用いて、メッシュの東西南北の座標を求める。\n\n Parameters\n ----------\n mesh_code : str\n 変換する地域メッシュコード。\n apply_correction : bool, optional\n メッシュの中心点を取得するかどうか(デフォルトは `True`)。\n\n Returns\n -------\n dict\n メッシュコードに対応する南北東西、中心点(center)の座標情報を辞書形式で返す。\n """\n # メッシュコードの長さに基づくレベルの設定\n mesh_lengths = {4: 0, 6: 1, 8: 2, 9: 3, 10: 4}\n \n # メッシュコードの長さを確認\n mesh_length = len(mesh_code.replace("-", "")) # ハイフンを削除して長さを取得\n \n if mesh_length not in mesh_lengths:\n raise ValueError(f"無効なメッシュコードです。長さが {mesh_length} では対応していません。")\n \n # メッシュレベルを取得\n mesh_level = mesh_lengths[mesh_length]\n \n # メッシュの中心点の座標を取得\n center_lat, center_lon = mesh_code_to_latlon(mesh_code, apply_correction)\n \n # メッシュのレベルに応じた増分(緯度・経度の単位距離)\n increments = [\n (40 / 60, 1), # 第1次メッシュ\n (5 / 60, 7.5 / 60), # 第2次メッシュ\n (30 / 3600, 45 / 3600), # 第3次メッシュ\n (15 / 3600, 22.5 / 3600), # 第4次メッシュ(2分の1地域メッシュ)\n (7.5 / 3600, 11.25 / 3600) # 第5次メッシュ(4分の1地域メッシュ)\n ]\n\n # メッシュの中心点からの増分(経度、緯度)\n lat_inc, lon_inc = increments[mesh_level] # メッシュレベルに基づいて増分を取得\n\n # メッシュの南北東西の座標を計算\n south = center_lat - lat_inc / 2\n north = center_lat + lat_inc / 2\n west = center_lon - lon_inc / 2\n east = center_lon + lon_inc / 2\n\n # 結果として辞書形式で南北東西、中心を返す\n return {\n 'north': north,\n 'south': south,\n 'east': east,\n 'west': west,\n 'center': [center_lon, center_lat]\n }\n\n\n# メッシュコードごとに座標情報を計算し、格納\n_meshes = {}\n\n# meshes(メッシュコードのリスト)が与えられている前提で、それぞれのメッシュコードに対する座標情報を計算\nfor meshcode in meshes:\n # 各メッシュコードの境界座標を取得\n _meshes[meshcode] = mesh_code_to_latlon_borders(meshcode)\n\n# 結果として_meshesには9桁のメッシュコードに対応する座標情報が格納される\nmeshes = _meshes # 最終的にmeshesを更新\n\n# 結果を確認\nprint(meshes)\n)
=IF(LEFT(L2,2)="令和", 2018 + MID(L2,3,LEN(L2)-3),
IF(LEFT(L2,2)="平成", 1988 + MID(L2,3,LEN(L2)-3),
IF(LEFT(L2,2)="昭和", 1925 + MID(L2,3,LEN(L2)-3), "エラー")))
=LEFT(W2,4)