text:
# Born's Classifier

from bornrule import BornClassifier

Bases: ClassifierMixin, BaseEstimator

Scikit-learn implementation of Born's Classifier

This class is compatible with the scikit-learn ecosystem. It supports both dense and sparse input and GPU-accelerated computing via CuPy. This classifier is suitable for classification with non-negative feature vectors. The data X are treated as unnormalized probability distributions.

Parameters:

Name Type Description Default
a float

Amplitude. Must be strictly positive.

0.5
b float

Balance. Must be non-negative.

1.0
h float

Entropy. Must be non-negative.

1.0

Attributes:

Name Type Description
gpu_ bool

Whether the model was fitted on GPU.

corpus_ array-like of shape (n_features_in_, n_classes)

Fitted corpus.

classes_ ndarray of shape (n_classes,)

Unique classes labels.

n_features_in_ int

Number of features seen during fit.

Source code in bornrule/born.py
  16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 class BornClassifier(ClassifierMixin, BaseEstimator): """Scikit-learn implementation of Born's Classifier This class is compatible with the [scikit-learn](https://scikit-learn.org) ecosystem. It supports both dense and sparse input and GPU-accelerated computing via [CuPy](https://cupy.dev). This classifier is suitable for classification with non-negative feature vectors. The data X are treated as unnormalized probability distributions. Parameters ---------- a : float Amplitude. Must be strictly positive. b : float Balance. Must be non-negative. h : float Entropy. Must be non-negative. Attributes ---------- gpu_ : bool Whether the model was fitted on GPU. corpus_ : array-like of shape (n_features_in_, n_classes) Fitted corpus. classes_ : ndarray of shape (n_classes,) Unique classes labels. n_features_in_ : int Number of features seen during fit. """ def __init__(self, a=0.5, b=1., h=1.): self.a = a self.b = b self.h = h def fit(self, X, y, sample_weight=None): """Fit the classifier according to the training data X, y. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is the number of features. y : array-like of shape (n_samples,) or (n_samples, n_classes) Target values. If 2d array, this is the probability distribution over the n_classes for each of the n_samples. sample_weight : array-like of shape (n_samples,) Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight. Returns ------- self : object Returns the instance itself. """ attrs = [ "gpu_", "corpus_", "classes_", "n_features_in_" ] for attr in attrs: if hasattr(self, attr): delattr(self, attr) return self.partial_fit(X, y, classes=y, sample_weight=sample_weight) def partial_fit(self, X, y, classes=None, sample_weight=None): """Incremental fit on a batch of samples. This method is expected to be called several times consecutively on different chunks of a dataset so as to implement out-of-core or online learning. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is the number of features. y : array-like of shape (n_samples,) or (n_samples, n_classes) Target values. If 2d array, this is the probability distribution over the n_classes for each of the n_samples. classes : array-like of shape (n_classes,) List of all the classes that can possibly appear in the y vector. Must be provided at the first call to partial_fit, can be omitted in subsequent calls. sample_weight : array-like of shape (n_samples,) Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight. Returns ------- self : object Returns the instance itself. """ X, y = self._sanitize(X, y) first_call = self._check_partial_fit_first_call(classes) if first_call: self.corpus_ = 0 self.n_features_in_ = X.shape[1] if not self._check_encoded(y): y = self._one_hot_encoding(y) if sample_weight is not None: sample_weight = self._check_sample_weight(sample_weight, X) y = self._multiply(y, sample_weight.reshape(-1, 1)) self.corpus_ += X.T @ self._multiply(y, self._power(self._sum(X, axis=1), -1)) return self def predict(self, X): """Perform classification on the test data X. Parameters ---------- X : array-like of shape (n_samples, n_features) Test data, where n_samples is the number of samples and n_features is the number of features. Returns ------- y : ndarray of shape (n_samples,) Predicted target classes for X. """ proba = self.predict_proba(X) idx = self._dense().argmax(proba, axis=1) return self.classes_[idx] def predict_proba(self, X): """Return probability estimates for the test data X. Parameters ---------- X : array-like of shape (n_samples, n_features) Test data, where n_samples is the number of samples and n_features is the number of features. Returns ------- y : ndarray of shape (n_samples, n_classes) Returns the probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. """ self._check_fitted() X = self._sanitize(X) u = self._power(self._power(X, self.a) @ self._weights(), 1. / self.a) y = self._normalize(u, axis=1) if self._sparse().issparse(y): y = y.todense() return self._dense().asarray(y) def explain(self, X=None, sample_weight=None): r"""Global and local explanation For each test vector $x$, the $a$-th power of the unnormalized probability for the $k$-th class is given by the matrix product: math u_k^a = \sum_j W_{jk}x_j^a  where $W$ is a matrix of non-negative weights that generally depends on the model's hyper-parameters ($a$, $b$, $h$). The classification probabilities are obtained by normalizing $u$ such that it sums up to $1$. This method returns global or local feature importance weights, depending on X: - When X is not provided, this method returns the global weights $W$. - When X is a single sample, this method returns a matrix of entries $(j,k)$ where each entry is given by $W_{jk}x_j^a$. - When X contains multiple samples, then the values above are computed for each sample and this method returns their weighted sum. By default, each sample is given unit weight. Parameters ---------- X : array-like of shape (n_samples, n_features) Test data, where n_samples is the number of samples and n_features is the number of features. If not provided, then global weights are returned. sample_weight : array-like of shape (n_samples,) Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight. Returns ------- E : array-like of shape (n_features, n_classes) Returns the feature importance for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. """ self._check_fitted() if X is None: return self._weights() X = self._sanitize(X) X = self._normalize(X, axis=1) X = self._power(X, self.a) if sample_weight is not None: sample_weight = self._check_sample_weight(sample_weight, X) X = self._multiply(X, sample_weight.reshape(-1, 1)) return self._multiply(self._weights(), self._sum(X, axis=0).T) # X = self._sanitize(X) # if sample_weight is not None: # sample_weight = self._check_sample_weight(sample_weight, X) # # W_jk = self._weights() # X_nj = self._power(X, self.a) # X_nk = X_nj @ W_jk # # if self.gpu_ and self._sparse().issparse(X_nj): # X_nj = X_nj.tocsc() # # E_jk = 0 # for n in range(X.shape[0]): # # X_j, X_k = X_nj[n:n+1].T, X_nk[n:n+1] # X_jk = self._multiply(W_jk, X_j) # # U_k = self._power(X_k, 1. / self.a) # Y_k = self._normalize(U_k, axis=1) # # if self._sparse().issparse(X_j): # Z_j = X_j != 0 # X_k = Z_j @ X_k # Y_k = Z_j @ Y_k # # U_jk = self._power(X_k - X_jk, 1. / self.a) # Y_jk = self._normalize(U_jk, axis=1) # # D_jk = Y_k - Y_jk # if sample_weight is not None: # D_jk = sample_weight[n] * D_jk # # E_jk += D_jk # # return E_jk if sample_weight is not None else E_jk / X.shape[0] def _dense(self): return cupy if self.gpu_ else numpy def _sparse(self): return cupy.sparse if self.gpu_ else scipy.sparse def _weights(self): P_jk = self.corpus_ if self.b != 0: P_jk = self._multiply(P_jk, self._power(self._sum(self.corpus_, axis=0), -self.b)) if self.b != 1: P_jk = self._multiply(P_jk, self._power(self._sum(self.corpus_, axis=1), self.b-1)) W_jk = self._power(P_jk, self.a) if self.h != 0 and len(self.classes_) > 1: P_jk = self._normalize(P_jk, axis=1) H_j = 1 + self._sum(self._multiply(P_jk, self._log(P_jk)), axis=1) / self._dense().log(P_jk.shape[1]) W_jk = self._multiply(W_jk, self._power(H_j, self.h)) return W_jk def _sum(self, x, axis): if self._sparse().issparse(x): return x.sum(axis=axis) return self._dense().asarray(x).sum(axis=axis, keepdims=True) def _multiply(self, x, y): if self._sparse().issparse(x): return x.multiply(y).tocsr() if self._sparse().issparse(y): return y.multiply(x).tocsr() return self._dense().multiply(x, y) def _power(self, x, p): x = x.copy() if self._sparse().issparse(x): x.data = self._dense().power(x.data, p) else: nz = self._dense().nonzero(x) x[nz] = self._dense().power(x[nz], p) return x def _log(self, x): x = x.copy() if self._sparse().issparse(x): x.data = self._dense().log(x.data) else: nz = self._dense().nonzero(x) x[nz] = self._dense().log(x[nz]) return x def _normalize(self, x, axis, p=1.): s = self._sum(x, axis) n = self._power(s, -p) return self._multiply(x, n) def _sanitize(self, X, y="no_validation"): only_X = isinstance(y, str) and y == "no_validation" gpu = self._check_gpu(X=X, y=y if not only_X else None) if getattr(self, "gpu_", None) is None: self.gpu_ = gpu elif self.gpu_ != gpu: raise ValueError( "X is not on the same device (CPU/GPU) as on last call " "to partial_fit, was: %r" % (self.gpu_, )) if not self.gpu_: kwargs = { "accept_sparse": "csr", "reset": False, "dtype": (numpy.float32, numpy.float64) } if only_X: X = super()._validate_data(X=X, **kwargs) else: X, y = super()._validate_data(X=X, y=y, multi_output=self._check_encoded(y), **kwargs) if not self._check_non_negative(X): raise ValueError("X must contain non-negative values") return X if only_X else (X, y) def _unique_labels(self, y): if self._check_encoded(y): return self._dense().arange(0, y.shape[1]) elif self.gpu_: return self._dense().unique(y) else: return unique_labels(y) def _one_hot_encoding(self, y): classes = self.classes_ n, m = len(y), len(classes) if self.gpu_: y = y.get() classes = classes.get() unseen = set(y) - set(classes) if unseen: raise ValueError( "classes=%r were not allowed on first call " "to partial_fit" % (unseen, )) idx = {c: i for i, c in enumerate(classes)} col = self._dense().array([idx[c] for c in y]) row = self._dense().array(range(0, n)) val = self._dense().ones(n) return self._sparse().csr_matrix((val, (row, col)), shape=(n, m)) def _check_encoded(self, y): return self._sparse().issparse(y) or (getattr(y, "ndim", 0) == 2 and y.shape[1] > 1) def _check_non_negative(self, X): if self._sparse().issparse(X): if self._dense().any(X.data < 0): return False elif self._dense().any(X < 0): return False return True def _check_sample_weight(self, sample_weight, X): if self.gpu_: return sample_weight return _check_sample_weight(sample_weight=sample_weight, X=X) def _check_partial_fit_first_call(self, classes): if getattr(self, "classes_", None) is None and classes is None: raise ValueError("classes must be passed on the first call to partial_fit") elif classes is not None: classes = self._unique_labels(classes) if getattr(self, "classes_", None) is not None: if not self._dense().array_equal(self.classes_, classes): raise ValueError( "classes=%r is not the same as on last call " "to partial_fit, was: %r" % (classes, self.classes_)) else: self.classes_ = classes return True return False def _check_gpu(self, X, y=None): if not gpu_support: return False cp_X = cupy.get_array_module(X).__name__ == "cupy" if y is None: return cp_X cp_y = cupy.get_array_module(y).__name__ == "cupy" if cp_X == cp_y: return cp_X elif cp_X and not cp_y: raise ValueError("X is on GPU, but y is not") elif not cp_X and cp_y: raise ValueError("y is on GPU, but X is not") def _check_fitted(self): if getattr(self, "corpus_", None) is None: raise NotFittedError( f"This {self.__class__.__name__} instance is not fitted yet. " "Call 'fit' with appropriate arguments before using this estimator") def _more_tags(self): return { 'requires_y': True, 'requires_positive_X': True, 'X_types': ['2darray', 'sparse'], '_xfail_checks': { 'check_classifiers_classes': 'This is a pathological data set for BornClassifier. ' 'For some specific cases, it predicts less classes than expected', 'check_classifiers_train': 'Test fails because of negative values in X' } }

## fit(X, y, sample_weight=None)

Fit the classifier according to the training data X, y.

Parameters:

Name Type Description Default
X array-like of shape (n_samples, n_features)

Training data, where n_samples is the number of samples and n_features is the number of features.

required
y array-like of shape (n_samples,) or (n_samples, n_classes)

Target values. If 2d array, this is the probability distribution over the n_classes for each of the n_samples.

required
sample_weight array-like of shape (n_samples,)

Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight.

None

Returns:

Name Type Description
self object

Returns the instance itself.

Source code in bornrule/born.py
 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 def fit(self, X, y, sample_weight=None): """Fit the classifier according to the training data X, y. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is the number of features. y : array-like of shape (n_samples,) or (n_samples, n_classes) Target values. If 2d array, this is the probability distribution over the n_classes for each of the n_samples. sample_weight : array-like of shape (n_samples,) Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight. Returns ------- self : object Returns the instance itself. """ attrs = [ "gpu_", "corpus_", "classes_", "n_features_in_" ] for attr in attrs: if hasattr(self, attr): delattr(self, attr) return self.partial_fit(X, y, classes=y, sample_weight=sample_weight)

## partial_fit(X, y, classes=None, sample_weight=None)

Incremental fit on a batch of samples.

This method is expected to be called several times consecutively on different chunks of a dataset so as to implement out-of-core or online learning.

Parameters:

Name Type Description Default
X array-like of shape (n_samples, n_features)

Training data, where n_samples is the number of samples and n_features is the number of features.

required
y array-like of shape (n_samples,) or (n_samples, n_classes)

Target values. If 2d array, this is the probability distribution over the n_classes for each of the n_samples.

required
classes array-like of shape (n_classes,)

List of all the classes that can possibly appear in the y vector. Must be provided at the first call to partial_fit, can be omitted in subsequent calls.

None
sample_weight array-like of shape (n_samples,)

Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight.

None

Returns:

Name Type Description
self object

Returns the instance itself.

Source code in bornrule/born.py
  85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 def partial_fit(self, X, y, classes=None, sample_weight=None): """Incremental fit on a batch of samples. This method is expected to be called several times consecutively on different chunks of a dataset so as to implement out-of-core or online learning. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is the number of features. y : array-like of shape (n_samples,) or (n_samples, n_classes) Target values. If 2d array, this is the probability distribution over the n_classes for each of the n_samples. classes : array-like of shape (n_classes,) List of all the classes that can possibly appear in the y vector. Must be provided at the first call to partial_fit, can be omitted in subsequent calls. sample_weight : array-like of shape (n_samples,) Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight. Returns ------- self : object Returns the instance itself. """ X, y = self._sanitize(X, y) first_call = self._check_partial_fit_first_call(classes) if first_call: self.corpus_ = 0 self.n_features_in_ = X.shape[1] if not self._check_encoded(y): y = self._one_hot_encoding(y) if sample_weight is not None: sample_weight = self._check_sample_weight(sample_weight, X) y = self._multiply(y, sample_weight.reshape(-1, 1)) self.corpus_ += X.T @ self._multiply(y, self._power(self._sum(X, axis=1), -1)) return self

## predict(X)

Perform classification on the test data X.

Parameters:

Name Type Description Default
X array-like of shape (n_samples, n_features)

Test data, where n_samples is the number of samples and n_features is the number of features.

required

Returns:

Name Type Description
y ndarray of shape (n_samples,)

Predicted target classes for X.

Source code in bornrule/born.py
 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 def predict(self, X): """Perform classification on the test data X. Parameters ---------- X : array-like of shape (n_samples, n_features) Test data, where n_samples is the number of samples and n_features is the number of features. Returns ------- y : ndarray of shape (n_samples,) Predicted target classes for X. """ proba = self.predict_proba(X) idx = self._dense().argmax(proba, axis=1) return self.classes_[idx]

## predict_proba(X)

Return probability estimates for the test data X.

Parameters:

Name Type Description Default
X array-like of shape (n_samples, n_features)

Test data, where n_samples is the number of samples and n_features is the number of features.

required

Returns:

Name Type Description
y ndarray of shape (n_samples, n_classes)

Returns the probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_.

Source code in bornrule/born.py
 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 def predict_proba(self, X): """Return probability estimates for the test data X. Parameters ---------- X : array-like of shape (n_samples, n_features) Test data, where n_samples is the number of samples and n_features is the number of features. Returns ------- y : ndarray of shape (n_samples, n_classes) Returns the probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. """ self._check_fitted() X = self._sanitize(X) u = self._power(self._power(X, self.a) @ self._weights(), 1. / self.a) y = self._normalize(u, axis=1) if self._sparse().issparse(y): y = y.todense() return self._dense().asarray(y)

## explain(X=None, sample_weight=None)

Global and local explanation

For each test vector $x$, the $a$-th power of the unnormalized probability for the $k$-th class is given by the matrix product:

$u_k^a = \sum_j W_{jk}x_j^a$

where $W$ is a matrix of non-negative weights that generally depends on the model's hyper-parameters ($a$, $b$, $h$). The classification probabilities are obtained by normalizing $u$ such that it sums up to $1$.

This method returns global or local feature importance weights, depending on X:

• When X is not provided, this method returns the global weights $W$.

• When X is a single sample, this method returns a matrix of entries $(j,k)$ where each entry is given by $W_{jk}x_j^a$.

• When X contains multiple samples, then the values above are computed for each sample and this method returns their weighted sum. By default, each sample is given unit weight.

Parameters:

Name Type Description Default
X array-like of shape (n_samples, n_features)

Test data, where n_samples is the number of samples and n_features is the number of features. If not provided, then global weights are returned.

None
sample_weight array-like of shape (n_samples,)

Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight.

None

Returns:

Name Type Description
E array-like of shape (n_features, n_classes)

Returns the feature importance for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_.

Source code in bornrule/born.py
 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 def explain(self, X=None, sample_weight=None): r"""Global and local explanation For each test vector $x$, the $a$-th power of the unnormalized probability for the $k$-th class is given by the matrix product: math u_k^a = \sum_j W_{jk}x_j^a  where $W$ is a matrix of non-negative weights that generally depends on the model's hyper-parameters ($a$, $b$, $h$). The classification probabilities are obtained by normalizing $u$ such that it sums up to $1$. This method returns global or local feature importance weights, depending on X: - When X is not provided, this method returns the global weights $W$. - When X is a single sample, this method returns a matrix of entries $(j,k)$ where each entry is given by $W_{jk}x_j^a$. - When X contains multiple samples, then the values above are computed for each sample and this method returns their weighted sum. By default, each sample is given unit weight. Parameters ---------- X : array-like of shape (n_samples, n_features) Test data, where n_samples is the number of samples and n_features is the number of features. If not provided, then global weights are returned. sample_weight : array-like of shape (n_samples,) Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight. Returns ------- E : array-like of shape (n_features, n_classes) Returns the feature importance for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. """ self._check_fitted() if X is None: return self._weights() X = self._sanitize(X) X = self._normalize(X, axis=1) X = self._power(X, self.a) if sample_weight is not None: sample_weight = self._check_sample_weight(sample_weight, X) X = self._multiply(X, sample_weight.reshape(-1, 1)) return self._multiply(self._weights(), self._sum(X, axis=0).T)


text:
Timezone: »

Spotlight
Model Selection for Contextual Bandits
Dylan Foster · Akshay Krishnamurthy · Haipeng Luo

Wed Dec 11 04:20 PM -- 04:25 PM (PST) @ West Exhibition Hall A
We introduce the problem of model selection for contextual bandits, where a learner must adapt to the complexity of the optimal policy while balancing exploration and exploitation. Our main result is a new model selection guarantee for linear contextual bandits. We work in the stochastic realizable setting with a sequence of nested linear policy classes of dimension $d_1 < d_2 < \ldots$, where the $m^\star$-th class contains the optimal policy, and we design an algorithm that achieves $\tilde{O}l(T^{2/3}d^{1/3}_{m^\star})$ regret with no prior knowledge of the optimal dimension $d_{m^\star}$. The algorithm also achieves regret $\tilde{O}(T^{3/4} + \sqrt{Td_{m^\star}})$, which is optimal for $d_{m^{\star}}\geq{}\sqrt{T}$. This is the first model selection result for contextual bandits with non-vacuous regret for all values of $d_{m^\star}$, and to the best of our knowledge is the first positive result of this type for any online learning setting with partial information. The core of the algorithm is a new estimator for the gap in the best loss achievable by two linear policy classes, which we show admits a convergence rate faster than the rate required to learn the parameters for either class.

format: plain


text:
# Parameters of an elliptic equation?

I know that an ellipse equation described by:

$\frac {x^2} {a^2} + \frac {y^2} {b^2} =1$

My question is in the equation above how many parameters we need to estimate? Two or four? The unknows parameters are only a, b or are also x, y???

-
I think there is no elliptic function here. Please consider retagging it. Thanks. –  awllower Feb 24 '13 at 16:31

For every fixed ellipse, $a$ and $b$ are determined, and $x$ and $y$ are variables. The ellipse itself is the collection of points in the plane whose $x$ and $y$-coordinates statisfy the equation. For instance, take the ellipse $$\frac{x^2}{1} + \frac{y^2}{4} = 1$$ then $a=1$ and $b=2$. For any point $(x_0, y_0)$, if it is the case that $\frac{x_0^2}{1} + \frac{y_0^2}{4} = 1$, then that point is on the ellipse. For any point on the ellipse, if you take the coordinates and put them into the equation, the left-hand side and right-hand side will turn out equal. For any other point in the plane (like the origin, or say $(535, -1234)$), the equation is not statisfied, and therefore they are not on the ellipse.
Any other coice of $a$ and $b$ will result in a different ellipse. So, $a$ and $b$ are numbers that are determined beforehand, like $1$ and $2$ above, or any other pair of numbers, really. The reason they are called $a$ and $b$, and not written out specifically is in order to cover any concievable choice of numbers. This is something done often in mathematics (and quite successfully at that, if you can get your head around it).
The weakness of using letters instead of numbers like this is that you lose the immediate and concrete grasp on the numbers involved if you're not used to it. The strengths, however, is that you can talk about them all at once, instead of taking care of every single choice one by one. Imagine if you want to say something about all those ellipses, and having to go through the same calculations for every possible choice of denominators. Or just call them $a$ and $b$, whatever they are, and do the calculations once. It's pretty clear which approach will be more fruitfull in the long run.


text:
SuanShu, a Java numerical and statistical library

com.numericalmethod.suanshu.stats.distribution.univariate

• java.lang.Object
• All Implemented Interfaces:
ProbabilityDistribution

public class GammaDistribution
extends Object
implements ProbabilityDistribution
This gamma distribution, when k is an integer, is the distribution of the sum of k independent exponentially distributed random variables, each of which has a mean of θ (which is equivalent to a rate parameter of θ-1).

The R equivalent functions are dgamma, pgamma, qgamma, rgamma.

Wikipedia: Gamma distribution distribution
• Constructor Summary

Constructors
Constructor and Description
GammaDistribution(double k, double theta)
Construct a Gamma distribution.
• Method Summary

All Methods
Modifier and Type Method and Description
double cdf(double x)
Gets the cumulative probability F(x) = Pr(X ≤ x).
double density(double x)
The density function, which, if exists, is the derivative of F.
double entropy()
Deprecated.
Not supported yet.
double kurtosis()
Gets the excess kurtosis of this distribution.
double mean()
Gets the mean of this distribution.
double median()
Gets the median of this distribution.
double moment(double t)
The moment generating function is the expected value of etX.
double quantile(double u)
Gets the quantile, the inverse of the cumulative distribution function.
double skew()
Gets the skewness of this distribution.
double variance()
Gets the variance of this distribution.
• Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
• Constructor Detail

public GammaDistribution(double k,
double theta)
Construct a Gamma distribution.
Parameters:
k - the shape parameter
theta - the scale parameter
• Method Detail

• mean

public double mean()
Description copied from interface: ProbabilityDistribution
Gets the mean of this distribution.
Specified by:
mean in interface ProbabilityDistribution
Returns:
the mean
Wikipedia: Expected value
• median

public double median()
Description copied from interface: ProbabilityDistribution
Gets the median of this distribution.
Specified by:
median in interface ProbabilityDistribution
Returns:
the median
Wikipedia: Median
• variance

public double variance()
Description copied from interface: ProbabilityDistribution
Gets the variance of this distribution.
Specified by:
variance in interface ProbabilityDistribution
Returns:
the variance
Wikipedia: Variance
• skew

public double skew()
Description copied from interface: ProbabilityDistribution
Gets the skewness of this distribution.
Specified by:
skew in interface ProbabilityDistribution
Returns:
the skewness
Wikipedia: Skewness
• kurtosis

public double kurtosis()
Description copied from interface: ProbabilityDistribution
Gets the excess kurtosis of this distribution.
Specified by:
kurtosis in interface ProbabilityDistribution
Returns:
the excess kurtosis
Wikipedia: Kurtosis
• entropy

@Deprecated
public double entropy()
Deprecated. Not supported yet.
Description copied from interface: ProbabilityDistribution
Gets the entropy of this distribution.
Specified by:
entropy in interface ProbabilityDistribution
Returns:
the entropy
Wikipedia: Entropy (information theory)
• cdf

public double cdf(double x)
Description copied from interface: ProbabilityDistribution
Gets the cumulative probability F(x) = Pr(X ≤ x).
Specified by:
cdf in interface ProbabilityDistribution
Parameters:
x - x
Returns:
F(x) = Pr(X ≤ x)
Wikipedia: Cumulative distribution function
• quantile

public double quantile(double u)
Description copied from interface: ProbabilityDistribution
Gets the quantile, the inverse of the cumulative distribution function. It is the value below which random draws from the distribution would fall u×100 percent of the time.

F-1(u) = x, such that
Pr(X ≤ x) = u

This may not always exist.
Specified by:
quantile in interface ProbabilityDistribution
Parameters:
u - u, a quantile
Returns:
F-1(u)
Wikipedia: Quantile function
• density

public double density(double x)
Description copied from interface: ProbabilityDistribution
The density function, which, if exists, is the derivative of F. It describes the density of probability at each point in the sample space.
f(x) = dF(X) / dx
This may not always exist.

For the discrete cases, this is the probability mass function. It gives the probability that a discrete random variable is exactly equal to some value.

Specified by:
density in interface ProbabilityDistribution
Parameters:
x - x
Returns:
f(x)
• moment

public double moment(double t)
Description copied from interface: ProbabilityDistribution
The moment generating function is the expected value of etX. That is,
E(etX)
This may not always exist.
Specified by:
moment in interface ProbabilityDistribution
Parameters:
t - t
Returns:
E(exp(tX))


text:
# Full Changelog¶

## 0.1.1 (2020-07-19)¶

Update that includes the DOI and for which the README.txt is clean enough for twine.

## 0.1 (2020-07-19)¶

Initial release. Project renamed from original scintillometry, but similar in that the documentation still suggests that tasks be imported from the various modules in baseband_tasks, which is the only way they can be used for baseband prior to 4.0.

There will be a new version soon after this one which will depend on baseband 4.0 as one can then assume (and document) the existence of baseband.tasks.


text:
OASIS Mailing List ArchivesView the OASIS mailing list archive below
or browse/search using MarkMail.

# virtio-dev message

[Date Prev] | [Thread Prev] | [Thread Next] | [Date Next] -- [Date Index] | [Thread Index] | [List Home]

Subject: Re: [PATCH v3 1/2] virtio-video: Add virtio video device specification

• From: Alexandre Courbot <acourbot@chromium.org>
• To: Keiichi Watanabe <keiichiw@chromium.org>
• Date: Mon, 1 Jun 2020 16:19:00 +0900

On Fri, May 29, 2020 at 11:22 PM Keiichi Watanabe <keiichiw@chromium.org> wrote:
>
> Hi Dmitry,
>
> On Wed, May 27, 2020 at 9:12 PM Dmitry Sepp <dmitry.sepp@opensynergy.com> wrote:
> >
> > Hi Keiichi,
> >
> > On Montag, 18. Mai 2020 07:17:53 CEST Keiichi Watanabe wrote:
> > > > +struct virtio_video_stream_create {
> > > > +        struct virtio_video_cmd_hdr hdr;
> > > > +        le32 in_mem_type; /* One of VIRTIO_VIDEO_MEM_TYPE_* types */
> > > > +        le32 out_mem_type; /* One of VIRTIO_VIDEO_MEM_TYPE_* types */
> > > > +        le32 coded_format; /* One of VIRTIO_VIDEO_FORMAT_* types */
> > > > +        u8 padding[4];
> > > > +        u8 tag[64];
> > > > +};
> > > > +\end{lstlisting}
> > > > +\begin{description}
> > > > +\item[\field{in_mem_type, out_mem_type}] is a type of buffer
> > > > +  management for input /output buffers. The driver MUST set a value in
> > > > +  \field{enum virtio_video_mem_type} that the device reported a
> > > > +  corresponding feature bit.
> > > > +\begin{description}
> > > > +\item[\field{VIRTIO_VIDEO_MEM_TYPE_GUEST_PAGES}] Use guest pages.
> > > > +\end{description}
> > > > +\item[\field{coded_format}] is the encoded format that will be
> > > > +  processed.
> > > > +\item[\field{tag}] is the name associated with this stream. The tag
> > > > +  MUST be encoded in UTF-8 and NUL-terminated.
> > >
> > > I wonder why we need this "tag" field. I have kept this field from
> > > Dmitry's first proposal, where this was called "char debug_name[64]".
> > > However, on second thought, I have no idea what is the necessity to
> > > have this field. Our VMM implementation in ChromeOS simply ignores
> > > this field.
> > > If OpenSynergy's implementation relies on this field, I'm curious
> > > about the usage. We might want to have an enum value instead of this
> > > field where arbitrary values can be stored.
> > >
> >
> > The use of this field is not so clear because it was renamed. In fact, one can
> > have an idea how it is used by simply looking at the driver code: the field is
> > useful to know about the guest client app that uses the context. If someone
> > wants to store arbitrary values, they have 64 bytes to do so with this so-
> > called tag.
>
> Hmm, though I understand this can be useful for you, I don't think we
> should support it in the standard.
> For the first example, I feel something is not abstracted well if you
> want to send some information from a user app to the host device. User
> applications shouldn't have a way to send messages to hardware
> directly.

I am also a bit uncomfortable with having fields whose usage is not
clearly defined in the kernel. How would user-space specify the value
it wants to set there?

> For the second example, who is "someone"? Driver or device? In any
> case, I don't think it's the right way. They should extend existing
> structs or add commands or feature flags, I think. Also, if arbitrary
> values are allowed, the field won't be used correctly except in cases
> where both driver implementation and device implementation are
> available. This is against what the spec should be: virtio protocol
> must work independently from the implementations.
> Of course, it's obviously okay to have it as a downstream extension in
>
> >
> > > > +\end{description}
> > > > +
> > > > +The driver MUST set \field{stream_id} in \field{virtio_video_cmd_hdr}
> > > > +to an integer that is not used before. If a used value is passed as
> > > > +\field{stream_id}, the device MUST reports an error with
> > > > +VIRTIO_VIDEO_RESP_ERR_INVALID_STREAM_ID.
> > >
> > > I'm wondering if we can't generate stream_id in the host side so that
> > > we will have less error control code. In the current design, both the
> > > device and the driver have error checks; the device must check that a
> > > given ID is available and the driver must check if the device didn't
> > > return the INVALID_STREAM_ID error. Instead, by generating IDs in the
> > > device, we will be free from this type of failure. Same for
> > > resource_id in RESOURCE_CREATE.
> > >
> > > I guess this design originally came from the virtio-gpu protocol.
> > > However, I couldn't find a benefit of adopting the same design here.
> > >
> >
> > Honestly I don't see too much difference: device still needs to check whether
> > the id provided by the driver within some particular command is correct. If it
> > is not, it will return an error. The driver needs to check (or skip checking)
> > for an error either way as long as it is possible for the driver code to send
> > a wrong number.
>
> I'm talking about creation commands only. So, other commands won't be affected.
>
> Let me try to explain my idea in a different way. The relationship
> between the driver and the device can be seen as a client-server
> model.
> The client (driver) sends a request and the server (device) sends a
> response by processing or generating some data.
> Thus, I feel it's more natural that new data, including IDs, are
> generated and provided by the device.

This also results in one less check on the device side: when creating
a stream it just needs to pick the first available ID, instead of
checking whether the client provided something valid. This also
removes the burden of managing stream IDs from the driver, since the
device is entirely in charge of it (something it would have to do
anyway in both cases since it would still need to check that the
client-provided ID is valid).

[Date Prev] | [Thread Prev] | [Thread Next] | [Date Next] -- [Date Index] | [Thread Index] | [List Home]


text:
# Writing to a csv file in a customized way using scrapy

I've written a script in scrapy to grab different names and links from different pages of a website and write those parsed items in a csv file. When I run my script, I get the results accordingly and find a data filled in csv file. I'm using python 3.5, so when I use scrapy's built-in command to write data in a csv file, I do get a csv file with blank lines in every alternate row. Eventually, I tried the below way to achieve the flawless output (with no blank lines in between). Now, It produces a csv file fixing blank line issues. I hope I did it in the right way. However, if there is anything I can/should do to make it more robust, I'm happy to cope with.

This is my script which provides me with a flawless output in a csv file:

import scrapy ,csv
from scrapy.crawler import CrawlerProcess

class GetInfoSpider(scrapy.Spider):
name = "infrarail"

start_urls= ['http://www.infrarail.com/2018/exhibitor-profile/?e={}'.format(page) for page in range(65,70)]

def __init__(self):
self.infile = open("output.csv","w",newline="")

def parse(self, response):
for q in response.css("article.contentslim"):
name = q.css("h1::text").extract_first()

writer = csv.writer(self.infile)

c = CrawlerProcess({
'USER_AGENT': 'Mozilla/5.0',
})
c.crawl(GetInfoSpider)
c.start()

Btw, I used .CrawlerProcess() to be able to run my spider from sublime text editor.

• Welcome to Code Review! That's quite a well-written question, especially for a new user. Well done. – Mast Jun 30 '18 at 8:00

I'd like to mention, that there is a special way of making output files in scrapy - item pipelines. So, in order to make it right, you should write your own pipeline (or modify standard one via subclassing).

Also, you does not close the file, once you're done and you keep it open most of the time. The both problems are handled nicely with pipelines.

UPD: Well, you've asked for a better way, there it is. Although, if it's not acceptable for some hard-to-explain reasons (it's understandable), here's the other approach, how to make it better.

1. Don't leave the file open. There is a method (__del__()) which destroys the spider object. Add the code to close the file before it.

2. Another one is to store only the filename in the variable and open / close the file each time you write into it.

3. Another option is to use NoSQL database, which does not need to be opened / closed. And after scraping is done - get the output file from it.

4. If you have a few values to scrape you can store it in object variable, and then export it before __del__() method.

All the ways above are NOT welcomed by the actual developer community and may lead to serious problem in future. Use them carefully. Sometimes it's easier (in the long run) to read and understand how it really should be done.

Maybe it's the exact case?

• I think you put those lines wrongly in the answer section whereas it should be in the comment. If it were for item pipelines, I would not make the title of my post using this customized keyword. Thanks. – SIM Jun 29 '18 at 21:01
• Actually, I cannot comment other's posts yet – Dmitry Arkhipenko Jun 29 '18 at 21:04
• @asmitu Is there a reason you went for a customized approach? As in, why is the approach suggested not acceptable for you? – Mast Jun 30 '18 at 8:04
• Check out this link to be sure as to why __del__() method should be avoided. – SIM Jun 30 '18 at 14:44

You should ensure that the file is closed. In addition you should avoid creating a new writer object every loop iteration using the with statement:

class GetInfoSpider(scrapy.Spider):
name = "infrarail"
start_urls= ['http://www.infrarail.com/2018/exhibitor-profile/?e={}'.format(page) for page in range(65,70)]
output = "output.csv"

def __init__(self):
# empty outputfile
open(self.output, "w").close()
# alternative:
# if os.path.isfile(self.output):
#     os.remove(self.output)

def parse(self, response):
with open(self.output, "a", newline="") as f:
writer = csv.writer(f)
for q in response.css("article.contentslim"):
name = q.css("h1::text").extract_first()

Note that I also added some spaces after commas to improve readability, according to Python's official style-guide, PEP8.

It also recommends only importing from one module per line (so while from random import rand, randint is fine, import scrapy, csv is not).

Also note that each item is only written to file when the next one is being requested, as a generator pauses after the yield. That means if you for example itertools.islice it, your last item won't be written to the file. Therefore I swapped those two lines.

• @asmitu That will still leave the file open. In addition if you ever have more than one GetInfoSpider object, they will have the same file object, because the file is actually opened at the time of the class definition, not the instance creation. See my updated answer for two ways how to use append mode and still make sure that the file is overwritten for each new run. – Graipher Jun 30 '18 at 11:36

You should opt for closed() method as I've tried below. This method will be called automatically once your spider is closed. This method provides a shortcut to signals.connect() for the spider_closed signal.

class InfraRailSpider(scrapy.Spider):
name = "infrarail"
start_urls = ['https://www.infrarail.com/2020/english/exhibitor-list/2018/']

def __init__(self):
self.outfile = open("output.csv", "w", newline="")
self.writer = csv.writer(self.outfile)
self.writer.writerow(['title'])
print("***"*20,"opened")

def closed(self,reason):
self.outfile.close()
print("***"*20,"closed")

def parse(self, response):
for item in response.css('#exhibitor_list > [class^="e"]'):
name = item.css('p.basic > b::text').get()
self.writer.writerow([name])
yield {'name':name}


text:
mlprof.fun {dosresmeta} R Documentation

Likelihood Functions for dosresmeta Models

Description

These functions compute the value of the log-likelihood for random-effects dose-response meta-analysis, in terms of model parameters. They are meant to be used internally and not directly run by the users.

Usage

remlprof.fn(par, Xlist, Zlist, ylist, Slist, nalist, q, nall, ctrl)

remlprof.gr(par, Xlist, ylist, Slist, nalist, p, nall, ctrl)

mlprof.fn(par, Xlist, Zlist, ylist, Slist, nalist, q, nall, ctrl)

mlprof.gr(par, Xlist, ylist, Slist, nalist, p, nall, ctrl)

iter.igls(Psi, Xlist, Zlist, ylist, Slist, nalist, q)

Arguments

 par a vector representing the random-effects parameters defining the between-study (co)variance matrix. Xlist a m-dimensional list of study-specific design matrices for the fixed-effects part of the model. Zlist a m-dimensional list of study-specific design matrices for the random-effects part of the model. ylist a m-dimensional list of study-specific of vectors of estimated outcomes. Slist a m-dimensional list of within-study (co)variance matrices of estimated outcomes. nalist a m-dimensional list of k-dimensional study-specific logical vectors, identifying missing outcomes. ctrl list of parameters for controlling the fitting process, usually internally set to default values by dosresmeta.control. p, q, nall numeric scalars: number of predictors, number of observations (excluding missing). Psi a p x p matrix representing the current estimate of the between-study (co)variance matrix.

Details

These functions are called internally by the fitting functions dosresmeta.ml and dosresmeta.reml to perform iterative optimization algorithms for estimating random effects meta-analytical models.

The maximization of the (restricted) likelihood starts with few runs of an iterative generalized least square algorithm implemented in iter.igls. This can be regarded as a fast and stable way to get starting values close to the maximum for the Quasi-Newton iterative algorithm, implemented in optim. Alternatively, starting values can be provided by the user in the control list (see mvmeta.control).

These functions actually specify the profiled version of the (restricted) likelihood, expressed only in terms of random-effects parameters, while the estimate of the fixed-effects coefficients is provided at each iteration by the internal function glsfit, based on the current value of the between-study (co)variance matrix. At convergence, the value of this profiled version is identical to the full (restricted) likelihood. This approach is computationally efficient, as it reduces the number of parameters in the optimization routine.

The parameterization of the between-study (co)variance matrix ensures the positive-definiteness of the estimated matrix. A Cholesky decomposition is then performed on the marginal (co)variance matrix in order to re-express the problem as standard least square equations, an approach which speeds up the computation of matrix inverses and determinants. These equations are finally solved through a QR decomposition, which guarantees stability.

Value

mlprof.fn and remlprof.fn return the value of the (restricted) log-likelihood for a given set of parameters in par. iter.igls returns an updated estimate of Psi given its initial value or the value at the previous iteration.

Author(s)

Alessio Crippa, alessio.crippa@ki.se

dosresmeta, mvmeta.fit, dosresmeta.control, mlprof.fn


text:
How can I make genesets for sigpathway
0
Entering edit mode
@srinivas-iyyer-939
Last seen 6.5 years ago
Dear group, in sigPathway package, authors used muscle data. when one loads: library(sigPathway) data(MuscleExample) I see a "G" object which is nothing but a lit of all genes. > G[1] [[1]] [[1]]$src [1] "GO:0030054" [[1]]$title [1] "cell junction" [[1]]$probes [1] "220519_s_at" "206083_at" "204455_at" "212253_x_at" I get clueless in R with list operations. How can I make my own sets mimicking "G" list object. Thank you . srini ________________________________________________________________ ____________________ Be a better friend, newshound, and sigPathway sigPathway • 454 views ADD COMMENTlink 0 Entering edit mode @james-w-macdonald-5106 Last seen 12 hours ago United States Hi Srini, Srinivas Iyyer wrote: > Dear group, > in sigPathway package, authors used > muscle data. > > when one loads: > library(sigPathway) > data(MuscleExample) > I see a "G" object which is nothing but a lit of all > genes. > >> G[1] > [[1]] > [[1]]$src > [1] "GO:0030054" > > [[1]]$title > [1] "cell junction" > > [[1]]$probes > [1] "220519_s_at" "206083_at" "204455_at" > "212253_x_at" > > > I get clueless in R with list operations. > > How can I make my own sets mimicking "G" list object. Well, it depends on what you are starting with. Do you have an Affy chip? Illumina? Did you roll yer own? Without knowing where you are starting I don't think anybody can help you. Also note that the authors seem to have a bunch of these lists already made that you can download from their site. Have you looked there to see if they already made what you want? Best, Jim > > Thank you . > srini > > > ______________________________________________________________ ______________________ > Be a better friend, newshound, and > > _______________________________________________ > Bioconductor mailing list > Bioconductor at stat.math.ethz.ch > https://stat.ethz.ch/mailman/listinfo/bioconductor > Search the archives: http://news.gmane.org/gmane.science.biology.informatics.conductor -- James W. MacDonald, M.S. Biostatistician Affymetrix and cDNA Microarray Core University of Michigan Cancer Center 1500 E. Medical Center Drive 7410 CCGC Ann Arbor MI 48109 734-647-5623
0
Entering edit mode
Dear Jim , thanks for your input. For now I am using U133Plus2 and Later I will be using affy and agilent mouse and rat chips respectively. Although, I found the site where they are describing how to make "G" object, the script that was provided is not straightforward and I get errors when I am trying to process what the author is asking me to do.( http://www.chip.org/~ppark/Supplements/PNAS05.html) My ultimate aim is to combine my choice of datasets: some from MsigDB, my own annotations, PPI sets etc. into "G"list object. For that the starting material I have is a TAB delim file with: Pathway Source Name of Pathway GENE symbols. Now I am clueless as how to create a annotation list. This is required to start doing what authors are describing in their code how to convert gene symbols to ID. Simply, I dont know how to make an object equivalent to "Genesets_EntrezGeneIDs.RData". "Genesets_EntrezGeneIDs.RData" is an R workspace containing Entrez GeneIDs corresponding to gene sets from GO, KEGG, and other pathway databases. egidDir <- getwd() > egidDir [1] "C:/Documents and Settings/srini/My Documents/software" >load(file.path(egidDir, "Genesets_EntrezGeneIDs.RData")) > biocAnnot <- "rat2302" > library(biocAnnot, character.only = TRUE) Error in library(biocAnnot, character.only = TRUE) : there is no package called 'rat2302' > biocAnnot [1] "rat2302" > ls() [1] "biocAnnot" "egidDir" "G.EGIDs" > xx <- as.list(get(paste(biocAnnot, "ENTREZID", sep = ""))) Error in get(paste(biocAnnot, "ENTREZID", sep = "")) : > sessionInfo() R version 2.6.1 (2007-11-26) i386-pc-mingw32 locale: LC_COLLATE=English_United States.1252;LC_CTYPE=English_United States.1252;LC_MONETARY=English_United States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] sigPathway_1.6.0 loaded via a namespace (and not attached): [1] rcompgen_0.1-17 tools_2.6.1 This might be as simple stupid question as how to make lists in R. But truly lists is one of my nightmares. Thanks Srini --- "James W. MacDonald" <jmacdon at="" med.umich.edu=""> wrote: > Hi Srini, > > Srinivas Iyyer wrote: > > Dear group, > > in sigPathway package, authors used > > muscle data. > > > > when one loads: > > library(sigPathway) > > data(MuscleExample) > > I see a "G" object which is nothing but a lit of > all > > genes. > > > >> G[1] > > [[1]] > > [[1]]$src > > [1] "GO:0030054" > > > > [[1]]$title > > [1] "cell junction" > > > > [[1]]$probes > > [1] "220519_s_at" "206083_at" "204455_at" > > "212253_x_at" > > > > > > I get clueless in R with list operations. > > > > How can I make my own sets mimicking "G" list > object. > > Well, it depends on what you are starting with. Do > you have an Affy > chip? Illumina? Did you roll yer own? > > Without knowing where you are starting I don't think > anybody can help you. > > Also note that the authors seem to have a bunch of > these lists already > made that you can download from their site. Have you > looked there to see > if they already made what you want? > > Best, > > Jim > > > > > > Thank you . > > srini > > > > > > > ______________________________________________________________________ ______________ > > Be a better friend, newshound, and > > > > _______________________________________________ > > Bioconductor mailing list > > Bioconductor at stat.math.ethz.ch > > https://stat.ethz.ch/mailman/listinfo/bioconductor > > Search the archives: > http://news.gmane.org/gmane.science.biology.informatics.conductor > > -- > James W. MacDonald, M.S. > Biostatistician > Affymetrix and cDNA Microarray Core > University of Michigan Cancer Center > 1500 E. Medical Center Drive > 7410 CCGC > Ann Arbor MI 48109 > 734-647-5623 > ________________________________________________________________ ____________________ Be a better friend, newshound, and ADD REPLYlink 0 Entering edit mode Hi Srini, Srinivas Iyyer wrote: > Dear Jim , > thanks for your input. > For now I am using U133Plus2 and Later I will be > using affy and agilent mouse and rat chips > respectively. > > Although, I found the site where they are describing > how to make "G" object, the script that was provided > is not straightforward and I get errors when I am > trying to process what the author is asking me to do.( > http://www.chip.org/~ppark/Supplements/PNAS05.html) > > > My ultimate aim is to combine my choice of datasets: > some from MsigDB, my own annotations, PPI sets etc. > into "G"list object. > > For that the starting material I have is a TAB delim > file with: > > Pathway Source Name of Pathway GENE symbols. > > > Now I am clueless as how to create a annotation list. > This is required to start doing what authors are > describing in their code how to convert gene symbols > to ID. > > Simply, I dont know how to make an object equivalent > to "Genesets_EntrezGeneIDs.RData". > > "Genesets_EntrezGeneIDs.RData" is an R workspace > containing Entrez GeneIDs corresponding to gene sets > from GO, KEGG, and other pathway databases. Well, I think this will be way too complicated for anyone to help you with via a listserv. > > > > > > egidDir <- getwd() >> egidDir > [1] "C:/Documents and Settings/srini/My > Documents/software" > >> load(file.path(egidDir, > "Genesets_EntrezGeneIDs.RData")) >> biocAnnot <- "rat2302" >> library(biocAnnot, character.only = TRUE) > Error in library(biocAnnot, character.only = TRUE) : > there is no package called 'rat2302' So the error ^^^^^^^^^^^^ right there indicates you don't have this package installed yet. >> biocAnnot > [1] "rat2302" >> ls() > [1] "biocAnnot" "egidDir" "G.EGIDs" >> xx <- as.list(get(paste(biocAnnot, "ENTREZID", sep = > ""))) > Error in get(paste(biocAnnot, "ENTREZID", sep = "")) : Since the package isn't installed, you will not be able to get anything from it. Anyway, if you want to do something this complicated (e.g., not just using the sigPathways package as intended) then you will likely have to get help from the authors to make your own G.EGIDs list. On the webpage you reference at the bottom it says to contact Peter J. Park if you have questions. I think probably that is the best way to go. Best, Jim > >> sessionInfo() > R version 2.6.1 (2007-11-26) > i386-pc-mingw32 > > locale: > LC_COLLATE=English_United > States.1252;LC_CTYPE=English_United > States.1252;LC_MONETARY=English_United > States.1252;LC_NUMERIC=C;LC_TIME=English_United > States.1252 > > attached base packages: > [1] stats graphics grDevices utils datasets > methods base > > other attached packages: > [1] sigPathway_1.6.0 > > loaded via a namespace (and not attached): > [1] rcompgen_0.1-17 tools_2.6.1 > > > This might be as simple stupid question as how to make > lists in R. But truly lists is one of my nightmares. > > Thanks > Srini > > > > > > > > > > > --- "James W. MacDonald" <jmacdon at="" med.umich.edu=""> > wrote: > >> Hi Srini, >> >> Srinivas Iyyer wrote: >>> Dear group, >>> in sigPathway package, authors used >>> muscle data. >>> >>> when one loads: >>> library(sigPathway) >>> data(MuscleExample) >>> I see a "G" object which is nothing but a lit of >> all >>> genes. >>> >>>> G[1] >>> [[1]] >>> [[1]]$src >>> [1] "GO:0030054" >>> >>> [[1]]$title >>> [1] "cell junction" >>> >>> [[1]]$probes >>> [1] "220519_s_at" "206083_at" "204455_at" >>> "212253_x_at" >>> >>> >>> I get clueless in R with list operations. >>> >>> How can I make my own sets mimicking "G" list >> object. >> >> Well, it depends on what you are starting with. Do >> you have an Affy >> chip? Illumina? Did you roll yer own? >> >> Without knowing where you are starting I don't think >> anybody can help you. >> >> Also note that the authors seem to have a bunch of >> these lists already >> made that you can download from their site. Have you >> looked there to see >> if they already made what you want? >> >> Best, >> >> Jim >> >> >>> Thank you . >>> srini >>> >>> >>> > ____________________________________________________________________ ________________ >>> Be a better friend, newshound, and >>> >>> _______________________________________________ >>> Bioconductor mailing list >>> Bioconductor at stat.math.ethz.ch >>> https://stat.ethz.ch/mailman/listinfo/bioconductor >>> Search the archives: > http://news.gmane.org/gmane.science.biology.informatics.conductor >> -- >> James W. MacDonald, M.S. >> Biostatistician >> Affymetrix and cDNA Microarray Core >> University of Michigan Cancer Center >> 1500 E. Medical Center Drive >> 7410 CCGC >> Ann Arbor MI 48109 >> 734-647-5623 >> > > > > ______________________________________________________________ ______________________ > Be a better friend, newshound, and > know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ > -- James W. MacDonald, M.S. Biostatistician Affymetrix and cDNA Microarray Core University of Michigan Cancer Center 1500 E. Medical Center Drive 7410 CCGC Ann Arbor MI 48109 734-647-5623


text:
# Fill opacity problem with pdflatex while upgrading MiKTeX from version 2.7 to 2.9

It's my first post. I solved it when writing this so I send it anyway in case it helps someone.

When compiled with pdflatex.exe from MiKTeX 2.7 it works. When compiled with pdflatex.exe from MiKTeX 2.9 the fill opacity property of \addplot also compiles without errors but when opened in a pdf reader, the reader returns error: pgf@ca0.5 blablabla.

To fix this problem (I don't know why) you should avoid using packages: pstricks, pst-node, pst-plot, pst-circ.

Here's my corrected code

\documentclass[addressstd,a4paper,10pt]{article}

\usepackage{tikz}
\usepackage{pgfplots}
%\usepackage{pstricks, pst-node, pst-plot, pst-circ}

\begin{document}
\begin{tikzpicture}
\begin{semilogxaxis}

coordinates {(22.1,68.9) (44.2,74.4) (88.4,86.5)};

coordinates {(22.1,78.9) (44.2,64.4) (88.4,86.5)};

\end{semilogxaxis}
\end{tikzpicture}
\end{document}

Do you know why?

-
Welcome to TeX.SX! You can have a look at our starter guide to familiarize yourself further with our format. I see no problem with your code, apart from suprious ; after the legends, and the output is fine when I run in a pstricks compatible way. Which engine are you using? Have you seen tex.stackexchange.com/q/8413/15925? –  Andrew Swann Apr 8 at 7:03
Thanks Andrew. The problem (perhaps not in the code) is when uncomment the line: %\usepackage{pstricks, pst-node, pst-plot, pst-circ} using miktex 2.9 pdflatex (I am using texnic 1.0 to compile) –  Ernesto Apr 10 at 16:55
Ernesto, this issue is very, very probably not related to MiKTeX itself, but to the fact that in MiKTeX 2.7 you necessarily have older package versions of pgf/TikZ and PSTricks & co. –  Speravir Apr 10 at 23:57
My remarks about the output applied to when the line was uncommented. –  Andrew Swann Apr 11 at 9:32
Speravir: Thanks for the hint on versions (Miktex, pgf/Tikz and PSTricks). I put the label Miktex because it was how I (and perhaps others) identified the problem. It was hard, for me, to discover that the problem was in packages versions not in the compiler. –  Ernesto Apr 12 at 0:26

use it this way:

[...]
\usepackage{ifpdf}
\usepackage{tikz}
\usepackage{pgfplots}
\ifpdf\else
\usepackage{pstricks,pst-node,pst-plot,pst-circ}
\psset{pgffunctions}
\fi
\begin{document}
[...]

then it will work with pdflatex --shell-escape, latex->dvips->ps2pdf, and xelatex

-
good answer! I can not vote because "my reputation" < 15 –  Ernesto Apr 10 at 16:53
you can accept the answer –  Herbert Apr 10 at 18:03


text:
# Texas Go Math Grade 8 Module 11 Quiz Answer Key

Refer to our Texas Go Math Grade 8 Answer Key Pdf to score good marks in the exams. Test yourself by practicing the problems from Texas Go Math Grade 8 Module 11 Quiz Answer Key.

## Texas Go Math Grade 8 Module 11 Quiz Answer Key

Texas Go Math Grade 8 Module 11 Ready to Go On? Answer Key

11.1 Equations with the Variable on Both Sides

Solve.

Question 1.
4a – 4 = 8 + a ____________
4a – 4 = 8 + a
(Subtract a from both sides.) 4a – 4 – a = 8 + a – a
(Add 4 to both sides.) 3a – 4 = 8
(Divide both sides by 3.) 3a = 12
a = 4
The statement is true. There is one solution.

Question 2.
4x + 5 = x + 8 ___________
4x + 5 = x + 8
(Subtract x from both sides) 4x + 5 – x = x + 8 – x
(Subtract 5 from both sides.) 3x + 5 = 8
(Divide both sides by 3.) 3x = 3
x = 1
The statement is true. There is one solution.

Question 3.
Hue is arranging chairs. She can form 6 rows of a given length with 3 chairs left over, or 8 rows of that same length if she gets 11 more chairs. Write and solve an equation to find how many chairs are in that row length.
(Write an equation) 6x + 3 = 8x – 11
(Subtract 3 from both sides.) 6x + 3 – 3 = 8x – 11 – 3
(Subtract 8x from both sides.) 6x = 8x – 14
(Divide by -2.)  – 2x = -14
x = 7
There are 7 chairs in each row.

11.2 Equations with Rational Numbers

Solve.

Question 4.
$$\frac{2}{3}$$s – $$\frac{2}{3}$$ = $$\frac{s}{6}$$ + $$\frac{4}{3}$$ ____________
(Multiply both sides by the LCM(3, 6) = 6) $$\frac{2}{3}$$s – $$\frac{2}{3}$$ = $$\frac{s}{6}$$ + $$\frac{4}{3}$$
6 ∙ $$\frac{2}{3}$$s – 6 ∙ $$\frac{2}{3}$$ = 6 ∙ $$\frac{s}{6}$$ + 6 ∙ $$\frac{4}{3}$$
4s – 4 = n + 8
(Add 4 to both sides) 4s – 4 + 4 = s + 8 + 4
4s = s + 12
(Subtract n from both sides) 4s – s = s + 12 – s
3s = 12
(Divide both sides by 3) $$\frac{3s}{3}$$ = $$\frac{12}{3}$$
s = 4

Question 5.
1.5d + 3.25 = 1 + 2.25d _____________
1.5d + 3.25 = 1 + 2.25d
(Subtract 3.25 from both sides) 1.5d + 3.25 – 3.25 = 1 + 2.25d – 3.25
1.5d = 2.25d – 2.25
(Subtract 2.25d from both sides.) 1.5d – 2.25d = 2.25d – 2.25 – 2.25d
-0.75d = -2.25
(Divide both sides by -0.75) $$\frac{-0.75d}{-0.75}$$ = $$\frac{-2.25}{-0.75}$$
d = 3

Question 6.
Happy Paws charges $19.00 plus$1.50 per hour to keep a dog during the day. Woof Watchers charges $15.00 plus$2.75 per hour. Write and solve an equation to find for how many hours the total cost of the services is equal.
Happy Paws charge for x hours
1.5x + 19
Woof Watchers charge for x hours
2.75x + 15
Put two expressions as equal
2.75x + 15 = 1.5x + 19
Subtract 1.5 from both sides
2.75x + 15 – 1.5x = 1.5x + 19 – 1.5x
1.25x + 15 = 19
Subtract 15 from both sides
1.25x + 15 – 15 = 19 – 15
1.25x = 4
Divide both sides by 1.25
x = $$\frac{4}{1.25}$$ = 3.2
The total cost of the services is equal after $3.2 hrs. 11.3 inequalities with the Variable on Both Sides Question 7. Write an inequality to represent the relationship “Two less than 2 times a number is greater than the number plus 64″. Then solve your inequality. Answer: Let us consider the number = x 2 – 2x ≥ x + 60 -2x -x ≥ 60 – 2 -3x ≥ 58 x ≥ 58/-3 x ≥ -19.33 2 – 2(-19.33) ≥ -19.33 + 60 40.66 ≥ 40.67. 11.4 Inequalities with Rational Numbers Question 8. One prepaid cell phone company charges$0.028 per minute and a $3 monthly fee. Another company charges$0.034 per minute with no monthly fee. For what numbers of minutes per month are the charges for the first company cheaper?
Let us consider the number of charges = x
The first company charges = $0.028 and$3 for the monthly fee.
The secondary company charges = $0.034 and no monthly fee. The inequality equation is$0.029 + $3 ≤$0.034x
Multiply both sides by 1000
28x + 2000 ≤ 34x
2000 ≤ 34x + 28x
2000 ≤ 62x
x ≥ 2000/62
X ≥ 32.2
32.2 minutes per month are the charges for the first company cheaper.

Essential Question

Question 9.
How can you use equations with the variable on both sides to solve real-world problems?
I could join a game club for $15 and rent games for$2 each, or I could pay $3 for each video rental, which is the better deal? Texas Go Math Grade 8 Module 11 Mixed Review Texas Test Prep Answer Key Selected Response Question 1. Two cars are traveling in the same direction. The first car is going 40 mi/h and the second car is going 55 mi/h. The first car left 3 hours before the second car. Which equation could you solve to find how many hours it will take for the second car to catch up to the first car? (A) 55t + 3 = 40t (B) 55t + 165 = 40t (C) 40t + 3 = 55t (D) 40t + 120 = 55t Answer: (D) 40t + 120 = 55t Explanation: We write an expression representing the distance that car A has traveled. Let’s denote the time by t. 3 * 40 + 40t = 120 + 40t We write an expression representing the distance that car B has traveled. Let’s denote the time by t 55t We write an equation that can be solved to find the time it will take for the second car to catch up to the first car. 40t + 120 = 55t Question 2. A wide screen television display measures approximately 15 inches high and 27 inches wide. A television is advertised by giving the approximate length of the diagonal of its screen. How should the television be advertised? (A) 36 inches (B) 31 inches (C) 30 inches (D) 21 inches Answer: The wide screen television display is in the shape of rectangle The formula for the length of the diagonal of a rectangle = c² = a² + b² The length of the rectangle = a = 15 Wide of the rectangle = b = 27 c² = 15² + 27² c² = 225 + 729 c = sq. root (954) c = 31 sq. inches. Option B is the correct answer. Question 3. Shawn’s Rentals charges$27.50 per hour to rent a surfboard and a wet suit. Darla’s Surf Shop charges $23.25 per hour to rent a surfboard plus$17 extra for a wetsuit. For what total number of hours are the charges for Shawn’s Rentals the same as the charges for Darla’s Surf Shop?
(A) 3
(B) 4
(C) 5
(D) 6
(B) 4

Explanation:
Shawn’s rentaL charge after x hrs
27.5x
Darlas surf shop charge after x hr
23.25x + 17
Equate the two expressions
23.25x + 17 = 27.5x
Subtract 23.25x from both sides
23.25x + 17 – 23.25x = 27.5x – 23.25x
4.25x = 17
Divide both sides by 4.25
x = $$\frac{17}{4.25}$$ = 4
The charge would be equal after \$4 hrs.

Question 4.
Which of the following is an irrational number?
(A) -8
(B) 4.63
(C) $$\sqrt{11}$$
(D) $$\frac{1}{3}$$
(C) $$\sqrt{11}$$

Explanation:
$$\sqrt{11}$$ is irrational.

Question 5.
Carlos has at least as many action figures in his collection as Josh. Carlos has 5 complete sets plus 4 individual figures. Josh has 3 complete sets plus 14 individual figures. Which inequality represents how many action figures can be in a complete set?
(A) x ≥ 7
(B) x ≤ 7
(C) x ≥ 5
(D) x ≤ 5
Let us consider the action figures in a complete set = x
The Charles has 5 complete sets + 4 individual figures
Josh has 3 complete sets + 14 individual figures
The inequality equation is
5x + 4 ≤ 3x + 14
5x – 3x ≤ 14 – 4
2x ≤ 10
x ≤ 10/2
x ≤ 5
Option D is the correct answer.

Question 6.
Which inequality represents the solution to 1.25x + 2.5 < 2.75x – 6.5?
(A) x > 6
(B) x < 6
(C) x > 2.25
(D) x < 2.25
1.25x + 2.5 < 2.75x – 6.5
1.25x – 2.75x < -6.5 – 2.5
-1.50x < -9
1.5x < 9
x < 9/1.5
x < 6
Option B is the correct answer.

Gridded Response

Question 7.
If both figures have the same perimeter, what is the perimeter of each figure?

Given that,
Perimeter of the rectangle = perimeter of the triangle
2(l + w) = a + b + c
l = x + 5
w = x
a = x + 7
b = x + 4
c = x + 11
2(x + 5 + x) = x + 7 + x + 4 + x + 11
4x + 10 = 3x + 22
22 – 10 = 4x – 3x
x = 12.
3(12) + 22 = 4(12) + 10
58 = 58
The perimeter of the rectangle is 58 sq. inches.
The perimeter of the triangle is 58 sq. inches.


text:
# Calculus and Computer Science Again?

Computer Science Level 4

$\large \displaystyle \int_{0}^{2 \pi} \ e^{\frac{x}{\pi}} \cos^{30}x \, dx = \, ?$

Give your answer to 3 decimal places.

×


text:
Home » Revision Notes for CBSE Class 6 to 12 » Class 10 Maths for Real Numbers of Chapter 1 Revision Notes

# Class 10 Maths for Real Numbers of Chapter 1 Revision Notes

## CBSE Class 10 Maths Chapter 1 – Real Numbers – Free PDF Download

Free PDF download of Class 10 Maths Chapter 1 – Real Numbers Revision Notes & Short Key-notes prepared by expert Mathematics teachers from latest edition of CBSE(NCERT) books.

## CBSE Class 10 Maths Revision Notes Chapter 1 Real Numbers

• Natural numbers: Counting numbers are called Natural numbers. These numbers are denoted by N = {1, 2, 3, ………}
• Whole numbers: The collection of natural numbers along with 0 is the collection of Whole number and is denoted by W.
• Integers: The collection of natural numbers, their negatives along with the number zero are called Integers. This collection is denoted by Z.
• Rational number: The numbers, which are obtained by dividing two integers, are called Rational numbers. Division by zero is not defined.
• Coprime: If HCF of two numbers is 1, then the two numbers area called relatively prime or coprime.

1. Euclid’s division lemma :
For given positive integers ‘a’ and ‘b’ there exist unique whole numbers ‘q’ and ‘r’ satisfying the relation .
Theorem: If  and  are non-zero integers, the least positive integer which is expressible as a linear combination of  and  is the HCF of  and , i.e., if  is the HCF of  and , then these exist integers  and , such that  and  is the smallest positive integer which is expressible in this form.
The HCF of  and  is denoted by HCF.
2. Euclid’s division algorithms :
HCF of any two positive integers a and b. With a > b is obtained as follows:
Step 1 : Apply Euclid’s division lemma to a and b to find q and r such that

b = Divisor
q = Quotient
r =  Remainder
Step II: If r  = 0, HCF (a,b)=b if , apply Euclid’s lemma to b and r.
Step III: Continue the process till the remainder is zero. The divisor at this stage will be the required HCF.
3. The Fundamental Theorem of Arithmetic :
Every composite number can be expressed (factorized) as a product of primes and this factorization is unique, apart from the order in which the prime factors occur.

4. Let    to be a rational number, such that the prime factorization of ‘q’ is of the form 2m+5n, where m, n are non-negative integers. Then x has a decimal expansion which is terminating.
5. Let  be a rational number, such that the prime factorization of q is not of the form 2m+5n, where m, n are non-negative integers. Then x has a decimal expansion which is non-terminating repeating.
6.  is irrational, which p is a prime. A number is called irrational if it cannot be written in the form  where p and q are integers and
8. If a and b are two positive integers, then HCF(a, b) x LCM(a, b) = a x b
i.e., (HCF x LCM) of two intergers = Product of intergers.
9. A rational number which when expressed in the lowest term has factors 2 or 5 in the denominator can be written as terminating decimal otherwise a non-terminating recurring decimal. In other words, if the rational number  is, such that the prime factorization of b is of form  where m and n are natural numbers, then  has a terminating decimal expansion.
10. We conclude that every rational number can be represented in the form of terminating or non-terminating recurring decimal.


text:
# Find real number $a$ such that matrix $A$ is NOT diagonalisable

Consider the matrix:

$\begin{bmatrix}2 & a & -1\\0 & 2 & 1\\-1 & 8 & -1\end{bmatrix}$

Find all $a \in \mathbb R$ such that $A$ is not diagonalisable.

I've never thought of such a problem before. What is the systematic way to make a matrix non-diagonalisable?

• A necessary conddition is an eigenvalue with multiplicity greater than $1$. Aug 7, 2018 at 19:56
• What is the criterion for a matrix to be diagonalizable? Try to establish this in dependence of $a$.
– blub
Aug 7, 2018 at 19:57
• Just make the first row a linear combination of the others
– N74
Aug 7, 2018 at 20:06
• The characteristic polynomial, if I'm not mistaken, is $-x^3+3x^2+9x-(22+a)$. Thus, for $-27<a<5$, this equation should on the first glimpse have three roots, i.e. three distinct eigenvalues and thus be diagonalizable for these values. As it is a cubic function, it always has at least one root in every case, i.e. there is always one eigenvalue at least. I don't know about the geometric multiplicities in these cases.
– blub
Aug 7, 2018 at 20:39
• Are we talking about diagonalization over the reals or over the complex numbers? Aug 7, 2018 at 22:22

(These Linear Algebra course notes by Michael Stoll, 2007 provide good background to my following assertions. As does the Wikipedia page on characteristic polynomials.)

Use the following facts:

a) A matrix $M \in \mathrm{Mat}(n,F)$ (where $n$ is the size of the matrix and $F$ is some field) is diagonalisable if and only if its minimal polynomial $m_M(x)$ is a product of distinct monic linear factors.

b) The characteristic polynomial of a matrix $M$ is defined as $p_M(x)=\mathrm{det}(xI-M)$

c) Matrices satisfy their own characteristic equations: $p_M(M)=0$ for all $M$. Hence a matrix's minimal polynomial always divides its characteristic polynomial: $m_M(x) \, \vert \, p_M(x)$.

d) The discriminant of a cubic polynomial $ax^3+bx^2+cx+d$ is given by: $$\Delta_3 = b^2c^2-4ac^3-4b^3d-27a^2d^2+18abcd$$ If $\Delta_3>0$ then the equation as three distinct real roots. If $\Delta_3=0$ then the equation has a repeated root and all its roots are real. If $\Delta_3<0$ then the equation has just one real root.

$$A:= \left( \begin{matrix}2 & a & -1\\0 & 2 & 1\\-1 & 8 & -1\end{matrix} \right)$$

we have that

\begin{align} p_A(x) &= \mathrm{det} \left( \begin{matrix} x-2 & -a & 1\\0 & x-2 & -1\\1 & -8 & x+1\end{matrix} \right) \\ \\ &= (x-2)((x-2)(x+1)-8) + (a - (x-2)) \\ &= x^3 -3x^2-9x+22+a \end{align}

With some calculation, the discriminant of $p_A$ is equal to $$\Delta_3 = -27(a-5)(a+27)$$

Firstly, $$\Delta_3>0 \iff -27<a<5$$ In this case, $p_A$ has three distinct real roots then it will factorise into three distinct linear factors. Hence $m_A(x)$ will also factorise into distinct linear factors and $A$ will be diagonalisable.

So $-27<a<5$ implies that $A$ is diagonalisable.

Secondly, $$\Delta_3=0 \iff a \in \{-27,5\}$$

If $a=-27$ then $$A:= \left( \begin{matrix}2 & a & -1\\0 & 2 & 1\\-1 & 8 & -1\end{matrix} \right)$$ and this matrix can be checked to have a maximum of two linearly independent eigenvectors $$v_1:= \left( \begin{matrix}-10\\1\\3\end{matrix} \right) \qquad v_2:= \left( \begin{matrix}-8\\-1\\3\end{matrix} \right)$$ and so $A$ is not diagonalisable. (We could also consider the Jordan Form of $A$ as calculated by @WillJagy in their answer to this question.)

Similarly for $a=5$, $A$ turns out to not be diagonalisable.

Thirdly,

$$\Delta_3<0 \iff a \in (-\infty , -27) \cup (5, \infty )$$

In this case $p_A(x)=(x- \lambda )(x^2+ \beta x + \gamma )$ where $\lambda$ , $\beta$ and $\gamma$ are real and $(x^2+ \beta x + \gamma )$ cannot be factorised over the reals. Since $m_A$ divides $p_A$ we have three options: \begin{align} \mathrm{(i)} \qquad & m_A(x)=(x- \lambda ) \\\mathrm{(ii)} \qquad & m_A(x)=(x^2+ \beta x + \gamma ) \\\mathrm{(iii)} \qquad & m_A(x)=(x- \lambda )(x^2+ \beta x + \gamma ) \end{align}

It is obvious that $(A-\lambda I )$ is not equal to $0$ for any $\lambda$ so we can rule out option $\mathrm{(i)}$. But in both of the options $\mathrm{(ii)}$ and $\mathrm{(iii)}$, $m_A$ is not a product of distinct monic linear factors and hence $A$ is not diagonalisable.

Therefore:

$A$ is not diagonalisable over $\mathbb{R}$ if and only if $a \in (-\infty , -27] \cup [5, \infty )$

Edit: diagonalisability over $\mathbb{C}$

Even if working in $\mathbb{C}$, the cases $\Delta_3>0$ and $\Delta_3=0$ above remain exactly the same: in these cases the characteristic polynomial has no complex roots.

However, $\Delta_3<0$ now gives us that $p_A$ can be factorised into three distinct linear factors in $\mathbb{C}[x]$. Hence $m_A(x)$ will also factorise into distinct linear factors in $\mathbb{C}[x]$ and $A$ will be diagonalisable.

Hence $A$ is not diagonalisable over $\mathbb{C}$ if and only if $a \in \{-27,5\}$.

In general, for $A \in \mathrm{Mat}(n,\mathbb{C})$, if the discriminant of $p_A$ is not equal to $0$ then $p_A$ has no repeated roots and $A$ will be diagonalisable over $\mathbb{C}$. If the discriminant of $p_A$ is equal to $0$ then check the eigenvectors of $A$ (or form the Jordan Form of $A$) in order to check individual cases of diagonalisability.

• a matrix can be diagionalizable even if it has repeated eigenvalues. Take $diag(1,1,1)$ for example. Aug 7, 2018 at 21:34
• As it happens, nontrivial Jordan form occurs for both endpoints, $a=5$ and $a=-27$ Aug 8, 2018 at 0:55
• Perfect answer. Thank you so much Aug 9, 2018 at 18:54
• The minimal polynomial is always the same independently on parameter $a$. The reason is that the system ${v,Av,A^2v}$ is linearly independent, where $v=(1,0,0)$. Thus no reason to cite Caley-Hamilton.
– MGy
Apr 21, 2019 at 10:46

Let's consider such an $a$. Then $A$ must necessarily have a repeated eigenvalue, otherwise it would be diagonalizable. If $f(t) = \det(tI-A)$ is the characteristic polynomial, then $f$ and $f'$ must have a common root. This severely restricts the values that $a$ can take.

Can you continue from here? Note that above is a necessary condition - after you figure out all potential candidates for $a$, you need to check if it actually makes $A$ non-diagionalizable.

Addendum. I have been slow on one point; if $a$ lies outside a certain range, then there must be complex eigenvalues, that is, not real numbers. That is what the other answers and comments are emphasizing, that it might not be possible to diagonalize over the real numbers.

Another way for non-diagonal Jordan form is real but repeated (generalized) eigenvalues, where there is not a basis of eigenvectors. This is the aspect I address below.

ORIGINAL: The derivative of the characteristic polynomial is $3(x-3)(x+1).$ When $a=5,$ we do get the characteristic polynomial as a multiple of $(x-3)^2.$ When $a=-27,$ we get the characteristic polynomial as a multiple of $(x+1)^2.$ These lead to non-diagonal (but real) Jordan forms, see below.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

With $a=5$ and $$\left( \begin{array}{ccc} 1&-9&5 \\ 1&27&5 \\ -6&18&6 \\ \end{array} \right) \left( \begin{array}{ccc} 2&4&5 \\ -1&1&0 \\ 5&1&1 \\ \end{array} \right) = \left( \begin{array}{ccc} 36&0&0 \\ 0&36&0 \\ 0&0&36 \\ \end{array} \right)$$ we get

$$\frac{1}{36} \; \left( \begin{array}{ccc} 1&-9&5 \\ 1&27&5 \\ -6&18&6 \\ \end{array} \right) \left( \begin{array}{ccc} 2&5&-1 \\ 0&2&1 \\ -1&0&-1 \\ \end{array} \right) \left( \begin{array}{ccc} 2&4&5 \\ -1&1&0 \\ 5&1&1 \\ \end{array} \right) = \left( \begin{array}{ccc} -3&0&0 \\ 0&3&1 \\ 0&0&3 \\ \end{array} \right)$$ The final version is called Jordan Normal Form. In the U.S. it is taught with the nilpotent part above the diagonal. In some countries, for example Uruguay, it is taught with any extra $1$s below the diagonal.

Actually using the Jordan form for something merely requires writing out $$\frac{1}{36} \; \left( \begin{array}{ccc} 2&4&5 \\ -1&1&0 \\ 5&1&1 \\ \end{array} \right) \left( \begin{array}{ccc} -3&0&0 \\ 0&3&1 \\ 0&0&3 \\ \end{array} \right) \left( \begin{array}{ccc} 1&-9&5 \\ 1&27&5 \\ -6&18&6 \\ \end{array} \right) = \left( \begin{array}{ccc} 2&5&-1 \\ 0&2&1 \\ -1&0&-1 \\ \end{array} \right)$$

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

WHEN $a=-27,$ With $$\left( \begin{array}{ccc} 1&-17&-3 \\ 1&19&-3 \\ 6&6&18 \\ \end{array} \right) \left( \begin{array}{ccc} 10&8&3 \\ -1&1&0 \\ -3&-3&1 \\ \end{array} \right) = \left( \begin{array}{ccc} 36&0&0 \\ 0&36&0 \\ 0&0&36 \\ \end{array} \right)$$ we get

$$\frac{1}{36} \; \left( \begin{array}{ccc} 1&-17&-3 \\ 1&19&-3 \\ 6&6&18 \\ \end{array} \right) \left( \begin{array}{ccc} 2&-27&-1 \\ 0&2&1 \\ -1&0&-1 \\ \end{array} \right) \left( \begin{array}{ccc} 10&8&3 \\ -1&1&0 \\ -3&-3&1 \\ \end{array} \right) = \left( \begin{array}{ccc} 5&0&0 \\ 0&-1&1 \\ 0&0&-1 \\ \end{array} \right)$$

$$\frac{1}{36} \; \left( \begin{array}{ccc} 10&8&3 \\ -1&1&0 \\ -3&-3&1 \\ \end{array} \right) \left( \begin{array}{ccc} 5&0&0 \\ 0&-1&1 \\ 0&0&-1 \\ \end{array} \right) \left( \begin{array}{ccc} 1&-17&-3 \\ 1&19&-3 \\ 6&6&18 \\ \end{array} \right) = \left( \begin{array}{ccc} 2&-27&-1 \\ 0&2&1 \\ -1&0&-1 \\ \end{array} \right)$$

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

• In case you weren't aware, you can write ---------- or <hr> to get clean HTML breaks, instead of the manual =-= Aug 9, 2018 at 12:11
• @GabrielRomon thanks. I had saved that visual divider in a text file, perfect width for the horizontal spacing of an answer window. Then just paste in. As the layout has changed in the past few days, I will need to experiment. Aug 10, 2018 at 17:37